CProfile::update('web.hostinventories.filter_exact', getRequest('filter_exact', 0), PROFILE_TYPE_INT); } elseif (hasRequest('filter_rst')) { DBStart(); CProfile::delete('web.hostinventories.filter_field'); CProfile::delete('web.hostinventories.filter_field_value'); CProfile::delete('web.hostinventories.filter_exact'); DBend(); } $data['filterField'] = CProfile::get('web.hostinventories.filter_field', ''); $data['filterFieldValue'] = CProfile::get('web.hostinventories.filter_field_value', ''); $data['filterExact'] = CProfile::get('web.hostinventories.filter_exact', 0); if ($data['pageFilter']->groupsSelected) { // which inventory fields we will need for displaying $requiredInventoryFields = ['name', 'type', 'os', 'serialno_a', 'tag', 'macaddress_a']; // checking if correct inventory field is specified for filter $possibleInventoryFields = getHostInventories(); $possibleInventoryFields = zbx_toHash($possibleInventoryFields, 'db_field'); if ($data['filterField'] !== '' && $data['filterFieldValue'] !== '' && !isset($possibleInventoryFields[$data['filterField']])) { error(_s('Impossible to filter by inventory field "%s", which does not exist.', $data['filterField'])); } else { // if we are filtering by field, this field is also required if ($data['filterField'] !== '' && $data['filterFieldValue'] !== '') { $requiredInventoryFields[] = $data['filterField']; } $options = ['output' => ['hostid', 'name', 'status'], 'selectInventory' => $requiredInventoryFields, 'withInventory' => true, 'selectGroups' => API_OUTPUT_EXTEND]; if ($data['pageFilter']->groupid > 0) { $options['groupids'] = $data['pageFilter']->groupid; } if ($data['filterField'] !== '' && $data['filterFieldValue'] !== '') { $options['searchInventory'] = [$data['filterField'] => [$data['filterFieldValue']]]; }
/** * Check, if items that are about to be inserted or updated violate the rule: * only one item can be linked to a inventory filed. * If everything is ok, function return true or throws Exception otherwise * * @static * * @param array $items * @param bool $update whether this is update operation * * @return bool */ public static function validateInventoryLinks(array $items, $update = false) { // inventory link field is not being updated, or being updated to 0, no need to validate anything then foreach ($items as $i => $item) { if (!isset($item['inventory_link']) || $item['inventory_link'] == 0) { unset($items[$i]); } } if (zbx_empty($items)) { return true; } $possibleHostInventories = getHostInventories(); if ($update) { // for successful validation we need three fields for each item: inventory_link, hostid and key_ // problem is, that when we are updating an item, we might not have them, because they are not changed // so, we need to find out what is missing and use API to get the lacking info $itemsWithNoHostId = array(); $itemsWithNoInventoryLink = array(); $itemsWithNoKeys = array(); foreach ($items as $item) { if (!isset($item['inventory_link'])) { $itemsWithNoInventoryLink[$item['itemid']] = $item['itemid']; } if (!isset($item['hostid'])) { $itemsWithNoHostId[$item['itemid']] = $item['itemid']; } if (!isset($item['key_'])) { $itemsWithNoKeys[$item['itemid']] = $item['itemid']; } } $itemsToFind = array_merge($itemsWithNoHostId, $itemsWithNoInventoryLink, $itemsWithNoKeys); // are there any items with lacking info? if (!zbx_empty($itemsToFind)) { $missingInfo = API::Item()->get(array('output' => array('hostid', 'inventory_link', 'key_'), 'filter' => array('itemid' => $itemsToFind), 'nopermissions' => true)); $missingInfo = zbx_toHash($missingInfo, 'itemid'); // appending host ids, inventory_links and keys where they are needed foreach ($items as $i => $item) { if (isset($missingInfo[$item['itemid']])) { if (!isset($items[$i]['hostid'])) { $items[$i]['hostid'] = $missingInfo[$item['itemid']]['hostid']; } if (!isset($items[$i]['inventory_link'])) { $items[$i]['inventory_link'] = $missingInfo[$item['itemid']]['inventory_link']; } if (!isset($items[$i]['key_'])) { $items[$i]['key_'] = $missingInfo[$item['itemid']]['key_']; } } } } } $hostids = zbx_objectValues($items, 'hostid'); // getting all inventory links on every affected host $itemsOnHostsInfo = API::Item()->get(array('output' => array('key_', 'inventory_link', 'hostid'), 'filter' => array('hostid' => $hostids), 'nopermissions' => true)); // now, changing array to: 'hostid' => array('key_'=>'inventory_link') $linksOnHostsCurr = array(); foreach ($itemsOnHostsInfo as $info) { // 0 means no link - we are not interested in those ones if ($info['inventory_link'] != 0) { if (!isset($linksOnHostsCurr[$info['hostid']])) { $linksOnHostsCurr[$info['hostid']] = array($info['key_'] => $info['inventory_link']); } else { $linksOnHostsCurr[$info['hostid']][$info['key_']] = $info['inventory_link']; } } } $linksOnHostsFuture = array(); foreach ($items as $item) { // checking if inventory_link value is a valid number if ($update || $item['value_type'] != ITEM_VALUE_TYPE_LOG) { // does inventory field with provided number exists? if (!isset($possibleHostInventories[$item['inventory_link']])) { $maxVar = max(array_keys($possibleHostInventories)); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item "%1$s" cannot populate a missing host inventory field number "%2$d". Choices are: from 0 (do not populate) to %3$d.', $item['name'], $item['inventory_link'], $maxVar)); } } if (!isset($linksOnHostsFuture[$item['hostid']])) { $linksOnHostsFuture[$item['hostid']] = array($item['key_'] => $item['inventory_link']); } else { $linksOnHostsFuture[$item['hostid']][$item['key_']] = $item['inventory_link']; } } foreach ($linksOnHostsFuture as $hostId => $linkFuture) { if (isset($linksOnHostsCurr[$hostId])) { $futureSituation = array_merge($linksOnHostsCurr[$hostId], $linksOnHostsFuture[$hostId]); } else { $futureSituation = $linksOnHostsFuture[$hostId]; } $valuesCount = array_count_values($futureSituation); // if we have a duplicate inventory links after merging - we are in trouble if (max($valuesCount) > 1) { // what inventory field caused this conflict? $conflictedLink = array_keys($valuesCount, 2); $conflictedLink = reset($conflictedLink); // which of updated items populates this link? $beingSavedItemName = ''; foreach ($items as $item) { if ($item['inventory_link'] == $conflictedLink) { if (isset($item['name'])) { $beingSavedItemName = $item['name']; } else { $thisItem = API::Item()->get(array('output' => array('name'), 'filter' => array('itemid' => $item['itemid']), 'nopermissions' => true)); $beingSavedItemName = $thisItem[0]['name']; } break; } } // name of the original item that already populates the field $originalItem = API::Item()->get(array('output' => array('name'), 'filter' => array('hostid' => $hostId, 'inventory_link' => $conflictedLink), 'nopermissions' => true)); $originalItemName = $originalItem[0]['name']; self::exception(ZBX_API_ERROR_PARAMETERS, _s('Two items ("%1$s" and "%2$s") cannot populate one host inventory field "%3$s", this would lead to a conflict.', $beingSavedItemName, $originalItemName, $possibleHostInventories[$conflictedLink]['title'])); } } return true; }
/** * Get data for item edit page. * * @param array $item item, item prototype or LLD rule to take the data from * @param bool $options['is_discovery_rule'] * * @return array */ function getItemFormData(array $item = array(), array $options = array()) { $data = array('form' => getRequest('form'), 'form_refresh' => getRequest('form_refresh'), 'is_discovery_rule' => !empty($options['is_discovery_rule']), 'parent_discoveryid' => getRequest('parent_discoveryid', !empty($options['is_discovery_rule']) ? getRequest('itemid') : null), 'itemid' => getRequest('itemid'), 'limited' => false, 'interfaceid' => getRequest('interfaceid', 0), 'name' => getRequest('name', ''), 'description' => getRequest('description', ''), 'key' => getRequest('key', ''), 'hostname' => getRequest('hostname'), 'delay' => getRequest('delay', ZBX_ITEM_DELAY_DEFAULT), 'history' => getRequest('history', 90), 'status' => getRequest('status', isset($_REQUEST['form_refresh']) ? 1 : 0), 'type' => getRequest('type', 0), 'snmp_community' => getRequest('snmp_community', 'public'), 'snmp_oid' => getRequest('snmp_oid', 'interfaces.ifTable.ifEntry.ifInOctets.1'), 'port' => getRequest('port', ''), 'value_type' => getRequest('value_type', ITEM_VALUE_TYPE_UINT64), 'data_type' => getRequest('data_type', ITEM_DATA_TYPE_DECIMAL), 'trapper_hosts' => getRequest('trapper_hosts', ''), 'units' => getRequest('units', ''), 'valuemapid' => getRequest('valuemapid', 0), 'params' => getRequest('params', ''), 'multiplier' => getRequest('multiplier', 0), 'delta' => getRequest('delta', 0), 'trends' => getRequest('trends', DAY_IN_YEAR), 'new_application' => getRequest('new_application', ''), 'applications' => getRequest('applications', array()), 'delay_flex' => getRequest('delay_flex', array()), 'new_delay_flex' => getRequest('new_delay_flex', array('delay' => 50, 'period' => ZBX_DEFAULT_INTERVAL)), 'snmpv3_contextname' => getRequest('snmpv3_contextname', ''), 'snmpv3_securityname' => getRequest('snmpv3_securityname', ''), 'snmpv3_securitylevel' => getRequest('snmpv3_securitylevel', 0), 'snmpv3_authprotocol' => getRequest('snmpv3_authprotocol', ITEM_AUTHPROTOCOL_MD5), 'snmpv3_authpassphrase' => getRequest('snmpv3_authpassphrase', ''), 'snmpv3_privprotocol' => getRequest('snmpv3_privprotocol', ITEM_PRIVPROTOCOL_DES), 'snmpv3_privpassphrase' => getRequest('snmpv3_privpassphrase', ''), 'ipmi_sensor' => getRequest('ipmi_sensor', ''), 'authtype' => getRequest('authtype', 0), 'username' => getRequest('username', ''), 'password' => getRequest('password', ''), 'publickey' => getRequest('publickey', ''), 'privatekey' => getRequest('privatekey', ''), 'formula' => getRequest('formula', 1), 'logtimefmt' => getRequest('logtimefmt', ''), 'add_groupid' => getRequest('add_groupid', getRequest('groupid', 0)), 'valuemaps' => null, 'possibleHostInventories' => null, 'alreadyPopulated' => null, 'initial_item_type' => null, 'templates' => array()); // hostid if (!empty($data['parent_discoveryid'])) { $discoveryRule = API::DiscoveryRule()->get(array('itemids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true)); $discoveryRule = reset($discoveryRule); $data['hostid'] = $discoveryRule['hostid']; } else { $data['hostid'] = getRequest('hostid', 0); } // types, http items only for internal processes $data['types'] = item_type2str(); unset($data['types'][ITEM_TYPE_HTTPTEST]); if (!empty($options['is_discovery_rule'])) { unset($data['types'][ITEM_TYPE_AGGREGATE], $data['types'][ITEM_TYPE_CALCULATED], $data['types'][ITEM_TYPE_SNMPTRAP]); } // item if ($item) { $data['item'] = $item; $data['hostid'] = !empty($data['hostid']) ? $data['hostid'] : $data['item']['hostid']; $data['limited'] = $data['item']['templateid'] != 0; // get templates $itemid = $item['itemid']; do { $params = array('itemids' => $itemid, 'output' => array('itemid', 'templateid'), 'selectHosts' => array('name')); if ($data['is_discovery_rule']) { $item = API::DiscoveryRule()->get($params); } else { $params['selectDiscoveryRule'] = array('itemid'); $params['filter'] = array('flags' => null); $item = API::Item()->get($params); } $item = reset($item); if (!empty($item)) { $host = reset($item['hosts']); if (!empty($item['hosts'])) { $host['name'] = CHtml::encode($host['name']); if (bccomp($data['itemid'], $itemid) == 0) { } elseif ($data['is_discovery_rule']) { $data['templates'][] = new CLink($host['name'], 'host_discovery.php?form=update&itemid=' . $item['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } elseif ($item['discoveryRule']) { $data['templates'][] = new CLink($host['name'], 'disc_prototypes.php?form=update&itemid=' . $item['itemid'] . '&parent_discoveryid=' . $item['discoveryRule']['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } else { $data['templates'][] = new CLink($host['name'], 'items.php?form=update&itemid=' . $item['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } } $itemid = $item['templateid']; } else { break; } } while ($itemid != 0); $data['templates'] = array_reverse($data['templates']); array_shift($data['templates']); } // caption if (!empty($data['is_discovery_rule'])) { $data['caption'] = _('Discovery rule'); } else { $data['caption'] = !empty($data['parent_discoveryid']) ? _('Item prototype') : _('Item'); } // hostname if (empty($data['is_discovery_rule']) && empty($data['hostname'])) { if (!empty($data['hostid'])) { $hostInfo = API::Host()->get(array('hostids' => $data['hostid'], 'output' => array('name'), 'templated_hosts' => true)); $hostInfo = reset($hostInfo); $data['hostname'] = $hostInfo['name']; } else { $data['hostname'] = _('not selected'); } } // fill data from item if (!hasRequest('form_refresh') && ($item || $data['limited'])) { $data['name'] = $data['item']['name']; $data['description'] = $data['item']['description']; $data['key'] = $data['item']['key_']; $data['interfaceid'] = $data['item']['interfaceid']; $data['type'] = $data['item']['type']; $data['snmp_community'] = $data['item']['snmp_community']; $data['snmp_oid'] = $data['item']['snmp_oid']; $data['port'] = $data['item']['port']; $data['value_type'] = $data['item']['value_type']; $data['data_type'] = $data['item']['data_type']; $data['trapper_hosts'] = $data['item']['trapper_hosts']; $data['units'] = $data['item']['units']; $data['valuemapid'] = $data['item']['valuemapid']; $data['multiplier'] = $data['item']['multiplier']; $data['hostid'] = $data['item']['hostid']; $data['params'] = $data['item']['params']; $data['snmpv3_contextname'] = $data['item']['snmpv3_contextname']; $data['snmpv3_securityname'] = $data['item']['snmpv3_securityname']; $data['snmpv3_securitylevel'] = $data['item']['snmpv3_securitylevel']; $data['snmpv3_authprotocol'] = $data['item']['snmpv3_authprotocol']; $data['snmpv3_authpassphrase'] = $data['item']['snmpv3_authpassphrase']; $data['snmpv3_privprotocol'] = $data['item']['snmpv3_privprotocol']; $data['snmpv3_privpassphrase'] = $data['item']['snmpv3_privpassphrase']; $data['ipmi_sensor'] = $data['item']['ipmi_sensor']; $data['authtype'] = $data['item']['authtype']; $data['username'] = $data['item']['username']; $data['password'] = $data['item']['password']; $data['publickey'] = $data['item']['publickey']; $data['privatekey'] = $data['item']['privatekey']; $data['logtimefmt'] = $data['item']['logtimefmt']; $data['new_application'] = getRequest('new_application', ''); if (!$data['is_discovery_rule']) { $data['formula'] = $data['item']['formula']; } if (!$data['limited'] || !isset($_REQUEST['form_refresh'])) { $data['delay'] = $data['item']['delay']; if (($data['type'] == ITEM_TYPE_TRAPPER || $data['type'] == ITEM_TYPE_SNMPTRAP) && $data['delay'] == 0) { $data['delay'] = ZBX_ITEM_DELAY_DEFAULT; } $data['history'] = $data['item']['history']; $data['status'] = $data['item']['status']; $data['delta'] = $data['item']['delta']; $data['trends'] = $data['item']['trends']; $db_delay_flex = $data['item']['delay_flex']; if (isset($db_delay_flex)) { $arr_of_dellays = explode(';', $db_delay_flex); foreach ($arr_of_dellays as $one_db_delay) { $arr_of_delay = explode('/', $one_db_delay); if (!isset($arr_of_delay[0]) || !isset($arr_of_delay[1])) { continue; } array_push($data['delay_flex'], array('delay' => $arr_of_delay[0], 'period' => $arr_of_delay[1])); } } $data['applications'] = array_unique(zbx_array_merge($data['applications'], get_applications_by_itemid($data['itemid']))); } } // applications if (count($data['applications']) == 0) { array_push($data['applications'], 0); } $data['db_applications'] = DBfetchArray(DBselect('SELECT DISTINCT a.applicationid,a.name' . ' FROM applications a' . ' WHERE a.hostid=' . zbx_dbstr($data['hostid']))); order_result($data['db_applications'], 'name'); // interfaces $data['interfaces'] = API::HostInterface()->get(array('hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND)); // valuemapid if ($data['limited']) { if (!empty($data['valuemapid'])) { if ($map_data = DBfetch(DBselect('SELECT v.name FROM valuemaps v WHERE v.valuemapid=' . zbx_dbstr($data['valuemapid'])))) { $data['valuemaps'] = $map_data['name']; } } } else { $data['valuemaps'] = DBfetchArray(DBselect('SELECT v.* FROM valuemaps v')); order_result($data['valuemaps'], 'name'); } // possible host inventories if (empty($data['parent_discoveryid'])) { $data['possibleHostInventories'] = getHostInventories(); // get already populated fields by other items $data['alreadyPopulated'] = API::item()->get(array('output' => array('inventory_link'), 'filter' => array('hostid' => $data['hostid']), 'nopermissions' => true)); $data['alreadyPopulated'] = zbx_toHash($data['alreadyPopulated'], 'inventory_link'); } // template $data['is_template'] = isTemplate($data['hostid']); // unset snmpv3 fields if ($data['type'] != ITEM_TYPE_SNMPV3) { $data['snmpv3_contextname'] = ''; $data['snmpv3_securityname'] = ''; $data['snmpv3_securitylevel'] = ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV; $data['snmpv3_authprotocol'] = ITEM_AUTHPROTOCOL_MD5; $data['snmpv3_authpassphrase'] = ''; $data['snmpv3_privprotocol'] = ITEM_PRIVPROTOCOL_DES; $data['snmpv3_privpassphrase'] = ''; } // unset ssh auth fields if ($data['type'] != ITEM_TYPE_SSH) { $data['authtype'] = ITEM_AUTHTYPE_PASSWORD; $data['publickey'] = ''; $data['privatekey'] = ''; } return $data; }
/** * 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]; $hosts_full = []; 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'] : '')); } // 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('No groups for host "%1$s".', $db_hosts[$host['hostid']]['host'])); } // Permissions to host groups is validated in massUpdate(). } $inventory_fields = zbx_objectValues(getHostInventories(), 'db_field'); $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', $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']; } $hosts_full[] = zbx_array_merge($db_host, $host); } 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_full); }
$_REQUEST['groupid'] = $pageFilter->groupid; $_REQUEST['hostid'] = get_request('hostid', 0); if ($_REQUEST['go'] == 'massupdate' && isset($_REQUEST['hosts'])) { $hostsWidget->addPageHeader(_('CONFIGURATION OF HOSTS')); $data = array('hosts' => get_request('hosts', array()), 'visible' => get_request('visible', array()), 'mass_replace_tpls' => get_request('mass_replace_tpls'), 'mass_clear_tpls' => get_request('mass_clear_tpls'), 'groups' => get_request('groups', array()), 'newgroup' => get_request('newgroup', ''), 'status' => get_request('status', HOST_STATUS_MONITORED), 'proxy_hostid' => get_request('proxy_hostid', ''), 'ipmi_authtype' => get_request('ipmi_authtype', -1), 'ipmi_privilege' => get_request('ipmi_privilege', 2), 'ipmi_username' => get_request('ipmi_username', ''), 'ipmi_password' => get_request('ipmi_password', ''), 'inventory_mode' => get_request('inventory_mode', HOST_INVENTORY_DISABLED), 'host_inventory' => get_request('host_inventory', array()), 'templates' => get_request('templates', array())); // sort templates natsort($data['templates']); // get groups $data['all_groups'] = API::HostGroup()->get(array('output' => API_OUTPUT_EXTEND, 'editable' => true)); order_result($data['all_groups'], 'name'); // get proxies $data['proxies'] = DBfetchArray(DBselect('SELECT h.hostid,h.host' . ' FROM hosts h' . ' WHERE h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')' . andDbNode('h.hostid'))); order_result($data['proxies'], 'host'); // get inventories if ($data['inventory_mode'] != HOST_INVENTORY_DISABLED) { $data['inventories'] = getHostInventories(); $data['inventories'] = zbx_toHash($data['inventories'], 'db_field'); } // get templates data $data['linkedTemplates'] = null; if (!empty($data['templates'])) { $getLinkedTemplates = API::Template()->get(array('templateids' => $data['templates'], 'output' => array('templateid', 'name'))); foreach ($getLinkedTemplates as $getLinkedTemplate) { $data['linkedTemplates'][] = array('id' => $getLinkedTemplate['templateid'], 'name' => $getLinkedTemplate['name']); } } $hostForm = new CView('configuration.host.massupdate', $data); $hostsWidget->addItem($hostForm->render()); } elseif (isset($_REQUEST['form'])) { $hostsWidget->addPageHeader(_('CONFIGURATION OF HOSTS')); $data = array();
} $macrosView = new CView('common.macros', array('macros' => $macros, 'readonly' => $isDiscovered)); $divTabs->addTab('macroTab', _('Macros'), $macrosView->render()); $inventoryFormList = new CFormList('inventorylist'); // radio buttons for inventory type choice $inventoryMode = isset($dbHost['inventory']['inventory_mode']) ? $dbHost['inventory']['inventory_mode'] : HOST_INVENTORY_DISABLED; $inventoryDisabledBtn = new CRadioButton('inventory_mode', HOST_INVENTORY_DISABLED, null, 'host_inventory_radio_' . HOST_INVENTORY_DISABLED, $inventoryMode == HOST_INVENTORY_DISABLED); $inventoryDisabledBtn->setEnabled(!$isDiscovered); $inventoryManualBtn = new CRadioButton('inventory_mode', HOST_INVENTORY_MANUAL, null, 'host_inventory_radio_' . HOST_INVENTORY_MANUAL, $inventoryMode == HOST_INVENTORY_MANUAL); $inventoryManualBtn->setEnabled(!$isDiscovered); $inventoryAutomaticBtn = new CRadioButton('inventory_mode', HOST_INVENTORY_AUTOMATIC, null, 'host_inventory_radio_' . HOST_INVENTORY_AUTOMATIC, $inventoryMode == HOST_INVENTORY_AUTOMATIC); $inventoryAutomaticBtn->setEnabled(!$isDiscovered); $inventoryTypeRadioButton = array($inventoryDisabledBtn, new CLabel(_('Disabled'), 'host_inventory_radio_' . HOST_INVENTORY_DISABLED), $inventoryManualBtn, new CLabel(_('Manual'), 'host_inventory_radio_' . HOST_INVENTORY_MANUAL), $inventoryAutomaticBtn, new CLabel(_('Automatic'), 'host_inventory_radio_' . HOST_INVENTORY_AUTOMATIC)); $inventoryFormList->addRow(SPACE, new CDiv($inventoryTypeRadioButton, 'jqueryinputset')); $hostInventoryTable = DB::getSchema('host_inventory'); $hostInventoryFields = getHostInventories(); foreach ($hostInventoryFields as $inventoryNo => $inventoryInfo) { if (!isset($host_inventory[$inventoryInfo['db_field']])) { $host_inventory[$inventoryInfo['db_field']] = ''; } if ($hostInventoryTable['fields'][$inventoryInfo['db_field']]['type'] == DB::FIELD_TYPE_TEXT) { $input = new CTextArea('host_inventory[' . $inventoryInfo['db_field'] . ']', $host_inventory[$inventoryInfo['db_field']]); $input->addStyle('width: 64em;'); } else { $fieldLength = $hostInventoryTable['fields'][$inventoryInfo['db_field']]['length']; $input = new CTextBox('host_inventory[' . $inventoryInfo['db_field'] . ']', $host_inventory[$inventoryInfo['db_field']]); $input->setAttribute('maxlength', $fieldLength); $input->addStyle('width: ' . ($fieldLength > 64 ? 64 : $fieldLength) . 'em;'); } if ($inventory_mode == HOST_INVENTORY_DISABLED) { $input->setAttribute('disabled', 'disabled');
/** * 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']['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) { $hosts = zbx_toArray($data['hosts']); $inputHostIds = zbx_objectValues($hosts, 'hostid'); $hostids = array_unique($inputHostIds); sort($hostids); $updHosts = $this->get(array('hostids' => $hostids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); foreach ($hosts as $host) { if (!isset($updHosts[$host['hostid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // check if hosts have at least 1 group if (isset($data['groups']) && empty($data['groups'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No groups for hosts.')); } /* * 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); $hostExists = $this->get(array('filter' => array('host' => $curHost['host']), 'output' => array('hostid'), 'editable' => true, 'nopermissions' => true)); $hostExist = reset($hostExists); if ($hostExist && bccomp($hostExist['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 if (API::Template()->exists(array('host' => $curHost['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template "%1$s" already exists.', $curHost['host'])); } } if (isset($data['groups'])) { $updateGroups = $data['groups']; } if (isset($data['interfaces'])) { $updateInterfaces = $data['interfaces']; } if (isset($data['templates_clear'])) { $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 = array(); } $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', array('values' => $data, 'where' => array('hostid' => $hostids))); } if (isset($updateStatus)) { updateHostStatus($hostids, $updateStatus); } /* * Update interfaces */ if (isset($updateInterfaces)) { $hostInterfaces = API::HostInterface()->get(array('hostids' => $hostids, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'nopermissions' => true)); $this->massRemove(array('hostids' => $hostids, 'interfaces' => $hostInterfaces)); $this->massAdd(array('hosts' => $hosts, 'interfaces' => $updateInterfaces)); } if (isset($updateTemplatesClear)) { $templateidsClear = zbx_objectValues($updateTemplatesClear, 'templateid'); if ($updateTemplatesClear) { $this->massRemove(array('hostids' => $hostids, 'templateids_clear' => $templateidsClear)); } } else { $templateidsClear = array(); } /* * Update template linkage */ if (isset($updateTemplates)) { $hostTemplates = API::Template()->get(array('hostids' => $hostids, 'output' => array('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(array('hostids' => $hostids, 'templateids' => $templatesToDel)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template')); } } $result = $this->massAdd(array('hosts' => $hosts, 'templates' => $updateTemplates)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template')); } } // macros if (isset($updateMacros)) { DB::delete('hostmacro', array('hostid' => $hostids)); $this->massAdd(array('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.')); } } else { $existingInventoriesDb = DBfetchArrayAssoc(DBselect('SELECT hostid,inventory_mode' . ' FROM host_inventory' . ' WHERE ' . dbConditionInt('hostid', $hostids)), 'hostid'); // check existing host inventory data $automaticHostIds = array(); 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'])); } elseif ($existingInventoriesDb[$hostId]['inventory_mode'] == HOST_INVENTORY_AUTOMATIC) { $automaticHostIds[] = $hostId; } } } $inventoriesToSave = array(); 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(array('output' => array('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', array('values' => $inventory, 'where' => array('hostid' => $hostId))); } else { DB::insert('host_inventory', array($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(array('output' => array('groupid'), 'hostids' => $hostids)); $hostGroupids = zbx_objectValues($hostGroups, 'groupid'); $newGroupids = zbx_objectValues($updateGroups, 'groupid'); $groupsToAdd = array_diff($newGroupids, $hostGroupids); if ($groupsToAdd) { $this->massAdd(array('hosts' => $hosts, 'groups' => zbx_toObject($groupsToAdd, 'groupid'))); } $groupidsToDel = array_diff($hostGroupids, $newGroupids); if ($groupidsToDel) { $this->massRemove(array('hostids' => $hostids, 'groupids' => $groupidsToDel)); } } return array('hostids' => $inputHostIds); }
_imap.mapcorners['mylocationbutton'] = 2; _imap.mapcorners['zoom'] = 2; /* Перевод для текущего языка */ <?php textdomain("frontend"); ?> locale.Search = '<?php echo _('Search'); ?> '; locale.inventoryfields = new Object; <?php foreach (getHostInventories() as $field) { ?> locale.inventoryfields["<?php echo $field['db_field']; ?> "] = "<?php echo $field['title']; ?> "; <?php } ?> locale['Ack'] = '<?php echo _('Ack'); ?>
$statusChangeCheckBox = new CCheckBox('status_change', $filter['statusChange'], 'javascript: this.checked ? $("status_change_days").enable() : $("status_change_days").disable()', 1); $statusChangeCheckBox->addStyle('vertical-align: middle;'); $daysSpan = new CSpan(_('days')); $daysSpan->addStyle('vertical-align: middle;'); $filterForm->addRow(_('Age less than'), array($statusChangeCheckBox, $statusChangeDays, SPACE, $daysSpan)); // name $filterForm->addRow(_('Filter by name'), new CTextBox('txt_select', $filter['txtSelect'], 40)); // application $filterForm->addRow(_('Filter by application'), array(new CTextBox('application', $filter['application'], 40), new CButton('application_name', _('Select'), 'return PopUp("popup.php?srctbl=applications&srcfld1=name&real_hosts=1&dstfld1=application&with_applications=1' . '&dstfrm=' . $filterForm->getName() . '");', 'filter-button'))); // inventory filter $inventoryFilters = $filter['inventory']; if (!$inventoryFilters) { $inventoryFilters = array(array('field' => '', 'value' => '')); } $inventoryFields = array(); foreach (getHostInventories() as $inventory) { $inventoryFields[$inventory['db_field']] = $inventory['title']; } $inventoryFilterTable = new CTable(); $inventoryFilterTable->setAttribute('id', 'inventory-filter'); $i = 0; foreach ($inventoryFilters as $field) { $inventoryFilterTable->addRow(array(new CComboBox('inventory[' . $i . '][field]', $field['field'], null, $inventoryFields), new CTextBox('inventory[' . $i . '][value]', $field['value'], 20), new CButton('inventory[' . $i . '][remove]', _('Remove'), null, 'link_menu element-table-remove')), 'form_row'); $i++; } $inventoryFilterTable->addRow(new CCol(new CButton('inventory_add', _('Add'), null, 'link_menu element-table-add'), null, 3)); $filterForm->addRow(_('Filter by host inventory'), $inventoryFilterTable); // maintenance filter $filterForm->addRow(_('Show hosts in maintenance'), new CCheckBox('show_maintenance', $filter['showMaintenance'], null, 1)); // show details if (!$overview) {
/** * 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']['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) { $hosts = zbx_toArray($data['hosts']); $hostids = zbx_objectValues($hosts, 'hostid'); $updHosts = $this->get(array('hostids' => $hostids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); foreach ($hosts as $host) { if (!isset($updHosts[$host['hostid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // check if hosts have at least 1 group if (isset($data['groups']) && empty($data['groups'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No groups for hosts.')); } /* * 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); $hostExists = $this->get(array('filter' => array('host' => $curHost['host']), 'output' => API_OUTPUT_SHORTEN, 'editable' => true, 'nopermissions' => true)); $hostExist = reset($hostExists); if ($hostExist && bccomp($hostExist['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 if (API::Template()->exists(array('host' => $curHost['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template "%1$s" already exists.', $curHost['host'])); } } if (isset($data['groups'])) { $updateGroups = $data['groups']; unset($data['groups']); } if (isset($data['interfaces'])) { $updateInterfaces = $data['interfaces']; unset($data['interfaces']); } if (isset($data['templates_clear'])) { $updateTemplatesClear = zbx_toArray($data['templates_clear']); unset($data['templates_clear']); } if (isset($data['templates'])) { $updateTemplates = $data['templates']; unset($data['templates']); } if (isset($data['macros'])) { $updateMacros = $data['macros']; unset($data['macros']); } if (isset($data['inventory'])) { $updateInventory = $data['inventory']; unset($data['inventory']); } if (isset($data['inventory_mode'])) { if (!isset($updateInventory)) { $updateInventory = array(); } $updateInventory['inventory_mode'] = $data['inventory_mode']; unset($data['inventory_mode']); } if (isset($data['status'])) { $updateStatus = $data['status']; unset($data['status']); } unset($data['hosts']); if (!zbx_empty($data)) { $update = array('values' => $data, 'where' => array('hostid' => $hostids)); DB::update('hosts', $update); } if (isset($updateStatus)) { updateHostStatus($hostids, $updateStatus); } /* * Update hostgroups linkage */ if (isset($updateGroups)) { $updateGroups = zbx_toArray($updateGroups); $hostGroups = API::HostGroup()->get(array('hostids' => $hostids)); $hostGroupids = zbx_objectValues($hostGroups, 'groupid'); $newGroupids = zbx_objectValues($updateGroups, 'groupid'); $result = $this->massAdd(array('hosts' => $hosts, 'groups' => $updateGroups)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot create host group.')); } $groupidsToDel = array_diff($hostGroupids, $newGroupids); if (!empty($groupidsToDel)) { $result = $this->massRemove(array('hostids' => $hostids, 'groupids' => $groupidsToDel)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete host group.')); } } } /* * Update interfaces */ if (isset($updateInterfaces)) { $hostInterfaces = API::HostInterface()->get(array('hostids' => $hostids, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'nopermissions' => true)); $this->massRemove(array('hostids' => $hostids, 'interfaces' => $hostInterfaces)); $this->massAdd(array('hosts' => $hosts, 'interfaces' => $updateInterfaces)); } if (isset($updateTemplatesClear)) { $templateidsClear = zbx_objectValues($updateTemplatesClear, 'templateid'); if (!empty($updateTemplatesClear)) { $this->massRemove(array('hostids' => $hostids, 'templateids_clear' => $templateidsClear)); } } else { $templateidsClear = array(); } /* * Update template linkage */ if (isset($updateTemplates)) { $hostTemplates = API::Template()->get(array('hostids' => $hostids, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true)); $hostTemplateids = array_keys($hostTemplates); $newTemplateids = zbx_objectValues($updateTemplates, 'templateid'); $templatesToDel = array_diff($hostTemplateids, $newTemplateids); $templatesToDel = array_diff($templatesToDel, $templateidsClear); if (!empty($templatesToDel)) { $result = $this->massRemove(array('hostids' => $hostids, 'templateids' => $templatesToDel)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template')); } } $result = $this->massAdd(array('hosts' => $hosts, 'templates' => $updateTemplates)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template')); } } // macros if (isset($updateMacros)) { DB::delete('hostmacro', array('hostid' => $hostids)); $this->massAdd(array('hosts' => $hosts, 'macros' => $updateMacros)); } /* * Inventory */ if (isset($updateInventory)) { 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.')); } } else { $hostsWithInventories = array(); $existingInventoriesDb = DBselect('SELECT hostid FROM host_inventory WHERE ' . dbConditionInt('hostid', $hostids)); while ($existingInventory = DBfetch($existingInventoriesDb)) { $hostsWithInventories[] = $existingInventory['hostid']; } // when hosts are being updated to use automatic mode for host inventories, // we must check if some items are set to populate inventory fields of every host. // if they do, mass update for those fields should be ignored if ($updateInventory['inventory_mode'] == HOST_INVENTORY_AUTOMATIC) { // getting all items on all affected hosts $itemsToInventories = API::item()->get(array('output' => array('inventory_link', 'hostid'), 'filter' => array('hostid' => $hostids), 'nopermissions' => true)); // gathering links to array: 'hostid'=>array('inventory_name_1'=>true, 'inventory_name_2'=>true) $inventoryLinksOnHosts = array(); $inventoryFields = getHostInventories(); foreach ($itemsToInventories as $hinv) { if ($hinv['inventory_link'] != 0) { // 0 means 'no link' if (isset($inventoryLinksOnHosts[$hinv['hostid']])) { $inventoryLinksOnHosts[$hinv['hostid']][$inventoryFields[$hinv['inventory_link']]['db_field']] = true; } else { $inventoryLinksOnHosts[$hinv['hostid']] = array($inventoryFields[$hinv['inventory_link']]['db_field'] => true); } } } // now we have all info we need to determine, which inventory fields should be saved $inventoriesToSave = array(); foreach ($hostids as $hostid) { $inventoriesToSave[$hostid] = $updateInventory; $inventoriesToSave[$hostid]['hostid'] = $hostid; foreach ($updateInventory as $inventoryName => $hinv) { if (isset($inventoryLinksOnHosts[$hostid][$inventoryName])) { unset($inventoriesToSave[$hostid][$inventoryName]); } } } } else { // if mode is not automatic, all fields can be saved $inventoriesToSave = array(); foreach ($hostids as $hostid) { $inventoriesToSave[$hostid] = $updateInventory; $inventoriesToSave[$hostid]['hostid'] = $hostid; } } $hostsWithoutInventory = array_diff($hostids, $hostsWithInventories); // hosts that have no inventory yet, need it to be inserted foreach ($hostsWithoutInventory as $hostid) { DB::insert('host_inventory', array($inventoriesToSave[$hostid]), false); } // those hosts that already have an inventory, need it to be updated foreach ($hostsWithInventories as $hostid) { DB::update('host_inventory', array('values' => $inventoriesToSave[$hostid], 'where' => array('hostid' => $hostid))); } } } return array('hostids' => $hostids); }
$data['discoveryRule'] = $dbHost['discoveryRule']; } $templateids = zbx_objectValues($dbHost['parentTemplates'], 'templateid'); $data['original_templates'] = array_combine($templateids, $templateids); } foreach ([INTERFACE_TYPE_AGENT, INTERFACE_TYPE_SNMP, INTERFACE_TYPE_JMX, INTERFACE_TYPE_IPMI] as $type) { if (array_key_exists($type, $data['mainInterfaces'])) { $interfaceid = $data['mainInterfaces'][$type]; $data['interfaces'][$interfaceid]['main'] = '1'; } } $data['interfaces'] = array_values($data['interfaces']); } if ($data['hostid'] != 0) { // get items that populate host inventory fields $data['inventory_items'] = API::Item()->get(['output' => ['inventory_link', 'itemid', 'hostid', 'name', 'key_'], 'hostids' => [$dbHost['hostid']], 'filter' => ['inventory_link' => array_keys(getHostInventories())]]); $data['inventory_items'] = zbx_toHash($data['inventory_items'], 'inventory_link'); $data['inventory_items'] = CMacrosResolverHelper::resolveItemNames($data['inventory_items']); } if ($data['flags'] == ZBX_FLAG_DISCOVERY_CREATED) { if ($data['proxy_hostid'] != 0) { $data['proxies'] = API::Proxy()->get(['output' => ['host'], 'proxyids' => [$data['proxy_hostid']], 'preservekeys' => true]); } else { $data['proxies'] = []; } } else { $data['proxies'] = API::Proxy()->get(['output' => ['host'], 'preservekeys' => true]); order_result($data['proxies'], 'host'); } foreach ($data['proxies'] as &$proxy) { $proxy = $proxy['host'];
/** * Get data for item edit page. * * @param array $item item, item prototype or LLD rule to take the data from * @param bool $options['is_discovery_rule'] * * @return array */ function getItemFormData(array $item = [], array $options = []) { $data = ['form' => getRequest('form'), 'form_refresh' => getRequest('form_refresh'), 'is_discovery_rule' => !empty($options['is_discovery_rule']), 'parent_discoveryid' => getRequest('parent_discoveryid', !empty($options['is_discovery_rule']) ? getRequest('itemid') : null), 'itemid' => getRequest('itemid'), 'limited' => false, 'interfaceid' => getRequest('interfaceid', 0), 'name' => getRequest('name', ''), 'description' => getRequest('description', ''), 'key' => getRequest('key', ''), 'hostname' => getRequest('hostname'), 'delay' => getRequest('delay', ZBX_ITEM_DELAY_DEFAULT), 'history' => getRequest('history', 90), 'status' => getRequest('status', isset($_REQUEST['form_refresh']) ? 1 : 0), 'type' => getRequest('type', 0), 'snmp_community' => getRequest('snmp_community', 'public'), 'snmp_oid' => getRequest('snmp_oid', 'interfaces.ifTable.ifEntry.ifInOctets.1'), 'port' => getRequest('port', ''), 'value_type' => getRequest('value_type', ITEM_VALUE_TYPE_UINT64), 'data_type' => getRequest('data_type', ITEM_DATA_TYPE_DECIMAL), 'trapper_hosts' => getRequest('trapper_hosts', ''), 'units' => getRequest('units', ''), 'valuemapid' => getRequest('valuemapid', 0), 'params' => getRequest('params', ''), 'multiplier' => getRequest('multiplier', 0), 'delta' => getRequest('delta', 0), 'trends' => getRequest('trends', DAY_IN_YEAR), 'new_application' => getRequest('new_application', ''), 'applications' => getRequest('applications', []), 'delay_flex' => getRequest('delay_flex', []), 'snmpv3_contextname' => getRequest('snmpv3_contextname', ''), 'snmpv3_securityname' => getRequest('snmpv3_securityname', ''), 'snmpv3_securitylevel' => getRequest('snmpv3_securitylevel', 0), 'snmpv3_authprotocol' => getRequest('snmpv3_authprotocol', ITEM_AUTHPROTOCOL_MD5), 'snmpv3_authpassphrase' => getRequest('snmpv3_authpassphrase', ''), 'snmpv3_privprotocol' => getRequest('snmpv3_privprotocol', ITEM_PRIVPROTOCOL_DES), 'snmpv3_privpassphrase' => getRequest('snmpv3_privpassphrase', ''), 'ipmi_sensor' => getRequest('ipmi_sensor', ''), 'authtype' => getRequest('authtype', 0), 'username' => getRequest('username', ''), 'password' => getRequest('password', ''), 'publickey' => getRequest('publickey', ''), 'privatekey' => getRequest('privatekey', ''), 'formula' => getRequest('formula', 1), 'logtimefmt' => getRequest('logtimefmt', ''), 'add_groupid' => getRequest('add_groupid', getRequest('groupid', 0)), 'valuemaps' => null, 'possibleHostInventories' => null, 'alreadyPopulated' => null, 'initial_item_type' => null, 'templates' => []]; // hostid if (!empty($data['parent_discoveryid'])) { $discoveryRule = API::DiscoveryRule()->get(['itemids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true]); $discoveryRule = reset($discoveryRule); $data['hostid'] = $discoveryRule['hostid']; $data['new_application_prototype'] = getRequest('new_application_prototype', ''); $data['application_prototypes'] = getRequest('application_prototypes', array()); } else { $data['hostid'] = getRequest('hostid', 0); } // types, http items only for internal processes $data['types'] = item_type2str(); unset($data['types'][ITEM_TYPE_HTTPTEST]); if (!empty($options['is_discovery_rule'])) { unset($data['types'][ITEM_TYPE_AGGREGATE], $data['types'][ITEM_TYPE_CALCULATED], $data['types'][ITEM_TYPE_SNMPTRAP]); } // item if ($item) { $data['item'] = $item; $data['hostid'] = !empty($data['hostid']) ? $data['hostid'] : $data['item']['hostid']; $data['limited'] = $data['item']['templateid'] != 0; // get templates $itemid = $item['itemid']; do { $params = ['itemids' => $itemid, 'output' => ['itemid', 'templateid'], 'selectHosts' => ['name']]; if ($data['is_discovery_rule']) { $item = API::DiscoveryRule()->get($params); } else { $params['selectDiscoveryRule'] = ['itemid']; $params['filter'] = ['flags' => null]; $item = API::Item()->get($params); } $item = reset($item); if (!empty($item)) { $host = reset($item['hosts']); if (!empty($item['hosts'])) { $host['name'] = CHtml::encode($host['name']); if (bccomp($data['itemid'], $itemid) == 0) { } elseif ($data['is_discovery_rule']) { $data['templates'][] = new CLink($host['name'], 'host_discovery.php?form=update&itemid=' . $item['itemid']); $data['templates'][] = SPACE . '⇒' . SPACE; } elseif ($item['discoveryRule']) { $data['templates'][] = new CLink($host['name'], 'disc_prototypes.php?form=update' . '&itemid=' . $item['itemid'] . '&parent_discoveryid=' . $item['discoveryRule']['itemid']); $data['templates'][] = SPACE . '⇒' . SPACE; } else { $data['templates'][] = new CLink($host['name'], 'items.php?form=update&itemid=' . $item['itemid']); $data['templates'][] = SPACE . '⇒' . SPACE; } } $itemid = $item['templateid']; } else { break; } } while ($itemid != 0); $data['templates'] = array_reverse($data['templates']); array_shift($data['templates']); } // caption if (!empty($data['is_discovery_rule'])) { $data['caption'] = _('Discovery rule'); } else { $data['caption'] = !empty($data['parent_discoveryid']) ? _('Item prototype') : _('Item'); } // hostname if (empty($data['is_discovery_rule']) && empty($data['hostname'])) { if (!empty($data['hostid'])) { $hostInfo = API::Host()->get(['hostids' => $data['hostid'], 'output' => ['name'], 'templated_hosts' => true]); $hostInfo = reset($hostInfo); $data['hostname'] = $hostInfo['name']; } else { $data['hostname'] = _('not selected'); } } // fill data from item if (!hasRequest('form_refresh') && ($item || $data['limited'])) { $data['name'] = $data['item']['name']; $data['description'] = $data['item']['description']; $data['key'] = $data['item']['key_']; $data['interfaceid'] = $data['item']['interfaceid']; $data['type'] = $data['item']['type']; $data['snmp_community'] = $data['item']['snmp_community']; $data['snmp_oid'] = $data['item']['snmp_oid']; $data['port'] = $data['item']['port']; $data['value_type'] = $data['item']['value_type']; $data['data_type'] = $data['item']['data_type']; $data['trapper_hosts'] = $data['item']['trapper_hosts']; $data['units'] = $data['item']['units']; $data['valuemapid'] = $data['item']['valuemapid']; $data['multiplier'] = $data['item']['multiplier']; $data['hostid'] = $data['item']['hostid']; $data['params'] = $data['item']['params']; $data['snmpv3_contextname'] = $data['item']['snmpv3_contextname']; $data['snmpv3_securityname'] = $data['item']['snmpv3_securityname']; $data['snmpv3_securitylevel'] = $data['item']['snmpv3_securitylevel']; $data['snmpv3_authprotocol'] = $data['item']['snmpv3_authprotocol']; $data['snmpv3_authpassphrase'] = $data['item']['snmpv3_authpassphrase']; $data['snmpv3_privprotocol'] = $data['item']['snmpv3_privprotocol']; $data['snmpv3_privpassphrase'] = $data['item']['snmpv3_privpassphrase']; $data['ipmi_sensor'] = $data['item']['ipmi_sensor']; $data['authtype'] = $data['item']['authtype']; $data['username'] = $data['item']['username']; $data['password'] = $data['item']['password']; $data['publickey'] = $data['item']['publickey']; $data['privatekey'] = $data['item']['privatekey']; $data['logtimefmt'] = $data['item']['logtimefmt']; $data['new_application'] = getRequest('new_application', ''); if ($data['parent_discoveryid'] != 0) { $data['new_application_prototype'] = getRequest('new_application_prototype', ''); } if (!$data['is_discovery_rule']) { $data['formula'] = $data['item']['formula']; } if (!$data['limited'] || !isset($_REQUEST['form_refresh'])) { $data['delay'] = $data['item']['delay']; if (($data['type'] == ITEM_TYPE_TRAPPER || $data['type'] == ITEM_TYPE_SNMPTRAP) && $data['delay'] == 0) { $data['delay'] = ZBX_ITEM_DELAY_DEFAULT; } $data['history'] = $data['item']['history']; $data['status'] = $data['item']['status']; $data['delta'] = $data['item']['delta']; $data['trends'] = $data['item']['trends']; $parser = new CItemDelayFlexParser($data['item']['delay_flex']); if ($parser->isValid()) { foreach ($parser->getIntervals() as $interval) { if ($interval['type'] == ITEM_DELAY_FLEX_TYPE_FLEXIBLE) { $interval_parts = explode('/', $interval['interval']); $data['delay_flex'][] = ['delay' => $interval_parts[0], 'period' => $interval_parts[1], 'type' => ITEM_DELAY_FLEX_TYPE_FLEXIBLE]; } else { $data['delay_flex'][] = ['schedule' => $interval['interval'], 'type' => ITEM_DELAY_FLEX_TYPE_SCHEDULING]; } } } $data['applications'] = array_unique(zbx_array_merge($data['applications'], get_applications_by_itemid($data['itemid']))); if ($data['parent_discoveryid'] != 0) { /* * Get a list of application prototypes assigned to item prototype. Don't select distinct names, * since database can be accidentally created case insensitive. */ $application_prototypes = DBfetchArray(DBselect('SELECT ap.name' . ' FROM application_prototype ap,item_application_prototype iap' . ' WHERE ap.application_prototypeid=iap.application_prototypeid' . ' AND ap.itemid=' . zbx_dbstr($data['parent_discoveryid']) . ' AND iap.itemid=' . zbx_dbstr($data['itemid']))); // Merge form submitted data with data existing in DB to find diff and correctly display ListBox. $data['application_prototypes'] = array_unique(zbx_array_merge($data['application_prototypes'], zbx_objectValues($application_prototypes, 'name'))); } } } if (!$data['delay_flex']) { $data['delay_flex'][] = ['delay' => '', 'period' => '', 'type' => ITEM_DELAY_FLEX_TYPE_FLEXIBLE]; } // applications if (count($data['applications']) == 0) { array_push($data['applications'], 0); } $data['db_applications'] = DBfetchArray(DBselect('SELECT DISTINCT a.applicationid,a.name' . ' FROM applications a' . ' WHERE a.hostid=' . zbx_dbstr($data['hostid']) . ($data['parent_discoveryid'] ? ' AND a.flags=' . ZBX_FLAG_DISCOVERY_NORMAL : ''))); order_result($data['db_applications'], 'name'); if ($data['parent_discoveryid'] != 0) { // Make the application prototype list no appearing empty, but filling it with "-None-" as first element. if (count($data['application_prototypes']) == 0) { $data['application_prototypes'][] = 0; } // Get a list of application prototypes by discovery rule. $data['db_application_prototypes'] = DBfetchArray(DBselect('SELECT ap.application_prototypeid,ap.name' . ' FROM application_prototype ap' . ' WHERE ap.itemid=' . zbx_dbstr($data['parent_discoveryid']))); order_result($data['db_application_prototypes'], 'name'); } // interfaces $data['interfaces'] = API::HostInterface()->get(['hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND]); // valuemapid if ($data['limited']) { if ($data['valuemapid'] != 0) { $valuemaps = API::ValueMap()->get(['output' => ['name'], 'valuemapids' => [$data['valuemapid']]]); if ($valuemaps) { $data['valuemaps'] = $valuemaps[0]['name']; } } } else { $data['valuemaps'] = API::ValueMap()->get(['output' => ['valemapid', 'name']]); CArrayHelper::sort($data['valuemaps'], ['name']); } // possible host inventories if (empty($data['parent_discoveryid'])) { $data['possibleHostInventories'] = getHostInventories(); // get already populated fields by other items $data['alreadyPopulated'] = API::item()->get(['output' => ['inventory_link'], 'filter' => ['hostid' => $data['hostid']], 'nopermissions' => true]); $data['alreadyPopulated'] = zbx_toHash($data['alreadyPopulated'], 'inventory_link'); } // unset snmpv3 fields if ($data['type'] != ITEM_TYPE_SNMPV3) { $data['snmpv3_contextname'] = ''; $data['snmpv3_securityname'] = ''; $data['snmpv3_securitylevel'] = ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV; $data['snmpv3_authprotocol'] = ITEM_AUTHPROTOCOL_MD5; $data['snmpv3_authpassphrase'] = ''; $data['snmpv3_privprotocol'] = ITEM_PRIVPROTOCOL_DES; $data['snmpv3_privpassphrase'] = ''; } // unset ssh auth fields if ($data['type'] != ITEM_TYPE_SSH) { $data['authtype'] = ITEM_AUTHTYPE_PASSWORD; $data['publickey'] = ''; $data['privatekey'] = ''; } return $data; }
function insert_host_inventory_form() { $frmHostP = new CFormTable(_('Host Inventory')); $table_titles = getHostInventories(); $table_titles = zbx_toHash($table_titles, 'db_field'); $sql_fields = implode(', ', array_keys($table_titles)); $sql = 'SELECT ' . $sql_fields . ' FROM host_inventory WHERE hostid=' . zbx_dbstr($_REQUEST['hostid']); $result = DBselect($sql); $row = DBfetch($result); foreach ($row as $key => $value) { if (!zbx_empty($value)) { $frmHostP->addRow($table_titles[$key]['title'], new CSpan(zbx_str2links($value), 'pre')); } } $frmHostP->addItemToBottomRow(new CButtonCancel(url_param('groupid'))); return $frmHostP; }
** 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. **/ $hostInventoryWidget = new CWidget(); $rForm = new CForm('get'); $rForm->addItem(array(_('Group'), SPACE, $this->data['pageFilter']->getGroupsCB())); $hostInventoryWidget->addPageHeader(_('HOST INVENTORY'), SPACE); $hostInventoryWidget->addHeader(_('Hosts'), $rForm); $filterTable = new CTable('', 'filter filter-center'); // getting inventory fields to make a drop down $inventoryFields = getHostInventories(true); // 'true' means list should be ordered by title $inventoryFieldsComboBox = new CComboBox('filter_field', $this->data['filterField']); foreach ($inventoryFields as $inventoryField) { $inventoryFieldsComboBox->addItem($inventoryField['db_field'], $inventoryField['title']); } $exactComboBox = new CComboBox('filter_exact', $this->data['filterExact']); $exactComboBox->addItem('0', _('like')); $exactComboBox->addItem('1', _('exactly')); $filterTable->addRow(array(array(array(bold(_('Field')), SPACE, $inventoryFieldsComboBox), array($exactComboBox, new CTextBox('filter_field_value', $this->data['filterFieldValue'], 20)))), 'host-inventories'); $filter = new CSubmit('filter_set', _('Filter')); $filter->useJQueryStyle('main'); $reset = new CSubmit('filter_rst', _('Reset')); $reset->useJQueryStyle(); $divButtons = new CDiv(array($filter, SPACE, $reset)); $divButtons->setAttribute('style', 'padding: 4px 0px;');
/** * Checks icon maps. * @throws APIException * @param $iconMaps * @param bool $mustExist if icon map should be checked against having at least one mapping * @return void */ protected function validateMappings($iconMaps, $mustExist = true) { $inventoryFields = getHostInventories(); $imageids = API::Image()->get(['output' => ['imageid'], 'preservekeys' => true, 'filter' => ['imagetype' => IMAGE_TYPE_ICON]]); foreach ($iconMaps as $iconMap) { if (isset($iconMap['mappings']) && empty($iconMap['mappings'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%s" must have at least one mapping.', $iconMap['name'])); } elseif (!isset($iconMap['mappings'])) { if ($mustExist) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%s" must have at least one mapping.', $iconMap['name'])); } else { continue; } } $uniqField = []; foreach ($iconMap['mappings'] as $mapping) { if (!isset($mapping['expression'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Required field "expression" is missing in icon mapping.')); } elseif (!isset($mapping['inventory_link'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Required field "inventory_link" is missing in icon mapping.')); } elseif (!isset($mapping['iconid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Required field "iconid" is missing in icon mapping.')); } elseif (!isset($inventoryFields[$mapping['inventory_link']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%1$s" has mapping with incorrect inventory link "%2$s".', $iconMap['name'], $mapping['inventory_link'])); } elseif (!isset($imageids[$mapping['iconid']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%1$s" has mapping with incorrect iconid "%2$s".', $iconMap['name'], $mapping['iconid'])); } try { CGlobalRegexp::isValid($mapping['expression']); } catch (Exception $e) { switch ($e->getCode()) { case CGlobalRegexp::ERROR_REGEXP_EMPTY: self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%s" cannot have mapping with empty expression.', $iconMap['name'])); break; case CGlobalRegexp::ERROR_REGEXP_NOT_EXISTS: self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%s" cannot have mapping with global expression that does not exist.', $iconMap['name'])); break; default: self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%s" has incorrect expression.', $iconMap['name'])); } } if (isset($uniqField[$mapping['inventory_link'] . $mapping['expression']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon mapping entry "%1$s" against "%2$s" already exists.', $mapping['expression'], $inventoryFields[$mapping['inventory_link']]['title'])); } $uniqField[$mapping['inventory_link'] . $mapping['expression']] = true; } } }
/** * Get icon id by mapping. * * @param array $iconMap * @param array $inventory * * @return int */ function getIconByMapping($iconMap, $inventory) { if (!empty($inventory['inventory'])) { $inventories = getHostInventories(); foreach ($iconMap['mappings'] as $mapping) { try { $expr = new CGlobalRegexp($mapping['expression']); if ($expr->match($inventory['inventory'][$inventories[$mapping['inventory_link']]['db_field']])) { return $mapping['iconid']; } } catch (Exception $e) { continue; } } } return $iconMap['default_iconid']; }
/** * @param array $iconMap * @param array $inventory * * @return int icon id */ function getIconByMapping($iconMap, $inventory) { $iconid = null; $inventories = getHostInventories(); if (isset($inventory['inventory'])) { foreach ($iconMap['mappings'] as $mapping) { try { $expr = new GlobalRegExp($mapping['expression']); if ($expr->match($inventory['inventory'][$inventories[$mapping['inventory_link']]['db_field']])) { $iconid = $mapping['iconid']; break; } } catch (Exception $e) { continue; } } } if (null === $iconid) { $iconid = $iconMap['default_iconid']; } return $iconid; }