/** * Process screen. * * @return CDiv (screen inside container) */ public function get() { // fetch hosts $hosts = API::Host()->get(['output' => ['hostid', 'status'], 'selectGraphs' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'selectScreens' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'groupids' => $this->screenitem['resourceid'], 'preservekeys' => true]); $hostids = array_keys($hosts); $options = ['output' => ['triggerid', 'expression', 'description', 'url', 'value', 'priority', 'lastchange', 'flags'], 'selectHosts' => ['hostid', 'name', 'status'], 'selectItems' => ['itemid', 'hostid', 'name', 'key_', 'value_type'], 'hostids' => $hostids, 'monitored' => true, 'skipDependent' => true, 'sortfield' => 'description', 'preservekeys' => true]; // application filter if ($this->screenitem['application'] !== '') { $applications = API::Application()->get(['output' => [], 'hostids' => $hostids, 'search' => ['name' => $this->screenitem['application']], 'preservekeys' => true]); $options['applicationids'] = array_keys($applications); } $triggers = API::Trigger()->get($options); $triggers = CMacrosResolverHelper::resolveTriggerUrls($triggers); /* * Each screen cell with "Triggers overview" depends on one specific group which in this case is 'resourceid'. * Pass it as 'groupid' to menu pop-up "Events" link. */ foreach ($triggers as &$trigger) { $trigger['groupid'] = $this->screenitem['resourceid']; } unset($trigger); $groups = API::HostGroup()->get(['output' => ['name'], 'groupids' => [$this->screenitem['resourceid']]]); $header = (new CDiv([new CTag('h4', true, _('Triggers overview')), (new CList())->addItem([_('Group'), ':', SPACE, $groups[0]['name']])]))->addClass(ZBX_STYLE_DASHBRD_WIDGET_HEAD); $table = getTriggersOverview($hosts, $triggers, $this->pageFile, $this->screenitem['style'], $this->screenid); $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT); return $this->getOutput(new CUiWidget(uniqid(), [$header, $table, $footer])); }
/** * Process screen. * * @return CDiv (screen inside container) */ public function get() { // fetch hosts $hosts = API::Host()->get(array('output' => array('hostid', 'status'), 'selectGraphs' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'selectScreens' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'groupids' => $this->screenitem['resourceid'], 'preservekeys' => true)); $hostIds = array_keys($hosts); $options = array('output' => array('description', 'expression', 'priority', 'url', 'value', 'triggerid', 'lastchange', 'flags'), 'selectHosts' => array('hostid', 'name', 'status'), 'hostids' => $hostIds, 'monitored' => true, 'skipDependent' => true, 'sortfield' => 'description'); // application filter if ($this->screenitem['application'] !== '') { $applications = API::Application()->get(array('output' => array('applicationid'), 'hostids' => $hostIds, 'search' => array('name' => $this->screenitem['application']))); $options['applicationids'] = zbx_objectValues($applications, 'applicationid'); } $triggers = API::Trigger()->get($options); return $this->getOutput(getTriggersOverview($hosts, $triggers, $this->pageFile, $this->screenitem['style'], $this->screenid)); }
/** * Process screen. * * @return CDiv (screen inside container) */ public function get() { // fetch hosts $hosts = API::Host()->get(array('output' => array('hostid', 'status'), 'selectGraphs' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'selectScreens' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'groupids' => $this->screenitem['resourceid'], 'preservekeys' => true)); $hostIds = array_keys($hosts); $options = array('output' => array('description', 'expression', 'priority', 'url', 'value', 'triggerid', 'lastchange', 'flags'), 'selectHosts' => array('hostid', 'name', 'status'), 'selectItems' => array('itemid', 'hostid', 'name', 'key_', 'value_type'), 'hostids' => $hostIds, 'monitored' => true, 'skipDependent' => true, 'sortfield' => 'description'); // application filter if ($this->screenitem['application'] !== '') { $applications = API::Application()->get(array('output' => array('applicationid'), 'hostids' => $hostIds, 'search' => array('name' => $this->screenitem['application']))); $options['applicationids'] = zbx_objectValues($applications, 'applicationid'); } $triggers = API::Trigger()->get($options); /* * Each screen cell with "Triggers overview" depends on one specific group which in this case is 'resourceid'. * Pass it as 'groupid' to menu pop-up "Events" link. */ foreach ($triggers as &$trigger) { $trigger['groupid'] = $this->screenitem['resourceid']; } unset($trigger); return $this->getOutput(getTriggersOverview($hosts, $triggers, $this->pageFile, $this->screenitem['style'], $this->screenid)); }
public function bodyToString() { $this->cleanItems(); $config = select_config(); // array of triggers (not classified, information, warning, average, high, disaster) in problem state $triggersProblemState = []; // number of triggers in OK state $triggersOkState = 0; $options = ['output' => ['triggerid', 'priority', 'value'], 'monitored' => true, 'skipDependent' => true]; if ($this->groupid != 0) { $options['groupids'] = $this->groupid; } $triggers = API::Trigger()->get($options); foreach ($triggers as $trigger) { switch ($trigger['value']) { case TRIGGER_VALUE_TRUE: if (!array_key_exists($trigger['priority'], $triggersProblemState)) { $triggersProblemState[$trigger['priority']] = 0; } $triggersProblemState[$trigger['priority']]++; break; case TRIGGER_VALUE_FALSE: $triggersOkState++; } } $severityCells = [getSeverityCell(null, $config, $triggersOkState . SPACE . _('Ok'), true)]; for ($severity = TRIGGER_SEVERITY_NOT_CLASSIFIED; $severity < TRIGGER_SEVERITY_COUNT; $severity++) { $severityCount = isset($triggersProblemState[$severity]) ? $triggersProblemState[$severity] : 0; $severityCells[] = getSeverityCell($severity, $config, $severityCount . SPACE . getSeverityName($severity, $config), !$severityCount); } if ($this->style == STYLE_HORIZONTAL) { $this->addRow($severityCells); } else { foreach ($severityCells as $severityCell) { $this->addRow($severityCell); } } return parent::bodyToString(); }
/** * Create DIV with latest problem triggers. * * If no sortfield and sortorder are defined, the sort indicater in the column name will not be displayed. * * @param array $filter['screenid'] * @param array $filter['groupids'] * @param array $filter['hostids'] * @param array $filter['maintenance'] * @param int $filter['extAck'] * @param int $filter['severity'] * @param int $filter['limit'] * @param string $filter['sortfield'] * @param string $filter['sortorder'] * @param string $filter['backUrl'] * * @return CDiv */ function make_latest_issues(array $filter = array()) { // hide the sort indicator if no sortfield and sortorder are given $showSortIndicator = isset($filter['sortfield']) || isset($filter['sortorder']); if (!isset($filter['sortfield'])) { $filter['sortfield'] = 'lastchange'; } if (!isset($filter['sortorder'])) { $filter['sortorder'] = ZBX_SORT_DOWN; } $options = array('groupids' => $filter['groupids'], 'hostids' => isset($filter['hostids']) ? $filter['hostids'] : null, 'monitored' => true, 'maintenance' => $filter['maintenance'], 'filter' => array('priority' => $filter['severity'], 'value' => TRIGGER_VALUE_TRUE)); $triggers = API::Trigger()->get(array_merge($options, array('withLastEventUnacknowledged' => isset($filter['extAck']) && $filter['extAck'] == EXTACK_OPTION_UNACK ? true : null, 'skipDependent' => true, 'output' => array('triggerid', 'state', 'error', 'url', 'expression', 'description', 'priority', 'lastchange'), 'selectHosts' => array('hostid', 'name'), 'selectLastEvent' => array('eventid', 'acknowledged', 'objectid', 'clock', 'ns'), 'sortfield' => $filter['sortfield'], 'sortorder' => $filter['sortorder'], 'limit' => isset($filter['limit']) ? $filter['limit'] : DEFAULT_LATEST_ISSUES_CNT))); // don't use withLastEventUnacknowledged and skipDependent because of performance issues $triggersTotalCount = API::Trigger()->get(array_merge($options, array('countOutput' => true))); // get acknowledges $eventIds = array(); foreach ($triggers as $trigger) { if ($trigger['lastEvent']) { $eventIds[] = $trigger['lastEvent']['eventid']; } } if ($eventIds) { $eventAcknowledges = API::Event()->get(array('eventids' => $eventIds, 'select_acknowledges' => API_OUTPUT_EXTEND, 'preservekeys' => true)); } foreach ($triggers as $tnum => $trigger) { // if trigger is lost (broken expression) we skip it if (empty($trigger['hosts'])) { unset($triggers[$tnum]); continue; } $host = reset($trigger['hosts']); $trigger['hostid'] = $host['hostid']; $trigger['hostname'] = $host['name']; if ($trigger['lastEvent']) { $trigger['lastEvent']['acknowledges'] = isset($eventAcknowledges[$trigger['lastEvent']['eventid']]) ? $eventAcknowledges[$trigger['lastEvent']['eventid']]['acknowledges'] : null; } $triggers[$tnum] = $trigger; } $hostIds = zbx_objectValues($triggers, 'hostid'); // get hosts $hosts = API::Host()->get(array('hostids' => $hostIds, 'output' => array('hostid', 'name', 'status', 'maintenance_status', 'maintenance_type', 'maintenanceid'), 'selectScreens' => API_OUTPUT_COUNT, 'preservekeys' => true)); // actions $actions = getEventActionsStatHints($eventIds); // ack params $ackParams = isset($filter['screenid']) ? array('screenid' => $filter['screenid']) : array(); $config = select_config(); // indicator of sort field if ($showSortIndicator) { $sortDiv = new CDiv(SPACE, $filter['sortorder'] === ZBX_SORT_DOWN ? 'icon_sortdown default_cursor' : 'icon_sortup default_cursor'); $sortDiv->addStyle('float: left'); $hostHeaderDiv = new CDiv(array(_('Host'), SPACE)); $hostHeaderDiv->addStyle('float: left'); $issueHeaderDiv = new CDiv(array(_('Issue'), SPACE)); $issueHeaderDiv->addStyle('float: left'); $lastChangeHeaderDiv = new CDiv(array(_('Time'), SPACE)); $lastChangeHeaderDiv->addStyle('float: left'); } $table = new CTableInfo(_('No events found.')); $table->setHeader(array(is_show_all_nodes() ? _('Node') : null, $showSortIndicator && $filter['sortfield'] === 'hostname' ? array($hostHeaderDiv, $sortDiv) : _('Host'), $showSortIndicator && $filter['sortfield'] === 'priority' ? array($issueHeaderDiv, $sortDiv) : _('Issue'), $showSortIndicator && $filter['sortfield'] === 'lastchange' ? array($lastChangeHeaderDiv, $sortDiv) : _('Last change'), _('Age'), _('Info'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions'))); $scripts = API::Script()->getScriptsByHosts($hostIds); // triggers foreach ($triggers as $trigger) { $host = $hosts[$trigger['hostid']]; $hostName = new CSpan($host['name'], 'link_menu'); $hostName->setMenuPopup(getMenuPopupHost($host, $scripts[$host['hostid']])); // add maintenance icon with hint if host is in maintenance $maintenanceIcon = null; if ($host['maintenance_status']) { $maintenanceIcon = new CDiv(null, 'icon-maintenance-abs'); // get maintenance $maintenances = API::Maintenance()->get(array('maintenanceids' => $host['maintenanceid'], 'output' => API_OUTPUT_EXTEND, 'limit' => 1)); if ($maintenance = reset($maintenances)) { $hint = $maintenance['name'] . ' [' . ($host['maintenance_type'] ? _('Maintenance without data collection') : _('Maintenance with data collection')) . ']'; if (isset($maintenance['description'])) { // double quotes mandatory $hint .= "\n" . $maintenance['description']; } $maintenanceIcon->setHint($hint); $maintenanceIcon->addClass('pointer'); } $hostName->addClass('left-to-icon-maintenance-abs'); } $hostDiv = new CDiv(array($hostName, $maintenanceIcon), 'maintenance-abs-cont'); // unknown triggers $unknown = SPACE; if ($trigger['state'] == TRIGGER_STATE_UNKNOWN) { $unknown = new CDiv(SPACE, 'status_icon iconunknown'); $unknown->setHint($trigger['error'], '', 'on'); } // trigger has events if ($trigger['lastEvent']) { // description $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['lastEvent']['clock'], 'ns' => $trigger['lastEvent']['ns']))); // ack $ack = getEventAckState($trigger['lastEvent'], empty($filter['backUrl']) ? true : $filter['backUrl'], true, $ackParams); } else { // description $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['lastchange'], 'ns' => '999999999'))); // ack $ack = new CSpan(_('No events'), 'unknown'); } // description if (!zbx_empty($trigger['url'])) { $description = new CLink($description, resolveTriggerUrl($trigger), null, null, true); } else { $description = new CSpan($description, 'pointer'); } $description = new CCol($description, getSeverityStyle($trigger['priority'])); if ($trigger['lastEvent']) { $description->setHint(make_popup_eventlist($trigger['triggerid'], $trigger['lastEvent']['eventid']), '', '', false); } // clock $clock = new CLink(zbx_date2str(_('d M Y H:i:s'), $trigger['lastchange']), 'events.php?triggerid=' . $trigger['triggerid'] . '&source=0&show_unknown=1&nav_time=' . $trigger['lastchange']); // actions $actionHint = $trigger['lastEvent'] && isset($actions[$trigger['lastEvent']['eventid']]) ? $actions[$trigger['lastEvent']['eventid']] : SPACE; $table->addRow(array(get_node_name_by_elid($trigger['triggerid']), $hostDiv, $description, $clock, zbx_date2age($trigger['lastchange']), $unknown, $ack, $actionHint)); } // initialize blinking zbx_add_post_js('jqBlink.blink();'); $script = new CJSScript(get_js("jQuery('#hat_lastiss_footer').html('" . _s('Updated: %s', zbx_date2str(_('H:i:s'))) . "')")); $infoDiv = new CDiv(_n('%1$d of %2$d issue is shown', '%1$d of %2$d issues are shown', count($triggers), $triggersTotalCount)); $infoDiv->addStyle('text-align: right; padding-right: 3px;'); return new CDiv(array($table, $infoDiv, $script)); }
$trigger = API::Trigger()->get(['triggerids' => $_REQUEST['triggerid'], 'output' => API_OUTPUT_EXTEND, 'expandDescription' => true]); if (!$trigger) { access_deny(); } $trigger = reset($trigger); /* * Actions */ if (hasRequest('update')) { DBstart(); $result = DBexecute('UPDATE triggers' . ' SET comments=' . zbx_dbstr(getRequest('comments')) . ' WHERE triggerid=' . zbx_dbstr(getRequest('triggerid'))); $trigger['comments'] = $_REQUEST['comments']; if ($result) { add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER, _('Trigger') . ' [' . $_REQUEST['triggerid'] . '] [' . $trigger['description'] . '] ' . _('Comments') . ' [' . $_REQUEST['comments'] . ']'); } $result = DBend($result); show_messages($result, _('Description updated'), _('Cannot update description')); } elseif (isset($_REQUEST['cancel'])) { jsRedirect('tr_status.php'); exit; } /* * Display */ $triggerEditable = API::Trigger()->get(['triggerids' => $_REQUEST['triggerid'], 'output' => ['triggerid'], 'editable' => true]); $data = ['triggerid' => getRequest('triggerid'), 'trigger' => $trigger, 'isTriggerEditable' => !empty($triggerEditable), 'isCommentExist' => !empty($trigger['comments'])]; // render view $triggerCommentView = new CView('monitoring.triggerComment', $data); $triggerCommentView->render(); $triggerCommentView->show(); require_once dirname(__FILE__) . '/include/page_footer.php';
public function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $itemids = array_keys($result); // adding applications if ($options['selectApplications'] !== null && $options['selectApplications'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'applicationid', 'items_applications'); $applications = API::Application()->get(array('output' => $options['selectApplications'], 'applicationids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $applications, 'applications'); } // adding interfaces if ($options['selectInterfaces'] !== null && $options['selectInterfaces'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'interfaceid'); $interfaces = API::HostInterface()->get(array('output' => $options['selectInterfaces'], 'interfaceids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $interfaces, 'interfaces'); } // adding triggers if (!is_null($options['selectTriggers'])) { if ($options['selectTriggers'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'triggerid', 'functions'); $triggers = API::Trigger()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']); } else { $triggers = API::Trigger()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $triggers = zbx_toHash($triggers, 'itemid'); foreach ($result as $itemid => $item) { if (isset($triggers[$itemid])) { $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount']; } else { $result[$itemid]['triggers'] = 0; } } } } // adding graphs if (!is_null($options['selectGraphs'])) { if ($options['selectGraphs'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'graphid', 'graphs_items'); $graphs = API::Graph()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']); } else { $graphs = API::Graph()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $graphs = zbx_toHash($graphs, 'itemid'); foreach ($result as $itemid => $item) { if (isset($graphs[$itemid])) { $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount']; } else { $result[$itemid]['graphs'] = 0; } } } } // adding discoveryrule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { $relationMap = new CRelationMap(); // discovered items $dbRules = DBselect('SELECT id1.itemid,id2.parent_itemid' . ' FROM item_discovery id1,item_discovery id2,items i' . ' WHERE ' . dbConditionInt('id1.itemid', $itemids) . ' AND id1.parent_itemid=id2.itemid' . ' AND i.itemid=id1.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_CREATED); while ($rule = DBfetch($dbRules)) { $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']); } // item prototypes // TODO: this should not be in the item API $dbRules = DBselect('SELECT id.parent_itemid,id.itemid' . ' FROM item_discovery id,items i' . ' WHERE ' . dbConditionInt('id.itemid', $itemids) . ' AND i.itemid=id.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_PROTOTYPE); while ($rule = DBfetch($dbRules)) { $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']); } $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding item discovery if ($options['selectItemDiscovery'] !== null) { $itemDiscoveries = API::getApiService()->select('item_discovery', array('output' => $this->outputExtend($options['selectItemDiscovery'], array('itemdiscoveryid', 'itemid')), 'filter' => array('itemid' => array_keys($result)), 'preservekeys' => true)); $relationMap = $this->createRelationMap($itemDiscoveries, 'itemid', 'itemdiscoveryid'); $itemDiscoveries = $this->unsetExtraFields($itemDiscoveries, array('itemid', 'itemdiscoveryid'), $options['selectItemDiscovery']); $result = $relationMap->mapOne($result, $itemDiscoveries, 'itemDiscovery'); } // adding history data $requestedOutput = array(); if ($this->outputIsRequested('lastclock', $options['output'])) { $requestedOutput['lastclock'] = true; } if ($this->outputIsRequested('lastns', $options['output'])) { $requestedOutput['lastns'] = true; } if ($this->outputIsRequested('lastvalue', $options['output'])) { $requestedOutput['lastvalue'] = true; } if ($this->outputIsRequested('prevvalue', $options['output'])) { $requestedOutput['prevvalue'] = true; } if ($requestedOutput) { $history = Manager::History()->getLast($result, 2, ZBX_HISTORY_PERIOD); foreach ($result as &$item) { $lastHistory = isset($history[$item['itemid']][0]) ? $history[$item['itemid']][0] : null; $prevHistory = isset($history[$item['itemid']][1]) ? $history[$item['itemid']][1] : null; if (isset($requestedOutput['lastclock'])) { $item['lastclock'] = $lastHistory ? $lastHistory['clock'] : '0'; } if (isset($requestedOutput['lastns'])) { $item['lastns'] = $lastHistory ? $lastHistory['ns'] : '0'; } if (isset($requestedOutput['lastvalue'])) { $item['lastvalue'] = $lastHistory ? $lastHistory['value'] : '0'; } if (isset($requestedOutput['prevvalue'])) { $item['prevvalue'] = $prevHistory ? $prevHistory['value'] : '0'; } } unset($item); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $eventIds = array_keys($result); // adding hosts if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) { // trigger events if ($options['object'] == EVENT_OBJECT_TRIGGER) { $query = DBselect('SELECT e.eventid,i.hostid' . ' FROM events e,functions f,items i' . ' WHERE ' . dbConditionInt('e.eventid', $eventIds) . ' AND e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['object']) . ' AND e.source=' . zbx_dbstr($options['source'])); } elseif ($options['object'] == EVENT_OBJECT_ITEM || $options['object'] == EVENT_OBJECT_LLDRULE) { $query = DBselect('SELECT e.eventid,i.hostid' . ' FROM events e,items i' . ' WHERE ' . dbConditionInt('e.eventid', $eventIds) . ' AND e.objectid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['object']) . ' AND e.source=' . zbx_dbstr($options['source'])); } $relationMap = new CRelationMap(); while ($relation = DBfetch($query)) { $relationMap->addRelation($relation['eventid'], $relation['hostid']); } $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $hosts, 'hosts'); } // adding the related object if ($options['selectRelatedObject'] !== null && $options['selectRelatedObject'] != API_OUTPUT_COUNT && $options['object'] != EVENT_OBJECT_AUTOREGHOST) { $relationMap = new CRelationMap(); foreach ($result as $event) { $relationMap->addRelation($event['eventid'], $event['objectid']); } switch ($options['object']) { case EVENT_OBJECT_TRIGGER: $api = API::Trigger(); break; case EVENT_OBJECT_DHOST: $api = API::DHost(); break; case EVENT_OBJECT_DSERVICE: $api = API::DService(); break; case EVENT_OBJECT_ITEM: $api = API::Item(); break; case EVENT_OBJECT_LLDRULE: $api = API::DiscoveryRule(); break; } $objects = $api->get(array('output' => $options['selectRelatedObject'], $api->pkOption() => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $objects, 'relatedObject'); } // adding alerts if ($options['select_alerts'] !== null && $options['select_alerts'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'eventid', 'alertid', 'alerts'); $alerts = API::Alert()->get(array('output' => $options['select_alerts'], 'selectMediatypes' => API_OUTPUT_EXTEND, 'alertids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true, 'sortfield' => 'clock', 'sortorder' => ZBX_SORT_DOWN)); $result = $relationMap->mapMany($result, $alerts, 'alerts'); } // adding acknowledges if ($options['select_acknowledges'] !== null) { if ($options['select_acknowledges'] != API_OUTPUT_COUNT) { // create the base query $sqlParts = API::getApiService()->createSelectQueryParts('acknowledges', 'a', array('output' => $this->outputExtend($options['select_acknowledges'], array('acknowledgeid', 'eventid', 'clock')), 'filter' => array('eventid' => $eventIds))); $sqlParts['order'][] = 'a.clock DESC'; // if the user data is requested via extended output or specified fields, join the users table $userFields = array('alias', 'name', 'surname'); $requestUserData = array(); foreach ($userFields as $userField) { if ($this->outputIsRequested($userField, $options['select_acknowledges'])) { $requestUserData[] = $userField; } } if ($requestUserData) { foreach ($requestUserData as $userField) { $sqlParts = $this->addQuerySelect('u.' . $userField, $sqlParts); } $sqlParts['from'][] = 'users u'; $sqlParts['where'][] = 'a.userid=u.userid'; } $acknowledges = DBFetchArrayAssoc(DBselect($this->createSelectQueryFromParts($sqlParts)), 'acknowledgeid'); $relationMap = $this->createRelationMap($acknowledges, 'eventid', 'acknowledgeid'); $acknowledges = $this->unsetExtraFields($acknowledges, array('eventid', 'acknowledgeid', 'clock'), $options['select_acknowledges']); $result = $relationMap->mapMany($result, $acknowledges, 'acknowledges'); } else { $acknowledges = DBFetchArrayAssoc(DBselect('SELECT COUNT(a.acknowledgeid) AS rowscount,a.eventid' . ' FROM acknowledges a' . ' WHERE ' . dbConditionInt('a.eventid', $eventIds) . ' GROUP BY a.eventid'), 'eventid'); foreach ($result as &$event) { if (isset($acknowledges[$event['eventid']])) { $event['acknowledges'] = $acknowledges[$event['eventid']]['rowscount']; } else { $event['acknowledges'] = 0; } } unset($event); } } return $result; }
** 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. **/ $table = (new CTableInfo())->setHeader([_('Host group'), _('Without problems'), _('With problems'), _('Total')]); // get host groups $groups = API::HostGroup()->get(['output' => ['groupid', 'name'], 'groupids' => $data['filter']['groupids'], 'hostids' => isset($data['filter']['hostids']) ? $data['filter']['hostids'] : null, 'monitored_hosts' => true, 'preservekeys' => true]); CArrayHelper::sort($groups, ['name']); // get hosts $hosts = API::Host()->get(['output' => ['hostid', 'name'], 'selectGroups' => ['groupid'], 'groupids' => array_keys($groups), 'hostids' => isset($data['filter']['hostids']) ? $data['filter']['hostids'] : null, 'filter' => ['maintenance_status' => $data['filter']['maintenance']], 'monitored_hosts' => true, 'preservekeys' => true]); CArrayHelper::sort($hosts, ['name']); // get triggers $triggers = API::Trigger()->get(['output' => ['triggerid', 'priority'], 'selectHosts' => ['hostid'], 'search' => $data['filter']['trigger_name'] !== '' ? ['description' => $data['filter']['trigger_name']] : null, 'filter' => ['priority' => $data['filter']['severity'], 'value' => TRIGGER_VALUE_TRUE], 'maintenance' => $data['filter']['maintenance'], 'monitored' => true]); if ($data['filter']['extAck']) { $hosts_with_unack_triggers = []; $triggers_unack = API::Trigger()->get(['output' => ['triggerid'], 'selectHosts' => ['hostid'], 'search' => $data['filter']['trigger_name'] !== '' ? ['description' => $data['filter']['trigger_name']] : null, 'filter' => ['priority' => $data['filter']['severity'], 'value' => TRIGGER_VALUE_TRUE], 'withLastEventUnacknowledged' => true, 'maintenance' => $data['filter']['maintenance'], 'monitored' => true, 'preservekeys' => true]); foreach ($triggers_unack as $tunack) { foreach ($tunack['hosts'] as $unack_host) { $hosts_with_unack_triggers[$unack_host['hostid']] = $unack_host['hostid']; } } } $hosts_data = []; $problematic_host_list = []; $lastUnack_host_list = []; $highest_severity = []; $highest_severity2 = []; foreach ($triggers as $trigger) { foreach ($trigger['hosts'] as $trigger_host) { if (!isset($hosts[$trigger_host['hostid']])) { continue;
/** * Import triggers. */ protected function processTriggers() { $allTriggers = $this->getFormattedTriggers(); if (empty($allTriggers)) { return; } $triggersToCreate = array(); $triggersToUpdate = array(); $triggersToCreateDependencies = array(); foreach ($allTriggers as $trigger) { $triggerId = $this->referencer->resolveTrigger($trigger['description'], $trigger['expression']); if ($triggerId) { $deps = array(); foreach ($trigger['dependencies'] as $dependency) { $depTriggerId = $this->referencer->resolveTrigger($dependency['name'], $dependency['expression']); if (!$depTriggerId) { throw new Exception(_s('Trigger "%1$s" depends on trigger "%2$s", which does not exist.', $trigger['description'], $dependency['name'])); } $deps[] = array('triggerid' => $depTriggerId); } $trigger['dependencies'] = $deps; $trigger['triggerid'] = $triggerId; $triggersToUpdate[] = $trigger; } else { $triggersToCreateDependencies[] = $trigger['dependencies']; unset($trigger['dependencies']); $triggersToCreate[] = $trigger; } } $triggerDependencies = array(); $newTriggers = array(); if ($this->options['triggers']['createMissing'] && $triggersToCreate) { $newTriggerIds = API::Trigger()->create($triggersToCreate); foreach ($newTriggerIds['triggerids'] as $tnum => $triggerId) { $trigger = $triggersToCreate[$tnum]; $this->referencer->addTriggerRef($trigger['description'], $trigger['expression'], $triggerId); $newTriggers[$triggerId] = $trigger; } } // if we have new triggers with dependencies and they were created, create their dependencies if ($triggersToCreateDependencies && isset($newTriggerIds)) { foreach ($newTriggerIds['triggerids'] as $tnum => $triggerId) { $deps = array(); foreach ($triggersToCreateDependencies[$tnum] as $dependency) { $depTriggerId = $this->referencer->resolveTrigger($dependency['name'], $dependency['expression']); if (!$depTriggerId) { $trigger = $newTriggers[$triggerId]; throw new Exception(_s('Trigger "%1$s" depends on trigger "%2$s", which does not exist.', $trigger['description'], $dependency['name'])); } $deps[] = array('triggerid' => $depTriggerId); } if (!empty($deps)) { $triggerDependencies[] = array('triggerid' => $triggerId, 'dependencies' => $deps); } } } if ($this->options['triggers']['updateExisting'] && $triggersToUpdate) { API::Trigger()->update($triggersToUpdate); } if ($triggerDependencies) { API::Trigger()->update($triggerDependencies); } // refresh triggers because template triggers can be inherited to host and used in maps $this->referencer->refreshTriggers(); }
/** * Get Template data * * @param array $options * @return array|boolean Template data as array or false if error */ public function get($options = array()) { $result = array(); $nodeCheck = false; $userType = self::$userData['type']; $userid = self::$userData['userid']; // allowed columns for sorting $sortColumns = array('hostid', 'host', 'name'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND); $sqlParts = array('select' => array('templates' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array('h.status=' . HOST_STATUS_TEMPLATE), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'parentTemplateids' => null, 'hostids' => null, 'graphids' => null, 'itemids' => null, 'triggerids' => null, 'with_items' => null, 'with_triggers' => null, 'with_graphs' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => '', 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectHosts' => null, 'selectTemplates' => null, 'selectParentTemplates' => null, 'selectItems' => null, 'selectDiscoveries' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectApplications' => null, 'selectMacros' => null, 'selectScreens' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); if (is_array($options['output'])) { unset($sqlParts['select']['templates']); $dbTable = DB::getSchema('hosts'); $sqlParts['select']['hostid'] = 'h.hostid'; foreach ($options['output'] as $field) { if ($field == 'templateid') { continue; } if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 'h.' . $field; } } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY; $userGroups = getUserGroupsByUserId($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)>=' . $permission . ')'; } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['groupid'] = 'hg.groupid'; } $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where']['hgh'] = 'hg.hostid=h.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['hg'] = 'hg.groupid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('hg.groupid', $nodeids); } } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); $sqlParts['where']['templateid'] = dbConditionInt('h.hostid', $options['templateids']); if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('h.hostid', $nodeids); } } // parentTemplateids if (!is_null($options['parentTemplateids'])) { zbx_value2array($options['parentTemplateids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['parentTemplateid'] = 'ht.templateid as parentTemplateid'; } $sqlParts['from']['hosts_templates'] = 'hosts_templates ht'; $sqlParts['where'][] = dbConditionInt('ht.templateid', $options['parentTemplateids']); $sqlParts['where']['hht'] = 'h.hostid=ht.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['templateid'] = 'ht.templateid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ht.templateid', $nodeids); } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['linked_hostid'] = 'ht.hostid as linked_hostid'; } $sqlParts['from']['hosts_templates'] = 'hosts_templates ht'; $sqlParts['where'][] = dbConditionInt('ht.hostid', $options['hostids']); $sqlParts['where']['hht'] = 'h.hostid=ht.templateid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['ht'] = 'ht.hostid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ht.hostid', $nodeids); } } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['itemid'] = 'i.itemid'; } $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('i.itemid', $options['itemids']); $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('i.itemid', $nodeids); } } // triggerids if (!is_null($options['triggerids'])) { zbx_value2array($options['triggerids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['triggerid'] = 'f.triggerid'; } $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'; if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('f.triggerid', $nodeids); } } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['graphid'] = 'gi.graphid'; } $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'; if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('gi.graphid', $nodeids); } } // node check !!!! // should last, after all ****IDS checks if (!$nodeCheck) { $sqlParts['where'][] = DBin_node('h.hostid', $nodeids); } // with_items if (!is_null($options['with_items'])) { $sqlParts['where'][] = 'EXISTS (SELECT NULL FROM items i WHERE h.hostid=i.hostid )'; } // with_triggers if (!is_null($options['with_triggers'])) { $sqlParts['where'][] = 'EXISTS(' . 'SELECT NULL' . ' FROM items i,functions f,triggers t' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid)'; } // with_graphs if (!is_null($options['with_graphs'])) { $sqlParts['where'][] = 'EXISTS(' . 'SELECT NULL' . ' FROM items i,graphs_items gi' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=gi.itemid)'; } // filter if (is_array($options['filter'])) { $this->dbFilter('hosts h', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('hosts h', $options, $sqlParts); } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['templates'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('count(DISTINCT h.hostid) as rowscount'); // groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'h'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } //------------- $templateids = array(); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($template = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $template; } else { $result = $template['rowscount']; } } else { $template['templateid'] = $template['hostid']; $templateids[$template['templateid']] = $template['templateid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$template['templateid']] = array('templateid' => $template['templateid']); } else { if (!isset($result[$template['templateid']])) { $result[$template['templateid']] = array(); } if (!is_null($options['selectGroups']) && !isset($result[$template['templateid']]['groups'])) { $template['groups'] = array(); } if (!is_null($options['selectTemplates']) && !isset($result[$template['templateid']]['templates'])) { $template['templates'] = array(); } if (!is_null($options['selectHosts']) && !isset($result[$template['templateid']]['hosts'])) { $template['hosts'] = array(); } if (!is_null($options['selectParentTemplates']) && !isset($result[$template['templateid']]['parentTemplates'])) { $template['parentTemplates'] = array(); } if (!is_null($options['selectItems']) && !isset($result[$template['templateid']]['items'])) { $template['items'] = array(); } if (!is_null($options['selectDiscoveries']) && !isset($result[$template['hostid']]['discoveries'])) { $result[$template['hostid']]['discoveries'] = array(); } if (!is_null($options['selectTriggers']) && !isset($result[$template['templateid']]['triggers'])) { $template['triggers'] = array(); } if (!is_null($options['selectGraphs']) && !isset($result[$template['templateid']]['graphs'])) { $template['graphs'] = array(); } if (!is_null($options['selectApplications']) && !isset($result[$template['templateid']]['applications'])) { $template['applications'] = array(); } if (!is_null($options['selectMacros']) && !isset($result[$template['templateid']]['macros'])) { $template['macros'] = array(); } if (!is_null($options['selectScreens']) && !isset($result[$template['templateid']]['screens'])) { $template['screens'] = array(); } // groupids if (isset($template['groupid']) && is_null($options['selectGroups'])) { if (!isset($result[$template['templateid']]['groups'])) { $result[$template['templateid']]['groups'] = array(); } $result[$template['templateid']]['groups'][] = array('groupid' => $template['groupid']); unset($template['groupid']); } // hostids if (isset($template['linked_hostid']) && is_null($options['selectHosts'])) { if (!isset($result[$template['templateid']]['hosts'])) { $result[$template['templateid']]['hosts'] = array(); } $result[$template['templateid']]['hosts'][] = array('hostid' => $template['linked_hostid']); unset($template['linked_hostid']); } // parentTemplateids if (isset($template['parentTemplateid']) && is_null($options['selectParentTemplates'])) { if (!isset($result[$template['templateid']]['parentTemplates'])) { $result[$template['templateid']]['parentTemplates'] = array(); } $result[$template['templateid']]['parentTemplates'][] = array('templateid' => $template['parentTemplateid']); unset($template['parentTemplateid']); } // itemids if (isset($template['itemid']) && is_null($options['selectItems'])) { if (!isset($result[$template['templateid']]['items'])) { $result[$template['templateid']]['items'] = array(); } $result[$template['templateid']]['items'][] = array('itemid' => $template['itemid']); unset($template['itemid']); } // triggerids if (isset($template['triggerid']) && is_null($options['selectTriggers'])) { if (!isset($result[$template['hostid']]['triggers'])) { $result[$template['hostid']]['triggers'] = array(); } $result[$template['hostid']]['triggers'][] = array('triggerid' => $template['triggerid']); unset($template['triggerid']); } // graphids if (isset($template['graphid']) && is_null($options['selectGraphs'])) { if (!isset($result[$template['templateid']]['graphs'])) { $result[$template['templateid']]['graphs'] = array(); } $result[$template['templateid']]['graphs'][] = array('graphid' => $template['graphid']); unset($template['graphid']); } $result[$template['templateid']] += $template; } } } if (!is_null($options['countOutput'])) { return $result; } // Adding Objects // Adding Groups if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) { $objParams = array('nodeids' => $nodeids, 'output' => $options['selectGroups'], 'hostids' => $templateids, 'preservekeys' => 1); $groups = API::HostGroup()->get($objParams); foreach ($groups as $groupid => $group) { $ghosts = $group['hosts']; unset($group['hosts']); foreach ($ghosts as $hnum => $template) { $result[$template['hostid']]['groups'][] = $group; } } } // Adding Templates if (!is_null($options['selectTemplates'])) { $objParams = array('nodeids' => $nodeids, 'parentTemplateids' => $templateids, 'preservekeys' => 1); if (is_array($options['selectTemplates']) || str_in_array($options['selectTemplates'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectTemplates']; $templates = API::Template()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['parentTemplates']); if (isset($template['parentTemplates']) && is_array($template['parentTemplates'])) { $count = array(); foreach ($template['parentTemplates'] as $parentTemplate) { if (!is_null($options['limitSelects'])) { if (!isset($count[$parentTemplate['templateid']])) { $count[$parentTemplate['templateid']] = 0; } $count[$parentTemplate['hostid']]++; if ($count[$parentTemplate['templateid']] > $options['limitSelects']) { continue; } } $result[$parentTemplate['templateid']]['templates'][] =& $templates[$templateid]; } } } } elseif (API_OUTPUT_COUNT == $options['selectTemplates']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $templates = API::Template()->get($objParams); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $templateid => $template) { if (isset($templates[$groupid])) { $result[$templateid]['templates'] = $templates[$templateid]['rowscount']; } else { $result[$templateid]['templates'] = 0; } } } } // Adding Hosts if (!is_null($options['selectHosts'])) { $objParams = array('nodeids' => $nodeids, 'templateids' => $templateids, 'preservekeys' => 1); if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectHosts']; $hosts = API::Host()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($hosts, 'host'); } foreach ($hosts as $hostid => $host) { unset($hosts[$hostid]['templates']); foreach ($host['templates'] as $tnum => $template) { if (!is_null($options['limitSelects'])) { if (!isset($count[$template['templateid']])) { $count[$template['templateid']] = 0; } $count[$template['templateid']]++; if ($count[$template['templateid']] > $options['limitSelects']) { continue; } } $result[$template['templateid']]['hosts'][] =& $hosts[$hostid]; } } } elseif (API_OUTPUT_COUNT == $options['selectHosts']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $hosts = API::Host()->get($objParams); $hosts = zbx_toHash($hosts, 'hostid'); foreach ($result as $templateid => $template) { if (isset($hosts[$templateid])) { $result[$templateid]['hosts'] = $hosts[$templateid]['rowscount']; } else { $result[$templateid]['hosts'] = 0; } } } } // Adding parentTemplates if (!is_null($options['selectParentTemplates'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => 1); if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectParentTemplates']; $templates = API::Template()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['hosts']); foreach ($template['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['parentTemplates'][] =& $templates[$templateid]; } } } elseif (API_OUTPUT_COUNT == $options['selectTemplates']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $templates = API::Template()->get($objParams); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $templateid => $template) { if (isset($templates[$groupid])) { $result[$templateid]['parentTemplates'] = $templates[$templateid]['rowscount']; } else { $result[$templateid]['parentTemplates'] = 0; } } } } // Adding Items if (!is_null($options['selectItems'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectItems']; $items = API::Item()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } $count = array(); foreach ($items as $itemid => $item) { if (!is_null($options['limitSelects'])) { if (!isset($count[$item['hostid']])) { $count[$item['hostid']] = 0; } $count[$item['hostid']]++; if ($count[$item['hostid']] > $options['limitSelects']) { continue; } } $result[$item['hostid']]['items'][] =& $items[$itemid]; } } elseif (API_OUTPUT_COUNT == $options['selectItems']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::Item()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $templateid => $template) { if (isset($items[$templateid])) { $result[$templateid]['items'] = $items[$templateid]['rowscount']; } else { $result[$templateid]['items'] = 0; } } } } // Adding Discoveries if (!is_null($options['selectDiscoveries'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectDiscoveries']) || str_in_array($options['selectDiscoveries'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDiscoveries']; $items = API::DiscoveryRule()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } foreach ($items as $itemid => $item) { unset($items[$itemid]['hosts']); foreach ($item['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['discoveries'][] =& $items[$itemid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDiscoveries']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::DiscoveryRule()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { if (isset($items[$hostid])) { $result[$hostid]['discoveries'] = $items[$hostid]['rowscount']; } else { $result[$hostid]['discoveries'] = 0; } } } } // Adding triggers if (!is_null($options['selectTriggers'])) { if (is_array($options['selectTriggers']) || str_in_array($options['selectTriggers'], $subselectsAllowedOutputs)) { $triggers = API::Trigger()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => true, 'output' => $options['selectTriggers'])); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } foreach ($triggers as $triggerid => $trigger) { unset($triggers[$triggerid]['hosts']); foreach ($trigger['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['triggers'][] =& $triggers[$triggerid]; } } } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) { $triggers = API::Trigger()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'countOutput' => true, 'groupCount' => true)); $triggers = zbx_toHash($triggers, 'hostid'); foreach ($result as $templateid => $template) { if (isset($triggers[$templateid])) { $result[$templateid]['triggers'] = $triggers[$templateid]['rowscount']; } else { $result[$templateid]['triggers'] = 0; } } } } // Adding graphs if (!is_null($options['selectGraphs'])) { if (is_array($options['selectGraphs']) || str_in_array($options['selectGraphs'], $subselectsAllowedOutputs)) { $graphs = API::Graph()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => true, 'output' => $options['selectGraphs'])); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } foreach ($graphs as $graphid => $graph) { unset($graphs[$graphid]['hosts']); foreach ($graph['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['graphs'][] =& $graphs[$graphid]; } } } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) { $graphs = API::Graph()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'countOutput' => true, 'groupCount' => true)); $graphs = zbx_toHash($graphs, 'hostid'); foreach ($result as $templateid => $template) { if (isset($graphs[$templateid])) { $result[$templateid]['graphs'] = $graphs[$templateid]['rowscount']; } else { $result[$templateid]['graphs'] = 0; } } } } // Adding applications if (!is_null($options['selectApplications'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectApplications']) || str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectApplications']; $applications = API::Application()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($applications, 'name'); } foreach ($applications as $applicationid => $application) { unset($applications[$applicationid]['hosts']); foreach ($application['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['applications'][] =& $applications[$applicationid]; } } } elseif (API_OUTPUT_COUNT == $options['selectApplications']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $applications = API::Application()->get($objParams); $applications = zbx_toHash($applications, 'hostid'); foreach ($result as $templateid => $template) { if (isset($applications[$templateid])) { $result[$templateid]['applications'] = $applications[$templateid]['rowscount']; } else { $result[$templateid]['applications'] = 0; } } } } // Adding screens if (!is_null($options['selectScreens'])) { $objParams = array('nodeids' => $nodeids, 'templateids' => $templateids, 'editable' => $options['editable'], 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectScreens']) || str_in_array($options['selectScreens'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectScreens']; $screens = API::TemplateScreen()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } foreach ($screens as $screenid => $screen) { if (!is_null($options['limitSelects'])) { if (count($result[$screen['hostid']]['screens']) >= $options['limitSelects']) { continue; } } unset($screens[$screenid]['templates']); $result[$screen['hostid']]['screens'][] =& $screens[$screenid]; } } elseif (API_OUTPUT_COUNT == $options['selectScreens']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $screens = API::TemplateScreen()->get($objParams); $screens = zbx_toHash($screens, 'hostid'); foreach ($result as $templateid => $template) { if (isset($screens[$templateid])) { $result[$templateid]['screens'] = $screens[$templateid]['rowscount']; } else { $result[$templateid]['screens'] = 0; } } } } // Adding macros if (!is_null($options['selectMacros']) && str_in_array($options['selectMacros'], $subselectsAllowedOutputs)) { $objParams = array('nodeids' => $nodeids, 'output' => $options['selectMacros'], 'hostids' => $templateids, 'preservekeys' => 1); $macros = API::UserMacro()->get($objParams); foreach ($macros as $macroid => $macro) { unset($macros[$macroid]['hosts']); foreach ($macro['hosts'] as $hnum => $host) { $result[$host['hostid']]['macros'][] = $macros[$macroid]; } } } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Select trigger ids for previously added trigger names/expressions. */ protected function selectTriggers() { if (!empty($this->triggers)) { $this->triggersRefs = array(); $dbTriggers = API::Trigger()->get(array('output' => array('triggerid', 'expression', 'description'), 'filter' => array('description' => array_keys($this->triggers), 'flags' => array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_PROTOTYPE, ZBX_FLAG_DISCOVERY_CREATED)), 'editable' => true)); foreach ($dbTriggers as $dbTrigger) { $dbTriggerExpression = explode_exp($dbTrigger['expression']); if (isset($this->triggers[$dbTrigger['description']][$dbTriggerExpression])) { $this->triggersRefs[$dbTrigger['description']][$dbTriggerExpression] = $dbTrigger['triggerid']; } } } }
/** * Validates the input for the addDependencies() method. * * @param array $triggerPrototypes * @param string $triggerPrototypes[]['triggerid'] * @param array $triggerPrototypes[]['dependencies'] * @param string $triggerPrototypes[]['dependencies'][]['triggerid'] * * @throws APIException if the given dependencies are invalid. */ protected function validateAddDependencies(array $triggerPrototypes) { $depTriggerIds = []; foreach ($triggerPrototypes as $triggerPrototype) { if (!array_key_exists('dependencies', $triggerPrototype)) { continue; } foreach ($triggerPrototype['dependencies'] as $dependency) { $depTriggerIds[$dependency['triggerid']] = $dependency['triggerid']; } } if (!$depTriggerIds) { return; } // Check if given IDs are actual trigger prototypes and get discovery rules if they are. $depTriggerPrototypes = $this->get(['output' => ['triggerid'], 'selectDiscoveryRule' => ['itemid'], 'triggerids' => $depTriggerIds, 'preservekeys' => true]); if ($depTriggerPrototypes) { // Get current trigger prototype discovery rules. $dRules = $this->get(['output' => ['triggerid'], 'selectDiscoveryRule' => ['itemid'], 'triggerids' => zbx_objectValues($triggerPrototypes, 'triggerid'), 'preservekeys' => true]); foreach ($triggerPrototypes as $triggerPrototype) { if (!array_key_exists('dependencies', $triggerPrototype)) { continue; } $dRuleId = $dRules[$triggerPrototype['triggerid']]['discoveryRule']['itemid']; // Check if current trigger prototype rules match dependent trigger prototype rules. foreach ($triggerPrototype['dependencies'] as $dependency) { if (isset($depTriggerPrototypes[$dependency['triggerid']])) { $depTriggerDRuleId = $depTriggerPrototypes[$dependency['triggerid']]['discoveryRule']['itemid']; if (bccomp($depTriggerDRuleId, $dRuleId) != 0) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } } } } // Check other dependency IDs if those are normal triggers. $triggers = API::Trigger()->get(['output' => ['triggerid'], 'triggerids' => $depTriggerIds, 'filter' => ['flags' => [ZBX_FLAG_DISCOVERY_NORMAL]]]); if (!$depTriggerPrototypes && !$triggers) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } $this->checkDependencies($triggerPrototypes); $this->checkDependencyParents($triggerPrototypes); $this->checkDependencyDuplicates($triggerPrototypes); }
/** * Resolve user macros in trigger expression. * * @param string $triggers[$triggerid]['expression'] * * @return array */ public function resolveTriggerExpressionUserMacro(array $triggers) { $usermacros = []; $macro_values = []; $types = ['usermacros' => true]; // Find macros. foreach ($triggers as $triggerid => $trigger) { $matched_macros = $this->extractMacros([$trigger['expression']], $types); if ($matched_macros['usermacros']) { $usermacros[$triggerid] = ['hostids' => [], 'macros' => $matched_macros['usermacros']]; } } if ($usermacros) { // Get hosts for triggers. $db_triggers = API::Trigger()->get(['output' => [], 'selectHosts' => ['hostid'], 'triggerids' => array_keys($usermacros), 'preservekeys' => true]); foreach ($usermacros as $triggerid => &$usermacros_data) { if (array_key_exists($triggerid, $db_triggers)) { $usermacros_data['hostids'] = zbx_objectValues($db_triggers[$triggerid]['hosts'], 'hostid'); } } unset($usermacros_data); // Get user macros values. foreach ($this->getUserMacros($usermacros) as $triggerid => $usermacros_data) { $macro_values[$triggerid] = array_key_exists($triggerid, $macro_values) ? array_merge($macro_values[$triggerid], $usermacros_data['macros']) : $usermacros_data['macros']; } } $types = $this->transformToPositionTypes($types); // Replace macros to value. foreach ($triggers as $triggerid => &$trigger) { $matched_macros = $this->getMacroPositions($trigger['expression'], $types); foreach (array_reverse($matched_macros, true) as $pos => $macro) { $trigger['expression'] = substr_replace($trigger['expression'], $macro_values[$triggerid][$macro], $pos, strlen($macro)); } } unset($trigger); return $triggers; }
function getLastEvents($options) { if (!isset($options['limit'])) { $options['limit'] = 15; } $triggerOptions = array('filter' => array(), 'skipDependent' => 1, 'selectHosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND, 'sortfield' => 'lastchange', 'sortorder' => ZBX_SORT_DOWN, 'limit' => $options['triggerLimit']); $eventOptions = array('source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER, 'output' => API_OUTPUT_EXTEND, 'sortfield' => array('clock', 'eventid'), 'sortorder' => ZBX_SORT_DOWN); if (isset($options['eventLimit'])) { $eventOptions['limit'] = $options['eventLimit']; } if (isset($options['nodeids'])) { $triggerOptions['nodeids'] = $options['nodeids']; } if (isset($options['priority'])) { $triggerOptions['filter']['priority'] = $options['priority']; } if (isset($options['monitored'])) { $triggerOptions['monitored'] = $options['monitored']; } if (isset($options['lastChangeSince'])) { $triggerOptions['lastChangeSince'] = $options['lastChangeSince']; $eventOptions['time_from'] = $options['lastChangeSince']; } if (isset($options['value'])) { $triggerOptions['filter']['value'] = $options['value']; $eventOptions['value'] = $options['value']; } // triggers $triggers = API::Trigger()->get($triggerOptions); $triggers = zbx_toHash($triggers, 'triggerid'); // events $eventOptions['objectids'] = zbx_objectValues($triggers, 'triggerid'); $events = API::Event()->get($eventOptions); $sortClock = array(); $sortEvent = array(); foreach ($events as $enum => $event) { if (!isset($triggers[$event['objectid']])) { continue; } $events[$enum]['trigger'] = $triggers[$event['objectid']]; $events[$enum]['host'] = reset($events[$enum]['trigger']['hosts']); $sortClock[$enum] = $event['clock']; $sortEvent[$enum] = $event['eventid']; //expanding description for the state where event was $merged_event = array_merge($event, $triggers[$event['objectid']]); $events[$enum]['trigger']['description'] = CMacrosResolverHelper::resolveEventDescription($merged_event); } array_multisort($sortClock, SORT_DESC, $sortEvent, SORT_DESC, $events); return $events; }
/** * Deletes triggers from DB that are missing in XML. * * @return null */ protected function deleteMissingTriggers() { if (!$this->options['triggers']['deleteMissing']) { return; } $processedHostIds = $this->importedObjectContainer->getHostIds(); $processedTemplateIds = $this->importedObjectContainer->getTemplateIds(); $processedHostIds = array_merge($processedHostIds, $processedTemplateIds); // no hosts or templates have been processed if (!$processedHostIds) { return; } $triggersXML = array(); $allTriggers = $this->getFormattedTriggers(); if ($allTriggers) { foreach ($allTriggers as $trigger) { $triggerId = $this->referencer->resolveTrigger($trigger['description'], $trigger['expression']); if ($triggerId) { $triggersXML[$triggerId] = $triggerId; } } } $dbTriggerIds = API::Trigger()->get(array('output' => array('triggerid'), 'hostids' => $processedHostIds, 'selectHosts' => array('hostid'), 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); // check that potentially deletable trigger belongs to same hosts that are in XML // if some triggers belong to more hosts than current XML contains, don't delete them $triggersToDelete = array_diff_key($dbTriggerIds, $triggersXML); $triggerIdsToDelete = array(); $processedHostIds = array_flip($processedHostIds); foreach ($triggersToDelete as $triggerId => $trigger) { $triggerHostIds = array_flip(zbx_objectValues($trigger['hosts'], 'hostid')); if (!array_diff_key($triggerHostIds, $processedHostIds)) { $triggerIdsToDelete[] = $triggerId; } } if ($triggerIdsToDelete) { API::Trigger()->delete($triggerIdsToDelete); } // refresh triggers because template triggers can be inherited to host and used in maps $this->referencer->refreshTriggers(); }
} // host items $hostItems = API::Item()->get(array('hostids' => $_REQUEST['hostid'], 'inherited' => false, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL), 'output' => array('itemid', 'key_', 'name'))); if (!empty($hostItems)) { $itemsList = array(); foreach ($hostItems as $hostItem) { $itemsList[$hostItem['itemid']] = itemName($hostItem); } order_result($itemsList); $listBox = new CListBox('items', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($itemsList); $hostList->addRow(_('Items'), $listBox); } // host triggers $hostTriggers = API::Trigger()->get(array('inherited' => false, 'hostids' => $_REQUEST['hostid'], 'output' => array('triggerid', 'description'), 'selectItems' => array('type'), 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL)))); if (!empty($hostTriggers)) { $triggersList = array(); foreach ($hostTriggers as $hostTrigger) { if (httpItemExists($hostTrigger['items'])) { continue; } $triggersList[$hostTrigger['triggerid']] = $hostTrigger['description']; } if (!empty($triggersList)) { order_result($triggersList); $listBox = new CListBox('triggers', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($triggersList); $hostList->addRow(_('Triggers'), $listBox); }
// items $hostItems = API::Item()->get(array('hostids' => $templateid, 'inherited' => false, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL), 'output' => array('itemid', 'key_', 'name', 'hostid'))); if ($hostItems) { $hostItems = CMacrosResolverHelper::resolveItemNames($hostItems); $itemsList = array(); foreach ($hostItems as $hostItem) { $itemsList[$hostItem['itemid']] = $hostItem['name_expanded']; } order_result($itemsList); $listBox = new CListBox('items', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($itemsList); $templateList->addRow(_('Items'), $listBox); } // Triggers $hostTriggers = API::Trigger()->get(array('inherited' => false, 'hostids' => $templateid, 'output' => API_OUTPUT_EXTEND, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL)))); if (!empty($hostTriggers)) { $triggersList = array(); foreach ($hostTriggers as $hostTrigger) { $triggersList[$hostTrigger['triggerid']] = $hostTrigger['description']; } order_result($triggersList); $listBox = new CListBox('triggers', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($triggersList); $templateList->addRow(_('Triggers'), $listBox); } // Graphs $hostGraphs = API::Graph()->get(array('inherited' => false, 'hostids' => $templateid, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL)), 'output' => API_OUTPUT_EXTEND)); if (!empty($hostGraphs)) { $graphsList = array();
**/ require_once dirname(__FILE__) . '/include/config.inc.php'; require_once dirname(__FILE__) . '/include/triggers.inc.php'; $page['file'] = 'chart4.php'; $page['type'] = PAGE_TYPE_IMAGE; require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('triggerid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, null)); check_fields($fields); /* * Permissions */ if (!hasRequest('triggerid')) { fatal_error(_('No triggers defined.')); } $dbTrigger = API::Trigger()->get(array('triggerids' => getRequest('triggerid'), 'output' => API_OUTPUT_EXTEND, 'expandDescription' => true)); if (!$dbTrigger) { access_deny(); } else { $dbTrigger = reset($dbTrigger); } /* * Display */ $startTime = microtime(true); $sizeX = 900; $sizeY = 300; $shiftX = 12; $shiftYup = 17; $shiftYdown = 55; $im = imagecreate($sizeX + $shiftX + 61, $sizeY + $shiftYup + $shiftYdown + 10);
/** * Get Host data * * @param array $options * @param array $options['nodeids'] Node IDs * @param array $options['groupids'] HostGroup IDs * @param array $options['hostids'] Host IDs * @param boolean $options['monitored_hosts'] only monitored Hosts * @param boolean $options['templated_hosts'] include templates in result * @param boolean $options['with_items'] only with items * @param boolean $options['with_monitored_items'] only with monitored items * @param boolean $options['with_historical_items'] only with historical items * @param boolean $options['with_triggers'] only with triggers * @param boolean $options['with_monitored_triggers'] only with monitored triggers * @param boolean $options['with_httptests'] only with http tests * @param boolean $options['with_monitored_httptests'] only with monitored http tests * @param boolean $options['with_graphs'] only with graphs * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins * @param boolean $options['selectGroups'] select HostGroups * @param boolean $options['selectItems'] select Items * @param boolean $options['selectTriggers'] select Triggers * @param boolean $options['selectGraphs'] select Graphs * @param boolean $options['selectApplications'] select Applications * @param boolean $options['selectMacros'] select Macros * @param boolean|array $options['selectInventory'] select Inventory * @param boolean $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 = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; // allowed columns for sorting $sortColumns = array('hostid', 'host', 'name', 'status'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM); $sqlParts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'proxyids' => null, 'templateids' => null, 'interfaceids' => null, 'itemids' => null, 'triggerids' => null, 'maintenanceids' => null, 'graphids' => null, 'applicationids' => null, 'dhostids' => null, 'dserviceids' => null, 'httptestids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'proxy_hosts' => null, 'with_items' => null, 'with_monitored_items' => null, 'with_historical_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' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectParentTemplates' => null, 'selectItems' => null, 'selectDiscoveries' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectDHosts' => null, 'selectDServices' => null, 'selectApplications' => null, 'selectMacros' => null, 'selectScreens' => null, 'selectInterfaces' => null, 'selectInventory' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); if (is_array($options['output'])) { unset($sqlParts['select']['hosts']); $dbTable = DB::getSchema('hosts'); $sqlParts['select']['hostid'] = 'h.hostid'; foreach ($options['output'] as $field) { if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 'h.' . $field; } } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY; $userGroups = getUserGroupsByUserId($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)>=' . $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']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['groupid'] = 'hg.groupid'; } $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where']['hgh'] = 'hg.hostid=h.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['groupid'] = 'hg.groupid'; } } // proxyids if (!is_null($options['proxyids'])) { zbx_value2array($options['proxyids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['proxy_hostid'] = 'h.proxy_hostid'; } $sqlParts['where'][] = dbConditionInt('h.proxy_hostid', $options['proxyids']); } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['templateid'] = 'ht.templateid'; } $sqlParts['from']['hosts_templates'] = 'hosts_templates ht'; $sqlParts['where'][] = dbConditionInt('ht.templateid', $options['templateids']); $sqlParts['where']['hht'] = 'h.hostid=ht.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['templateid'] = 'ht.templateid'; } } // interfaceids if (!is_null($options['interfaceids'])) { zbx_value2array($options['interfaceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['interfaceid'] = 'hi.interfaceid'; } $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']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['itemid'] = 'i.itemid'; } $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']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['triggerid'] = 'f.triggerid'; } $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']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['httptestid'] = 'ht.httptestid'; } $sqlParts['from']['applications'] = 'applications a'; $sqlParts['from']['httptest'] = 'httptest ht'; $sqlParts['where'][] = dbConditionInt('ht.httptestid', $options['httptestids']); $sqlParts['where']['aht'] = 'a.applicationid=ht.applicationid'; $sqlParts['where']['ah'] = 'a.hostid=h.hostid'; } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['graphid'] = 'gi.graphid'; } $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']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['applicationid'] = 'a.applicationid'; } $sqlParts['from']['applications'] = 'applications a'; $sqlParts['where'][] = dbConditionInt('a.applicationid', $options['applicationids']); $sqlParts['where']['ah'] = 'a.hostid=h.hostid'; } // dhostids if (!is_null($options['dhostids'])) { zbx_value2array($options['dhostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dhostid'] = 'ds.dhostid'; } $sqlParts['from']['dservices'] = 'dservices ds'; $sqlParts['where'][] = dbConditionInt('ds.dhostid', $options['dhostids']); $sqlParts['where']['dsh'] = 'ds.ip=h.ip'; if (!is_null($options['groupCount'])) { $sqlParts['group']['dhostid'] = 'ds.dhostid'; } } // dserviceids if (!is_null($options['dserviceids'])) { zbx_value2array($options['dserviceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dserviceid'] = 'ds.dserviceid'; } $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 (!is_null($options['groupCount'])) { $sqlParts['group']['dserviceid'] = 'ds.dserviceid'; } } // maintenanceids if (!is_null($options['maintenanceids'])) { zbx_value2array($options['maintenanceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['maintenanceid'] = 'mh.maintenanceid'; } $sqlParts['from']['maintenances_hosts'] = 'maintenances_hosts mh'; $sqlParts['where'][] = dbConditionInt('mh.maintenanceid', $options['maintenanceids']); $sqlParts['where']['hmh'] = 'h.hostid=mh.hostid'; if (!is_null($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_historical_items, with_simple_graph_items if (!is_null($options['with_items'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ')'; } 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 . ')'; } elseif (!is_null($options['with_historical_items'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ' AND i.status IN (' . ITEM_STATUS_ACTIVE . ',' . ITEM_STATUS_NOTSUPPORTED . ')' . ' AND i.lastvalue IS NOT NULL' . ')'; } 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' . ')'; } 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 . ')'; } // with_httptests, with_monitored_httptests if (!is_null($options['with_httptests'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,httptest ht' . ' WHERE h.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ')'; } elseif (!is_null($options['with_monitored_httptests'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,httptest ht' . ' WHERE h.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')'; } // with_graphs if (!is_null($options['with_graphs'])) { $sqlParts['where'][] = 'EXISTS (' . ' SELECT 1' . ' FROM items i,graphs_items gi' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=gi.itemid ' . zbx_limit(1) . ')'; } // 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'; } } // 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'; } } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['hosts'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('COUNT(DISTINCT h.hostid) AS rowscount'); // groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'h'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $hostids = array(); $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($host = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $host; } else { $result = $host['rowscount']; } } else { $hostids[$host['hostid']] = $host['hostid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$host['hostid']] = array('hostid' => $host['hostid']); } else { if (!isset($result[$host['hostid']])) { $result[$host['hostid']] = array(); } if (!is_null($options['selectGroups']) && !isset($result[$host['hostid']]['groups'])) { $result[$host['hostid']]['groups'] = array(); } if (!is_null($options['selectParentTemplates']) && !isset($result[$host['hostid']]['parentTemplates'])) { $result[$host['hostid']]['parentTemplates'] = array(); } if (!is_null($options['selectItems']) && !isset($result[$host['hostid']]['items'])) { $result[$host['hostid']]['items'] = array(); } if (!is_null($options['selectDiscoveries']) && !isset($result[$host['hostid']]['discoveries'])) { $result[$host['hostid']]['discoveries'] = array(); } if (!is_null($options['selectInventory']) && !isset($result[$host['hostid']]['inventory'])) { $result[$host['hostid']]['inventory'] = array(); } if (!is_null($options['selectTriggers']) && !isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } if (!is_null($options['selectGraphs']) && !isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } if (!is_null($options['selectDHosts']) && !isset($result[$host['hostid']]['dhosts'])) { $result[$host['hostid']]['dhosts'] = array(); } if (!is_null($options['selectDServices']) && !isset($result[$host['hostid']]['dservices'])) { $result[$host['hostid']]['dservices'] = array(); } if (!is_null($options['selectApplications']) && !isset($result[$host['hostid']]['applications'])) { $result[$host['hostid']]['applications'] = array(); } if (!is_null($options['selectMacros']) && !isset($result[$host['hostid']]['macros'])) { $result[$host['hostid']]['macros'] = array(); } if (!is_null($options['selectScreens']) && !isset($result[$host['hostid']]['screens'])) { $result[$host['hostid']]['screens'] = array(); } if (!is_null($options['selectInterfaces']) && !isset($result[$host['hostid']]['interfaces'])) { $result[$host['hostid']]['interfaces'] = array(); } // groupids if (isset($host['groupid']) && is_null($options['selectGroups'])) { if (!isset($result[$host['hostid']]['groups'])) { $result[$host['hostid']]['groups'] = array(); } $result[$host['hostid']]['groups'][] = array('groupid' => $host['groupid']); unset($host['groupid']); } // templateids if (isset($host['templateid'])) { if (!isset($result[$host['hostid']]['templates'])) { $result[$host['hostid']]['templates'] = array(); } $result[$host['hostid']]['templates'][] = array('templateid' => $host['templateid'], 'hostid' => $host['templateid']); unset($host['templateid']); } // triggerids if (isset($host['triggerid']) && is_null($options['selectTriggers'])) { if (!isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } $result[$host['hostid']]['triggers'][] = array('triggerid' => $host['triggerid']); unset($host['triggerid']); } // interfaceids if (isset($host['interfaceid']) && is_null($options['selectInterfaces'])) { if (!isset($result[$host['hostid']]['interfaces'])) { $result[$host['hostid']]['interfaces'] = array(); } $result[$host['hostid']]['interfaces'][] = array('interfaceid' => $host['interfaceid']); unset($host['interfaceid']); } // itemids if (isset($host['itemid']) && is_null($options['selectItems'])) { if (!isset($result[$host['hostid']]['items'])) { $result[$host['hostid']]['items'] = array(); } $result[$host['hostid']]['items'][] = array('itemid' => $host['itemid']); unset($host['itemid']); } // graphids if (isset($host['graphid']) && is_null($options['selectGraphs'])) { if (!isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } $result[$host['hostid']]['graphs'][] = array('graphid' => $host['graphid']); unset($host['graphid']); } // graphids if (isset($host['applicationid'])) { if (!isset($result[$host['hostid']]['applications'])) { $result[$host['hostid']]['applications'] = array(); } $result[$host['hostid']]['applications'][] = array('applicationid' => $host['applicationid']); unset($host['applicationid']); } // httptestids if (isset($host['httptestid'])) { if (!isset($result[$host['hostid']]['httptests'])) { $result[$host['hostid']]['httptests'] = array(); } $result[$host['hostid']]['httptests'][] = array('httptestid' => $host['httptestid']); unset($host['httptestid']); } // dhostids if (isset($host['dhostid']) && is_null($options['selectDHosts'])) { if (!isset($result[$host['hostid']]['dhosts'])) { $result[$host['hostid']]['dhosts'] = array(); } $result[$host['hostid']]['dhosts'][] = array('dhostid' => $host['dhostid']); unset($host['dhostid']); } // dserviceids if (isset($host['dserviceid']) && is_null($options['selectDServices'])) { if (!isset($result[$host['hostid']]['dservices'])) { $result[$host['hostid']]['dservices'] = array(); } $result[$host['hostid']]['dservices'][] = array('dserviceid' => $host['dserviceid']); unset($host['dserviceid']); } // maintenanceids if (isset($host['maintenanceid'])) { if (!isset($result[$host['hostid']]['maintenances'])) { $result[$host['hostid']]['maintenances'] = array(); } if ($host['maintenanceid'] > 0) { $result[$host['hostid']]['maintenances'][] = array('maintenanceid' => $host['maintenanceid']); } } $result[$host['hostid']] += $host; } } } if (!is_null($options['countOutput'])) { return $result; } /* * adding objects */ // adding groups if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) { $groups = API::HostGroup()->get(array('nodeids' => $options['nodeids'], 'output' => $options['selectGroups'], 'hostids' => $hostids, 'preservekeys' => true)); foreach ($groups as $group) { $ghosts = $group['hosts']; unset($group['hosts']); foreach ($ghosts as $host) { $result[$host['hostid']]['groups'][] = $group; } } } // adding inventories if (!is_null($options['selectInventory']) && $options['selectInventory'] !== false) { if (is_array($options['selectInventory'])) { // if we are given a list of fields that needs to be fetched $dbTable = DB::getSchema('host_inventory'); $selectHIn = array('hin.hostid'); foreach ($options['selectInventory'] as $field) { if (isset($dbTable['fields'][$field])) { $selectHIn[] = 'hin.' . $field; } } } else { // all fields are needed $selectHIn = array('hin.*'); } $dbInventory = DBselect('SELECT ' . implode(', ', $selectHIn) . ' FROM host_inventory hin' . ' WHERE ' . dbConditionInt('hin.hostid', $hostids)); while ($inventory = DBfetch($dbInventory)) { $result[$inventory['hostid']]['inventory'] = $inventory; } } // adding templates if (!is_null($options['selectParentTemplates'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true); if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectParentTemplates']; $templates = API::Template()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['hosts']); $count = array(); foreach ($template['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['parentTemplates'][] =& $templates[$templateid]; } } } elseif (API_OUTPUT_COUNT == $options['selectParentTemplates']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $templates = API::Template()->get($objParams); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['templates'] = isset($templates[$hostid]) ? $templates[$hostid]['rowscount'] : 0; } } } // adding hostinterfaces if (!is_null($options['selectInterfaces'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectInterfaces']) || str_in_array($options['selectInterfaces'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectInterfaces']; $interfaces = API::HostInterface()->get($objParams); // we need to order interfaces for proper linkage and viewing order_result($interfaces, 'interfaceid', ZBX_SORT_UP); $count = array(); foreach ($interfaces as $interfaceid => $interface) { if (!is_null($options['limitSelects'])) { if (!isset($count[$interface['hostid']])) { $count[$interface['hostid']] = 0; } $count[$interface['hostid']]++; if ($count[$interface['hostid']] > $options['limitSelects']) { continue; } } $result[$interface['hostid']]['interfaces'][$interfaceid] =& $interfaces[$interfaceid]; } } elseif (API_OUTPUT_COUNT == $options['selectInterfaces']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $interfaces = API::HostInterface()->get($objParams); $interfaces = zbx_toHash($interfaces, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['interfaces'] = isset($interfaces[$hostid]) ? $interfaces[$hostid]['rowscount'] : 0; } } } // adding items if (!is_null($options['selectItems'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectItems']; $items = API::Item()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } $count = array(); foreach ($items as $itemid => $item) { if (!is_null($options['limitSelects'])) { if (!isset($count[$item['hostid']])) { $count[$item['hostid']] = 0; } $count[$item['hostid']]++; if ($count[$item['hostid']] > $options['limitSelects']) { continue; } } $result[$item['hostid']]['items'][] =& $items[$itemid]; } } elseif (API_OUTPUT_COUNT == $options['selectItems']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::Item()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['items'] = isset($items[$hostid]) ? $items[$hostid]['rowscount'] : 0; } } } // adding discoveries if (!is_null($options['selectDiscoveries'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectDiscoveries']) || str_in_array($options['selectDiscoveries'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDiscoveries']; $items = API::DiscoveryRule()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } $count = array(); foreach ($items as $itemid => $item) { unset($items[$itemid]['hosts']); foreach ($item['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['discoveries'][] =& $items[$itemid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDiscoveries']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::DiscoveryRule()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['discoveries'] = isset($items[$hostid]) ? $items[$hostid]['rowscount'] : 0; } } } // adding triggers if (!is_null($options['selectTriggers'])) { if (is_array($options['selectTriggers']) || str_in_array($options['selectTriggers'], $subselectsAllowedOutputs)) { $triggers = API::Trigger()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true, 'output' => $options['selectTriggers'])); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } $count = array(); foreach ($triggers as $triggerid => $trigger) { unset($triggers[$triggerid]['hosts']); foreach ($trigger['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['triggers'][] =& $triggers[$triggerid]; } } } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) { $triggers = API::Trigger()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'countOutput' => true, 'groupCount' => true)); $triggers = zbx_toHash($triggers, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['triggers'] = isset($triggers[$hostid]) ? $triggers[$hostid]['rowscount'] : 0; } } } // adding graphs if (!is_null($options['selectGraphs'])) { if (is_array($options['selectGraphs']) || str_in_array($options['selectGraphs'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectGraphs']; $graphs = API::Graph()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true, 'output' => $options['selectGraphs'])); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } $count = array(); foreach ($graphs as $graphid => $graph) { unset($graphs[$graphid]['hosts']); foreach ($graph['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['graphs'][] =& $graphs[$graphid]; } } } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) { $graphs = API::Graph()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'countOutput' => true, 'groupCount' => true)); $graphs = zbx_toHash($graphs, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['graphs'] = isset($graphs[$hostid]) ? $graphs[$hostid]['rowscount'] : 0; } } } // adding discovery hosts if (!is_null($options['selectDHosts'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectDHosts']) || str_in_array($options['selectDHosts'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDHosts']; $dhosts = API::DHost()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($dhosts, 'dhostid'); } $count = array(); foreach ($dhosts as $dhostid => $dhost) { unset($dhosts[$dhostid]['hosts']); foreach ($dhost['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['dhosts'][] =& $dhosts[$dhostid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDHosts']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $dhosts = API::DHost()->get($objParams); $dhosts = zbx_toHash($dhosts, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['dhosts'] = isset($dhosts[$hostid]) ? $dhosts[$hostid]['rowscount'] : 0; } } } // adding applications if (!is_null($options['selectApplications'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectApplications']) || str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectApplications']; $applications = API::Application()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($applications, 'name'); } $count = array(); foreach ($applications as $applicationid => $application) { unset($applications[$applicationid]['hosts']); foreach ($application['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['applications'][] =& $applications[$applicationid]; } } } elseif (API_OUTPUT_COUNT == $options['selectApplications']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $applications = API::Application()->get($objParams); $applications = zbx_toHash($applications, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['applications'] = isset($applications[$hostid]) ? $applications[$hostid]['rowscount'] : 0; } } } // adding macros if (!is_null($options['selectMacros']) && str_in_array($options['selectMacros'], $subselectsAllowedOutputs)) { $objParams = array('nodeids' => $options['nodeids'], 'output' => $options['selectMacros'], 'hostids' => $hostids, 'preservekeys' => true); $macros = API::UserMacro()->get($objParams); foreach ($macros as $macroid => $macro) { $mhosts = $macro['hosts']; unset($macro['hosts']); foreach ($mhosts as $host) { $result[$host['hostid']]['macros'][$macroid] = $macro; } } } // adding screens if (!is_null($options['selectScreens'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'editable' => $options['editable'], 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectScreens']) || str_in_array($options['selectScreens'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectScreens']; $screens = API::TemplateScreen()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } foreach ($screens as $snum => $screen) { if (!is_null($options['limitSelects'])) { if (count($result[$screen['hostid']]['screens']) >= $options['limitSelects']) { continue; } } unset($screens[$snum]['hosts']); $result[$screen['hostid']]['screens'][] =& $screens[$snum]; } } elseif (API_OUTPUT_COUNT == $options['selectScreens']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $screens = API::TemplateScreen()->get($objParams); $screens = zbx_toHash($screens, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['screens'] = isset($screens[$hostid]) ? $screens[$hostid]['rowscount'] : 0; } } } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Generate data for the trigger configuration form. * * @param string $exprAction expression constructor action, see remakeExpression() for a list of supported values * * @return array */ function getTriggerFormData($exprAction) { $data = array('form' => getRequest('form'), 'form_refresh' => getRequest('form_refresh'), 'parent_discoveryid' => getRequest('parent_discoveryid'), 'dependencies' => getRequest('dependencies', array()), 'db_dependencies' => array(), 'triggerid' => getRequest('triggerid'), 'expression' => getRequest('expression', ''), 'expr_temp' => getRequest('expr_temp', ''), 'description' => getRequest('description', ''), 'type' => getRequest('type', 0), 'priority' => getRequest('priority', 0), 'status' => getRequest('status', 0), 'comments' => getRequest('comments', ''), 'url' => getRequest('url', ''), 'input_method' => getRequest('input_method', IM_ESTABLISHED), 'limited' => false, 'templates' => array(), 'hostid' => getRequest('hostid', 0)); if (!empty($data['triggerid'])) { // get trigger $options = array('output' => API_OUTPUT_EXTEND, 'selectHosts' => array('hostid'), 'triggerids' => $data['triggerid']); $trigger = $data['parent_discoveryid'] ? API::TriggerPrototype()->get($options) : API::Trigger()->get($options); $data['trigger'] = reset($trigger); // get templates $tmp_triggerid = $data['triggerid']; do { $db_triggers = DBfetch(DBselect('SELECT t.triggerid,t.templateid,id.parent_itemid,h.name,h.hostid' . ' FROM triggers t' . ' LEFT JOIN functions f ON t.triggerid=f.triggerid' . ' LEFT JOIN items i ON f.itemid=i.itemid' . ' LEFT JOIN hosts h ON i.hostid=h.hostid' . ' LEFT JOIN item_discovery id ON i.itemid=id.itemid' . ' WHERE t.triggerid=' . zbx_dbstr($tmp_triggerid))); if (bccomp($data['triggerid'], $tmp_triggerid) != 0) { // parent trigger prototype link if ($data['parent_discoveryid']) { $link = 'trigger_prototypes.php?form=update&triggerid=' . $db_triggers['triggerid'] . '&parent_discoveryid=' . $db_triggers['parent_itemid'] . '&hostid=' . $db_triggers['hostid']; } else { $link = 'triggers.php?form=update&triggerid=' . $db_triggers['triggerid'] . '&hostid=' . $db_triggers['hostid']; } $data['templates'][] = new CLink(CHtml::encode($db_triggers['name']), $link, 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } $tmp_triggerid = $db_triggers['templateid']; } while ($tmp_triggerid != 0); $data['templates'] = array_reverse($data['templates']); array_shift($data['templates']); $data['limited'] = $data['trigger']['templateid'] != 0; // select first host from triggers if gived not match $hosts = $data['trigger']['hosts']; if (count($hosts) > 0 && !in_array(array('hostid' => $data['hostid']), $hosts)) { $host = reset($hosts); $data['hostid'] = $host['hostid']; } } if (!empty($data['triggerid']) && !isset($_REQUEST['form_refresh']) || $data['limited']) { $data['expression'] = explode_exp($data['trigger']['expression']); if (!$data['limited'] || !isset($_REQUEST['form_refresh'])) { $data['description'] = $data['trigger']['description']; $data['type'] = $data['trigger']['type']; $data['priority'] = $data['trigger']['priority']; $data['status'] = $data['trigger']['status']; $data['comments'] = $data['trigger']['comments']; $data['url'] = $data['trigger']['url']; $db_triggers = DBselect('SELECT t.triggerid,t.description' . ' FROM triggers t,trigger_depends d' . ' WHERE t.triggerid=d.triggerid_up' . ' AND d.triggerid_down=' . zbx_dbstr($data['triggerid'])); while ($trigger = DBfetch($db_triggers)) { if (uint_in_array($trigger['triggerid'], $data['dependencies'])) { continue; } array_push($data['dependencies'], $trigger['triggerid']); } } } if ($data['input_method'] == IM_TREE) { $analyze = analyzeExpression($data['expression']); if ($analyze !== false) { list($data['outline'], $data['eHTMLTree']) = $analyze; if ($exprAction !== null && $data['eHTMLTree'] != null) { $new_expr = remakeExpression($data['expression'], $_REQUEST['expr_target_single'], $exprAction, $data['expr_temp']); if ($new_expr !== false) { $data['expression'] = $new_expr; $analyze = analyzeExpression($data['expression']); if ($analyze !== false) { list($data['outline'], $data['eHTMLTree']) = $analyze; } else { show_messages(false, '', _('Expression Syntax Error.')); } $data['expr_temp'] = ''; } else { show_messages(false, '', _('Expression Syntax Error.')); } } $data['expression_field_name'] = 'expr_temp'; $data['expression_field_value'] = $data['expr_temp']; $data['expression_field_readonly'] = true; } else { show_messages(false, '', _('Expression Syntax Error.')); $data['input_method'] = IM_ESTABLISHED; } } if ($data['input_method'] != IM_TREE) { $data['expression_field_name'] = 'expression'; $data['expression_field_value'] = $data['expression']; $data['expression_field_readonly'] = $data['limited']; } if (empty($data['parent_discoveryid'])) { $data['db_dependencies'] = API::Trigger()->get(array('triggerids' => $data['dependencies'], 'output' => array('triggerid', 'flags', 'description'), 'preservekeys' => true, 'selectHosts' => array('hostid', 'name'))); foreach ($data['db_dependencies'] as &$dependency) { if (count($dependency['hosts']) > 1) { order_result($dependency['hosts'], 'name', ZBX_SORT_UP); } $dependency['hosts'] = array_values($dependency['hosts']); $dependency['hostid'] = $dependency['hosts'][0]['hostid']; } unset($dependency); order_result($data['db_dependencies'], 'description'); } return $data; }
public static function parseMain($rules) { $triggersForDependencies = array(); if (!empty($rules['hosts']['updateExisting']) || !empty($rules['hosts']['createMissing']) || !empty($rules['templates']['createMissing']) || !empty($rules['templates']['updateExisting'])) { $xpath = new DOMXPath(self::$xml); $hosts = $xpath->query('hosts/host'); foreach ($hosts as $host) { $host_db = self::mapXML2arr($host, XML_TAG_HOST); if (!isset($host_db['status'])) { $host_db['status'] = HOST_STATUS_TEMPLATE; } $current_host = $host_db['status'] == HOST_STATUS_TEMPLATE ? API::Template()->exists($host_db) : API::Host()->exists($host_db); if (!$current_host && ($host_db['status'] == HOST_STATUS_TEMPLATE && empty($rules['templates']['createMissing']) || $host_db['status'] != HOST_STATUS_TEMPLATE && empty($rules['hosts']['createMissing']))) { continue; } if ($current_host && ($host_db['status'] == HOST_STATUS_TEMPLATE && empty($rules['templates']['updateExisting']) || $host_db['status'] != HOST_STATUS_TEMPLATE && empty($rules['hosts']['updateExisting']))) { continue; } // there were no host visible names in 1.8 if (!isset($host_db['name'])) { $host_db['name'] = $host_db['host']; } // host will have no interfaces - we will be creating them separately $host_db['interfaces'] = null; // it is possible, that data is imported from 1.8, where there was only one network interface per host /** * @todo when new XML format will be introduced, this check should be changed to XML version check */ $old_version_input = $host_db['status'] != HOST_STATUS_TEMPLATE; if ($old_version_input) { // rearranging host structure, so it would look more like 2.0 host $interfaces = array(); // the main interface is always "agent" type if (!is_null($host_db['ip'])) { $interfaces[] = array('main' => INTERFACE_PRIMARY, 'type' => INTERFACE_TYPE_AGENT, 'useip' => $host_db['useip'], 'ip' => $host_db['ip'], 'dns' => $host_db['dns'], 'port' => $host_db['port']); } // now we need to check if host had SNMP items. If it had, we need and SNMP interface for every different port. $items = $xpath->query('items/item', $host); $snmp_interface_ports_created = array(); foreach ($items as $item) { $item_db = self::mapXML2arr($item, XML_TAG_ITEM); if (($item_db['type'] == ITEM_TYPE_SNMPV1 || $item_db['type'] == ITEM_TYPE_SNMPV2C || $item_db['type'] == ITEM_TYPE_SNMPV3) && !isset($snmp_interface_ports_created[$item_db['snmp_port']])) { $interfaces[] = array('main' => INTERFACE_PRIMARY, 'type' => INTERFACE_TYPE_SNMP, 'useip' => $host_db['useip'], 'ip' => $host_db['ip'], 'dns' => $host_db['dns'], 'port' => $item_db['snmp_port']); $snmp_interface_ports_created[$item_db['snmp_port']] = 1; } } unset($snmp_interface_ports_created); // it was a temporary variable // we ned to add ipmi interface if at least one ipmi item exists foreach ($items as $item) { $item_db = self::mapXML2arr($item, XML_TAG_ITEM); if ($item_db['type'] == ITEM_TYPE_IPMI) { // when saving a host in 1.8, it's possible to set useipmi=1 and not to fill an IP address // we were not really sure what to do with this host, // and decided to take host IP address instead and show info message about this if ($host_db['ipmi_ip'] == '') { $ipmi_ip = $host_db['ip']; info(_s('Host "%s" has "useipmi" parameter checked, but has no "ipmi_ip" parameter! Using host IP address as an address for IPMI interface.', $host_db['host'])); } else { $ipmi_ip = $host_db['ipmi_ip']; } $interfaces[] = array('main' => INTERFACE_PRIMARY, 'type' => INTERFACE_TYPE_IPMI, 'useip' => INTERFACE_USE_DNS, 'ip' => '', 'dns' => $ipmi_ip, 'port' => $host_db['ipmi_port']); // we need only one ipmi interface break; } } } if ($current_host) { $options = array('filter' => array('host' => $host_db['host']), 'output' => API_OUTPUT_EXTEND, 'editable' => 1, 'selectInterfaces' => API_OUTPUT_EXTEND); if ($host_db['status'] == HOST_STATUS_TEMPLATE) { $current_host = API::Template()->get($options); } else { $current_host = API::Host()->get($options); } if (empty($current_host)) { throw new Exception(_s('No permission for host "%1$s".', $host_db['host'])); } else { $current_host = reset($current_host); } // checking if host already exists - then some of the interfaces may not need to be created if ($host_db['status'] != HOST_STATUS_TEMPLATE) { // for every interface we got based on XML foreach ($interfaces as $i => $interface_db) { // checking every interface of current host foreach ($current_host['interfaces'] as $interface) { // if all parameters of interface are identical if ($interface['type'] == $interface_db['type'] && $interface['ip'] == $interface_db['ip'] && $interface['dns'] == $interface_db['dns'] && $interface['port'] == $interface_db['port'] && $interface['useip'] == $interface_db['useip']) { // this interface is the same as existing one! $interfaces[$i]['interfaceid'] = $interface['interfaceid']; break; } } } } $interfaces_created_with_host = false; } else { if ($host_db['status'] != HOST_STATUS_TEMPLATE) { $host_db['interfaces'] = $interfaces; $interfaces_created_with_host = true; } } // HOST GROUPS {{{ $groups = $xpath->query('groups/group', $host); $host_db['groups'] = array(); $groups_to_parse = array(); foreach ($groups as $group) { $groups_to_parse[] = array('name' => $group->nodeValue); } if (empty($groups_to_parse)) { $groups_to_parse[] = array('name' => ZBX_DEFAULT_IMPORT_HOST_GROUP); } foreach ($groups_to_parse as $group) { $current_group = API::HostGroup()->exists($group); if ($current_group) { $options = array('filter' => $group, 'output' => API_OUTPUT_EXTEND, 'editable' => 1); $current_group = API::HostGroup()->get($options); if (empty($current_group)) { throw new Exception(_s('No permissions for group "%1$s".', $group['name'])); } $host_db['groups'][] = reset($current_group); } else { $result = API::HostGroup()->create($group); if (!$result) { throw new Exception(); } $options = array('groupids' => $result['groupids'], 'output' => API_OUTPUT_EXTEND); $new_group = API::HostGroup()->get($options); $host_db['groups'][] = reset($new_group); } } // }}} HOST GROUPS // MACROS $macros = $xpath->query('macros/macro', $host); if ($macros->length > 0) { $host_db['macros'] = array(); foreach ($macros as $macro) { $host_db['macros'][] = self::mapXML2arr($macro, XML_TAG_MACRO); } } // }}} MACROS // host inventory if ($old_version_input) { if (!isset($host_db['inventory'])) { $host_db['inventory'] = array(); } $inventoryNode = $xpath->query('host_profile/*', $host); if ($inventoryNode->length > 0) { foreach ($inventoryNode as $field) { $newInventoryName = self::mapInventoryName($field->nodeName); $host_db['inventory'][$newInventoryName] = $field->nodeValue; } } $inventoryNodeExt = $xpath->query('host_profiles_ext/*', $host); if ($inventoryNodeExt->length > 0) { foreach ($inventoryNodeExt as $field) { $newInventoryName = self::mapInventoryName($field->nodeName); if (isset($host_db['inventory'][$newInventoryName]) && $field->nodeValue !== '') { $host_db['inventory'][$newInventoryName] .= "\r\n\r\n"; $host_db['inventory'][$newInventoryName] .= $field->nodeValue; } else { $host_db['inventory'][$newInventoryName] = $field->nodeValue; } } } $host_db['inventory_mode'] = isset($host_db['inventory']) ? HOST_INVENTORY_MANUAL : HOST_INVENTORY_DISABLED; } // HOSTS if (isset($host_db['proxy_hostid'])) { $proxy_exists = API::Proxy()->get(array('proxyids' => $host_db['proxy_hostid'])); if (empty($proxy_exists)) { $host_db['proxy_hostid'] = 0; } } if ($current_host && (!empty($rules['hosts']['updateExisting']) || !empty($rules['templates']['updateExisting']))) { if ($host_db['status'] == HOST_STATUS_TEMPLATE) { $host_db['templateid'] = $current_host['templateid']; $result = API::Template()->update($host_db); $current_hostid = $current_host['templateid']; } else { $host_db['hostid'] = $current_host['hostid']; $result = API::Host()->update($host_db); $current_hostid = $current_host['hostid']; } if (!$result) { throw new Exception(); } } if (!$current_host && (!empty($rules['hosts']['createMissing']) || !empty($rules['templates']['createMissing']))) { if ($host_db['status'] == HOST_STATUS_TEMPLATE) { $result = API::Template()->create($host_db); if (!$result) { throw new Exception(); } $current_hostid = reset($result['templateids']); } else { $result = API::Host()->create($host_db); if (!$result) { throw new Exception(); } $current_hostid = reset($result['hostids']); } } $current_hostname = $host_db['host']; // TEMPLATES {{{ if (!empty($rules['templateLinkage']['createMissing'])) { $templates = $xpath->query('templates/template', $host); $templateLinkage = array(); foreach ($templates as $template) { $options = array('filter' => array('host' => $template->nodeValue), 'output' => array('templateid'), 'editable' => true); $current_template = API::Template()->get($options); if (empty($current_template)) { throw new Exception(_s('No permission for template "%1$s".', $template->nodeValue)); } $current_template = reset($current_template); $templateLinkage[] = $current_template; } if ($templateLinkage) { $result = API::Template()->massAdd(array('hosts' => array('hostid' => $current_hostid), 'templates' => $templateLinkage)); if (!$result) { throw new Exception(); } } } // }}} TEMPLATES // ITEMS {{{ if (!empty($rules['items']['updateExisting']) || !empty($rules['items']['createMissing'])) { $items = $xpath->query('items/item', $host); // if this is an export from 1.8, we need to make some adjustments to items if ($old_version_input) { if (!$interfaces_created_with_host) { // if host had another interfaces, we are not touching them: they remain as is foreach ($interfaces as $i => $interface) { // interface was not already created if (!isset($interface['interfaceid'])) { // creating interface $interface['hostid'] = $current_hostid; $ids = API::HostInterface()->create($interface); if ($ids === false) { throw new Exception(); } $interfaces[$i]['interfaceid'] = reset($ids['interfaceids']); } } } else { $options = array('hostids' => $current_hostid, 'output' => API_OUTPUT_EXTEND); $interfaces = API::HostInterface()->get($options); } // we must know interface ids to assign them to items $agent_interface_id = null; $ipmi_interface_id = null; $snmp_interfaces = array(); // hash 'port' => 'iterfaceid' foreach ($interfaces as $interface) { switch ($interface['type']) { case INTERFACE_TYPE_AGENT: $agent_interface_id = $interface['interfaceid']; break; case INTERFACE_TYPE_IPMI: $ipmi_interface_id = $interface['interfaceid']; break; case INTERFACE_TYPE_SNMP: $snmp_interfaces[$interface['port']] = $interface['interfaceid']; break; } } } foreach ($items as $item) { $item_db = self::mapXML2arr($item, XML_TAG_ITEM); $item_db['hostid'] = $current_hostid; // item needs interfaces if ($old_version_input) { // 'snmp_port' column was renamed to 'port' if ($item_db['snmp_port'] != 0) { // zabbix agent items have no ports $item_db['port'] = $item_db['snmp_port']; } unset($item_db['snmp_port']); // assigning appropriate interface depending on item type switch ($item_db['type']) { // zabbix agent interface case ITEM_TYPE_ZABBIX: case ITEM_TYPE_SIMPLE: case ITEM_TYPE_EXTERNAL: case ITEM_TYPE_SSH: case ITEM_TYPE_TELNET: $item_db['interfaceid'] = $agent_interface_id; break; // snmp interface // snmp interface case ITEM_TYPE_SNMPV1: case ITEM_TYPE_SNMPV2C: case ITEM_TYPE_SNMPV3: // for an item with different port - different interface $item_db['interfaceid'] = $snmp_interfaces[$item_db['port']]; break; case ITEM_TYPE_IPMI: $item_db['interfaceid'] = $ipmi_interface_id; break; // no interfaces required for these item types // no interfaces required for these item types case ITEM_TYPE_HTTPTEST: case ITEM_TYPE_CALCULATED: case ITEM_TYPE_AGGREGATE: case ITEM_TYPE_INTERNAL: case ITEM_TYPE_ZABBIX_ACTIVE: case ITEM_TYPE_TRAPPER: case ITEM_TYPE_DB_MONITOR: $item_db['interfaceid'] = null; break; } $item_db['key_'] = self::convertOldSimpleKey($item_db['key_']); } $options = array('filter' => array('hostid' => $item_db['hostid'], 'key_' => $item_db['key_']), 'webitems' => 1, 'output' => API_OUTPUT_EXTEND, 'editable' => 1); $current_item = API::Item()->get($options); $current_item = reset($current_item); if (!$current_item && empty($rules['items']['createMissing'])) { info(_s('Item "%1$s" skipped - user rule.', $item_db['key_'])); continue; // break if not update updateExisting } if ($current_item && empty($rules['items']['updateExisting'])) { info(_s('Item "%1$s" skipped - user rule.', $item_db['key_'])); continue; // break if not update updateExisting } // ITEM APPLICATIONS {{{ $applications = $xpath->query('applications/application', $item); $item_applications = array(); $applications_to_add = array(); $applicationsIds = array(); foreach ($applications as $application) { $application_db = array('name' => $application->nodeValue, 'hostid' => $current_hostid); $current_application = API::Application()->get(array('filter' => $application_db, 'output' => API_OUTPUT_EXTEND)); $applicationValue = reset($current_application); if ($current_application) { if (empty($item_applications)) { $item_applications = $current_application; $applicationsIds[] = $applicationValue['applicationid']; } else { if (!in_array($applicationValue['applicationid'], $applicationsIds)) { $item_applications = array_merge($item_applications, $current_application); $applicationsIds[] = $applicationValue['applicationid']; } } } else { $applications_to_add[] = $application_db; } } if (!empty($applications_to_add)) { $result = API::Application()->create($applications_to_add); if (!$result) { throw new Exception(); } $options = array('applicationids' => $result['applicationids'], 'output' => API_OUTPUT_EXTEND); $new_applications = API::Application()->get($options); $item_applications = array_merge($item_applications, $new_applications); } // }}} ITEM APPLICATIONS if ($current_item && !empty($rules['items']['updateExisting'])) { $item_db['itemid'] = $current_item['itemid']; $result = API::Item()->update($item_db); if (!$result) { throw new Exception(); } $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND); $current_item = API::Item()->get($options); } if (!$current_item && !empty($rules['items']['createMissing'])) { $result = API::Item()->create($item_db); if (!$result) { throw new Exception(); } $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND); $current_item = API::Item()->get($options); } if (!empty($item_applications)) { $r = API::Application()->massAdd(array('applications' => $item_applications, 'items' => $current_item)); if ($r === false) { throw new Exception(); } } } } // }}} ITEMS // TRIGGERS {{{ if (!empty($rules['triggers']['updateExisting']) || !empty($rules['triggers']['createMissing'])) { $triggers = $xpath->query('triggers/trigger', $host); $triggers_to_add = array(); $triggers_to_upd = array(); foreach ($triggers as $trigger) { $trigger_db = self::mapXML2arr($trigger, XML_TAG_TRIGGER); if ($old_version_input) { $expressionPart = explode(':', $trigger_db['expression']); $keyName = explode(',', $expressionPart[1], 2); if (count($keyName) == 2) { $keyValue = explode('.', $keyName[1], 2); $key = $keyName[0] . "," . $keyValue[0]; if (in_array($keyName[0], self::$oldKeys) || in_array($keyName[0], self::$oldKeysPref)) { $trigger_db['expression'] = str_replace($key, self::convertOldSimpleKey($key), $trigger_db['expression']); } } } // {HOSTNAME} is here for backward compatibility $trigger_db['expression'] = str_replace('{{HOSTNAME}:', '{' . $host_db['host'] . ':', $trigger_db['expression']); $trigger_db['expression'] = str_replace('{{HOST.HOST}:', '{' . $host_db['host'] . ':', $trigger_db['expression']); $trigger_db['hostid'] = $current_hostid; if ($current_trigger = API::Trigger()->exists($trigger_db)) { $ctriggers = API::Trigger()->get(array('filter' => array('description' => $trigger_db['description']), 'hostids' => $current_hostid, 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); $current_trigger = false; foreach ($ctriggers as $ct) { $tmp_exp = explode_exp($ct['expression']); if (strcmp($trigger_db['expression'], $tmp_exp) == 0) { $current_trigger = $ct; break; } } if (!$current_trigger) { throw new Exception(_s('No permission for trigger "%s".', $trigger_db['description'])); } } unset($trigger_db['hostid']); if (!$current_trigger && empty($rules['triggers']['createMissing'])) { info(_s('Trigger "%1$s" skipped - user rule.', $trigger_db['description'])); continue; // break if not update updateExisting } if ($current_trigger && empty($rules['triggers']['updateExisting'])) { info(_s('Trigger "%1$s" skipped - user rule.', $trigger_db['description'])); continue; // break if not update updateExisting } if ($current_trigger && !empty($rules['triggers']['updateExisting'])) { $trigger_db['triggerid'] = $current_trigger['triggerid']; $triggers_to_upd[] = $trigger_db; } if (!$current_trigger && !empty($rules['triggers']['createMissing'])) { $triggers_to_add[] = $trigger_db; } } if (!empty($triggers_to_upd)) { $result = API::Trigger()->update($triggers_to_upd); if (!$result) { throw new Exception(); } $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND); $r = API::Trigger()->get($options); $triggersForDependencies = array_merge($triggersForDependencies, $r); } if (!empty($triggers_to_add)) { $result = API::Trigger()->create($triggers_to_add); if (!$result) { throw new Exception(); } $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND); $r = API::Trigger()->get($options); $triggersForDependencies = array_merge($triggersForDependencies, $r); } } // }}} TRIGGERS // GRAPHS {{{ if (!empty($rules['graphs']['updateExisting']) || !empty($rules['graphs']['createMissing'])) { $graphs = $xpath->query('graphs/graph', $host); $graphs_to_add = array(); $graphs_to_upd = array(); foreach ($graphs as $graph) { // GRAPH ITEMS {{{ $gitems = $xpath->query('graph_elements/graph_element', $graph); $graph_hostids = array(); $graph_items = array(); foreach ($gitems as $gitem) { $gitem_db = self::mapXML2arr($gitem, XML_TAG_GRAPH_ELEMENT); $data = explode(':', $gitem_db['host_key_']); $gitem_host = array_shift($data); // {HOSTNAME} is here for backward compatibility $gitem_db['host'] = $gitem_host == '{HOSTNAME}' ? $host_db['host'] : $gitem_host; $gitem_db['host'] = $gitem_host == '{HOST.HOST}' ? $host_db['host'] : $gitem_host; if ($old_version_input) { $data[0] = self::convertOldSimpleKey($data[0]); } $gitem_db['key_'] = implode(':', $data); if ($current_item = API::Item()->exists($gitem_db)) { $current_item = API::Item()->get(array('filter' => array('key_' => $gitem_db['key_']), 'webitems' => 1, 'host' => $gitem_db['host'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); if (empty($current_item)) { throw new Exception(_s('No permission for item "%1$s".', $gitem_db['key_'])); } $current_item = reset($current_item); $graph_hostids[] = $current_item['hostid']; $gitem_db['itemid'] = $current_item['itemid']; $graph_items[] = $gitem_db; } else { throw new Exception(_s('Item "%1$s" does not exist.', $gitem_db['host_key_'])); } } // }}} GRAPH ITEMS $graph_db = self::mapXML2arr($graph, XML_TAG_GRAPH); $graph_db['hostids'] = $graph_hostids; // do we need to show the graph legend, after it is imported? // in 1.8, this setting was present only for pie and exploded graphs // for other graph types we are always showing the legend if ($graph_db['graphtype'] != GRAPH_TYPE_PIE && $graph_db['graphtype'] != GRAPH_TYPE_EXPLODED) { $graph_db['show_legend'] = 1; } $current_graph = API::Graph()->exists($graph_db); if ($current_graph) { $current_graph = API::Graph()->get(array('filter' => array('name' => $graph_db['name']), 'hostids' => $graph_db['hostids'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); if (empty($current_graph)) { throw new Exception(_s('No permission for graph "%1$s".', $graph_db['name'])); } $current_graph = reset($current_graph); } if (!$current_graph && empty($rules['graphs']['createMissing'])) { info(_s('Graph "%1$s" skipped - user rule.', $graph_db['name'])); continue; // break if not update updateExisting } if ($current_graph && empty($rules['graphs']['updateExisting'])) { info(_s('Graph "%1$s" skipped - user rule.', $graph_db['name'])); continue; // break if not update updateExisting } if (!isset($graph_db['ymin_type'])) { throw new Exception(_s('No "ymin_type" field for graph "%s".', $graph_db['name'])); } if (!isset($graph_db['ymax_type'])) { throw new Exception(_s('No "ymax_type" field for graph "%s".', $graph_db['name'])); } if ($graph_db['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) { $item_data = explode(':', $graph_db['ymin_item_key'], 2); if (count($item_data) < 2) { throw new Exception(_s('Incorrect y min item for graph "%1$s".', $graph_db['name'])); } if (!($item = get_item_by_key($item_data[1], $item_data[0]))) { throw new Exception(_s('Missing item "%1$s" for host "%2$s".', $graph_db['ymin_item_key'], $host_db['host'])); } $graph_db['ymin_itemid'] = $item['itemid']; } if ($graph_db['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) { $item_data = explode(':', $graph_db['ymax_item_key'], 2); if (count($item_data) < 2) { throw new Exception(_s('Incorrect y max item for graph "%1$s".', $graph_db['name'])); } if (!($item = get_item_by_key($item_data[1], $item_data[0]))) { throw new Exception(_s('Missing item "%1$s" for host "%2$s".', $graph_db['ymax_item_key'], $host_db['host'])); } $graph_db['ymax_itemid'] = $item['itemid']; } $graph_db['gitems'] = $graph_items; if ($current_graph) { $graph_db['graphid'] = $current_graph['graphid']; $graphs_to_upd[] = $graph_db; } else { $graphs_to_add[] = $graph_db; } } if (!empty($graphs_to_add)) { $r = API::Graph()->create($graphs_to_add); if ($r === false) { throw new Exception(); } } if (!empty($graphs_to_upd)) { $r = API::Graph()->update($graphs_to_upd); if ($r === false) { throw new Exception(); } } } // SCREENS if (!empty($rules['screens']['updateExisting']) || !empty($rules['screens']['createMissing'])) { $screens_node = $xpath->query('screens', $host); if ($screens_node->length > 0) { $importScreens = self::XMLtoArray($screens_node->item(0)); foreach ($importScreens as $screen) { $current_screen = API::TemplateScreen()->get(array('filter' => array('name' => $screen['name']), 'templateids' => $current_hostid, 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); $current_screen = reset($current_screen); if (!$current_screen && empty($rules['screens']['createMissing'])) { info(_s('Screen "%1$s" skipped - user rule.', $screen['name'])); continue; } if ($current_screen && empty($rules['screens']['updateExisting'])) { info(_s('Screen "%1$s" skipped - user rule.', $screen['name'])); continue; } if (isset($screen['screenitems'])) { foreach ($screen['screenitems'] as &$screenitem) { $nodeCaption = isset($screenitem['resourceid']['node']) ? $screenitem['resourceid']['node'] . ':' : ''; if (!isset($screenitem['resourceid'])) { $screenitem['resourceid'] = 0; } if (is_array($screenitem['resourceid'])) { switch ($screenitem['resourcetype']) { case SCREEN_RESOURCE_GRAPH: $db_graphs = API::Graph()->getObjects($screenitem['resourceid']); if (empty($db_graphs)) { $error = _s('Cannot find graph "%1$s" used in screen "%2$s".', $nodeCaption . $screenitem['resourceid']['host'] . ':' . $screenitem['resourceid']['name'], $screen['name']); throw new Exception($error); } $tmp = reset($db_graphs); $screenitem['resourceid'] = $tmp['graphid']; break; case SCREEN_RESOURCE_SIMPLE_GRAPH: case SCREEN_RESOURCE_PLAIN_TEXT: $db_items = API::Item()->getObjects($screenitem['resourceid']); if (empty($db_items)) { $error = _s('Cannot find item "%1$s" used in screen "%2$s".', $nodeCaption . $screenitem['resourceid']['host'] . ':' . $screenitem['resourceid']['key_'], $screen['name']); throw new Exception($error); } $tmp = reset($db_items); $screenitem['resourceid'] = $tmp['itemid']; break; default: $screenitem['resourceid'] = 0; break; } } } } $screen['templateid'] = $current_hostid; if ($current_screen) { $screen['screenid'] = $current_screen['screenid']; $result = API::TemplateScreen()->update($screen); if (!$result) { throw new Exception(_('Cannot update screen.')); } info('[' . $current_hostname . '] ' . _s('Screen "%1$s" updated.', $screen['name'])); } else { $result = API::TemplateScreen()->create($screen); if (!$result) { throw new Exception(_('Cannot create screen.')); } info('[' . $current_hostname . '] ' . _s('Screen "%1$s" added.', $screen['name'])); } } } } } // DEPENDENCIES $dependencies = $xpath->query('dependencies/dependency'); if ($dependencies->length > 0) { $triggersForDependencies = zbx_objectValues($triggersForDependencies, 'triggerid'); $triggersForDependencies = array_flip($triggersForDependencies); $newDependencies = array(); foreach ($dependencies as $dependency) { $triggerDescription = $dependency->getAttribute('description'); $currentTrigger = get_trigger_by_description($triggerDescription); if ($currentTrigger && isset($triggersForDependencies[$currentTrigger['triggerid']])) { $dependsOnList = $xpath->query('depends', $dependency); foreach ($dependsOnList as $dependsOn) { $depTrigger = get_trigger_by_description($dependsOn->nodeValue); if ($depTrigger['triggerid']) { $newDependencies[] = array('triggerid' => $currentTrigger['triggerid'], 'dependsOnTriggerid' => $depTrigger['triggerid']); } } } } if ($newDependencies) { API::Trigger()->addDependencies($newDependencies); } } } }
function get_triggers_unacknowledged($db_element, $count_problems = null, $ack = false) { $elements = array('hosts' => array(), 'hosts_groups' => array(), 'triggers' => array()); get_map_elements($db_element, $elements); if (empty($elements['hosts_groups']) && empty($elements['hosts']) && empty($elements['triggers'])) { return 0; } $config = select_config(); $options = array('nodeids' => get_current_nodeid(), 'monitored' => true, 'countOutput' => true, 'filter' => array(), 'limit' => $config['search_limit'] + 1); if ($ack) { $options['withAcknowledgedEvents'] = 1; } else { $options['withUnacknowledgedEvents'] = 1; } if ($count_problems) { $options['filter']['value'] = TRIGGER_VALUE_TRUE; } if (!empty($elements['hosts_groups'])) { $options['groupids'] = array_unique($elements['hosts_groups']); } if (!empty($elements['hosts'])) { $options['hostids'] = array_unique($elements['hosts']); } if (!empty($elements['triggers'])) { $options['triggerids'] = array_unique($elements['triggers']); } return API::Trigger()->get($options); }
/** * Delete triggers. * * @param int|string|array $triggerIds array with trigger ids * @param bool $nopermissions * * @return array */ public function delete($triggerIds, $nopermissions = false) { if (empty($triggerIds)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $triggerIds = zbx_toArray($triggerIds); $triggerPrototypeIds = $triggerIds; $delTriggers = $this->get(array('triggerids' => $triggerIds, 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'preservekeys' => true)); // TODO: remove $nopermissions hack if (!$nopermissions) { foreach ($triggerIds as $triggerId) { if (!isset($delTriggers[$triggerId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } if ($delTriggers[$triggerId]['templateid'] != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot delete templated trigger "%1$s:%2$s".', $delTriggers[$triggerId]['description'], explode_exp($delTriggers[$triggerId]['expression']))); } } } // get child triggers $parentTriggerids = $triggerIds; do { $dbItems = DBselect('SELECT triggerid FROM triggers WHERE ' . dbConditionInt('templateid', $parentTriggerids)); $parentTriggerids = array(); while ($dbTrigger = DBfetch($dbItems)) { $parentTriggerids[] = $dbTrigger['triggerid']; $triggerIds[$dbTrigger['triggerid']] = $dbTrigger['triggerid']; } } while (!empty($parentTriggerids)); // select all triggers which are deleted (include childs) $delTriggers = $this->get(array('triggerids' => $triggerIds, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => array('name'))); // created triggers $createdTriggers = array(); $sql = 'SELECT triggerid FROM trigger_discovery WHERE ' . dbConditionInt('parent_triggerid', $triggerIds); $dbTriggers = DBselect($sql); while ($trigger = DBfetch($dbTriggers)) { $createdTriggers[$trigger['triggerid']] = $trigger['triggerid']; } if (!empty($createdTriggers)) { $result = API::Trigger()->delete($createdTriggers, true); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete triggers created by low level discovery.')); } } // TODO: REMOVE info foreach ($delTriggers as $trigger) { info(_s('Deleted: Trigger prototype "%1$s" on "%2$s".', $trigger['description'], implode(', ', zbx_objectValues($trigger['hosts'], 'name')))); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_TRIGGER_PROTOTYPE, $trigger['triggerid'], $trigger['description'] . ':' . $trigger['expression'], null, null, null); } DB::delete('triggers', array('triggerid' => $triggerIds)); return array('triggerids' => $triggerPrototypeIds); }
} $triggersEventCount = array(); // get 100 triggerids with max event count $sql = 'SELECT e.objectid,count(distinct e.eventid) AS cnt_event' . ' FROM triggers t,events e' . ' WHERE t.triggerid=e.objectid' . ' AND e.source=' . EVENT_SOURCE_TRIGGERS . ' AND e.object=' . EVENT_OBJECT_TRIGGER . ' AND e.clock>' . (time() - $time_dif); // add permission filter if (CWebUser::getType() != USER_TYPE_SUPER_ADMIN) { $userid = CWebUser::$data['userid']; $userGroups = getUserGroupsByUserId($userid); $sql .= ' AND EXISTS (' . 'SELECT NULL' . ' FROM functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE t.triggerid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY f.triggerid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ')'; } $sql .= ' AND ' . dbConditionInt('t.flags', array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED)) . ' GROUP BY e.objectid' . ' ORDER BY cnt_event desc'; $result = DBselect($sql, 100); while ($row = DBfetch($result)) { $triggersEventCount[$row['objectid']] = $row['cnt_event']; } $triggers = API::Trigger()->get(array('triggerids' => array_keys($triggersEventCount), 'output' => array('triggerid', 'description', 'expression', 'priority', 'flags', 'url', 'lastchange'), 'selectHosts' => array('hostid', 'status', 'name'), 'selectItems' => array('itemid', 'hostid', 'name', 'key_', 'value_type'), 'expandDescription' => true, 'preservekeys' => true, 'nopermissions' => true)); $hostIds = array(); foreach ($triggers as $triggerId => $trigger) { $hostIds[$trigger['hosts'][0]['hostid']] = $trigger['hosts'][0]['hostid']; $triggers[$triggerId]['cnt_event'] = $triggersEventCount[$triggerId]; } CArrayHelper::sort($triggers, array(array('field' => 'cnt_event', 'order' => ZBX_SORT_DOWN), 'host', 'description', 'priority')); $hosts = API::Host()->get(array('output' => array('hostid', 'status'), 'hostids' => $hostIds, 'selectGraphs' => API_OUTPUT_COUNT, 'selectScreens' => API_OUTPUT_COUNT, 'preservekeys' => true)); $scripts = API::Script()->getScriptsByHosts($hostIds); $monitoredHostIds = array(); foreach ($triggers as $trigger) { foreach ($trigger['hosts'] as $host) { if ($host['status'] == HOST_STATUS_MONITORED) { $monitoredHostIds[$host['hostid']] = true; } }
function condition_value2str($conditiontype, $value) { switch ($conditiontype) { case CONDITION_TYPE_HOST_GROUP: $groups = API::HostGroup()->get(array('groupids' => $value, 'output' => array('name'), 'nodeids' => get_current_nodeid(true), 'limit' => 1)); if ($groups) { $group = reset($groups); $str_val = ''; if (id2nodeid($value) != get_current_nodeid()) { $str_val = get_node_name_by_elid($value, true, NAME_DELIMITER); } $str_val .= $group['name']; } else { return _('Unknown'); } break; case CONDITION_TYPE_TRIGGER: $trigs = API::Trigger()->get(array('triggerids' => $value, 'expandDescription' => true, 'output' => array('description'), 'selectHosts' => array('name'), 'nodeids' => get_current_nodeid(true), 'limit' => 1)); if ($trigs) { $trig = reset($trigs); $host = reset($trig['hosts']); $str_val = ''; if (id2nodeid($value) != get_current_nodeid()) { $str_val = get_node_name_by_elid($value, true, NAME_DELIMITER); } $str_val .= $host['name'] . NAME_DELIMITER . $trig['description']; } else { return _('Unknown'); } break; case CONDITION_TYPE_HOST: case CONDITION_TYPE_TEMPLATE: if ($host = get_host_by_hostid($value)) { $str_val = ''; if (id2nodeid($value) != get_current_nodeid()) { $str_val = get_node_name_by_elid($value, true, NAME_DELIMITER); } $str_val .= $host['name']; } else { return _('Unknown'); } break; case CONDITION_TYPE_TRIGGER_NAME: case CONDITION_TYPE_HOST_METADATA: case CONDITION_TYPE_HOST_NAME: $str_val = $value; break; case CONDITION_TYPE_TRIGGER_VALUE: $str_val = trigger_value2str($value); break; case CONDITION_TYPE_TRIGGER_SEVERITY: $str_val = getSeverityCaption($value); break; case CONDITION_TYPE_TIME_PERIOD: $str_val = $value; break; case CONDITION_TYPE_MAINTENANCE: $str_val = _('maintenance'); break; case CONDITION_TYPE_NODE: if ($node = get_node_by_nodeid($value)) { $str_val = $node['name']; } else { return _('Unknown'); } break; case CONDITION_TYPE_DRULE: if ($drule = get_discovery_rule_by_druleid($value)) { $str_val = $drule['name']; } else { return _('Unknown'); } break; case CONDITION_TYPE_DCHECK: $row = DBfetch(DBselect('SELECT dr.name,c.dcheckid,c.type,c.key_,c.ports' . ' FROM drules dr,dchecks c' . ' WHERE dr.druleid=c.druleid' . ' AND c.dcheckid=' . zbx_dbstr($value))); if ($row) { $str_val = $row['name'] . NAME_DELIMITER . discovery_check2str($row['type'], $row['key_'], $row['ports']); } else { return _('Unknown'); } break; case CONDITION_TYPE_DOBJECT: $str_val = discovery_object2str($value); break; case CONDITION_TYPE_PROXY: if ($host = get_host_by_hostid($value)) { $str_val = $host['host']; } else { return _('Unknown'); } break; case CONDITION_TYPE_DHOST_IP: $str_val = $value; break; case CONDITION_TYPE_DSERVICE_TYPE: $str_val = discovery_check_type2str($value); break; case CONDITION_TYPE_DSERVICE_PORT: $str_val = $value; break; case CONDITION_TYPE_DSTATUS: $str_val = discovery_object_status2str($value); break; case CONDITION_TYPE_DUPTIME: $str_val = $value; break; case CONDITION_TYPE_DVALUE: $str_val = $value; break; case CONDITION_TYPE_EVENT_ACKNOWLEDGED: $str_val = $value ? _('Ack') : _('Not Ack'); break; case CONDITION_TYPE_APPLICATION: $str_val = $value; break; case CONDITION_TYPE_EVENT_TYPE: $str_val = eventType($value); break; default: return _('Unknown'); } return $str_val; }
/** * Prepare map elements data. * Calculate problem triggers and priorities. Populate map elements with automatic icon mapping, acknowledging and * recent change markers. * * @param array $sysmap * @param int $options * @param int $options['severity_min'] Minimum trigger severity, default value is maximal (Disaster) * * @return array */ function getSelementsInfo($sysmap, array $options = array()) { if (!isset($options['severity_min'])) { $options['severity_min'] = TRIGGER_SEVERITY_NOT_CLASSIFIED; } $config = select_config(); $showUnacknowledged = $config['event_ack_enable'] ? $sysmap['show_unack'] : EXTACK_OPTION_ALL; $triggerIdToSelementIds = array(); $subSysmapTriggerIdToSelementIds = array(); $hostGroupIdToSelementIds = array(); $hostIdToSelementIds = array(); if ($sysmap['sysmapid']) { $iconMap = API::IconMap()->get(array('sysmapids' => $sysmap['sysmapid'], 'selectMappings' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND)); $iconMap = reset($iconMap); } $hostsToGetInventories = array(); $selements = $sysmap['selements']; $selementIdToSubSysmaps = array(); foreach ($selements as $selementId => &$selement) { $selement['hosts'] = array(); $selement['triggers'] = array(); switch ($selement['elementtype']) { case SYSMAP_ELEMENT_TYPE_MAP: $sysmapIds = array($selement['elementid']); while (!empty($sysmapIds)) { $subSysmaps = API::Map()->get(array('sysmapids' => $sysmapIds, 'output' => array('sysmapid'), 'selectSelements' => API_OUTPUT_EXTEND, 'nopermissions' => true, 'preservekeys' => true)); if (!isset($selementIdToSubSysmaps[$selementId])) { $selementIdToSubSysmaps[$selementId] = array(); } $selementIdToSubSysmaps[$selementId] += $subSysmaps; $sysmapIds = array(); foreach ($subSysmaps as $subSysmap) { foreach ($subSysmap['selements'] as $subSysmapSelement) { switch ($subSysmapSelement['elementtype']) { case SYSMAP_ELEMENT_TYPE_MAP: $sysmapIds[] = $subSysmapSelement['elementid']; break; case SYSMAP_ELEMENT_TYPE_HOST_GROUP: $hostGroupIdToSelementIds[$subSysmapSelement['elementid']][$selementId] = $selementId; break; case SYSMAP_ELEMENT_TYPE_HOST: $hostIdToSelementIds[$subSysmapSelement['elementid']][$selementId] = $selementId; break; case SYSMAP_ELEMENT_TYPE_TRIGGER: $subSysmapTriggerIdToSelementIds[$subSysmapSelement['elementid']][$selementId] = $selementId; break; } } } } break; case SYSMAP_ELEMENT_TYPE_HOST_GROUP: $hostGroupId = $selement['elementid']; $hostGroupIdToSelementIds[$hostGroupId][$selementId] = $selementId; break; case SYSMAP_ELEMENT_TYPE_HOST: $hostId = $selement['elementid']; $hostIdToSelementIds[$hostId][$selementId] = $selementId; // if we have icon map applied, we need to get inventories for all hosts, // where automatic icon selection is enabled. if ($sysmap['iconmapid'] && $selement['use_iconmap']) { $hostsToGetInventories[] = $hostId; } break; case SYSMAP_ELEMENT_TYPE_TRIGGER: $triggerId = $selement['elementid']; $triggerIdToSelementIds[$triggerId][$selementId] = $selementId; break; } } unset($selement); // get host inventories if ($sysmap['iconmapid']) { $hostInventories = API::Host()->get(array('hostids' => $hostsToGetInventories, 'output' => array('hostid'), 'nopermissions' => true, 'preservekeys' => true, 'selectInventory' => API_OUTPUT_EXTEND)); } $allHosts = array(); if (!empty($hostIdToSelementIds)) { $hosts = API::Host()->get(array('hostids' => array_keys($hostIdToSelementIds), 'output' => array('name', 'status', 'maintenance_status', 'maintenanceid'), 'nopermissions' => true, 'preservekeys' => true)); $allHosts = array_merge($allHosts, $hosts); foreach ($hosts as $hostId => $host) { foreach ($hostIdToSelementIds[$hostId] as $selementId) { $selements[$selementId]['hosts'][$hostId] = $hostId; } } } $hostsFromHostGroups = array(); if (!empty($hostGroupIdToSelementIds)) { $hostsFromHostGroups = API::Host()->get(array('groupids' => array_keys($hostGroupIdToSelementIds), 'output' => array('name', 'status', 'maintenance_status', 'maintenanceid'), 'selectGroups' => array('groupid'), 'nopermissions' => true, 'preservekeys' => true)); foreach ($hostsFromHostGroups as $hostId => $host) { foreach ($host['groups'] as $group) { $groupId = $group['groupid']; if (isset($hostGroupIdToSelementIds[$groupId])) { foreach ($hostGroupIdToSelementIds[$groupId] as $selementId) { $selement =& $selements[$selementId]; $selement['hosts'][$hostId] = $hostId; // add hosts to hosts_map for trigger selection; if (!isset($hostIdToSelementIds[$hostId])) { $hostIdToSelementIds[$hostId] = array(); } $hostIdToSelementIds[$hostId][$selementId] = $selementId; unset($selement); } } } } $allHosts = array_merge($allHosts, $hostsFromHostGroups); } $allHosts = zbx_toHash($allHosts, 'hostid'); // get triggers data, triggers from current map, select all $allTriggers = array(); if (!empty($triggerIdToSelementIds)) { $triggerOptions = array('output' => array('triggerid', 'status', 'value', 'priority', 'lastchange', 'description', 'expression'), 'triggerids' => array_keys($triggerIdToSelementIds), 'filter' => array('state' => null), 'nopermissions' => true, 'preservekeys' => true); if ($showUnacknowledged) { $triggerOptions['selectLastEvent'] = array('acknowledged'); } $triggers = API::Trigger()->get($triggerOptions); $allTriggers = array_merge($allTriggers, $triggers); foreach ($triggers as $triggerId => $trigger) { foreach ($triggerIdToSelementIds[$triggerId] as $selementId) { $selements[$selementId]['triggers'][$triggerId] = $triggerId; } } } // triggers from submaps, skip dependent if (!empty($subSysmapTriggerIdToSelementIds)) { $triggerOptions = array('output' => array('triggerid', 'status', 'value', 'priority', 'lastchange', 'description', 'expression'), 'triggerids' => array_keys($subSysmapTriggerIdToSelementIds), 'filter' => array('state' => null), 'skipDependent' => true, 'nopermissions' => true, 'preservekeys' => true, 'only_true' => true); if ($showUnacknowledged) { $triggerOptions['selectLastEvent'] = array('acknowledged'); } $triggers = API::Trigger()->get($triggerOptions); $allTriggers = array_merge($allTriggers, $triggers); foreach ($triggers as $triggerId => $trigger) { foreach ($subSysmapTriggerIdToSelementIds[$triggerId] as $selementId) { $selements[$selementId]['triggers'][$triggerId] = $triggerId; } } } $monitoredHostIds = array(); foreach ($allHosts as $hostId => $host) { if ($host['status'] == HOST_STATUS_MONITORED) { $monitoredHostIds[$hostId] = $hostId; } } // triggers from all hosts/hostgroups, skip dependent if ($monitoredHostIds) { $triggerOptions = array('output' => array('triggerid', 'status', 'value', 'priority', 'lastchange', 'description', 'expression'), 'selectHosts' => array('hostid'), 'selectItems' => array('itemid'), 'hostids' => $monitoredHostIds, 'filter' => array('state' => null), 'monitored' => true, 'skipDependent' => true, 'nopermissions' => true, 'preservekeys' => true, 'only_true' => true); if ($showUnacknowledged) { $triggerOptions['selectLastEvent'] = array('acknowledged'); } $triggersFromMonitoredHosts = API::Trigger()->get($triggerOptions); foreach ($triggersFromMonitoredHosts as $triggerId => $trigger) { foreach ($trigger['hosts'] as $host) { $hostId = $host['hostid']; if (isset($hostIdToSelementIds[$hostId])) { foreach ($hostIdToSelementIds[$hostId] as $selementId) { $selements[$selementId]['triggers'][$triggerId] = $triggerId; } } } } $subSysmapHostApplicationFilters = getSelementHostApplicationFilters($selements, $selementIdToSubSysmaps, $hostsFromHostGroups); $selements = filterSysmapTriggers($selements, $subSysmapHostApplicationFilters, $triggersFromMonitoredHosts, $subSysmapTriggerIdToSelementIds); $allTriggers = array_merge($allTriggers, $triggersFromMonitoredHosts); } $allTriggers = zbx_toHash($allTriggers, 'triggerid'); $info = array(); foreach ($selements as $selementId => $selement) { $i = array('disabled' => 0, 'maintenance' => 0, 'problem' => 0, 'problem_unack' => 0, 'priority' => 0, 'trigger_disabled' => 0, 'latelyChanged' => false, 'ack' => true); foreach ($selement['hosts'] as $hostId) { $host = $allHosts[$hostId]; $last_hostid = $hostId; if ($host['status'] == HOST_STATUS_NOT_MONITORED) { $i['disabled']++; } elseif ($host['maintenance_status'] == HOST_MAINTENANCE_STATUS_ON) { $i['maintenance']++; } } foreach ($selement['triggers'] as $triggerId) { $trigger = $allTriggers[$triggerId]; if ($options['severity_min'] <= $trigger['priority']) { if ($trigger['status'] == TRIGGER_STATUS_DISABLED) { $i['trigger_disabled']++; } else { if ($trigger['value'] == TRIGGER_VALUE_TRUE) { $i['problem']++; $lastProblemId = $triggerId; if ($i['priority'] < $trigger['priority']) { $i['priority'] = $trigger['priority']; } } if ($showUnacknowledged && $trigger['lastEvent'] && !$trigger['lastEvent']['acknowledged']) { $i['problem_unack']++; } $i['latelyChanged'] |= time() - $trigger['lastchange'] < $config['blink_period']; } } } $i['ack'] = (bool) (!$i['problem_unack']); if ($sysmap['expandproblem'] && $i['problem'] == 1) { if (!isset($lastProblemId)) { $lastProblemId = null; } $i['problem_title'] = CMacrosResolverHelper::resolveTriggerName($allTriggers[$lastProblemId]); } if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST && $i['maintenance'] == 1) { $mnt = get_maintenance_by_maintenanceid($allHosts[$last_hostid]['maintenanceid']); $i['maintenance_title'] = $mnt['name']; } // replace default icons if (!$selement['iconid_on']) { $selement['iconid_on'] = $selement['iconid_off']; } if (!$selement['iconid_maintenance']) { $selement['iconid_maintenance'] = $selement['iconid_off']; } if (!$selement['iconid_disabled']) { $selement['iconid_disabled'] = $selement['iconid_off']; } switch ($selement['elementtype']) { case SYSMAP_ELEMENT_TYPE_MAP: $info[$selementId] = getMapsInfo($selement, $i, $showUnacknowledged); break; case SYSMAP_ELEMENT_TYPE_HOST_GROUP: $info[$selementId] = getHostGroupsInfo($selement, $i, $showUnacknowledged); break; case SYSMAP_ELEMENT_TYPE_HOST: $info[$selementId] = getHostsInfo($selement, $i, $showUnacknowledged); if ($sysmap['iconmapid'] && $selement['use_iconmap']) { $info[$selementId]['iconid'] = getIconByMapping($iconMap, $hostInventories[$selement['elementid']]); } break; case SYSMAP_ELEMENT_TYPE_TRIGGER: $info[$selementId] = getTriggersInfo($selement, $i, $showUnacknowledged); break; case SYSMAP_ELEMENT_TYPE_IMAGE: $info[$selementId] = getImagesInfo($selement); break; } } if ($sysmap['label_format'] == SYSMAP_LABEL_ADVANCED_OFF) { $hlabel = $hglabel = $tlabel = $mlabel = $sysmap['label_type'] == MAP_LABEL_TYPE_NAME; } else { $hlabel = $sysmap['label_type_host'] == MAP_LABEL_TYPE_NAME; $hglabel = $sysmap['label_type_hostgroup'] == MAP_LABEL_TYPE_NAME; $tlabel = $sysmap['label_type_trigger'] == MAP_LABEL_TYPE_NAME; $mlabel = $sysmap['label_type_map'] == MAP_LABEL_TYPE_NAME; } // get names if needed $elems = separateMapElements($sysmap); if (!empty($elems['sysmaps']) && $mlabel) { $subSysmaps = API::Map()->get(array('sysmapids' => zbx_objectValues($elems['sysmaps'], 'elementid'), 'nopermissions' => true, 'output' => array('name'))); $subSysmaps = zbx_toHash($subSysmaps, 'sysmapid'); foreach ($elems['sysmaps'] as $elem) { $info[$elem['selementid']]['name'] = $subSysmaps[$elem['elementid']]['name']; } } if (!empty($elems['hostgroups']) && $hglabel) { $hostgroups = API::HostGroup()->get(array('groupids' => zbx_objectValues($elems['hostgroups'], 'elementid'), 'nopermissions' => true, 'output' => array('name'))); $hostgroups = zbx_toHash($hostgroups, 'groupid'); foreach ($elems['hostgroups'] as $elem) { $info[$elem['selementid']]['name'] = $hostgroups[$elem['elementid']]['name']; } } if (!empty($elems['triggers']) && $tlabel) { foreach ($elems['triggers'] as $elem) { $info[$elem['selementid']]['name'] = CMacrosResolverHelper::resolveTriggerName($allTriggers[$elem['elementid']]); } } if (!empty($elems['hosts']) && $hlabel) { foreach ($elems['hosts'] as $elem) { $info[$elem['selementid']]['name'] = $allHosts[$elem['elementid']]['name']; } } return $info; }
throw new Exception(); } $hostNew = API::Host()->get(array('hostids' => $hostId, 'editable' => true, 'output' => API_OUTPUT_EXTEND)); $hostNew = reset($hostNew); add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_HOST, $hostNew['hostid'], $hostNew['host'], 'hosts', $hostOld, $hostNew); } if ($_REQUEST['form'] == 'full_clone') { $srcHostId = get_request('hostid'); if (!copyApplications($srcHostId, $hostId)) { throw new Exception(); } if (!copyItems($srcHostId, $hostId)) { throw new Exception(); } // clone triggers $triggers = API::Trigger()->get(array('output' => array('triggerid'), 'hostids' => $srcHostId, 'inherited' => false)); if ($triggers) { if (!copyTriggersToHosts(zbx_objectValues($triggers, 'triggerid'), $hostId, $srcHostId)) { throw new Exception(); } } // clone discovery rules $discoveryRules = API::DiscoveryRule()->get(array('output' => array('itemid'), 'hostids' => $srcHostId, 'inherited' => false)); if ($discoveryRules) { $copyDiscoveryRules = API::DiscoveryRule()->copy(array('discoveryids' => zbx_objectValues($discoveryRules, 'itemid'), 'hostids' => array($hostId))); if (!$copyDiscoveryRules) { throw new Exception(); } } $graphs = API::Graph()->get(array('hostids' => $srcHostId, 'selectItems' => array('type'), 'output' => API_OUTPUT_EXTEND, 'inherited' => false, 'selectHosts' => array('hostid'), 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); foreach ($graphs as $graph) {
/** * Get map 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 int $options['count'] count Hosts, returned column name is rowscount * @param string $options['pattern'] search hosts by pattern in host names * @param int $options['limit'] limit selection * @param string $options['sortorder'] * @param string $options['sortfield'] * * @return array|boolean Host data as array or false if error */ public function get(array $options = array()) { $result = array(); $userType = self::$userData['type']; $sqlParts = array('select' => array('sysmaps' => 's.sysmapid'), 'from' => array('sysmaps' => 'sysmaps s'), 'where' => array(), 'order' => array(), 'limit' => null); $defOptions = array('sysmapids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectSelements' => null, 'selectLinks' => null, 'selectIconMap' => null, 'selectUrls' => null, 'countOutput' => null, 'expandUrls' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); // sysmapids if (!is_null($options['sysmapids'])) { zbx_value2array($options['sysmapids']); $sqlParts['where']['sysmapid'] = dbConditionInt('s.sysmapid', $options['sysmapids']); } // search if (!is_null($options['search'])) { zbx_db_search('sysmaps s', $options, $sqlParts); } // filter if (!is_null($options['filter'])) { $this->dbFilter('sysmaps s', $options, $sqlParts); } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $sysmapids = array(); $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 ($sysmap = DBfetch($res)) { if ($options['countOutput']) { $result = $sysmap['rowscount']; } else { $sysmapids[$sysmap['sysmapid']] = $sysmap['sysmapid']; // originally we intended not to pass those parameters if advanced labels are off, but they might be useful // leaving this block commented // if (isset($sysmap['label_format']) && ($sysmap['label_format'] == SYSMAP_LABEL_ADVANCED_OFF)) { // unset($sysmap['label_string_hostgroup'], $sysmap['label_string_host'], $sysmap['label_string_trigger'], $sysmap['label_string_map'], $sysmap['label_string_image']); // } $result[$sysmap['sysmapid']] = $sysmap; } } if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { if ($result) { $linkTriggers = array(); $dbLinkTriggers = DBselect('SELECT slt.triggerid,sl.sysmapid' . ' FROM sysmaps_link_triggers slt,sysmaps_links sl' . ' WHERE ' . dbConditionInt('sl.sysmapid', $sysmapids) . ' AND sl.linkid=slt.linkid'); while ($linkTrigger = DBfetch($dbLinkTriggers)) { $linkTriggers[$linkTrigger['sysmapid']] = $linkTrigger['triggerid']; } if ($linkTriggers) { $trigOptions = array('triggerids' => $linkTriggers, 'editable' => $options['editable'], 'output' => array('triggerid'), 'preservekeys' => true); $allTriggers = API::Trigger()->get($trigOptions); foreach ($linkTriggers as $id => $triggerid) { if (!isset($allTriggers[$triggerid])) { unset($result[$id], $sysmapids[$id]); } } } $hostsToCheck = array(); $mapsToCheck = array(); $triggersToCheck = array(); $hostGroupsToCheck = array(); $selements = array(); $dbSelements = DBselect('SELECT se.* FROM sysmaps_elements se WHERE ' . dbConditionInt('se.sysmapid', $sysmapids)); while ($selement = DBfetch($dbSelements)) { $selements[$selement['selementid']] = $selement; switch ($selement['elementtype']) { case SYSMAP_ELEMENT_TYPE_HOST: $hostsToCheck[$selement['elementid']] = $selement['elementid']; break; case SYSMAP_ELEMENT_TYPE_MAP: $mapsToCheck[$selement['elementid']] = $selement['elementid']; break; case SYSMAP_ELEMENT_TYPE_TRIGGER: $triggersToCheck[$selement['elementid']] = $selement['elementid']; break; case SYSMAP_ELEMENT_TYPE_HOST_GROUP: $hostGroupsToCheck[$selement['elementid']] = $selement['elementid']; break; } } if ($hostsToCheck) { $allowedHosts = API::Host()->get(array('hostids' => $hostsToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('hostid'))); foreach ($hostsToCheck as $elementid) { if (!isset($allowedHosts[$elementid])) { foreach ($selements as $selementid => $selement) { if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST && bccomp($selement['elementid'], $elementid) == 0) { unset($result[$selement['sysmapid']], $selements[$selementid]); } } } } } if ($mapsToCheck) { $allowedMaps = $this->get(array('sysmapids' => $mapsToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('sysmapid'))); foreach ($mapsToCheck as $elementid) { if (!isset($allowedMaps[$elementid])) { foreach ($selements as $selementid => $selement) { if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_MAP && bccomp($selement['elementid'], $elementid) == 0) { unset($result[$selement['sysmapid']], $selements[$selementid]); } } } } } if ($triggersToCheck) { $allowedTriggers = API::Trigger()->get(array('triggerids' => $triggersToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('triggerid'))); foreach ($triggersToCheck as $elementid) { if (!isset($allowedTriggers[$elementid])) { foreach ($selements as $selementid => $selement) { if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_TRIGGER && bccomp($selement['elementid'], $elementid) == 0) { unset($result[$selement['sysmapid']], $selements[$selementid]); } } } } } if ($hostGroupsToCheck) { $allowedHostGroups = API::HostGroup()->get(array('groupids' => $hostGroupsToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('groupid'))); foreach ($hostGroupsToCheck as $elementid) { if (!isset($allowedHostGroups[$elementid])) { foreach ($selements as $selementid => $selement) { if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP && bccomp($selement['elementid'], $elementid) == 0) { unset($result[$selement['sysmapid']], $selements[$selementid]); } } } } } } } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
$item['applications_list'] = ''; } } unset($item); } $data['flicker'] = getItemFilterForm($data['items']); // remove subfiltered items if (!empty($data['items'])) { foreach ($data['items'] as $number => $item) { foreach ($item['subfilters'] as $subfilter => $value) { if (!$value) { unset($data['items'][$number]); break; } } } } order_result($data['items'], $data['sortfield'], getPageSortOrder()); $data['paging'] = getPagingLine($data['items']); $itemTriggerIds = array(); foreach ($data['items'] as $item) { $itemTriggerIds = array_merge($itemTriggerIds, zbx_objectValues($item['triggers'], 'triggerid')); } $data['itemTriggers'] = API::Trigger()->get(array('triggerids' => $itemTriggerIds, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => array('hostid', 'name', 'host'), 'selectFunctions' => API_OUTPUT_EXTEND, 'selectItems' => API_OUTPUT_EXTEND, 'preservekeys' => true)); $data['triggerRealHosts'] = getParentHostsByTriggers($data['itemTriggers']); // render view $itemView = new CView('configuration.item.list', $data); $itemView->render(); $itemView->show(); } require_once dirname(__FILE__) . '/include/page_footer.php';