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
|
<?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 hosts.
*/
class CHost extends CHostGeneral {
protected $sortColumns = ['hostid', 'host', 'name', 'status'];
/**
* Get host data.
*
* @param array $options
* @param array $options['groupids'] HostGroup IDs
* @param array $options['hostids'] Host IDs
* @param bool $options['monitored_hosts'] only monitored Hosts
* @param bool $options['templated_hosts'] include templates in result
* @param bool $options['with_items'] only with items
* @param bool $options['with_monitored_items'] only with monitored items
* @param bool $options['with_triggers'] only with triggers
* @param bool $options['with_monitored_triggers'] only with monitored triggers
* @param bool $options['with_httptests'] only with http tests
* @param bool $options['with_monitored_httptests'] only with monitored http tests
* @param bool $options['with_graphs'] only with graphs
* @param bool $options['editable'] only with read-write permission. Ignored for SuperAdmins
* @param bool $options['selectGroups'] select HostGroups
* @param bool $options['selectItems'] select Items
* @param bool $options['selectTriggers'] select Triggers
* @param bool $options['selectGraphs'] select Graphs
* @param bool $options['selectApplications'] select Applications
* @param bool $options['selectMacros'] select Macros
* @param bool|array $options['selectInventory'] select Inventory
* @param bool $options['withInventory'] select only hosts with inventory
* @param int $options['count'] count Hosts, returned column name is rowscount
* @param string $options['pattern'] search hosts by pattern in Host name
* @param string $options['extendPattern'] search hosts by pattern in Host name, ip and DNS
* @param int $options['limit'] limit selection
* @param string $options['sortfield'] field to sort by
* @param string $options['sortorder'] sort order
*
* @return array|boolean Host data as array or false if error
*/
public function get($options = []) {
$result = [];
$sqlParts = [
'select' => ['hosts' => 'h.hostid'],
'from' => ['hosts' => 'hosts h'],
'where' => ['flags' => 'h.flags IN ('.ZBX_FLAG_DISCOVERY_NORMAL.','.ZBX_FLAG_DISCOVERY_CREATED.')'],
'group' => [],
'order' => [],
'limit' => null
];
$defOptions = [
'groupids' => null,
'hostids' => null,
'proxyids' => null,
'templateids' => null,
'interfaceids' => null,
'itemids' => null,
'triggerids' => null,
'maintenanceids' => null,
'graphids' => null,
'applicationids' => null,
'dserviceids' => null,
'httptestids' => null,
'monitored_hosts' => null,
'templated_hosts' => null,
'proxy_hosts' => null,
'with_items' => null,
'with_monitored_items' => null,
'with_simple_graph_items' => null,
'with_triggers' => null,
'with_monitored_triggers' => null,
'with_httptests' => null,
'with_monitored_httptests' => null,
'with_graphs' => null,
'with_applications' => null,
'withInventory' => null,
'editable' => false,
'nopermissions' => null,
// filter
'filter' => null,
'search' => null,
'searchInventory' => null,
'searchByAny' => null,
'startSearch' => false,
'excludeSearch' => false,
'searchWildcardsEnabled' => false,
// output
'output' => API_OUTPUT_EXTEND,
'selectGroups' => null,
'selectParentTemplates' => null,
'selectItems' => null,
'selectDiscoveries' => null,
'selectTriggers' => null,
'selectGraphs' => null,
'selectApplications' => null,
'selectMacros' => null,
'selectScreens' => null,
'selectInterfaces' => null,
'selectInventory' => null,
'selectHttpTests' => null,
'selectDiscoveryRule' => null,
'selectHostDiscovery' => null,
'countOutput' => false,
'groupCount' => false,
'preservekeys' => false,
'sortfield' => '',
'sortorder' => '',
'limit' => null,
'limitSelects' => null
];
$options = zbx_array_merge($defOptions, $options);
// editable + PERMISSION CHECK
if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
$permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ;
$userGroups = getUserGroupsByUserId(self::$userData['userid']);
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM hosts_groups hgg'.
' JOIN rights r'.
' ON r.id=hgg.groupid'.
' AND '.dbConditionInt('r.groupid', $userGroups).
' WHERE h.hostid=hgg.hostid'.
' GROUP BY hgg.hostid'.
' HAVING MIN(r.permission)>'.PERM_DENY.
' AND MAX(r.permission)>='.zbx_dbstr($permission).
')';
}
// hostids
if (!is_null($options['hostids'])) {
zbx_value2array($options['hostids']);
$sqlParts['where']['hostid'] = dbConditionInt('h.hostid', $options['hostids']);
}
// groupids
if (!is_null($options['groupids'])) {
zbx_value2array($options['groupids']);
$sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
$sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']);
$sqlParts['where']['hgh'] = 'hg.hostid=h.hostid';
if ($options['groupCount']) {
$sqlParts['group']['groupid'] = 'hg.groupid';
}
}
// proxyids
if (!is_null($options['proxyids'])) {
zbx_value2array($options['proxyids']);
$sqlParts['where'][] = dbConditionId('h.proxy_hostid', $options['proxyids']);
}
// templateids
if (!is_null($options['templateids'])) {
zbx_value2array($options['templateids']);
$sqlParts['from']['hosts_templates'] = 'hosts_templates ht';
$sqlParts['where'][] = dbConditionInt('ht.templateid', $options['templateids']);
$sqlParts['where']['hht'] = 'h.hostid=ht.hostid';
if ($options['groupCount']) {
$sqlParts['group']['templateid'] = 'ht.templateid';
}
}
// interfaceids
if (!is_null($options['interfaceids'])) {
zbx_value2array($options['interfaceids']);
$sqlParts['from']['interface'] = 'interface hi';
$sqlParts['where'][] = dbConditionInt('hi.interfaceid', $options['interfaceids']);
$sqlParts['where']['hi'] = 'h.hostid=hi.hostid';
}
// itemids
if (!is_null($options['itemids'])) {
zbx_value2array($options['itemids']);
$sqlParts['from']['items'] = 'items i';
$sqlParts['where'][] = dbConditionInt('i.itemid', $options['itemids']);
$sqlParts['where']['hi'] = 'h.hostid=i.hostid';
}
// triggerids
if (!is_null($options['triggerids'])) {
zbx_value2array($options['triggerids']);
$sqlParts['from']['functions'] = 'functions f';
$sqlParts['from']['items'] = 'items i';
$sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
$sqlParts['where']['hi'] = 'h.hostid=i.hostid';
$sqlParts['where']['fi'] = 'f.itemid=i.itemid';
}
// httptestids
if (!is_null($options['httptestids'])) {
zbx_value2array($options['httptestids']);
$sqlParts['from']['httptest'] = 'httptest ht';
$sqlParts['where'][] = dbConditionInt('ht.httptestid', $options['httptestids']);
$sqlParts['where']['aht'] = 'ht.hostid=h.hostid';
}
// graphids
if (!is_null($options['graphids'])) {
zbx_value2array($options['graphids']);
$sqlParts['from']['graphs_items'] = 'graphs_items gi';
$sqlParts['from']['items'] = 'items i';
$sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']);
$sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
$sqlParts['where']['hi'] = 'h.hostid=i.hostid';
}
// applicationids
if (!is_null($options['applicationids'])) {
zbx_value2array($options['applicationids']);
$sqlParts['from']['applications'] = 'applications a';
$sqlParts['where'][] = dbConditionInt('a.applicationid', $options['applicationids']);
$sqlParts['where']['ah'] = 'a.hostid=h.hostid';
}
// dserviceids
if (!is_null($options['dserviceids'])) {
zbx_value2array($options['dserviceids']);
$sqlParts['from']['dservices'] = 'dservices ds';
$sqlParts['from']['interface'] = 'interface i';
$sqlParts['where'][] = dbConditionInt('ds.dserviceid', $options['dserviceids']);
$sqlParts['where']['dsh'] = 'ds.ip=i.ip';
$sqlParts['where']['hi'] = 'h.hostid=i.hostid';
if ($options['groupCount']) {
$sqlParts['group']['dserviceid'] = 'ds.dserviceid';
}
}
// maintenanceids
if (!is_null($options['maintenanceids'])) {
zbx_value2array($options['maintenanceids']);
$sqlParts['from']['maintenances_hosts'] = 'maintenances_hosts mh';
$sqlParts['where'][] = dbConditionInt('mh.maintenanceid', $options['maintenanceids']);
$sqlParts['where']['hmh'] = 'h.hostid=mh.hostid';
if ($options['groupCount']) {
$sqlParts['group']['maintenanceid'] = 'mh.maintenanceid';
}
}
// monitored_hosts, templated_hosts
if (!is_null($options['monitored_hosts'])) {
$sqlParts['where']['status'] = 'h.status='.HOST_STATUS_MONITORED;
}
elseif (!is_null($options['templated_hosts'])) {
$sqlParts['where']['status'] = 'h.status IN ('.HOST_STATUS_MONITORED.','.HOST_STATUS_NOT_MONITORED.','.HOST_STATUS_TEMPLATE.')';
}
elseif (!is_null($options['proxy_hosts'])) {
$sqlParts['where']['status'] = 'h.status IN ('.HOST_STATUS_PROXY_ACTIVE.','.HOST_STATUS_PROXY_PASSIVE.')';
}
else {
$sqlParts['where']['status'] = 'h.status IN ('.HOST_STATUS_MONITORED.','.HOST_STATUS_NOT_MONITORED.')';
}
// with_items, with_monitored_items, with_simple_graph_items
if (!is_null($options['with_items'])) {
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM items i'.
' WHERE h.hostid=i.hostid'.
' AND i.flags IN ('.ZBX_FLAG_DISCOVERY_NORMAL.','.ZBX_FLAG_DISCOVERY_CREATED.')'.
')';
}
elseif (!is_null($options['with_monitored_items'])) {
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM items i'.
' WHERE h.hostid=i.hostid'.
' AND i.status='.ITEM_STATUS_ACTIVE.
' AND i.flags IN ('.ZBX_FLAG_DISCOVERY_NORMAL.','.ZBX_FLAG_DISCOVERY_CREATED.')'.
')';
}
elseif (!is_null($options['with_simple_graph_items'])) {
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM items i'.
' WHERE h.hostid=i.hostid'.
' AND i.value_type IN ('.ITEM_VALUE_TYPE_FLOAT.','.ITEM_VALUE_TYPE_UINT64.')'.
' AND i.status='.ITEM_STATUS_ACTIVE.
' AND i.flags IN ('.ZBX_FLAG_DISCOVERY_NORMAL.','.ZBX_FLAG_DISCOVERY_CREATED.')'.
')';
}
// with_triggers, with_monitored_triggers
if (!is_null($options['with_triggers'])) {
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM items i,functions f,triggers t'.
' WHERE h.hostid=i.hostid'.
' AND i.itemid=f.itemid'.
' AND f.triggerid=t.triggerid'.
' AND t.flags IN ('.ZBX_FLAG_DISCOVERY_NORMAL.','.ZBX_FLAG_DISCOVERY_CREATED.')'.
')';
}
elseif (!is_null($options['with_monitored_triggers'])) {
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM items i,functions f,triggers t'.
' WHERE h.hostid=i.hostid'.
' AND i.itemid=f.itemid'.
' AND f.triggerid=t.triggerid'.
' AND i.status='.ITEM_STATUS_ACTIVE.
' AND t.status='.TRIGGER_STATUS_ENABLED.
' AND t.flags IN ('.ZBX_FLAG_DISCOVERY_NORMAL.','.ZBX_FLAG_DISCOVERY_CREATED.')'.
')';
}
// with_httptests, with_monitored_httptests
if (!empty($options['with_httptests'])) {
$sqlParts['where'][] = 'EXISTS (SELECT NULL FROM httptest ht WHERE ht.hostid=h.hostid)';
}
elseif (!empty($options['with_monitored_httptests'])) {
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM httptest ht'.
' WHERE h.hostid=ht.hostid'.
' AND ht.status='.HTTPTEST_STATUS_ACTIVE.
')';
}
// with_graphs
if (!is_null($options['with_graphs'])) {
$sqlParts['where'][] = 'EXISTS ('.
'SELECT NULL'.
' FROM items i,graphs_items gi,graphs g'.
' WHERE i.hostid=h.hostid'.
' AND i.itemid=gi.itemid '.
' AND gi.graphid=g.graphid'.
' AND g.flags IN ('.ZBX_FLAG_DISCOVERY_NORMAL.','.ZBX_FLAG_DISCOVERY_CREATED.')'.
')';
}
// with applications
if (!is_null($options['with_applications'])) {
$sqlParts['from']['applications'] = 'applications a';
$sqlParts['where'][] = 'a.hostid=h.hostid';
}
// withInventory
if (!is_null($options['withInventory']) && $options['withInventory']) {
$sqlParts['where'][] = ' h.hostid IN ('.
' SELECT hin.hostid'.
' FROM host_inventory hin'.
')';
}
// search
if (is_array($options['search'])) {
zbx_db_search('hosts h', $options, $sqlParts);
if (zbx_db_search('interface hi', $options, $sqlParts)) {
$sqlParts['from']['interface'] = 'interface hi';
$sqlParts['where']['hi'] = 'h.hostid=hi.hostid';
}
}
// search inventory
if ($options['searchInventory'] !== null) {
$sqlParts['from']['host_inventory'] = 'host_inventory hii';
$sqlParts['where']['hii'] = 'h.hostid=hii.hostid';
zbx_db_search('host_inventory hii',
[
'search' => $options['searchInventory'],
'startSearch' => $options['startSearch'],
'excludeSearch' => $options['excludeSearch'],
'searchWildcardsEnabled' => $options['searchWildcardsEnabled'],
'searchByAny' => $options['searchByAny']
],
$sqlParts
);
}
// filter
if (is_array($options['filter'])) {
$this->dbFilter('hosts h', $options, $sqlParts);
if ($this->dbFilter('interface hi', $options, $sqlParts)) {
$sqlParts['from']['interface'] = 'interface hi';
$sqlParts['where']['hi'] = 'h.hostid=hi.hostid';
}
}
// limit
if (zbx_ctype_digit($options['limit']) && $options['limit']) {
$sqlParts['limit'] = $options['limit'];
}
$sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
$sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
$res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
while ($host = DBfetch($res)) {
if ($options['countOutput']) {
if ($options['groupCount']) {
$result[] = $host;
}
else {
$result = $host['rowscount'];
}
}
else {
$result[$host['hostid']] = $host;
}
}
if ($options['countOutput']) {
return $result;
}
if ($result) {
$result = $this->addRelatedObjects($options, $result);
}
// removing keys (hash -> array)
if (!$options['preservekeys']) {
$result = zbx_cleanHashes($result);
}
return $result;
}
/**
* Add host.
*
* @param array $hosts An array with hosts data.
* @param string $hosts[]['host'] Host technical name.
* @param string $hosts[]['name'] Host visible name (optional).
* @param array $hosts[]['groups'] An array of host group objects with IDs that host will be added to.
* @param int $hosts[]['status'] Status of the host (optional).
* @param array $hosts[]['interfaces'] An array of host interfaces data.
* @param int $hosts[]['interfaces']['type'] Interface type.
* @param int $hosts[]['interfaces']['main'] Is this the default interface to use.
* @param string $hosts[]['interfaces']['ip'] Interface IP (optional).
* @param int $hosts[]['interfaces']['port'] Interface port (optional).
* @param int $hosts[]['interfaces']['useip'] Interface shoud use IP (optional).
* @param string $hosts[]['interfaces']['dns'] Interface shoud use DNS (optional).
* @param int $hosts[]['interfaces']['bulk'] Use bulk requests for interface (optional).
* @param int $hosts[]['proxy_hostid'] ID of the proxy that is used to monitor the host (optional).
* @param int $hosts[]['ipmi_authtype'] IPMI authentication type (optional).
* @param int $hosts[]['ipmi_privilege'] IPMI privilege (optional).
* @param string $hosts[]['ipmi_username'] IPMI username (optional).
* @param string $hosts[]['ipmi_password'] IPMI password (optional).
* @param array $hosts[]['inventory'] An array of host inventory data (optional).
* @param array $hosts[]['macros'] An array of host macros (optional).
* @param string $hosts[]['macros'][]['macro'] Host macro (required if "macros" is set).
* @param array $hosts[]['templates'] An array of template objects with IDs that will be linked to host (optional).
* @param string $hosts[]['templates'][]['templateid'] Template ID (required if "templates" is set).
* @param string $hosts[]['tls_connect'] Connections to host (optional).
* @param string $hosts[]['tls_accept'] Connections from host (optional).
* @param string $hosts[]['tls_psk_identity'] PSK identity (required if "PSK" type is set).
* @param string $hosts[]['tls_psk'] PSK (required if "PSK" type is set).
* @param string $hosts[]['tls_issuer'] Certificate issuer (optional).
* @param string $hosts[]['tls_subject'] Certificate subject (optional).
*
* @return array
*/
public function create($hosts) {
$hosts = zbx_toArray($hosts);
$this->validateCreate($hosts);
$hostids = [];
foreach ($hosts as $host) {
// If visible name is not given or empty it should be set to host name.
if (!array_key_exists('name', $host) || !trim($host['name'])) {
$host['name'] = $host['host'];
}
$hostid = DB::insert('hosts', [$host]);
$hostid = reset($hostid);
$host['hostid'] = $hostid;
$hostids[] = $hostid;
// Save groups. Groups must be added before calling massAdd() for permission validation to work.
$groupsToAdd = [];
foreach ($host['groups'] as $group) {
$groupsToAdd[] = [
'hostid' => $hostid,
'groupid' => $group['groupid']
];
}
DB::insert('hosts_groups', $groupsToAdd);
$options = [
'hosts' => $host
];
if (isset($host['templates']) && !is_null($host['templates'])) {
$options['templates'] = $host['templates'];
}
if (isset($host['macros']) && !is_null($host['macros'])) {
$options['macros'] = $host['macros'];
}
if (isset($host['interfaces']) && !is_null($host['interfaces'])) {
$options['interfaces'] = $host['interfaces'];
}
$result = API::Host()->massAdd($options);
if (!$result) {
self::exception();
}
if (array_key_exists('inventory', $host) && $host['inventory']) {
$hostInventory = $host['inventory'];
$hostInventory['inventory_mode'] = HOST_INVENTORY_MANUAL;
}
else {
$hostInventory = [];
}
if (array_key_exists('inventory_mode', $host) && $host['inventory_mode'] != HOST_INVENTORY_DISABLED) {
$hostInventory['inventory_mode'] = $host['inventory_mode'];
}
if (array_key_exists('inventory_mode', $hostInventory)
&& ($hostInventory['inventory_mode'] == HOST_INVENTORY_MANUAL
|| $hostInventory['inventory_mode'] == HOST_INVENTORY_AUTOMATIC)) {
$hostInventory['hostid'] = $hostid;
DB::insert('host_inventory', [$hostInventory], false);
}
}
return ['hostids' => $hostids];
}
/**
* Update host.
*
* @param array $hosts An array with hosts data.
* @param string $hosts[]['hostid'] Host ID.
* @param string $hosts[]['host'] Host technical name (optional).
* @param string $hosts[]['name'] Host visible name (optional).
* @param array $hosts[]['groups'] An array of host group objects with IDs that host will be replaced to.
* @param int $hosts[]['status'] Status of the host (optional).
* @param array $hosts[]['interfaces'] An array of host interfaces data to be replaced.
* @param int $hosts[]['interfaces']['type'] Interface type.
* @param int $hosts[]['interfaces']['main'] Is this the default interface to use.
* @param string $hosts[]['interfaces']['ip'] Interface IP (optional).
* @param int $hosts[]['interfaces']['port'] Interface port (optional).
* @param int $hosts[]['interfaces']['useip'] Interface shoud use IP (optional).
* @param string $hosts[]['interfaces']['dns'] Interface shoud use DNS (optional).
* @param int $hosts[]['interfaces']['bulk'] Use bulk requests for interface (optional).
* @param int $hosts[]['proxy_hostid'] ID of the proxy that is used to monitor the host (optional).
* @param int $hosts[]['ipmi_authtype'] IPMI authentication type (optional).
* @param int $hosts[]['ipmi_privilege'] IPMI privilege (optional).
* @param string $hosts[]['ipmi_username'] IPMI username (optional).
* @param string $hosts[]['ipmi_password'] IPMI password (optional).
* @param array $hosts[]['inventory'] An array of host inventory data (optional).
* @param array $hosts[]['macros'] An array of host macros (optional).
* @param string $hosts[]['macros'][]['macro'] Host macro (required if "macros" is set).
* @param array $hosts[]['templates'] An array of template objects with IDs that will be linked to host (optional).
* @param string $hosts[]['templates'][]['templateid'] Template ID (required if "templates" is set).
* @param array $hosts[]['templates_clear'] Templates to unlink and clear from the host (optional).
* @param string $hosts[]['templates_clear'][]['templateid'] Template ID (required if "templates" is set).
* @param string $hosts[]['tls_connect'] Connections to host (optional).
* @param string $hosts[]['tls_accept'] Connections from host (optional).
* @param string $hosts[]['tls_psk_identity'] PSK identity (required if "PSK" type is set).
* @param string $hosts[]['tls_psk'] PSK (required if "PSK" type is set).
* @param string $hosts[]['tls_issuer'] Certificate issuer (optional).
* @param string $hosts[]['tls_subject'] Certificate subject (optional).
*
* @return array
*/
public function update($hosts) {
$hosts = zbx_toArray($hosts);
$hostids = zbx_objectValues($hosts, 'hostid');
$db_hosts = $this->get([
'output' => ['hostid', 'host', 'flags', 'tls_connect', 'tls_accept', 'tls_issuer', 'tls_subject',
'tls_psk_identity', 'tls_psk'
],
'hostids' => $hostids,
'editable' => true,
'preservekeys' => true
]);
$hosts = $this->validateUpdate($hosts, $db_hosts);
$inventories = [];
foreach ($hosts as &$host) {
// If visible name is not given or empty it should be set to host name.
if (array_key_exists('host', $host) && (!array_key_exists('name', $host) || !trim($host['name']))) {
$host['name'] = $host['host'];
}
// Fetch fields required to update host inventory.
if (array_key_exists('inventory', $host)) {
$inventory = $host['inventory'];
$inventory['hostid'] = $host['hostid'];
$inventories[] = $inventory;
}
}
unset($host);
$inventories = $this->extendObjects('host_inventory', $inventories, ['inventory_mode']);
$inventories = zbx_toHash($inventories, 'hostid');
$macros = [];
foreach ($hosts as &$host) {
if (isset($host['macros'])) {
$macros[$host['hostid']] = $host['macros'];
unset($host['macros']);
}
}
unset($host);
if ($macros) {
API::UserMacro()->replaceMacros($macros);
}
$hosts = $this->extendObjectsByKey($hosts, $db_hosts, 'hostid', ['tls_connect', 'tls_accept', 'tls_issuer',
'tls_subject', 'tls_psk_identity', 'tls_psk'
]);
foreach ($hosts as $host) {
// Extend host inventory with the required data.
if (array_key_exists('inventory', $host) && $host['inventory']) {
// If inventory mode is HOST_INVENTORY_DISABLED, database record is not created.
if (array_key_exists('inventory_mode', $inventories[$host['hostid']])
&& ($inventories[$host['hostid']]['inventory_mode'] == HOST_INVENTORY_MANUAL
|| $inventories[$host['hostid']]['inventory_mode'] == HOST_INVENTORY_AUTOMATIC)) {
$host['inventory'] = $inventories[$host['hostid']];
}
}
$data = $host;
$data['hosts'] = ['hostid' => $host['hostid']];
$result = $this->massUpdate($data);
if (!$result) {
self::exception(ZBX_API_ERROR_INTERNAL, _('Host update failed.'));
}
}
return ['hostids' => $hostids];
}
/**
* Additionally allows to create new interfaces on hosts.
*
* Checks write permissions for hosts.
*
* Additional supported $data parameters are:
* - interfaces - an array of interfaces to create on the hosts
* - templates - an array of templates to link to the hosts, overrides the CHostGeneral::massAdd()
* 'templates' parameter
*
* @param array $data
*
* @return array
*/
public function massAdd(array $data) {
$hosts = isset($data['hosts']) ? zbx_toArray($data['hosts']) : [];
$hostIds = zbx_objectValues($hosts, 'hostid');
$this->checkPermissions($hostIds, _('You do not have permission to perform this operation.'));
// add new interfaces
if (!empty($data['interfaces'])) {
API::HostInterface()->massAdd([
'hosts' => $data['hosts'],
'interfaces' => zbx_toArray($data['interfaces'])
]);
}
// rename the "templates" parameter to the common "templates_link"
if (isset($data['templates'])) {
$data['templates_link'] = $data['templates'];
unset($data['templates']);
}
$data['templates'] = [];
return parent::massAdd($data);
}
/**
* Mass update hosts.
*
* @param array $hosts multidimensional array with Hosts data
* @param array $hosts['hosts'] Array of Host objects to update
* @param string $hosts['fields']['host'] Host name.
* @param array $hosts['fields']['groupids'] HostGroup IDs add Host to.
* @param int $hosts['fields']['port'] Port. OPTIONAL
* @param int $hosts['fields']['status'] Host Status. OPTIONAL
* @param int $hosts['fields']['useip'] Use IP. OPTIONAL
* @param string $hosts['fields']['dns'] DNS. OPTIONAL
* @param string $hosts['fields']['ip'] IP. OPTIONAL
* @param int $hosts['fields']['bulk'] bulk. OPTIONAL
* @param int $hosts['fields']['proxy_hostid'] Proxy Host ID. OPTIONAL
* @param int $hosts['fields']['ipmi_authtype'] IPMI authentication type. OPTIONAL
* @param int $hosts['fields']['ipmi_privilege'] IPMI privilege. OPTIONAL
* @param string $hosts['fields']['ipmi_username'] IPMI username. OPTIONAL
* @param string $hosts['fields']['ipmi_password'] IPMI password. OPTIONAL
*
* @return boolean
*/
public function massUpdate($data) {
if (!array_key_exists('hosts', $data) || !is_array($data['hosts'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Field "%1$s" is mandatory.', 'hosts'));
}
$hosts = zbx_toArray($data['hosts']);
$inputHostIds = zbx_objectValues($hosts, 'hostid');
$hostids = array_unique($inputHostIds);
sort($hostids);
$db_hosts = $this->get([
'output' => ['hostid', 'host'],
'hostids' => $hostids,
'editable' => true,
'preservekeys' => true
]);
foreach ($hosts as $host) {
if (!array_key_exists($host['hostid'], $db_hosts)) {
self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.'));
}
}
// Check inventory mode value.
if (array_key_exists('inventory_mode', $data)) {
$valid_inventory_modes = [HOST_INVENTORY_DISABLED, HOST_INVENTORY_MANUAL, HOST_INVENTORY_AUTOMATIC];
$inventory_mode = new CLimitedSetValidator([
'values' => $valid_inventory_modes,
'messageInvalid' => _s('Incorrect value for field "%1$s": %2$s.', 'inventory_mode',
_s('value must be one of %1$s', implode(', ', $valid_inventory_modes)))
]);
$this->checkValidator($data['inventory_mode'], $inventory_mode);
}
// Check connection fields only for massupdate action.
if (array_key_exists('tls_connect', $data) || array_key_exists('tls_accept', $data)
|| array_key_exists('tls_psk_identity', $data) || array_key_exists('tls_psk', $data)
|| array_key_exists('tls_issuer', $data) || array_key_exists('tls_subject', $data)) {
if (!array_key_exists('tls_connect', $data) || !array_key_exists('tls_accept', $data)) {
self::exception(ZBX_API_ERROR_PERMISSIONS, _(
'Cannot update host encryption settings. Connection settings for both directions should be specified.'
));
}
// Clean PSK fields.
if ($data['tls_connect'] != HOST_ENCRYPTION_PSK && !($data['tls_accept'] & HOST_ENCRYPTION_PSK)) {
$data['tls_psk_identity'] = '';
$data['tls_psk'] = '';
}
// Clean certificate fields.
if ($data['tls_connect'] != HOST_ENCRYPTION_CERTIFICATE
&& !($data['tls_accept'] & HOST_ENCRYPTION_CERTIFICATE)) {
$data['tls_issuer'] = '';
$data['tls_subject'] = '';
}
}
$this->validateEncryption([$data]);
if (array_key_exists('groups', $data) && !$data['groups'] && $db_hosts) {
$host = reset($db_hosts);
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Host "%1$s" cannot be without host group.', $host['host'])
);
}
// Property 'auto_compress' is not supported for hosts.
if (array_key_exists('auto_compress', $data)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect input parameters.'));
}
/*
* Update hosts properties
*/
if (isset($data['name'])) {
if (count($hosts) > 1) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update visible host name.'));
}
}
if (isset($data['host'])) {
if (!preg_match('/^'.ZBX_PREG_HOST_FORMAT.'$/', $data['host'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for host name "%s".', $data['host']));
}
if (count($hosts) > 1) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update host name.'));
}
$curHost = reset($hosts);
$sameHostnameHost = $this->get([
'output' => ['hostid'],
'filter' => ['host' => $data['host']],
'nopermissions' => true,
'limit' => 1
]);
$sameHostnameHost = reset($sameHostnameHost);
if ($sameHostnameHost && (bccomp($sameHostnameHost['hostid'], $curHost['hostid']) != 0)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host "%1$s" already exists.', $data['host']));
}
// can't add host with the same name as existing template
$sameHostnameTemplate = API::Template()->get([
'output' => ['templateid'],
'filter' => ['host' => $data['host']],
'nopermissions' => true,
'limit' => 1
]);
if ($sameHostnameTemplate) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template "%1$s" already exists.', $data['host']));
}
}
if (isset($data['groups'])) {
$updateGroups = $data['groups'];
}
if (isset($data['interfaces'])) {
$updateInterfaces = $data['interfaces'];
}
if (array_key_exists('templates_clear', $data)) {
$updateTemplatesClear = zbx_toArray($data['templates_clear']);
}
if (isset($data['templates'])) {
$updateTemplates = $data['templates'];
}
if (isset($data['macros'])) {
$updateMacros = $data['macros'];
}
// second check is necessary, because import incorrectly inputs unset 'inventory' as empty string rather than null
if (isset($data['inventory']) && $data['inventory']) {
if (isset($data['inventory_mode']) && $data['inventory_mode'] == HOST_INVENTORY_DISABLED) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set inventory fields for disabled inventory.'));
}
$updateInventory = $data['inventory'];
$updateInventory['inventory_mode'] = null;
}
if (isset($data['inventory_mode'])) {
if (!isset($updateInventory)) {
$updateInventory = [];
}
$updateInventory['inventory_mode'] = $data['inventory_mode'];
}
if (isset($data['status'])) {
$updateStatus = $data['status'];
}
unset($data['hosts'], $data['groups'], $data['interfaces'], $data['templates_clear'], $data['templates'],
$data['macros'], $data['inventory'], $data['inventory_mode'], $data['status']);
if (!zbx_empty($data)) {
DB::update('hosts', [
'values' => $data,
'where' => ['hostid' => $hostids]
]);
}
if (isset($updateStatus)) {
updateHostStatus($hostids, $updateStatus);
}
/*
* Update template linkage
*/
if (isset($updateTemplatesClear)) {
$templateIdsClear = zbx_objectValues($updateTemplatesClear, 'templateid');
if ($updateTemplatesClear) {
$this->massRemove(['hostids' => $hostids, 'templateids_clear' => $templateIdsClear]);
}
}
else {
$templateIdsClear = [];
}
// unlink templates
if (isset($updateTemplates)) {
$hostTemplates = API::Template()->get([
'hostids' => $hostids,
'output' => ['templateid'],
'preservekeys' => true
]);
$hostTemplateids = array_keys($hostTemplates);
$newTemplateids = zbx_objectValues($updateTemplates, 'templateid');
$templatesToDel = array_diff($hostTemplateids, $newTemplateids);
$templatesToDel = array_diff($templatesToDel, $templateIdsClear);
if ($templatesToDel) {
$result = $this->massRemove([
'hostids' => $hostids,
'templateids' => $templatesToDel
]);
if (!$result) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template'));
}
}
}
/*
* update interfaces
*/
if (isset($updateInterfaces)) {
foreach($hostids as $hostid) {
API::HostInterface()->replaceHostInterfaces([
'hostid' => $hostid,
'interfaces' => $updateInterfaces
]);
}
}
// link new templates
if (isset($updateTemplates)) {
$result = $this->massAdd([
'hosts' => $hosts,
'templates' => $updateTemplates
]);
if (!$result) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template'));
}
}
// macros
if (isset($updateMacros)) {
DB::delete('hostmacro', ['hostid' => $hostids]);
$this->massAdd([
'hosts' => $hosts,
'macros' => $updateMacros
]);
}
/*
* Inventory
*/
if (isset($updateInventory)) {
// disabling inventory
if ($updateInventory['inventory_mode'] == HOST_INVENTORY_DISABLED) {
$sql = 'DELETE FROM host_inventory WHERE '.dbConditionInt('hostid', $hostids);
if (!DBexecute($sql)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete inventory.'));
}
}
// changing inventory mode or setting inventory fields
else {
$existingInventoriesDb = DBfetchArrayAssoc(DBselect(
'SELECT hostid,inventory_mode'.
' FROM host_inventory'.
' WHERE '.dbConditionInt('hostid', $hostids)
), 'hostid');
// check existing host inventory data
$automaticHostIds = [];
if ($updateInventory['inventory_mode'] === null) {
foreach ($hostids as $hostid) {
// if inventory is disabled for one of the updated hosts, throw an exception
if (!isset($existingInventoriesDb[$hostid])) {
$host = get_host_by_hostid($hostid);
self::exception(ZBX_API_ERROR_PARAMETERS, _s(
'Inventory disabled for host "%1$s".', $host['host']
));
}
// if inventory mode is set to automatic, save its ID for later usage
elseif ($existingInventoriesDb[$hostid]['inventory_mode'] == HOST_INVENTORY_AUTOMATIC) {
$automaticHostIds[] = $hostid;
}
}
}
$inventoriesToSave = [];
foreach ($hostids as $hostid) {
$hostInventory = $updateInventory;
$hostInventory['hostid'] = $hostid;
// if no 'inventory_mode' has been passed, set inventory 'inventory_mode' from DB
if ($updateInventory['inventory_mode'] === null) {
$hostInventory['inventory_mode'] = $existingInventoriesDb[$hostid]['inventory_mode'];
}
$inventoriesToSave[$hostid] = $hostInventory;
}
// when updating automatic inventory, ignore fields that have items linked to them
if ($updateInventory['inventory_mode'] == HOST_INVENTORY_AUTOMATIC
|| ($updateInventory['inventory_mode'] === null && $automaticHostIds)) {
$itemsToInventories = API::item()->get([
'output' => ['inventory_link', 'hostid'],
'hostids' => $automaticHostIds ? $automaticHostIds : $hostids,
'nopermissions' => true
]);
$inventoryFields = getHostInventories();
foreach ($itemsToInventories as $hinv) {
// 0 means 'no link'
if ($hinv['inventory_link'] != 0) {
$inventoryName = $inventoryFields[$hinv['inventory_link']]['db_field'];
unset($inventoriesToSave[$hinv['hostid']][$inventoryName]);
}
}
}
// save inventory data
foreach ($inventoriesToSave as $inventory) {
$hostid = $inventory['hostid'];
if (isset($existingInventoriesDb[$hostid])) {
DB::update('host_inventory', [
'values' => $inventory,
'where' => ['hostid' => $hostid]
]);
}
else {
DB::insert('host_inventory', [$inventory], false);
}
}
}
}
/*
* Update host and host group linkage. This procedure should be done the last because user can unlink
* him self from a group with write permissions leaving only read premissions. Thus other procedures, like
* host-template linkage, inventory update, macros update, must be done before this.
*/
if (isset($updateGroups)) {
$updateGroups = zbx_toArray($updateGroups);
$hostGroups = API::HostGroup()->get([
'output' => ['groupid'],
'hostids' => $hostids
]);
$hostGroupIds = zbx_objectValues($hostGroups, 'groupid');
$newGroupIds = zbx_objectValues($updateGroups, 'groupid');
$groupsToAdd = array_diff($newGroupIds, $hostGroupIds);
if ($groupsToAdd) {
$this->massAdd([
'hosts' => $hosts,
'groups' => zbx_toObject($groupsToAdd, 'groupid')
]);
}
$groupIdsToDelete = array_diff($hostGroupIds, $newGroupIds);
if ($groupIdsToDelete) {
$this->massRemove([
'hostids' => $hostids,
'groupids' => $groupIdsToDelete
]);
}
}
return ['hostids' => $inputHostIds];
}
/**
* Additionally allows to remove interfaces from hosts.
*
* Checks write permissions for hosts.
*
* Additional supported $data parameters are:
* - interfaces - an array of interfaces to delete from the hosts
*
* @param array $data
*
* @return array
*/
public function massRemove(array $data) {
$hostids = zbx_toArray($data['hostids']);
$this->checkPermissions($hostids, _('No permissions to referred object or it does not exist!'));
if (isset($data['interfaces'])) {
$options = [
'hostids' => $hostids,
'interfaces' => zbx_toArray($data['interfaces'])
];
API::HostInterface()->massRemove($options);
}
// rename the "templates" parameter to the common "templates_link"
if (isset($data['templateids'])) {
$data['templateids_link'] = $data['templateids'];
unset($data['templateids']);
}
$data['templateids'] = [];
return parent::massRemove($data);
}
/**
* Validates the input parameters for the delete() method.
*
* @throws APIException if the input is invalid
*
* @param array $hostIds
* @param bool $nopermissions
*/
protected function validateDelete(array $hostIds, $nopermissions = false) {
if (!$hostIds) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
}
if (!$nopermissions) {
$this->checkPermissions($hostIds, _('No permissions to referred object or it does not exist!'));
}
$this->validateDeleteCheckMaintenances($hostIds);
}
/**
* Validates if hosts may be deleted, due to maintenance constrain.
*
* @throws APIException if a constrain failed
*
* @param array $hostids
*/
protected function validateDeleteCheckMaintenances(array $hostids) {
$maintenance = DBfetch(DBselect(
'SELECT m.name'.
' FROM maintenances m'.
' WHERE NOT EXISTS ('.
'SELECT NULL'.
' FROM maintenances_hosts mh'.
' WHERE m.maintenanceid=mh.maintenanceid'.
' AND '.dbConditionInt('mh.hostid', $hostids, true).
')'.
' AND NOT EXISTS ('.
'SELECT NULL'.
' FROM maintenances_groups mg'.
' WHERE m.maintenanceid=mg.maintenanceid'.
')'
));
if ($maintenance) {
self::exception(ZBX_API_ERROR_PARAMETERS, _n(
'Cannot delete host because maintenance "%1$s" must contain at least one host or host group.',
'Cannot delete selected hosts because maintenance "%1$s" must contain at least one host or host group.',
$maintenance['name'],
count($hostids)
));
}
}
/**
* Delete Host.
*
* @param array $hostIds
* @param bool $nopermissions
*
* @return array
*/
public function delete(array $hostIds, $nopermissions = false) {
$this->validateDelete($hostIds, $nopermissions);
// delete the discovery rules first
$del_rules = API::DiscoveryRule()->get([
'output' => [],
'hostids' => $hostIds,
'nopermissions' => true,
'preservekeys' => true
]);
if ($del_rules) {
API::DiscoveryRule()->delete(array_keys($del_rules), true);
}
// delete the items
$del_items = API::Item()->get([
'output' => [],
'templateids' => $hostIds,
'nopermissions' => true,
'preservekeys' => true
]);
if ($del_items) {
CItemManager::delete(array_keys($del_items));
}
// delete web tests
$delHttptests = [];
$dbHttptests = get_httptests_by_hostid($hostIds);
while ($dbHttptest = DBfetch($dbHttptests)) {
$delHttptests[$dbHttptest['httptestid']] = $dbHttptest['httptestid'];
}
if (!empty($delHttptests)) {
API::HttpTest()->delete($delHttptests, true);
}
// delete screen items
DB::delete('screens_items', [
'resourceid' => $hostIds,
'resourcetype' => SCREEN_RESOURCE_HOST_TRIGGERS
]);
// delete host from maps
if (!empty($hostIds)) {
DB::delete('sysmaps_elements', [
'elementtype' => SYSMAP_ELEMENT_TYPE_HOST,
'elementid' => $hostIds
]);
}
// disable actions
// actions from conditions
$actionids = [];
$sql = 'SELECT DISTINCT actionid'.
' FROM conditions'.
' WHERE conditiontype='.CONDITION_TYPE_HOST.
' AND '.dbConditionString('value', $hostIds);
$dbActions = DBselect($sql);
while ($dbAction = DBfetch($dbActions)) {
$actionids[$dbAction['actionid']] = $dbAction['actionid'];
}
// actions from operations
$sql = 'SELECT DISTINCT o.actionid'.
' FROM operations o, opcommand_hst oh'.
' WHERE o.operationid=oh.operationid'.
' AND '.dbConditionInt('oh.hostid', $hostIds);
$dbActions = DBselect($sql);
while ($dbAction = DBfetch($dbActions)) {
$actionids[$dbAction['actionid']] = $dbAction['actionid'];
}
if (!empty($actionids)) {
$update = [];
$update[] = [
'values' => ['status' => ACTION_STATUS_DISABLED],
'where' => ['actionid' => $actionids]
];
DB::update('actions', $update);
}
// delete action conditions
DB::delete('conditions', [
'conditiontype' => CONDITION_TYPE_HOST,
'value' => $hostIds
]);
// delete action operation commands
$operationids = [];
$sql = 'SELECT DISTINCT oh.operationid'.
' FROM opcommand_hst oh'.
' WHERE '.dbConditionInt('oh.hostid', $hostIds);
$dbOperations = DBselect($sql);
while ($dbOperation = DBfetch($dbOperations)) {
$operationids[$dbOperation['operationid']] = $dbOperation['operationid'];
}
DB::delete('opcommand_hst', [
'hostid' => $hostIds,
]);
// delete empty operations
$delOperationids = [];
$sql = 'SELECT DISTINCT o.operationid'.
' FROM operations o'.
' WHERE '.dbConditionInt('o.operationid', $operationids).
' AND NOT EXISTS(SELECT oh.opcommand_hstid FROM opcommand_hst oh WHERE oh.operationid=o.operationid)';
$dbOperations = DBselect($sql);
while ($dbOperation = DBfetch($dbOperations)) {
$delOperationids[$dbOperation['operationid']] = $dbOperation['operationid'];
}
DB::delete('operations', [
'operationid' => $delOperationids,
]);
$hosts = API::Host()->get([
'output' => [
'hostid',
'name'
],
'hostids' => $hostIds,
'nopermissions' => true
]);
// delete host inventory
DB::delete('host_inventory', ['hostid' => $hostIds]);
// delete host applications
DB::delete('applications', ['hostid' => $hostIds]);
// delete host
DB::delete('hosts', ['hostid' => $hostIds]);
// TODO: remove info from API
foreach ($hosts as $host) {
info(_s('Deleted: Host "%1$s".', $host['name']));
add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['name'], 'hosts', NULL, NULL);
}
// remove Monitoring > Latest data toggle profile values related to given hosts
DB::delete('profiles', ['idx' => 'web.latest.toggle_other', 'idx2' => $hostIds]);
return ['hostids' => $hostIds];
}
/**
* Retrieves and adds additional requested data to the result set.
*
* @param array $options
* @param array $result
*
* @return array
*/
protected function addRelatedObjects(array $options, array $result) {
$result = parent::addRelatedObjects($options, $result);
$hostids = array_keys($result);
// adding inventory
if ($options['selectInventory'] !== null) {
$inventory = API::getApiService()->select('host_inventory', [
'output' => $options['selectInventory'],
'filter' => ['hostid' => $hostids],
'preservekeys' => true
]);
foreach ($hostids as $hostid) {
// There is no DB record if inventory mode is HOST_INVENTORY_DISABLED.
if (!array_key_exists($hostid, $inventory)) {
$inventory[$hostid] = [
'hostid' => (string) $hostid,
'inventory_mode' => (string) HOST_INVENTORY_DISABLED
];
}
}
$relation_map = $this->createRelationMap($result, 'hostid', 'hostid');
$inventory = $this->unsetExtraFields($inventory, ['hostid', 'inventory_mode'], $options['selectInventory']);
$result = $relation_map->mapOne($result, $inventory, 'inventory');
}
// adding hostinterfaces
if ($options['selectInterfaces'] !== null) {
if ($options['selectInterfaces'] != API_OUTPUT_COUNT) {
$interfaces = API::HostInterface()->get([
'output' => $this->outputExtend($options['selectInterfaces'], ['hostid', 'interfaceid']),
'hostids' => $hostids,
'nopermissions' => true,
'preservekeys' => true
]);
// we need to order interfaces for proper linkage and viewing
order_result($interfaces, 'interfaceid', ZBX_SORT_UP);
$relationMap = $this->createRelationMap($interfaces, 'hostid', 'interfaceid');
$interfaces = $this->unsetExtraFields($interfaces, ['hostid', 'interfaceid'], $options['selectInterfaces']);
$result = $relationMap->mapMany($result, $interfaces, 'interfaces', $options['limitSelects']);
}
else {
$interfaces = API::HostInterface()->get([
'hostids' => $hostids,
'nopermissions' => true,
'countOutput' => true,
'groupCount' => true
]);
$interfaces = zbx_toHash($interfaces, 'hostid');
foreach ($result as $hostid => $host) {
$result[$hostid]['interfaces'] = isset($interfaces[$hostid]) ? $interfaces[$hostid]['rowscount'] : 0;
}
}
}
// adding screens
if ($options['selectScreens'] !== null) {
if ($options['selectScreens'] != API_OUTPUT_COUNT) {
$screens = API::TemplateScreen()->get([
'output' => $this->outputExtend($options['selectScreens'], ['hostid']),
'hostids' => $hostids,
'nopermissions' => true
]);
if (!is_null($options['limitSelects'])) {
order_result($screens, 'name');
}
// inherited screens do not have a unique screenid, so we're building a map using array keys
$relationMap = new CRelationMap();
foreach ($screens as $key => $screen) {
$relationMap->addRelation($screen['hostid'], $key);
}
$screens = $this->unsetExtraFields($screens, ['hostid'], $options['selectScreens']);
$result = $relationMap->mapMany($result, $screens, 'screens', $options['limitSelects']);
}
else {
$screens = API::TemplateScreen()->get([
'hostids' => $hostids,
'nopermissions' => true,
'countOutput' => true,
'groupCount' => true
]);
$screens = zbx_toHash($screens, 'hostid');
foreach ($result as $hostid => $host) {
$result[$hostid]['screens'] = isset($screens[$hostid]) ? $screens[$hostid]['rowscount'] : 0;
}
}
}
// adding discovery rule
if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) {
// discovered items
$discoveryRules = DBFetchArray(DBselect(
'SELECT hd.hostid,hd2.parent_itemid'.
' FROM host_discovery hd,host_discovery hd2'.
' WHERE '.dbConditionInt('hd.hostid', $hostids).
' AND hd.parent_hostid=hd2.hostid'
));
$relationMap = $this->createRelationMap($discoveryRules, 'hostid', 'parent_itemid');
$discoveryRules = API::DiscoveryRule()->get([
'output' => $options['selectDiscoveryRule'],
'itemids' => $relationMap->getRelatedIds(),
'preservekeys' => true
]);
$result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule');
}
// adding host discovery
if ($options['selectHostDiscovery'] !== null) {
$hostDiscoveries = API::getApiService()->select('host_discovery', [
'output' => $this->outputExtend($options['selectHostDiscovery'], ['hostid']),
'filter' => ['hostid' => $hostids],
'preservekeys' => true
]);
$relationMap = $this->createRelationMap($hostDiscoveries, 'hostid', 'hostid');
$hostDiscoveries = $this->unsetExtraFields($hostDiscoveries, ['hostid'],
$options['selectHostDiscovery']
);
$result = $relationMap->mapOne($result, $hostDiscoveries, 'hostDiscovery');
}
return $result;
}
/**
* Checks if all of the given hosts are available for writing.
*
* @throws APIException if a host is not writable or does not exist
*
* @param array $hostids
* @param string $error
*/
protected function checkPermissions(array $hostids, $error) {
if ($hostids) {
$hostids = array_unique($hostids);
$count = $this->get([
'countOutput' => true,
'hostids' => $hostids,
'editable' => true
]);
if ($count != count($hostids)) {
self::exception(ZBX_API_ERROR_PERMISSIONS, $error);
}
}
}
/**
* Validate connections from/to host and PSK fields.
*
* @param array $hosts
* @param string $hosts[]['hostid'] (optional if $db_hosts is null)
* @param int $hosts[]['tls_connect'] (optionsl)
* @param int $hosts[]['tls_accept'] (optional)
* @param string $hosts[]['tls_psk_identity'] (optional)
* @param string $hosts[]['tls_psk'] (optional)
* @param string $hosts[]['tls_issuer'] (optional)
* @param string $hosts[]['tls_subject'] (optional)
* @param array $db_hosts (optional)
* @param int $hosts[<hostid>]['tls_connect']
* @param int $hosts[<hostid>]['tls_accept']
* @param string $hosts[<hostid>]['tls_psk_identity']
* @param string $hosts[<hostid>]['tls_psk']
* @param string $hosts[<hostid>]['tls_issuer']
* @param string $hosts[<hostid>]['tls_subject']
*
* @throws APIException if incorrect encryption options.
*/
protected function validateEncryption(array $hosts, array $db_hosts = null) {
$available_connect_types = [HOST_ENCRYPTION_NONE, HOST_ENCRYPTION_PSK, HOST_ENCRYPTION_CERTIFICATE];
$min_accept_type = HOST_ENCRYPTION_NONE;
$max_accept_type = HOST_ENCRYPTION_NONE | HOST_ENCRYPTION_PSK | HOST_ENCRYPTION_CERTIFICATE;
foreach ($hosts as $host) {
foreach (['tls_connect', 'tls_accept'] as $field_name) {
$$field_name = array_key_exists($field_name, $host)
? $host[$field_name]
: ($db_hosts !== null ? $db_hosts[$host['hostid']][$field_name] : HOST_ENCRYPTION_NONE);
}
if (!in_array($tls_connect, $available_connect_types)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.', 'tls_connect',
_s('unexpected value "%1$s"', $tls_connect)
));
}
if ($tls_accept < $min_accept_type || $tls_accept > $max_accept_type) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.', 'tls_accept',
_s('unexpected value "%1$s"', $tls_accept)
));
}
foreach (['tls_psk_identity', 'tls_psk', 'tls_issuer', 'tls_subject'] as $field_name) {
$$field_name = array_key_exists($field_name, $host)
? $host[$field_name]
: ($db_hosts !== null ? $db_hosts[$host['hostid']][$field_name] : '');
}
// PSK validation.
if ($tls_connect == HOST_ENCRYPTION_PSK || ($tls_accept & HOST_ENCRYPTION_PSK)) {
if ($tls_psk_identity === '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'tls_psk_identity', _('cannot be empty'))
);
}
if ($tls_psk === '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'tls_psk', _('cannot be empty'))
);
}
if (!preg_match('/^([0-9a-f]{2})+$/i', $tls_psk)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.', 'tls_psk',
_('an even number of hexadecimal characters is expected')
));
}
if (strlen($tls_psk) < PSK_MIN_LEN) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.', 'tls_psk',
_s('minimum length is %1$s characters', PSK_MIN_LEN)
));
}
}
else {
if ($tls_psk_identity !== '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'tls_psk_identity', _('should be empty'))
);
}
if ($tls_psk !== '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'tls_psk', _('should be empty'))
);
}
}
// Certificate validation.
if ($tls_connect != HOST_ENCRYPTION_CERTIFICATE && !($tls_accept & HOST_ENCRYPTION_CERTIFICATE)) {
if ($tls_issuer !== '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'tls_issuer', _('should be empty'))
);
}
if ($tls_subject !== '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'tls_subject', _('should be empty'))
);
}
}
}
}
/**
* Validates the input parameters for the create() method.
*
* @param array $hosts hosts data array
*
* @throws APIException if the input is invalid.
*/
protected function validateCreate(array $hosts) {
$host_db_fields = ['host' => null];
$groupids = [];
foreach ($hosts as &$host) {
// Validate mandatory fields.
if (!check_db_fields($host_db_fields, $host)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Wrong fields for host "%1$s".', array_key_exists('host', $host) ? $host['host'] : '')
);
}
// Property 'auto_compress' is not supported for hosts.
if (array_key_exists('auto_compress', $host)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect input parameters.'));
}
// Validate "host" field.
if (!preg_match('/^'.ZBX_PREG_HOST_FORMAT.'$/', $host['host'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect characters used for host name "%s".', $host['host'])
);
}
// If visible name is not given or empty it should be set to host name. Required for duplicate checks.
if (!array_key_exists('name', $host) || !trim($host['name'])) {
$host['name'] = $host['host'];
}
// Validate "groups" field.
if (!array_key_exists('groups', $host) || !is_array($host['groups']) || !$host['groups']) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Host "%1$s" cannot be without host group.', $host['host'])
);
}
$groupids = array_merge($groupids, zbx_objectValues($host['groups'], 'groupid'));
}
unset($host);
// Check for duplicate "host" and "name" fields.
$duplicate = CArrayHelper::findDuplicate($hosts, 'host');
if ($duplicate) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Duplicate host. Host with the same host name "%s" already exists in data.', $duplicate['host'])
);
}
$duplicate = CArrayHelper::findDuplicate($hosts, 'name');
if ($duplicate) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Duplicate host. Host with the same visible name "%s" already exists in data.', $duplicate['name'])
);
}
// Validate permissions to host groups.
if ($groupids) {
$db_groups = API::HostGroup()->get([
'output' => ['groupid'],
'groupids' => $groupids,
'editable' => true,
'preservekeys' => true
]);
}
foreach ($hosts as $host) {
foreach ($host['groups'] as $group) {
if (!array_key_exists($group['groupid'], $db_groups)) {
self::exception(ZBX_API_ERROR_PERMISSIONS,
_('No permissions to referred object or it does not exist!')
);
}
}
}
$inventory_fields = zbx_objectValues(getHostInventories(), 'db_field');
$valid_inventory_modes = [HOST_INVENTORY_DISABLED, HOST_INVENTORY_MANUAL, HOST_INVENTORY_AUTOMATIC];
$inventory_mode = new CLimitedSetValidator([
'values' => $valid_inventory_modes,
'messageInvalid' => _s('Incorrect value for field "%1$s": %2$s.', 'inventory_mode',
_s('value must be one of %1$s', implode(', ', $valid_inventory_modes)))
]);
$status_validator = new CLimitedSetValidator([
'values' => [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED],
'messageInvalid' => _('Incorrect status for host "%1$s".')
]);
$host_names = [];
foreach ($hosts as $host) {
if (!array_key_exists('interfaces', $host) || !is_array($host['interfaces']) || !$host['interfaces']) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('No interfaces for host "%s".', $host['host']));
}
if (array_key_exists('status', $host)) {
$status_validator->setObjectName($host['host']);
$this->checkValidator($host['status'], $status_validator);
}
if (array_key_exists('inventory_mode', $host)) {
$inventory_mode->setObjectName($host['host']);
$this->checkValidator($host['inventory_mode'], $inventory_mode);
}
if (array_key_exists('inventory', $host) && $host['inventory']) {
if (array_key_exists('inventory_mode', $host) && $host['inventory_mode'] == HOST_INVENTORY_DISABLED) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set inventory fields for disabled inventory.'));
}
$fields = array_keys($host['inventory']);
foreach ($fields as $field) {
if (!in_array($field, $inventory_fields)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect inventory field "%s".', $field));
}
}
}
// Collect technical and visible names to check if they exist in hosts and templates.
$host_names['host'][$host['host']] = true;
$host_names['name'][$host['name']] = true;
}
$filter = [
'host' => array_keys($host_names['host']),
'name' => array_keys($host_names['name'])
];
$hosts_exists = $this->get([
'output' => ['host', 'name'],
'filter' => $filter,
'searchByAny' => true,
'nopermissions' => true
]);
foreach ($hosts_exists as $host_exists) {
if (array_key_exists($host_exists['host'], $host_names['host'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Host with the same name "%s" already exists.', $host_exists['host'])
);
}
if (array_key_exists($host_exists['name'], $host_names['name'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Host with the same visible name "%s" already exists.', $host_exists['name'])
);
}
}
$templates_exists = API::Template()->get([
'output' => ['host', 'name'],
'filter' => $filter,
'searchByAny' => true,
'nopermissions' => true
]);
foreach ($templates_exists as $template_exists) {
if (array_key_exists($template_exists['host'], $host_names['host'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Template with the same name "%s" already exists.', $template_exists['host'])
);
}
if (array_key_exists($template_exists['name'], $host_names['name'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Template with the same visible name "%s" already exists.', $template_exists['name'])
);
}
}
$this->validateEncryption($hosts);
}
/**
* Validates the input parameters for the update() method.
*
* @param array $hosts hosts data array
* @param array $db_hosts db hosts data array
*
* @throws APIException if the input is invalid.
*/
protected function validateUpdate(array $hosts, array $db_hosts) {
$host_db_fields = ['hostid' => null];
foreach ($hosts as $host) {
// Validate mandatory fields.
if (!check_db_fields($host_db_fields, $host)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Wrong fields for host "%1$s".', array_key_exists('host', $host) ? $host['host'] : '')
);
}
// Property 'auto_compress' is not supported for hosts.
if (array_key_exists('auto_compress', $host)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect input parameters.'));
}
// Validate host permissions.
if (!array_key_exists($host['hostid'], $db_hosts)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _(
'No permissions to referred object or it does not exist!'
));
}
// Validate "groups" field.
if (array_key_exists('groups', $host) && (!is_array($host['groups']) || !$host['groups'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Host "%1$s" cannot be without host group.', $db_hosts[$host['hostid']]['host'])
);
}
// Permissions to host groups is validated in massUpdate().
}
$inventory_fields = zbx_objectValues(getHostInventories(), 'db_field');
$valid_inventory_modes = [HOST_INVENTORY_DISABLED, HOST_INVENTORY_MANUAL, HOST_INVENTORY_AUTOMATIC];
$inventory_mode = new CLimitedSetValidator([
'values' => $valid_inventory_modes,
'messageInvalid' => _s('Incorrect value for field "%1$s": %2$s.', 'inventory_mode',
_s('value must be one of %1$s', implode(', ', $valid_inventory_modes)))
]);
$status_validator = new CLimitedSetValidator([
'values' => [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED],
'messageInvalid' => _('Incorrect status for host "%1$s".')
]);
$update_discovered_validator = new CUpdateDiscoveredValidator([
'allowed' => ['hostid', 'status', 'inventory', 'description'],
'messageAllowedField' => _('Cannot update "%2$s" for a discovered host "%1$s".')
]);
$host_names = [];
foreach ($hosts as &$host) {
$db_host = $db_hosts[$host['hostid']];
$host_name = array_key_exists('host', $host) ? $host['host'] : $db_host['host'];
if (array_key_exists('status', $host)) {
$status_validator->setObjectName($host_name);
$this->checkValidator($host['status'], $status_validator);
}
if (array_key_exists('inventory_mode', $host)) {
$inventory_mode->setObjectName($host_name);
$this->checkValidator($host['inventory_mode'], $inventory_mode);
}
if (array_key_exists('inventory', $host) && $host['inventory']) {
if (array_key_exists('inventory_mode', $host) && $host['inventory_mode'] == HOST_INVENTORY_DISABLED) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set inventory fields for disabled inventory.'));
}
$fields = array_keys($host['inventory']);
foreach ($fields as $field) {
if (!in_array($field, $inventory_fields)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect inventory field "%s".', $field));
}
}
}
// cannot update certain fields for discovered hosts
$update_discovered_validator->setObjectName($host_name);
$this->checkPartialValidator($host, $update_discovered_validator, $db_host);
if (array_key_exists('interfaces', $host)) {
if (!is_array($host['interfaces']) || !$host['interfaces']) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('No interfaces for host "%s".', $host['host']));
}
}
if (array_key_exists('host', $host)) {
if (!preg_match('/^'.ZBX_PREG_HOST_FORMAT.'$/', $host['host'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect characters used for host name "%s".', $host['host'])
);
}
if (array_key_exists('host', $host_names) && array_key_exists($host['host'], $host_names['host'])) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Duplicate host. Host with the same host name "%s" already exists in data.', $host['host'])
);
}
$host_names['host'][$host['host']] = $host['hostid'];
}
if (array_key_exists('name', $host)) {
// if visible name is empty replace it with host name
if (zbx_empty(trim($host['name']))) {
if (!array_key_exists('host', $host)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Visible name cannot be empty if host name is missing.')
);
}
$host['name'] = $host['host'];
}
if (array_key_exists('name', $host_names) && array_key_exists($host['name'], $host_names['name'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s(
'Duplicate host. Host with the same visible name "%s" already exists in data.', $host['name'])
);
}
$host_names['name'][$host['name']] = $host['hostid'];
}
if (array_key_exists('tls_connect', $host) || array_key_exists('tls_accept', $host)) {
$tls_connect = array_key_exists('tls_connect', $host) ? $host['tls_connect'] : $db_host['tls_connect'];
$tls_accept = array_key_exists('tls_accept', $host) ? $host['tls_accept'] : $db_host['tls_accept'];
// Clean PSK fields.
if ($tls_connect != HOST_ENCRYPTION_PSK && !($tls_accept & HOST_ENCRYPTION_PSK)) {
if (!array_key_exists('tls_psk_identity', $host)) {
$host['tls_psk_identity'] = '';
}
if (!array_key_exists('tls_psk', $host)) {
$host['tls_psk'] = '';
}
}
// Clean certificate fields.
if ($tls_connect != HOST_ENCRYPTION_CERTIFICATE && !($tls_accept & HOST_ENCRYPTION_CERTIFICATE)) {
if (!array_key_exists('tls_issuer', $host)) {
$host['tls_issuer'] = '';
}
if (!array_key_exists('tls_subject', $host)) {
$host['tls_subject'] = '';
}
}
}
}
unset($host);
if (array_key_exists('host', $host_names) || array_key_exists('name', $host_names)) {
$filter = [];
if (array_key_exists('host', $host_names)) {
$filter['host'] = array_keys($host_names['host']);
}
if (array_key_exists('name', $host_names)) {
$filter['name'] = array_keys($host_names['name']);
}
$hosts_exists = $this->get([
'output' => ['hostid', 'host', 'name'],
'filter' => $filter,
'searchByAny' => true,
'nopermissions' => true,
'preservekeys' => true
]);
foreach ($hosts_exists as $host_exists) {
if (array_key_exists('host', $host_names) && array_key_exists($host_exists['host'], $host_names['host'])
&& bccomp($host_exists['hostid'], $host_names['host'][$host_exists['host']]) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Host with the same name "%s" already exists.', $host_exists['host'])
);
}
if (array_key_exists('name', $host_names) && array_key_exists($host_exists['name'], $host_names['name'])
&& bccomp($host_exists['hostid'], $host_names['name'][$host_exists['name']]) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Host with the same visible name "%s" already exists.', $host_exists['name'])
);
}
}
$templates_exists = API::Template()->get([
'output' => ['hostid', 'host', 'name'],
'filter' => $filter,
'searchByAny' => true,
'nopermissions' => true,
'preservekeys' => true
]);
foreach ($templates_exists as $template_exists) {
if (array_key_exists('host', $host_names)
&& array_key_exists($template_exists['host'], $host_names['host'])
&& bccomp($template_exists['templateid'], $host_names['host'][$template_exists['host']]) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Template with the same name "%s" already exists.', $template_exists['host'])
);
}
if (array_key_exists('name', $host_names)
&& array_key_exists($template_exists['name'], $host_names['name'])
&& bccomp($template_exists['templateid'], $host_names['name'][$template_exists['name']]) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Template with the same visible name "%s" already exists.', $template_exists['name'])
);
}
}
}
$this->validateEncryption($hosts, $db_hosts);
return $hosts;
}
}
|