public function bodyToString() { $this->cleanItems(); $total = 0; // fetch accessible host ids $hosts = API::Host()->get(array('nodeids' => get_current_nodeid(true), 'output' => array('hostid'), 'preservekeys' => true)); $hostIds = array_keys($hosts); if (remove_nodes_from_id($this->groupid) > 0) { $cond_from = ',hosts_groups hg'; $cond_where = ' AND hg.hostid=h.hostid AND hg.groupid=' . zbx_dbstr($this->groupid); } else { $cond_from = ''; $cond_where = andDbNode('h.hostid', $this->nodeid); } $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_TRUE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where); $host_cnt = DBfetch($db_host_cnt); $avail = $host_cnt['cnt']; $total += $host_cnt['cnt']; $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_FALSE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where); $host_cnt = DBfetch($db_host_cnt); $notav = $host_cnt['cnt']; $total += $host_cnt['cnt']; $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_UNKNOWN . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where); $host_cnt = DBfetch($db_host_cnt); $uncn = $host_cnt['cnt']; $total += $host_cnt['cnt']; $node = get_node_by_nodeid($this->nodeid); $header_str = _('Hosts info') . SPACE; if ($node > 0) { $header_str .= '(' . $node['name'] . ')' . SPACE; } if (remove_nodes_from_id($this->groupid) > 0) { $group = get_hostgroup_by_groupid($this->groupid); $header_str .= _('Group') . SPACE . '"' . $group['name'] . '"'; } else { $header_str .= _('All groups'); } $header = new CCol($header_str, 'header'); if ($this->style == STYLE_HORISONTAL) { $header->setColspan(4); } $this->addRow($header); $avail = new CCol($avail . ' ' . _('Available'), 'avail'); $notav = new CCol($notav . ' ' . _('Not available'), 'notav'); $uncn = new CCol($uncn . ' ' . _('Unknown'), 'uncn'); $total = new CCol($total . ' ' . _('Total'), 'total'); if ($this->style == STYLE_HORISONTAL) { $this->addRow(array($avail, $notav, $uncn, $total)); } else { $this->addRow($avail); $this->addRow($notav); $this->addRow($uncn); $this->addRow($total); } return parent::bodyToString(); }
protected function doAction() { $sortField = $this->getInput('sort', CProfile::get('web.proxies.php.sort', 'host')); $sortOrder = $this->getInput('sortorder', CProfile::get('web.proxies.php.sortorder', ZBX_SORT_UP)); CProfile::update('web.proxies.php.sort', $sortField, PROFILE_TYPE_STR); CProfile::update('web.proxies.php.sortorder', $sortOrder, PROFILE_TYPE_STR); $config = select_config(); $data = ['uncheck' => $this->hasInput('uncheck'), 'sort' => $sortField, 'sortorder' => $sortOrder, 'config' => ['max_in_table' => $config['max_in_table']]]; $data['proxies'] = API::Proxy()->get(['output' => ['proxyid', 'host', 'status', 'lastaccess', 'tls_connect', 'tls_accept'], 'selectHosts' => ['hostid', 'name', 'status'], 'sortfield' => $sortField, 'limit' => $config['search_limit'] + 1, 'editable' => true, 'preservekeys' => true]); // sorting & paging order_result($data['proxies'], $sortField, $sortOrder); $url = (new CUrl('zabbix.php'))->setArgument('action', 'proxy.list'); $data['paging'] = getPagingLine($data['proxies'], $sortOrder, $url); foreach ($data['proxies'] as &$proxy) { order_result($proxy['hosts'], 'name'); } unset($proxy); // get proxy IDs for a *selected* page $proxyIds = array_keys($data['proxies']); if ($proxyIds) { // calculate performance $dbPerformance = DBselect('SELECT h.proxy_hostid,SUM(1.0/i.delay) AS qps' . ' FROM hosts h,items i' . ' WHERE h.hostid=i.hostid' . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.delay<>0' . ' AND i.flags<>' . ZBX_FLAG_DISCOVERY_PROTOTYPE . ' AND ' . dbConditionInt('h.proxy_hostid', $proxyIds) . ' GROUP BY h.proxy_hostid'); while ($performance = DBfetch($dbPerformance)) { $data['proxies'][$performance['proxy_hostid']]['perf'] = round($performance['qps'], 2); } // get items $items = API::Item()->get(['proxyids' => $proxyIds, 'groupCount' => true, 'countOutput' => true, 'webitems' => true, 'monitored' => true]); foreach ($items as $item) { $data['proxies'][$item['proxy_hostid']]['item_count'] = $item['rowscount']; } } $response = new CControllerResponseData($data); $response->setTitle(_('Configuration of proxies')); $this->setResponse($response); }
/** * Get GraphItems data * * @param array $options * @return array|boolean */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = array('select' => array('gitems' => 'gi.gitemid'), 'from' => array('graphs_items' => 'graphs_items gi'), 'where' => array(), 'order' => array(), 'limit' => null); $defOptions = array('graphids' => null, 'itemids' => null, 'type' => null, 'editable' => null, 'nopermissions' => null, 'selectGraphs' => null, 'output' => API_OUTPUT_EXTEND, 'expandData' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); $this->checkDeprecatedParam($options, 'expandData'); // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ; $userGroups = getUserGroupsByUserId($userid); $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE gi.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY i.itemid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')'; } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); $sqlParts['from']['graphs'] = 'graphs g'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where'][] = dbConditionInt('g.graphid', $options['graphids']); } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); $sqlParts['where'][] = dbConditionInt('gi.itemid', $options['itemids']); } // type if (!is_null($options['type'])) { $sqlParts['where'][] = 'gi.type=' . zbx_dbstr($options['type']); } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $dbRes = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($gitem = DBfetch($dbRes)) { if (!is_null($options['countOutput'])) { $result = $gitem['rowscount']; } else { $result[$gitem['gitemid']] = $gitem; } } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, array('graphid'), $options['output']); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Process screen. * * @return CDiv (screen inside container) */ public function get() { $total = 0; // fetch accessible host ids $hosts = API::Host()->get(['output' => ['hostid'], 'preservekeys' => true]); $hostids = array_keys($hosts); if ($this->screenitem['resourceid'] != 0) { $cond_from = ',hosts_groups hg'; $cond_where = ' AND hg.hostid=h.hostid AND hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']); } else { $cond_from = ''; $cond_where = ''; } $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_TRUE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where); $host_cnt = DBfetch($db_host_cnt); $avail = $host_cnt['cnt']; $total += $host_cnt['cnt']; $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_FALSE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where); $host_cnt = DBfetch($db_host_cnt); $notav = $host_cnt['cnt']; $total += $host_cnt['cnt']; $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_UNKNOWN . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where); $host_cnt = DBfetch($db_host_cnt); $uncn = $host_cnt['cnt']; $total += $host_cnt['cnt']; $avail = (new CCol($avail . ' ' . _('Available')))->addClass(ZBX_STYLE_GREEN); $notav = (new CCol($notav . ' ' . _('Not available')))->addClass(ZBX_STYLE_RED); $uncn = (new CCol($uncn . ' ' . _('Unknown')))->addClass(ZBX_STYLE_GREY); $total = new CCol($total . ' ' . _('Total')); $header = (new CDiv([new CTag('h4', true, _('Hosts info'))]))->addClass(ZBX_STYLE_DASHBRD_WIDGET_HEAD); if ($this->screenitem['resourceid'] != 0) { $groups = API::HostGroup()->get(['output' => ['name'], 'groupids' => [$this->screenitem['resourceid']]]); $header->addItem((new CList())->addItem([_('Group'), ':', SPACE, $groups[0]['name']])); } $table = new CTableInfo(); if ($this->screenitem['style'] == STYLE_HORIZONTAL) { $table->addRow([$avail, $notav, $uncn, $total]); } else { $table->addRow($avail); $table->addRow($notav); $table->addRow($uncn); $table->addRow($total); } $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])); }
/** * Get scripts data. * * @param array $options * @param array $options['itemids'] * @param array $options['hostids'] deprecated (very slow) * @param array $options['groupids'] * @param array $options['triggerids'] * @param array $options['scriptids'] * @param bool $options['status'] * @param bool $options['editable'] * @param bool $options['count'] * @param string $options['pattern'] * @param int $options['limit'] * @param string $options['order'] * * @return array */ public function get(array $options) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = array('select' => array('scripts' => 's.scriptid'), 'from' => array('scripts s'), 'where' => array(), 'order' => array(), 'limit' => null); $defOptions = array('groupids' => null, 'hostids' => null, 'scriptids' => null, 'usrgrpids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectGroups' => null, 'selectHosts' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); // editable + permission check if ($userType != USER_TYPE_SUPER_ADMIN) { if (!is_null($options['editable'])) { return $result; } $userGroups = getUserGroupsByUserId($userid); $sqlParts['where'][] = '(s.usrgrpid IS NULL OR ' . dbConditionInt('s.usrgrpid', $userGroups) . ')'; $sqlParts['where'][] = '(s.groupid IS NULL OR EXISTS (' . 'SELECT NULL' . ' FROM rights r' . ' WHERE s.groupid=r.id' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' GROUP BY r.id' . ' HAVING MIN(r.permission)>' . PERM_DENY . '))'; } // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); $sqlParts['where'][] = '(s.groupid IS NULL OR ' . dbConditionInt('s.groupid', $options['groupids']) . ')'; } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); // return scripts that are assigned to the hosts' groups or to no group $hostGroups = API::HostGroup()->get(array('output' => array('groupid'), 'hostids' => $options['hostids'])); $hostGroupIds = zbx_objectValues($hostGroups, 'groupid'); $sqlParts['where'][] = '(' . dbConditionInt('s.groupid', $hostGroupIds) . ' OR s.groupid IS NULL)'; } // usrgrpids if (!is_null($options['usrgrpids'])) { zbx_value2array($options['usrgrpids']); $sqlParts['where'][] = '(s.usrgrpid IS NULL OR ' . dbConditionInt('s.usrgrpid', $options['usrgrpids']) . ')'; } // scriptids if (!is_null($options['scriptids'])) { zbx_value2array($options['scriptids']); $sqlParts['where'][] = dbConditionInt('s.scriptid', $options['scriptids']); } // search if (is_array($options['search'])) { zbx_db_search('scripts s', $options, $sqlParts); } // filter if (is_array($options['filter'])) { $this->dbFilter('scripts s', $options, $sqlParts); } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($script = DBfetch($res)) { if ($options['countOutput']) { $result = $script['rowscount']; } else { $result[$script['scriptid']] = $script; } } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, array('groupid', 'host_access'), $options['output']); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Create and return a DIV with web monitoring overview. * * @param array $filter * @param array $filter['groupids'] * @param bool $filter['maintenance'] * * @return CDiv */ function make_webmon_overview($filter) { $groups = API::HostGroup()->get(array('groupids' => $filter['groupids'], 'hostids' => isset($filter['hostids']) ? $filter['hostids'] : null, 'monitored_hosts' => true, 'with_monitored_httptests' => true, 'output' => array('groupid', 'name'), 'preservekeys' => true)); foreach ($groups as &$group) { $group['nodename'] = get_node_name_by_elid($group['groupid']); } unset($group); CArrayHelper::sort($groups, array(array('field' => 'nodename', 'order' => ZBX_SORT_UP), array('field' => 'name', 'order' => ZBX_SORT_UP))); $groupIds = array_keys($groups); $availableHosts = API::Host()->get(array('groupids' => $groupIds, 'hostids' => isset($filter['hostids']) ? $filter['hostids'] : null, 'monitored_hosts' => true, 'filter' => array('maintenance_status' => $filter['maintenance']), 'output' => array('hostid'), 'preservekeys' => true)); $availableHostIds = array_keys($availableHosts); $table = new CTableInfo(_('No web scenarios found.')); $table->setHeader(array(is_show_all_nodes() ? _('Node') : null, _('Host group'), _('Ok'), _('Failed'), _('Unknown'))); $data = array(); // fetch links between HTTP tests and host groups $result = DbFetchArray(DBselect('SELECT DISTINCT ht.httptestid,hg.groupid' . ' FROM httptest ht,hosts_groups hg' . ' WHERE ht.hostid=hg.hostid' . ' AND ' . dbConditionInt('hg.hostid', $availableHostIds) . ' AND ' . dbConditionInt('hg.groupid', $groupIds))); // fetch HTTP test execution data $httpTestData = Manager::HttpTest()->getLastData(zbx_objectValues($result, 'httptestid')); foreach ($result as $row) { if (!isset($httpTestData[$row['httptestid']])) { $data[$row['groupid']]['unknown'] = empty($data[$row['groupid']]['unknown']) ? 1 : ++$data[$row['groupid']]['unknown']; } elseif ($httpTestData[$row['httptestid']]['lastfailedstep'] != 0) { $data[$row['groupid']]['failed'] = empty($data[$row['groupid']]['failed']) ? 1 : ++$data[$row['groupid']]['failed']; } else { $data[$row['groupid']]['ok'] = empty($data[$row['groupid']]['ok']) ? 1 : ++$data[$row['groupid']]['ok']; } } foreach ($groups as $group) { if (!empty($data[$group['groupid']])) { $table->addRow(array(is_show_all_nodes() ? $group['nodename'] : null, $group['name'], new CSpan(empty($data[$group['groupid']]['ok']) ? 0 : $data[$group['groupid']]['ok'], 'off'), new CSpan(empty($data[$group['groupid']]['failed']) ? 0 : $data[$group['groupid']]['failed'], empty($data[$group['groupid']]['failed']) ? 'off' : 'on'), new CSpan(empty($data[$group['groupid']]['unknown']) ? 0 : $data[$group['groupid']]['unknown'], 'unknown'))); } } $script = new CJSScript(get_js("jQuery('#hat_webovr_footer').html('" . _s('Updated: %s', zbx_date2str(_('H:i:s'))) . "')")); return new CDiv(array($table, $script)); }
break; case 'day': default: $time_dif = SEC_PER_DAY; break; } $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) {
/** * Apply filter conditions to sql built query. * * @param string $table * @param array $options * @param array $sqlParts * * @return bool */ protected function dbFilter($table, $options, &$sqlParts) { list($table, $tableShort) = explode(' ', $table); $tableSchema = DB::getSchema($table); $filter = []; foreach ($options['filter'] as $field => $value) { // skip missing fields and text fields (not supported by Oracle) // skip empty values if (!isset($tableSchema['fields'][$field]) || $tableSchema['fields'][$field]['type'] == DB::FIELD_TYPE_TEXT || zbx_empty($value)) { continue; } zbx_value2array($value); $fieldName = $this->fieldId($field, $tableShort); $filter[$field] = DB::isNumericFieldType($tableSchema['fields'][$field]['type']) ? dbConditionInt($fieldName, $value) : dbConditionString($fieldName, $value); } if ($filter) { if (isset($sqlParts['where']['filter'])) { $filter[] = $sqlParts['where']['filter']; } if (is_null($options['searchByAny']) || $options['searchByAny'] === false || count($filter) == 1) { $sqlParts['where']['filter'] = implode(' AND ', $filter); } else { $sqlParts['where']['filter'] = '(' . implode(' OR ', $filter) . ')'; } return true; } return false; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $graphids = array_keys($result); // adding Items if ($options['selectItems'] !== null && $options['selectItems'] !== API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'graphid', 'itemid', 'graphs_items'); $items = API::Item()->get(array('output' => $options['selectItems'], 'itemids' => $relationMap->getRelatedIds(), 'webitems' => true, 'nopermissions' => true, 'preservekeys' => true, 'filter' => array('flags' => null))); $result = $relationMap->mapMany($result, $items, 'items'); } // adding discoveryRule if (!is_null($options['selectDiscoveryRule'])) { $dbRules = DBselect('SELECT id.parent_itemid,gi.graphid' . ' FROM item_discovery id,graphs_items gi' . ' WHERE ' . dbConditionInt('gi.graphid', $graphids) . ' AND gi.itemid=id.itemid'); $relationMap = new CRelationMap(); while ($relation = DBfetch($dbRules)) { $relationMap->addRelation($relation['graphid'], $relation['parent_itemid']); } $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } return $result; }
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); $hostids = array_keys($result); // adding inventories if ($options['selectInventory'] !== null) { $relationMap = $this->createRelationMap($result, 'hostid', 'hostid'); $inventory = API::getApiService()->select('host_inventory', ['output' => $options['selectInventory'], 'filter' => ['hostid' => $hostids]]); $result = $relationMap->mapOne($result, zbx_toHash($inventory, 'hostid'), 'inventory'); } // adding hostinterfaces if ($options['selectInterfaces'] !== null) { if ($options['selectInterfaces'] != API_OUTPUT_COUNT) { $interfaces = API::HostInterface()->get(['output' => $this->outputExtend($options['selectInterfaces'], ['hostid', 'interfaceid']), 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true]); // we need to order interfaces for proper linkage and viewing order_result($interfaces, 'interfaceid', ZBX_SORT_UP); $relationMap = $this->createRelationMap($interfaces, 'hostid', 'interfaceid'); $interfaces = $this->unsetExtraFields($interfaces, ['hostid', 'interfaceid'], $options['selectInterfaces']); $result = $relationMap->mapMany($result, $interfaces, 'interfaces', $options['limitSelects']); } else { $interfaces = API::HostInterface()->get(['hostids' => $hostids, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true]); $interfaces = zbx_toHash($interfaces, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['interfaces'] = isset($interfaces[$hostid]) ? $interfaces[$hostid]['rowscount'] : 0; } } } // adding screens if ($options['selectScreens'] !== null) { if ($options['selectScreens'] != API_OUTPUT_COUNT) { $screens = API::TemplateScreen()->get(['output' => $this->outputExtend($options['selectScreens'], ['hostid']), 'hostids' => $hostids, 'nopermissions' => true]); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } // inherited screens do not have a unique screenid, so we're building a map using array keys $relationMap = new CRelationMap(); foreach ($screens as $key => $screen) { $relationMap->addRelation($screen['hostid'], $key); } $screens = $this->unsetExtraFields($screens, ['hostid'], $options['selectScreens']); $result = $relationMap->mapMany($result, $screens, 'screens', $options['limitSelects']); } else { $screens = API::TemplateScreen()->get(['hostids' => $hostids, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true]); $screens = zbx_toHash($screens, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['screens'] = isset($screens[$hostid]) ? $screens[$hostid]['rowscount'] : 0; } } } // adding discovery rule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { // discovered items $discoveryRules = DBFetchArray(DBselect('SELECT hd.hostid,hd2.parent_itemid' . ' FROM host_discovery hd,host_discovery hd2' . ' WHERE ' . dbConditionInt('hd.hostid', $hostids) . ' AND hd.parent_hostid=hd2.hostid')); $relationMap = $this->createRelationMap($discoveryRules, 'hostid', 'parent_itemid'); $discoveryRules = API::DiscoveryRule()->get(['output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding host discovery if ($options['selectHostDiscovery'] !== null) { $hostDiscoveries = API::getApiService()->select('host_discovery', ['output' => $this->outputExtend($options['selectHostDiscovery'], ['hostid']), 'filter' => ['hostid' => $hostids], 'preservekeys' => true]); $relationMap = $this->createRelationMap($hostDiscoveries, 'hostid', 'hostid'); $hostDiscoveries = $this->unsetExtraFields($hostDiscoveries, ['hostid'], $options['selectHostDiscovery']); $result = $relationMap->mapOne($result, $hostDiscoveries, 'hostDiscovery'); } return $result; }
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; }
function get_accessible_hosts_by_rights(&$rights, $user_type, $perm) { $result = []; $res_perm = []; foreach ($rights as $id => $right) { $res_perm[$right['id']] = $right['permission']; } $host_perm = []; $where = []; array_push($where, 'h.status in (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')'); array_push($where, dbConditionInt('h.flags', [ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED])); $where = count($where) ? $where = ' WHERE ' . implode(' AND ', $where) : ''; $perm_by_host = []; $dbHosts = DBselect('SELECT hg.groupid AS groupid,h.hostid,h.host,h.name AS host_name,h.status' . ' FROM hosts h' . ' LEFT JOIN hosts_groups hg ON hg.hostid=h.hostid' . $where); while ($dbHost = DBfetch($dbHosts)) { if (isset($dbHost['groupid']) && isset($res_perm[$dbHost['groupid']])) { if (!isset($perm_by_host[$dbHost['hostid']])) { $perm_by_host[$dbHost['hostid']] = []; } $perm_by_host[$dbHost['hostid']][] = $res_perm[$dbHost['groupid']]; $host_perm[$dbHost['hostid']][$dbHost['groupid']] = $res_perm[$dbHost['groupid']]; } $host_perm[$dbHost['hostid']]['data'] = $dbHost; } foreach ($host_perm as $hostid => $dbHost) { $dbHost = $dbHost['data']; // select min rights from groups if (USER_TYPE_SUPER_ADMIN == $user_type) { $dbHost['permission'] = PERM_READ_WRITE; } else { if (isset($perm_by_host[$hostid])) { $dbHost['permission'] = min($perm_by_host[$hostid]) == PERM_DENY ? PERM_DENY : max($perm_by_host[$hostid]); } else { $dbHost['permission'] = PERM_DENY; } } if ($dbHost['permission'] < $perm) { continue; } $result[$dbHost['hostid']] = $dbHost; } CArrayHelper::sort($result, [['field' => 'host_name', 'order' => ZBX_SORT_UP]]); return $result; }
function getUserFormData($userid, $isProfile = false) { $config = select_config(); $data = array('is_profile' => $isProfile); if (isset($userid)) { $users = API::User()->get(array('userids' => $userid, 'output' => API_OUTPUT_EXTEND)); $user = reset($users); } if (isset($userid) && (!isset($_REQUEST['form_refresh']) || isset($_REQUEST['register']))) { $data['alias'] = $user['alias']; $data['name'] = $user['name']; $data['surname'] = $user['surname']; $data['password1'] = null; $data['password2'] = null; $data['url'] = $user['url']; $data['autologin'] = $user['autologin']; $data['autologout'] = $user['autologout']; $data['lang'] = $user['lang']; $data['theme'] = $user['theme']; $data['refresh'] = $user['refresh']; $data['rows_per_page'] = $user['rows_per_page']; $data['user_type'] = $user['type']; $data['messages'] = getMessageSettings(); $userGroups = API::UserGroup()->get(array('userids' => $userid, 'output' => array('usrgrpid'))); $userGroup = zbx_objectValues($userGroups, 'usrgrpid'); $data['user_groups'] = zbx_toHash($userGroup); $data['user_medias'] = array(); $dbMedia = DBselect('SELECT m.mediaid,m.mediatypeid,m.period,m.sendto,m.severity,m.active' . ' FROM media m' . ' WHERE m.userid=' . zbx_dbstr($userid)); while ($dbMedium = DBfetch($dbMedia)) { $data['user_medias'][] = $dbMedium; } if ($data['autologout'] > 0) { $_REQUEST['autologout'] = $data['autologout']; } } else { $data['alias'] = getRequest('alias', ''); $data['name'] = getRequest('name', ''); $data['surname'] = getRequest('surname', ''); $data['password1'] = getRequest('password1', ''); $data['password2'] = getRequest('password2', ''); $data['url'] = getRequest('url', ''); $data['autologin'] = getRequest('autologin', 0); $data['autologout'] = getRequest('autologout', 900); $data['lang'] = getRequest('lang', 'en_gb'); $data['theme'] = getRequest('theme', THEME_DEFAULT); $data['refresh'] = getRequest('refresh', 30); $data['rows_per_page'] = getRequest('rows_per_page', 50); $data['user_type'] = getRequest('user_type', USER_TYPE_ZABBIX_USER); $data['user_groups'] = getRequest('user_groups', array()); $data['change_password'] = getRequest('change_password'); $data['user_medias'] = getRequest('user_medias', array()); // set messages $data['messages'] = getRequest('messages', array()); if (!isset($data['messages']['enabled'])) { $data['messages']['enabled'] = 0; } if (!isset($data['messages']['sounds.recovery'])) { $data['messages']['sounds.recovery'] = 'alarm_ok.wav'; } if (!isset($data['messages']['triggers.recovery'])) { $data['messages']['triggers.recovery'] = 0; } if (!isset($data['messages']['triggers.severities'])) { $data['messages']['triggers.severities'] = array(); } $data['messages'] = array_merge(getMessageSettings(), $data['messages']); } // authentication type if ($data['user_groups']) { $data['auth_type'] = getGroupAuthenticationType($data['user_groups'], GROUP_GUI_ACCESS_INTERNAL); } else { $data['auth_type'] = $userid === null ? $config['authentication_type'] : getUserAuthenticationType($userid, GROUP_GUI_ACCESS_INTERNAL); } // set autologout if ($data['autologin'] || !isset($data['autologout'])) { $data['autologout'] = 0; } // set media types if (!empty($data['user_medias'])) { $mediaTypeDescriptions = array(); $dbMediaTypes = DBselect('SELECT mt.mediatypeid,mt.description FROM media_type mt WHERE ' . dbConditionInt('mt.mediatypeid', zbx_objectValues($data['user_medias'], 'mediatypeid'))); while ($dbMediaType = DBfetch($dbMediaTypes)) { $mediaTypeDescriptions[$dbMediaType['mediatypeid']] = $dbMediaType['description']; } foreach ($data['user_medias'] as &$media) { $media['description'] = $mediaTypeDescriptions[$media['mediatypeid']]; } unset($media); CArrayHelper::sort($data['user_medias'], array('description', 'sendto')); } // set user rights if (!$data['is_profile']) { $data['groups'] = API::UserGroup()->get(array('usrgrpids' => $data['user_groups'], 'output' => array('usrgrpid', 'name'))); order_result($data['groups'], 'name'); $group_ids = array_values($data['user_groups']); if (count($group_ids) == 0) { $group_ids = array(-1); } $db_rights = DBselect('SELECT r.* FROM rights r WHERE ' . dbConditionInt('r.groupid', $group_ids)); // deny beat all, read-write beat read $tmp_permitions = array(); while ($db_right = DBfetch($db_rights)) { if (isset($tmp_permitions[$db_right['id']]) && $tmp_permitions[$db_right['id']] != PERM_DENY) { $tmp_permitions[$db_right['id']] = $db_right['permission'] == PERM_DENY ? PERM_DENY : max($tmp_permitions[$db_right['id']], $db_right['permission']); } else { $tmp_permitions[$db_right['id']] = $db_right['permission']; } } $data['user_rights'] = array(); foreach ($tmp_permitions as $id => $permition) { array_push($data['user_rights'], array('id' => $id, 'permission' => $permition)); } } return $data; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); if ($options['globalmacro'] === null) { $hostMacroIds = array_keys($result); /* * Adding objects */ // adding groups if ($options['selectGroups'] !== null && $options['selectGroups'] != API_OUTPUT_COUNT) { $res = DBselect('SELECT hm.hostmacroid,hg.groupid' . ' FROM hostmacro hm,hosts_groups hg' . ' WHERE ' . dbConditionInt('hm.hostmacroid', $hostMacroIds) . ' AND hm.hostid=hg.hostid'); $relationMap = new CRelationMap(); while ($relation = DBfetch($res)) { $relationMap->addRelation($relation['hostmacroid'], $relation['groupid']); } $groups = API::HostGroup()->get(array('output' => $options['selectGroups'], 'groupids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $groups, 'groups'); } // adding templates if ($options['selectTemplates'] !== null && $options['selectTemplates'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'hostmacroid', 'hostid'); $templates = API::Template()->get(array('output' => $options['selectTemplates'], 'templateids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $templates, 'templates'); } // adding templates if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'hostmacroid', 'hostid'); $templates = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $templates, 'hosts'); } } return $result; }
/** * Add Items to applications * * @param array $data * @param array $data['applications'] * @param array $data['items'] * @return boolean */ public function massAdd($data) { if (empty($data['applications'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $applications = zbx_toArray($data['applications']); $items = zbx_toArray($data['items']); $applicationids = zbx_objectValues($applications, 'applicationid'); $itemids = zbx_objectValues($items, 'itemid'); // validate permissions $appOptions = array('applicationids' => $applicationids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1); $allowedApplications = $this->get($appOptions); foreach ($applications as $application) { if (!isset($allowedApplications[$application['applicationid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $allowedItems = API::Item()->get(array('itemids' => $itemids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CHILD, ZBX_FLAG_DISCOVERY_CREATED)))); foreach ($items as $num => $item) { if (!isset($allowedItems[$item['itemid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $linkedDb = DBselect('SELECT ia.itemid,ia.applicationid' . ' FROM items_applications ia' . ' WHERE ' . dbConditionInt('ia.itemid', $itemids) . ' AND ' . dbConditionInt('ia.applicationid', $applicationids)); while ($pair = DBfetch($linkedDb)) { $linked[$pair['applicationid']] = array($pair['itemid'] => $pair['itemid']); } $appsInsert = array(); foreach ($applicationids as $applicationid) { foreach ($itemids as $inum => $itemid) { if (isset($linked[$applicationid]) && isset($linked[$applicationid][$itemid])) { continue; } $appsInsert[] = array('itemid' => $itemid, 'applicationid' => $applicationid); } } DB::insert('items_applications', $appsInsert); foreach ($itemids as $inum => $itemid) { $dbChilds = DBselect('SELECT i.itemid,i.hostid FROM items i WHERE i.templateid=' . zbx_dbstr($itemid)); while ($child = DBfetch($dbChilds)) { $dbApps = DBselect('SELECT a1.applicationid' . ' FROM applications a1,applications a2' . ' WHERE a1.name=a2.name' . ' AND a1.hostid=' . $child['hostid'] . ' AND ' . dbConditionInt('a2.applicationid', $applicationids)); $childApplications = array(); while ($app = DBfetch($dbApps)) { $childApplications[] = $app; } $result = $this->massAdd(array('items' => $child, 'applications' => $childApplications)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot add items.'); } } } return array('applicationids' => $applicationids); }
/** * Delete GraphPrototype. * * @param int|string|array $graphids * @param bool $nopermissions * * @return array */ public function delete($graphids, $nopermissions = false) { if (empty($graphids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $graphids = zbx_toArray($graphids); $delGraphs = $this->get(array('graphids' => $graphids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); if (!$nopermissions) { foreach ($graphids as $graphid) { if (!isset($delGraphs[$graphid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } if ($delGraphs[$graphid]['templateid'] != 0) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('Cannot delete templated graphs.')); } } } $parentGraphids = $graphids; do { $dbGraphs = DBselect('SELECT g.graphid FROM graphs g WHERE ' . dbConditionInt('g.templateid', $parentGraphids)); $parentGraphids = array(); while ($dbGraph = DBfetch($dbGraphs)) { $parentGraphids[] = $dbGraph['graphid']; $graphids[] = $dbGraph['graphid']; } } while (!empty($parentGraphids)); $graphids = array_unique($graphids); $createdGraphs = array(); $dbGraphs = DBselect('SELECT gd.graphid FROM graph_discovery gd WHERE ' . dbConditionInt('gd.parent_graphid', $graphids)); while ($graph = DBfetch($dbGraphs)) { $createdGraphs[$graph['graphid']] = $graph['graphid']; } if (!empty($createdGraphs)) { $result = API::Graph()->delete($createdGraphs, true); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete graphs created by low level discovery.')); } } DB::delete('graphs', array('graphid' => $graphids)); foreach ($delGraphs as $graph) { info(_s('Graph prototype "%s" deleted.', $graph['name'])); } return array('graphids' => $graphids); }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $httpTestIds = array_keys($result); // adding hosts if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'httptestid', 'hostid'); $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostid' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'templated_hosts' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $hosts, 'hosts'); } // adding steps if ($options['selectSteps'] !== null) { if ($options['selectSteps'] != API_OUTPUT_COUNT) { $httpSteps = API::getApiService()->select('httpstep', array('output' => $this->outputExtend($options['selectSteps'], array('httptestid', 'httpstepid')), 'filters' => array('httptestid' => $httpTestIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($httpSteps, 'httptestid', 'httpstepid'); $httpSteps = $this->unsetExtraFields($httpSteps, array('httptestid', 'httpstepid'), $options['selectSteps']); $result = $relationMap->mapMany($result, $httpSteps, 'steps'); } else { $dbHttpSteps = DBselect('SELECT hs.httptestid,COUNT(hs.httpstepid) AS stepscnt' . ' FROM httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', $httpTestIds) . ' GROUP BY hs.httptestid'); while ($dbHttpStep = DBfetch($dbHttpSteps)) { $result[$dbHttpStep['httptestid']]['steps'] = $dbHttpStep['stepscnt']; } } } return $result; }
/* * Display */ if (isset($_REQUEST['form'])) { $data = ['form_refresh' => getRequest('form_refresh'), 'regexpid' => getRequest('regexpid')]; if (isset($_REQUEST['regexpid']) && !isset($_REQUEST['form_refresh'])) { $regExp = DBfetch(DBSelect('SELECT re.name,re.test_string' . ' FROM regexps re' . ' WHERE re.regexpid=' . zbx_dbstr($_REQUEST['regexpid']))); $data['name'] = $regExp['name']; $data['test_string'] = $regExp['test_string']; $data['expressions'] = DBfetchArray(DBselect('SELECT e.expressionid,e.expression,e.expression_type,e.exp_delimiter,e.case_sensitive' . ' FROM expressions e' . ' WHERE e.regexpid=' . zbx_dbstr($_REQUEST['regexpid']) . ' ORDER BY e.expression_type')); } else { $data['name'] = getRequest('name', ''); $data['test_string'] = getRequest('test_string', ''); $data['expressions'] = getRequest('expressions', [['expression' => '', 'expression_type' => EXPRESSION_TYPE_INCLUDED, 'exp_delimiter' => ',', 'case_sensitive' => 0]]); } $view = new CView('administration.general.regularexpressions.edit', $data); } else { $data = ['regexps' => [], 'regexpids' => []]; $dbRegExp = DBselect('SELECT re.* FROM regexps re'); while ($regExp = DBfetch($dbRegExp)) { $regExp['expressions'] = []; $data['regexps'][$regExp['regexpid']] = $regExp; $data['regexpids'][$regExp['regexpid']] = $regExp['regexpid']; } order_result($data['regexps'], 'name'); $data['db_exps'] = DBfetchArray(DBselect('SELECT e.*' . ' FROM expressions e' . ' WHERE ' . dbConditionInt('e.regexpid', $data['regexpids']) . ' ORDER BY e.expression_type')); $view = new CView('administration.general.regularexpressions.list', $data); } $view->render(); $view->show(); require_once dirname(__FILE__) . '/include/page_footer.php';
function getDeletableHostGroupIds(array $groupIds) { // selecting the list of hosts linked to the host groups $dbResult = DBselect('SELECT hg.hostid' . ' FROM hosts_groups hg' . ' WHERE ' . dbConditionInt('hg.groupid', $groupIds)); $linkedHostIds = array(); while ($dbRow = DBfetch($dbResult)) { $linkedHostIds[] = $dbRow['hostid']; } // the list of hosts which can be unlinked from the host groups $hostIds = getUnlinkableHostIds($groupIds, $linkedHostIds); $dbResult = DBselect('SELECT g.groupid' . ' FROM groups g' . ' WHERE g.internal=' . ZBX_NOT_INTERNAL_GROUP . ' AND ' . dbConditionInt('g.groupid', $groupIds) . ' AND NOT EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hg' . ' WHERE g.groupid=hg.groupid' . ($hostIds ? ' AND ' . dbConditionInt('hg.hostid', $hostIds, true) : '') . ')'); $deletableGroupIds = array(); while ($dbRow = DBfetch($dbResult)) { $deletableGroupIds[$dbRow['groupid']] = $dbRow['groupid']; } return $deletableGroupIds; }
protected function deleteChecks(array $checkids) { $actionids = array(); // conditions $sql = 'SELECT DISTINCT actionid ' . ' FROM conditions ' . ' WHERE conditiontype=' . CONDITION_TYPE_DCHECK . ' AND ' . dbConditionString('value', $checkids); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[] = $dbAction['actionid']; } // disabling actions with deleted conditions if (!empty($actionids)) { DBexecute('UPDATE actions ' . ' SET status=' . ACTION_STATUS_DISABLED . ' WHERE ' . dbConditionInt('actionid', $actionids)); // delete action conditions DBexecute('DELETE FROM conditions ' . ' WHERE conditiontype=' . CONDITION_TYPE_DCHECK . ' AND ' . dbConditionString('value', $checkids)); } DB::delete('dchecks', array('dcheckid' => $checkids)); }
} else { $data['pageFilter'] = $pageFilter; $data['showDisabled'] = $showDisabled; $data['showAllApps'] = $showAllApps; $data['db_apps'] = array(); $db_app_result = DBselect('SELECT DISTINCT h.name AS hostname,a.*' . ' FROM applications a,hosts h' . ' WHERE a.hostid=h.hostid' . ($data['hostid'] > 0 ? ' AND h.hostid=' . $data['hostid'] : '') . ' AND ' . dbConditionInt('h.hostid', $pageFilter->hostsSelected ? array_keys($pageFilter->hosts) : array())); while ($db_app = DBfetch($db_app_result)) { $db_app['scenarios_cnt'] = 0; $data['db_apps'][$db_app['applicationid']] = $db_app; } // get http tests $data['db_httptests'] = array(); $dbHttpTests_result = DBselect('SELECT wt.*,a.name AS application,h.name AS hostname,h.hostid' . ' FROM httptest wt,applications a,hosts h' . ' WHERE wt.applicationid=a.applicationid' . ' AND a.hostid=h.hostid' . ' AND ' . dbConditionInt('a.applicationid', array_keys($data['db_apps'])) . ($showDisabled == 0 ? ' AND wt.status=' . HTTPTEST_STATUS_ACTIVE : '')); while ($httptest_data = DBfetch($dbHttpTests_result)) { $data['db_apps'][$httptest_data['applicationid']]['scenarios_cnt']++; $httptest_data['step_count'] = null; $data['db_httptests'][$httptest_data['httptestid']] = $httptest_data; } // get http steps $httpstep_res = DBselect('SELECT hs.httptestid,COUNT(hs.httpstepid) AS cnt' . ' FROM httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', array_keys($data['db_httptests'])) . ' GROUP BY hs.httptestid'); while ($step_count = DBfetch($httpstep_res)) { $data['db_httptests'][$step_count['httptestid']]['step_count'] = $step_count['cnt']; } order_result($data['db_httptests'], getPageSortField('host'), getPageSortOrder()); $data['paging'] = getPagingLine($data['db_httptests']); // render view $httpView = new CView('configuration.httpconf.list', $data); $httpView->render(); $httpView->show(); } require_once dirname(__FILE__) . '/include/page_footer.php';
/** * Resolve positional macros and functional item macros, for example, {{HOST.HOST1}:key.func(param)}. * ! if same graph will be passed more than once only name for first entry will be resolved. * * @static * * @param array $data list or hashmap of graphs * @param int $data[n]['graphid'] id of graph * @param string $data[n]['name'] name of graph * * @return array inputted data with resolved names */ public static function resolveGraphNameByIds(array $data) { self::init(); $graphIds = array(); $graphMap = array(); foreach ($data as $graph) { // skip graphs without macros if (strpos($graph['name'], '{') !== false) { $graphMap[$graph['graphid']] = array('graphid' => $graph['graphid'], 'name' => $graph['name'], 'items' => array()); $graphIds[$graph['graphid']] = $graph['graphid']; } } $items = DBfetchArray(DBselect('SELECT i.hostid,gi.graphid,h.host' . ' FROM graphs_items gi,items i,hosts h' . ' WHERE gi.itemid=i.itemid' . ' AND i.hostid=h.hostid' . ' AND ' . dbConditionInt('gi.graphid', $graphIds) . ' ORDER BY gi.sortorder')); foreach ($items as $item) { $graphMap[$item['graphid']]['items'][] = array('hostid' => $item['hostid'], 'host' => $item['host']); } $graphMap = self::$macrosResolver->resolve(array('config' => 'graphName', 'data' => $graphMap)); $resolvedGraph = reset($graphMap); foreach ($data as &$graph) { if ($graph['graphid'] === $resolvedGraph['graphid']) { $graph['name'] = $resolvedGraph['name']; $resolvedGraph = next($graphMap); } } unset($graph); return $data; }
/** * Check if proxy is used to monitor hosts. * * @param array $proxyIds */ protected function checkUsedForMonitoring(array $proxyIds) { $host = DBfetch(DBselect('SELECT h.name,h.proxy_hostid' . ' FROM hosts h' . ' WHERE ' . dbConditionInt('h.proxy_hostid', $proxyIds), 1)); if ($host) { $proxy = DBfetch(DBselect('SELECT h.host FROM hosts h WHERE h.hostid=' . $host['proxy_hostid'])); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host "%1$s" is monitored with proxy "%2$s".', $host['name'], $proxy['host'])); } }
/** * Get Service data * * @param _array $options * @param array $options['nodeids'] Node IDs * @param array $options['groupids'] ServiceGroup IDs * @param array $options['hostids'] Service IDs * @param boolean $options['monitored_hosts'] only monitored Services * @param boolean $options['templated_hosts'] include templates in result * @param boolean $options['with_items'] only with items * @param boolean $options['with_historical_items'] only with historical items * @param boolean $options['with_triggers'] only with triggers * @param boolean $options['with_httptests'] only with 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 ServiceGroups * @param boolean $options['selectTemplates'] select Templates * @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 int $options['count'] count Services, returned column name is rowscount * @param string $options['pattern'] search hosts by pattern in Service name * @param string $options['extendPattern'] search hosts by pattern in Service 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 Service data as array or false if error */ public function get($options = array()) { $result = array(); $nodeCheck = false; $userType = self::$userData['type']; // allowed columns for sorting $sortColumns = array('dserviceid', 'dhostid', 'ip'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM); $sqlParts = array('select' => array('dservices' => 'ds.dserviceid'), 'from' => array('dservices' => 'dservices ds'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'dserviceids' => null, 'dhostids' => null, 'dcheckids' => null, 'druleids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectDRules' => null, 'selectDHosts' => null, 'selectDChecks' => null, 'selectHosts' => 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']['dservices']); $dbTable = DB::getSchema('dservices'); foreach ($options['output'] as $field) { if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 's.' . $field; } } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == $userType) { } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) { } elseif (!is_null($options['editable']) && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { return array(); } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // dserviceids if (!is_null($options['dserviceids'])) { zbx_value2array($options['dserviceids']); $sqlParts['where']['dserviceid'] = dbConditionInt('ds.dserviceid', $options['dserviceids']); if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids); } } // dhostids if (!is_null($options['dhostids'])) { zbx_value2array($options['dhostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dhostid'] = 'ds.dhostid'; } $sqlParts['where'][] = dbConditionInt('ds.dhostid', $options['dhostids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['dhostid'] = 'ds.dhostid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ds.dhostid', $nodeids); } } // dcheckids if (!is_null($options['dcheckids'])) { zbx_value2array($options['dcheckids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dcheckid'] = 'dc.dcheckid'; } $sqlParts['from']['dhosts'] = 'dhosts dh'; $sqlParts['from']['dchecks'] = 'dchecks dc'; $sqlParts['where'][] = dbConditionInt('dc.dcheckid', $options['dcheckids']); $sqlParts['where']['dhds'] = 'dh.hostid=ds.hostid'; $sqlParts['where']['dcdh'] = 'dc.druleid=dh.druleid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['dcheckid'] = 'dc.dcheckid'; } } // druleids if (!is_null($options['druleids'])) { zbx_value2array($options['druleids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['druleid'] = 'dh.druleid'; } $sqlParts['from']['dhosts'] = 'dhosts dh'; $sqlParts['where']['druleid'] = dbConditionInt('dh.druleid', $options['druleids']); $sqlParts['where']['dhds'] = 'dh.dhostid=ds.dhostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['druleid'] = 'dh.druleid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('dh.druleid', $nodeids); } } // node check !!!!! // should last, after all ****IDS checks if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids); } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['dservices'] = 'ds.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('count(DISTINCT ds.dserviceid) as rowscount'); //groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // filter if (is_array($options['filter'])) { $this->dbFilter('dservices ds', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('dservices ds', $options, $sqlParts); } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'ds'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } //------- $dserviceids = array(); $sqlParts['select'] = array_unique($sqlParts['select']); $sqlParts['from'] = array_unique($sqlParts['from']); $sqlParts['where'] = array_unique($sqlParts['where']); $sqlParts['group'] = array_unique($sqlParts['group']); $sqlParts['order'] = array_unique($sqlParts['order']); $sqlSelect = ''; $sqlFrom = ''; $sqlWhere = ''; $sqlGroup = ''; $sqlOrder = ''; if (!empty($sqlParts['select'])) { $sqlSelect .= implode(',', $sqlParts['select']); } if (!empty($sqlParts['from'])) { $sqlFrom .= implode(',', $sqlParts['from']); } if (!empty($sqlParts['where'])) { $sqlWhere .= implode(' AND ', $sqlParts['where']); } if (!empty($sqlParts['group'])) { $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']); } if (!empty($sqlParts['order'])) { $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']); } $sqlLimit = $sqlParts['limit']; $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder; //SDI($sql); $res = DBselect($sql, $sqlLimit); while ($dservice = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $dservice; } else { $result = $dservice['rowscount']; } } else { $dserviceids[$dservice['dserviceid']] = $dservice['dserviceid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$dservice['dserviceid']] = array('dserviceid' => $dservice['dserviceid']); } else { if (!isset($result[$dservice['dserviceid']])) { $result[$dservice['dserviceid']] = array(); } if (!is_null($options['selectDRules']) && !isset($result[$dservice['dserviceid']]['drules'])) { $result[$dservice['dserviceid']]['drules'] = array(); } if (!is_null($options['selectDHosts']) && !isset($result[$dservice['dserviceid']]['dhosts'])) { $result[$dservice['dserviceid']]['dhosts'] = array(); } if (!is_null($options['selectDChecks']) && !isset($result[$dservice['dserviceid']]['dchecks'])) { $result[$dservice['dserviceid']]['dchecks'] = array(); } if (!is_null($options['selectHosts']) && !isset($result[$dservice['dserviceid']]['hosts'])) { $result[$dservice['dserviceid']]['hosts'] = array(); } // druleids if (isset($dservice['druleid']) && is_null($options['selectDRules'])) { if (!isset($result[$dservice['dserviceid']]['drules'])) { $result[$dservice['dserviceid']]['drules'] = array(); } $result[$dservice['dserviceid']]['drules'][] = array('druleid' => $dservice['druleid']); } // dhostids if (isset($dservice['dhostid']) && is_null($options['selectDHosts'])) { if (!isset($result[$dservice['dserviceid']]['dhosts'])) { $result[$dservice['dserviceid']]['dhosts'] = array(); } $result[$dservice['dserviceid']]['dhosts'][] = array('dhostid' => $dservice['dhostid']); } // dcheckids if (isset($dservice['dcheckid']) && is_null($options['selectDChecks'])) { if (!isset($result[$dservice['dserviceid']]['dchecks'])) { $result[$dservice['dserviceid']]['dchecks'] = array(); } $result[$dservice['dserviceid']]['dchecks'][] = array('dcheckid' => $dservice['dcheckid']); } $result[$dservice['dserviceid']] += $dservice; } } } if (!is_null($options['countOutput'])) { return $result; } // Adding Objects // select_drules if (!is_null($options['selectDRules'])) { $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1); if (is_array($options['selectDRules']) || str_in_array($options['selectDRules'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDRules']; $drules = API::DRule()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($drules, 'name'); } foreach ($drules as $druleid => $drule) { unset($drules[$druleid]['dservices']); $count = array(); foreach ($drule['dservices'] as $dnum => $dservice) { if (!is_null($options['limitSelects'])) { if (!isset($count[$dservice['dserviceid']])) { $count[$dservice['dserviceid']] = 0; } $count[$dservice['dserviceid']]++; if ($count[$dservice['dserviceid']] > $options['limitSelects']) { continue; } } $result[$dservice['dserviceid']]['drules'][] =& $drules[$druleid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDRules']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $drules = API::DRule()->get($objParams); $drules = zbx_toHash($drules, 'dserviceid'); foreach ($result as $dserviceid => $dservice) { if (isset($drules[$dserviceid])) { $result[$dserviceid]['drules'] = $drules[$dserviceid]['rowscount']; } else { $result[$dserviceid]['drules'] = 0; } } } } // selectDHosts if (!is_null($options['selectDHosts'])) { $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1); 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'); } foreach ($dhosts as $dhostid => $dhost) { unset($dhosts[$dhostid]['dservices']); foreach ($dhost['dservices'] as $snum => $dservice) { if (!is_null($options['limitSelects'])) { if (!isset($count[$dservice['dserviceid']])) { $count[$dservice['dserviceid']] = 0; } $count[$dservice['dserviceid']]++; if ($count[$dservice['dserviceid']] > $options['limitSelects']) { continue; } } $result[$dservice['dserviceid']]['dhosts'][] =& $dhosts[$dhostid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDHosts']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $dhosts = API::DHost()->get($objParams); $dhosts = zbx_toHash($dhosts, 'dhostid'); foreach ($result as $dserviceid => $dservice) { if (isset($dhosts[$dserviceid])) { $result[$dserviceid]['dhosts'] = $dhosts[$dserviceid]['rowscount']; } else { $result[$dserviceid]['dhosts'] = 0; } } } } // selectHosts if (!is_null($options['selectHosts'])) { $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1, 'sortfield' => 'status'); 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, 'hostid'); } foreach ($hosts as $hostid => $host) { unset($hosts[$hostid]['dservices']); foreach ($host['dservices'] as $dnum => $dservice) { if (!is_null($options['limitSelects'])) { if (!isset($count[$dservice['dserviceid']])) { $count[$dservice['dserviceid']] = 0; } $count[$dservice['dserviceid']]++; if ($count[$dservice['dserviceid']] > $options['limitSelects']) { continue; } } $result[$dservice['dserviceid']]['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 $dserviceid => $dservice) { if (isset($hosts[$dserviceid])) { $result[$dserviceid]['hosts'] = $hosts[$dserviceid]['rowscount']; } else { $result[$dserviceid]['hosts'] = 0; } } } } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
public function get($options) { $result = array(); $userType = self::$userData['type']; $sqlParts = array('select' => array('dchecks' => 'dc.dcheckid'), 'from' => array('dchecks' => 'dchecks dc'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('dcheckids' => null, 'druleids' => null, 'dserviceids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectDRules' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == $userType) { } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) { } elseif (!is_null($options['editable']) && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { return array(); } // dcheckids if (!is_null($options['dcheckids'])) { zbx_value2array($options['dcheckids']); $sqlParts['where']['dcheckid'] = dbConditionInt('dc.dcheckid', $options['dcheckids']); } // druleids if (!is_null($options['druleids'])) { zbx_value2array($options['druleids']); $sqlParts['where'][] = dbConditionInt('dc.druleid', $options['druleids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['druleid'] = 'dc.druleid'; } } // dserviceids if (!is_null($options['dserviceids'])) { zbx_value2array($options['dserviceids']); $sqlParts['from']['dhosts'] = 'dhosts dh'; $sqlParts['from']['dservices'] = 'dservices ds'; $sqlParts['where']['ds'] = dbConditionInt('ds.dserviceid', $options['dserviceids']); $sqlParts['where']['dcdh'] = 'dc.druleid=dh.druleid'; $sqlParts['where']['dhds'] = 'dh.hostid=ds.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['dserviceid'] = 'ds.dserviceid'; } } // filter if (is_array($options['filter'])) { $this->dbFilter('dchecks dc', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('dchecks dc', $options, $sqlParts); } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } //------- $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($dcheck = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $dcheck; } else { $result = $dcheck['rowscount']; } } else { $result[$dcheck['dcheckid']] = $dcheck; } } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, array('druleid'), $options['output']); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
protected function inherit(array $items, array $hostids = null) { if (!$items) { return true; } // fetch the corresponding discovery rules for the child items $ruleids = array(); $dbResult = DBselect('SELECT i.itemid AS ruleid,id.itemid,i.hostid' . ' FROM items i,item_discovery id' . ' WHERE i.templateid=id.parent_itemid' . ' AND ' . dbConditionInt('id.itemid', zbx_objectValues($items, 'itemid'))); while ($rule = DBfetch($dbResult)) { if (!isset($ruleids[$rule['itemid']])) { $ruleids[$rule['itemid']] = array(); } $ruleids[$rule['itemid']][$rule['hostid']] = $rule['ruleid']; } // prepare the child items $newItems = $this->prepareInheritedItems($items, $hostids); if (!$items) { return true; } $insertItems = array(); $updateItems = array(); foreach ($newItems as $newItem) { if (isset($newItem['itemid'])) { unset($newItem['ruleid']); $updateItems[] = $newItem; } else { // set the corresponding discovery rule id for the new items $newItem['ruleid'] = $ruleids[$newItem['templateid']][$newItem['hostid']]; $newItem['flags'] = ZBX_FLAG_DISCOVERY_PROTOTYPE; $insertItems[] = $newItem; } } // save the new items $this->createReal($insertItems); $this->updateReal($updateItems); // propagate the inheritance to the children $this->inherit(array_merge($insertItems, $updateItems)); }
/** * Get items from expression. * * @param CTriggerExpression $triggerExpression * * @return array */ function getExpressionItems(CTriggerExpression $triggerExpression) { $items = array(); $processedFunctions = array(); $processedItems = array(); foreach ($triggerExpression->expressions as $expression) { if (isset($processedFunctions[$expression['expression']])) { continue; } if (!isset($processedItems[$expression['host']][$expression['item']])) { $dbItems = DBselect('SELECT i.itemid,i.flags' . ' FROM items i,hosts h' . ' WHERE i.key_=' . zbx_dbstr($expression['item']) . ' AND ' . dbConditionInt('i.flags', array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED, ZBX_FLAG_DISCOVERY_PROTOTYPE)) . ' AND h.host=' . zbx_dbstr($expression['host']) . ' AND h.hostid=i.hostid' . andDbNode('i.itemid')); if ($dbItem = DBfetch($dbItems)) { $items[] = $dbItem; $processedItems[$expression['host']][$expression['item']] = true; } } $processedFunctions[$expression['expression']] = true; } return $items; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $sysmapIds = array_keys($result); // adding elements if ($options['selectSelements'] !== null && $options['selectSelements'] != API_OUTPUT_COUNT) { $selements = API::getApiService()->select('sysmaps_elements', array('output' => $this->outputExtend($options['selectSelements'], array('selementid', 'sysmapid')), 'filter' => array('sysmapid' => $sysmapIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($selements, 'sysmapid', 'selementid'); // add selement URLs if ($this->outputIsRequested('urls', $options['selectSelements'])) { foreach ($selements as &$selement) { $selement['urls'] = array(); } unset($selement); if (!is_null($options['expandUrls'])) { $dbMapUrls = DBselect('SELECT su.sysmapurlid,su.sysmapid,su.name,su.url,su.elementtype' . ' FROM sysmap_url su' . ' WHERE ' . dbConditionInt('su.sysmapid', $sysmapIds)); while ($mapUrl = DBfetch($dbMapUrls)) { foreach ($selements as $snum => $selement) { if (bccomp($selement['sysmapid'], $mapUrl['sysmapid']) == 0 && ($selement['elementtype'] == $mapUrl['elementtype'] && $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP || $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS && $mapUrl['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST)) { $selements[$snum]['urls'][] = $this->expandUrlMacro($mapUrl, $selement); } } } } $dbSelementUrls = DBselect('SELECT seu.sysmapelementurlid,seu.selementid,seu.name,seu.url' . ' FROM sysmap_element_url seu' . ' WHERE ' . dbConditionInt('seu.selementid', array_keys($selements))); while ($selementUrl = DBfetch($dbSelementUrls)) { $selements[$selementUrl['selementid']]['urls'][] = is_null($options['expandUrls']) ? $selementUrl : $this->expandUrlMacro($selementUrl, $selements[$selementUrl['selementid']]); } } $selements = $this->unsetExtraFields($selements, array('sysmapid', 'selementid'), $options['selectSelements']); $result = $relationMap->mapMany($result, $selements, 'selements'); } // adding icon maps if ($options['selectIconMap'] !== null && $options['selectIconMap'] != API_OUTPUT_COUNT) { $iconMaps = API::IconMap()->get(array('output' => $this->outputExtend($options['selectIconMap'], array('sysmapid', 'iconmapid')), 'sysmapids' => $sysmapIds, 'preservekeys' => true, 'nopermissions' => true)); $relationMap = $this->createRelationMap($iconMaps, 'sysmapid', 'iconmapid'); $iconMaps = $this->unsetExtraFields($iconMaps, array('sysmapid', 'iconmapid'), $options['selectIconMap']); $result = $relationMap->mapOne($result, $iconMaps, 'iconmap'); } // adding links if ($options['selectLinks'] !== null && $options['selectLinks'] != API_OUTPUT_COUNT) { $links = API::getApiService()->select('sysmaps_links', array('output' => $this->outputExtend($options['selectLinks'], array('sysmapid', 'linkid')), 'filter' => array('sysmapid' => $sysmapIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($links, 'sysmapid', 'linkid'); // add link triggers if ($this->outputIsRequested('linktriggers', $options['selectLinks'])) { $linkTriggers = DBFetchArrayAssoc(DBselect('SELECT DISTINCT slt.*' . ' FROM sysmaps_link_triggers slt' . ' WHERE ' . dbConditionInt('slt.linkid', $relationMap->getRelatedIds())), 'linktriggerid'); $linkTriggerRelationMap = $this->createRelationMap($linkTriggers, 'linkid', 'linktriggerid'); $links = $linkTriggerRelationMap->mapMany($links, $linkTriggers, 'linktriggers'); } $links = $this->unsetExtraFields($links, array('sysmapid', 'linkid'), $options['selectLinks']); $result = $relationMap->mapMany($result, $links, 'links'); } // adding urls if ($options['selectUrls'] !== null && $options['selectUrls'] != API_OUTPUT_COUNT) { $links = API::getApiService()->select('sysmap_url', array('output' => $this->outputExtend($options['selectUrls'], array('sysmapid', 'sysmapurlid')), 'filter' => array('sysmapid' => $sysmapIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($links, 'sysmapid', 'sysmapurlid'); $links = $this->unsetExtraFields($links, array('sysmapid', 'sysmapurlid'), $options['selectUrls']); $result = $relationMap->mapMany($result, $links, 'urls'); } return $result; }
/** * Delete Maintenances. * * @param array $maintenanceids * * @return array */ public function delete(array $maintenanceids) { if (self::$userData['type'] == USER_TYPE_ZABBIX_USER) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } $options = ['output' => ['maintenanceid', 'name'], 'maintenanceids' => $maintenanceids, 'editable' => true, 'preservekeys' => true]; $maintenances = $this->get($options); foreach ($maintenanceids as $maintenanceid) { if (!isset($maintenances[$maintenanceid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } $timeperiodids = []; $dbTimeperiods = DBselect('SELECT DISTINCT tp.timeperiodid' . ' FROM timeperiods tp,maintenances_windows mw' . ' WHERE ' . dbConditionInt('mw.maintenanceid', $maintenanceids) . ' AND tp.timeperiodid=mw.timeperiodid'); while ($timeperiod = DBfetch($dbTimeperiods)) { $timeperiodids[] = $timeperiod['timeperiodid']; } $midCond = ['maintenanceid' => $maintenanceids]; // remove maintenanceid from hosts table $options = ['real_hosts' => true, 'output' => ['hostid'], 'filter' => ['maintenanceid' => $maintenanceids]]; $hosts = API::Host()->get($options); if (!empty($hosts)) { DB::update('hosts', ['values' => ['maintenanceid' => 0], 'where' => ['hostid' => zbx_objectValues($hosts, 'hostid')]]); } DB::delete('timeperiods', ['timeperiodid' => $timeperiodids]); DB::delete('maintenances_windows', $midCond); DB::delete('maintenances_hosts', $midCond); DB::delete('maintenances_groups', $midCond); DB::delete('maintenances', $midCond); foreach ($maintenances as $maintenanceid => $maintenance) { add_audit_details(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_MAINTENANCE, $maintenanceid, $maintenance['name'], null); } return ['maintenanceids' => $maintenanceids]; }