/** * Get value maps. * * @param array $options * * @return array */ public function get($options = []) { $options = zbx_array_merge($this->getOptions, $options); if ($options['editable'] !== null && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { return $options['countOutput'] !== null && $options['groupCount'] === null ? 0 : []; } $res = DBselect($this->createSelectQuery($this->tableName(), $options), $options['limit']); $result = []; while ($row = DBfetch($res)) { if ($options['countOutput'] === null) { $result[$row[$this->pk()]] = $row; } else { if ($options['groupCount'] === null) { $result = $row['rowscount']; } else { $result[] = $row; } } } if ($options['countOutput'] !== null) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); } // removing keys (hash -> array) if ($options['preservekeys'] === null) { $result = zbx_cleanHashes($result); } return $result; }
/** * Get host prototypes. * * @param array $options * * @return array */ public function get(array $options) { $options = zbx_array_merge($this->getOptions, $options); $options['filter']['flags'] = ZBX_FLAG_DISCOVERY_PROTOTYPE; // build and execute query $sql = $this->createSelectQuery($this->tableName(), $options); $res = DBselect($sql, $options['limit']); // fetch results $result = []; while ($row = DBfetch($res)) { // a count query, return a single result if ($options['countOutput'] !== null) { if ($options['groupCount'] !== null) { $result[] = $row; } else { $result = $row['rowscount']; } } else { $result[$row[$this->pk()]] = $row; } } if ($options['countOutput'] !== null) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, ['triggerid'], $options['output']); } if ($options['preservekeys'] === null) { $result = zbx_cleanHashes($result); } return $result; }
/** * 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; }
/** * Get IconMap data. * @param array $options * @param array $options['iconmapids'] * @param array $options['sysmapids'] * @param array $options['editable'] * @param array $options['count'] * @param array $options['limit'] * @param array $options['order'] * @return array */ public function get(array $options = []) { $result = []; $sqlParts = ['select' => ['icon_map' => 'im.iconmapid'], 'from' => ['icon_map' => 'icon_map im'], 'where' => [], 'order' => [], 'limit' => null]; $defOptions = ['iconmapids' => null, 'sysmapids' => null, 'nopermissions' => null, 'editable' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectMappings' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null]; $options = zbx_array_merge($defOptions, $options); // editable + PERMISSION CHECK if ($options['editable'] && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { return []; } // iconmapids if (!is_null($options['iconmapids'])) { zbx_value2array($options['iconmapids']); $sqlParts['where'][] = dbConditionInt('im.iconmapid', $options['iconmapids']); } // sysmapids if (!is_null($options['sysmapids'])) { zbx_value2array($options['sysmapids']); $sqlParts['from']['sysmaps'] = 'sysmaps s'; $sqlParts['where'][] = dbConditionInt('s.sysmapid', $options['sysmapids']); $sqlParts['where']['ims'] = 'im.iconmapid=s.iconmapid'; } // filter if (is_array($options['filter'])) { $this->dbFilter('icon_map im', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('icon_map im', $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); $dbRes = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($iconMap = DBfetch($dbRes)) { if ($options['countOutput']) { $result = $iconMap['rowscount']; } else { $result[$iconMap['iconmapid']] = $iconMap; } } 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; }
/** * Get screen item data. * * @param array $options * @param array $options['hostid'] Use hostid to get real resource id * @param array $options['screenitemids'] Search by screen item IDs * @param array $options['screenids'] Search by screen IDs * @param array $options['filter'] Result filter * @param array $options['limit'] The size of the result set * * @return array */ public function get(array $options = []) { $options = zbx_array_merge($this->getOptions, $options); // build and execute query $sql = $this->createSelectQuery($this->tableName(), $options); $res = DBselect($sql, $options['limit']); // fetch results $result = []; while ($row = DBfetch($res)) { // count query, return a single result if ($options['countOutput'] !== null) { $result = $row['rowscount']; } else { if ($options['preservekeys'] !== null) { $result[$row['screenitemid']] = $row; } else { $result[] = $row; } } } // fill result with real resourceid if ($options['hostids'] && $result) { if (empty($options['screenitemid'])) { $options['screenitemid'] = zbx_objectValues($result, 'screenitemid'); } $dbTemplateScreens = API::TemplateScreen()->get(['output' => ['screenitemid'], 'screenitemids' => $options['screenitemid'], 'hostids' => $options['hostids'], 'selectScreenItems' => API_OUTPUT_EXTEND]); if ($dbTemplateScreens) { foreach ($result as &$screenItem) { foreach ($dbTemplateScreens as $dbTemplateScreen) { foreach ($dbTemplateScreen['screenitems'] as $dbScreenItem) { if ($screenItem['screenitemid'] == $dbScreenItem['screenitemid'] && isset($dbScreenItem['real_resourceid']) && $dbScreenItem['real_resourceid']) { $screenItem['real_resourceid'] = $dbScreenItem['real_resourceid']; } } } } unset($screenItem); } } return $result; }
/** * Get ScreemItem data * * @param array $options * @param array $options['nodeids'] Node IDs * @param array $options['screenitemids'] Search by screen item IDs * @param array $options['screenids'] Search by screen IDs * @param array $options['filter'] Result filter * @param array $options['limit'] The size of the result set * * @return array|boolean Host data as array or false if error */ public function get(array $options = array()) { $options = zbx_array_merge($this->getOptions, $options); // build and execute query $sql = $this->createSelectQuery($this->tableName(), $options); $res = DBselect($sql, $options['limit']); // fetch results $result = array(); while ($row = DBfetch($res)) { // count query, return a single result if ($options['countOutput'] !== null) { $result = $row['rowscount']; } else { if ($options['preservekeys'] !== null) { $result[$row['screenitemid']] = $row; } else { $result[] = $row; } } } return $result; }
/** * 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 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)); }
/** * 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; }
/** * Get history data * * {@source} * @access public * @static * @since 1.8.3 * @version 1.3 * * @param array $options * @param array $options['itemids'] * @param boolean $options['editable'] * @param string $options['pattern'] * @param int $options['limit'] * @param string $options['order'] * @return array|int item data as array or false if error */ public static function get($options = array()) { global $USER_DETAILS; $nodeCheck = false; $result = array(); $sort_columns = array('itemid', 'clock'); // allowed columns for sorting $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND); // allowed output options for [ select_* ] params $sql_parts = array('select' => array('history' => 'h.itemid'), 'from' => array(), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $def_options = array('history' => ITEM_VALUE_TYPE_UINT64, 'nodeids' => null, 'hostids' => null, 'itemids' => null, 'triggerids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'time_from' => null, 'time_till' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'groupCount' => null, 'groupOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($def_options, $options); switch ($options['history']) { case ITEM_VALUE_TYPE_LOG: $sql_parts['from']['history'] = 'history_log h'; $sort_columns[] = 'id'; break; case ITEM_VALUE_TYPE_TEXT: $sql_parts['from']['history'] = 'history_text h'; $sort_columns[] = 'id'; break; case ITEM_VALUE_TYPE_STR: $sql_parts['from']['history'] = 'history_str h'; break; case ITEM_VALUE_TYPE_UINT64: $sql_parts['from']['history'] = 'history_uint h'; break; case ITEM_VALUE_TYPE_FLOAT: default: $sql_parts['from']['history'] = 'history h'; } // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == $USER_DETAILS['type'] || $options['nopermissions']) { } else { $itemOptions = array('editable' => $options['editable'], 'preservekeys' => 1); if (!is_null($options['itemids'])) { $itemOptions['itemids'] = $options['itemids']; } $items = CItem::get($itemOptions); $options['itemids'] = array_keys($items); } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); $sql_parts['where']['itemid'] = DBcondition('h.itemid', $options['itemids']); if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.itemid', $nodeids); } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['hostid'] = 'i.hostid'; } $sql_parts['from']['items'] = 'items i'; $sql_parts['where']['i'] = DBcondition('i.hostid', $options['hostids']); $sql_parts['where']['hi'] = 'h.itemid=i.itemid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('i.hostid', $nodeids); } } // node check !!!!! // should be last, after all ****IDS checks if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.itemid', $nodeids); } // time_from if (!is_null($options['time_from'])) { $sql_parts['select']['clock'] = 'h.clock'; $sql_parts['where']['clock_from'] = 'h.clock>=' . $options['time_from']; } // time_till if (!is_null($options['time_till'])) { $sql_parts['select']['clock'] = 'h.clock'; $sql_parts['where']['clock_till'] = 'h.clock<=' . $options['time_till']; } // filter if (is_array($options['filter'])) { zbx_db_filter($sql_parts['from']['history'], $options, $sql_parts); } // search if (is_array($options['search'])) { zbx_db_search($sql_parts['from']['history'], $options, $sql_parts); } // output if ($options['output'] == API_OUTPUT_EXTEND) { unset($sql_parts['select']['clock']); $sql_parts['select']['history'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sql_parts['select'] = array('count(DISTINCT h.hostid) as rowscount'); //groupCount if (!is_null($options['groupCount'])) { foreach ($sql_parts['group'] as $key => $fields) { $sql_parts['select'][$key] = $fields; } } } // groupOutput $groupOutput = false; if (!is_null($options['groupOutput'])) { if (str_in_array('h.' . $options['groupOutput'], $sql_parts['select']) || str_in_array('h.*', $sql_parts['select'])) { $groupOutput = true; } } // order // restrict not allowed columns for sorting $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : ''; if (!zbx_empty($options['sortfield'])) { $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP; if ($options['sortfield'] == 'clock') { $sql_parts['order']['itemid'] = 'h.itemid ' . $sortorder; } $sql_parts['order'][$options['sortfield']] = 'h.' . $options['sortfield'] . ' ' . $sortorder; if (!str_in_array('h.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('h.*', $sql_parts['select'])) { $sql_parts['select'][$options['sortfield']] = 'h.' . $options['sortfield']; } } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sql_parts['limit'] = $options['limit']; } //--------------- $itemids = array(); $triggerids = array(); $sql_parts['select'] = array_unique($sql_parts['select']); $sql_parts['from'] = array_unique($sql_parts['from']); $sql_parts['where'] = array_unique($sql_parts['where']); $sql_parts['order'] = array_unique($sql_parts['order']); $sql_select = ''; $sql_from = ''; $sql_where = ''; $sql_order = ''; if (!empty($sql_parts['select'])) { $sql_select .= implode(',', $sql_parts['select']); } if (!empty($sql_parts['from'])) { $sql_from .= implode(',', $sql_parts['from']); } if (!empty($sql_parts['where'])) { $sql_where .= implode(' AND ', $sql_parts['where']); } if (!empty($sql_parts['order'])) { $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']); } $sql_limit = $sql_parts['limit']; $sql = 'SELECT ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_order; $db_res = DBselect($sql, $sql_limit); //SDI($sql); $count = 0; $group = array(); while ($data = DBfetch($db_res)) { if ($options['countOutput']) { $result = $data; } else { $itemids[$data['itemid']] = $data['itemid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$count] = array('itemid' => $data['itemid']); } else { $result[$count] = array(); // hostids if (isset($data['hostid'])) { if (!isset($result[$count]['hosts'])) { $result[$count]['hosts'] = array(); } $result[$count]['hosts'][] = array('hostid' => $data['hostid']); unset($data['hostid']); } // triggerids if (isset($data['triggerid'])) { if (!isset($result[$count]['triggers'])) { $result[$count]['triggers'] = array(); } $result[$count]['triggers'][] = array('triggerid' => $data['triggerid']); unset($data['triggerid']); } // itemids // if(isset($data['itemid']) && !is_null($options['itemids'])){ // if(!isset($result[$count]['items'])) $result[$count]['items'] = array(); // $result[$count]['items'][] = array('itemid' => $data['itemid']); // } $result[$count] += $data; // grouping if ($groupOutput) { $dataid = $data[$options['groupOutput']]; if (!isset($group[$dataid])) { $group[$dataid] = array(); } $group[$dataid][] = $result[$count]; } $count++; } } } COpt::memoryPick(); if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
function get_viewed_hosts($perm, $groupid = 0, $options = array(), $nodeid = null, $sql = array()) { global $USER_DETAILS; global $page; $userid = $USER_DETAILS['userid']; $def_sql = array('select' => array('h.hostid', 'h.host'), 'from' => array('hosts h'), 'where' => array(), 'order' => array()); $def_options = array('deny_all' => 0, 'allow_all' => 0, 'select_first_host' => 0, 'select_first_host_if_empty' => 0, 'select_host_on_group_switch' => 0, 'do_not_select' => 0, 'do_not_select_if_empty' => 0, 'monitored_hosts' => 0, 'templated_hosts' => 0, 'real_hosts' => 0, 'not_proxy_hosts' => 0, 'with_items' => 0, 'with_monitored_items' => 0, 'with_historical_items' => 0, 'with_triggers' => 0, 'with_monitored_triggers' => 0, 'with_httptests' => 0, 'with_monitored_httptests' => 0, 'with_graphs' => 0, 'only_current_node' => 0); $def_options = zbx_array_merge($def_options, $options); $config = select_config(); $dd_first_entry = $config['dropdown_first_entry']; if ($def_options['allow_all']) { $dd_first_entry = ZBX_DROPDOWN_FIRST_ALL; } if ($def_options['deny_all']) { $dd_first_entry = ZBX_DROPDOWN_FIRST_NONE; } if ($dd_first_entry == ZBX_DROPDOWN_FIRST_ALL) { $def_options['select_host_on_group_switch'] = 1; } $result = array('original' => -1, 'selected' => 0, 'hosts' => array(), 'hostids' => array()); $hosts =& $result['hosts']; $hostids =& $result['hostids']; $first_entry = $dd_first_entry == ZBX_DROPDOWN_FIRST_NONE ? S_NOT_SELECTED_SMALL : S_ALL_SMALL; $hosts['0'] = $first_entry; if (!is_array($groupid) && $groupid == 0) { if ($dd_first_entry == ZBX_DROPDOWN_FIRST_NONE) { return $result; } } else { zbx_value2array($groupid); $def_sql['from'][] = 'hosts_groups hg'; $def_sql['where'][] = DBcondition('hg.groupid', $groupid); $def_sql['where'][] = 'hg.hostid=h.hostid'; } $_REQUEST['hostid'] = $result['original'] = get_request('hostid', -1); //----- if (is_null($nodeid)) { if (!$def_options['only_current_node']) { $nodeid = get_current_nodeid(); } else { $nodeid = get_current_nodeid(false); } } //$nodeid = is_null($nodeid)?get_current_nodeid($opt):$nodeid; //$available_hosts = get_accessible_hosts_by_user($USER_DETAILS,$perm,PERM_RES_IDS_ARRAY,$nodeid,AVAILABLE_NOCACHE); if (USER_TYPE_SUPER_ADMIN != $USER_DETAILS['type']) { $def_sql['from']['hg'] = 'hosts_groups hg'; $def_sql['from']['r'] = 'rights r'; $def_sql['from']['ug'] = 'users_groups ug'; $def_sql['where']['hgh'] = 'hg.hostid=h.hostid'; $def_sql['where'][] = 'r.id=hg.groupid '; $def_sql['where'][] = 'r.groupid=ug.usrgrpid'; $def_sql['where'][] = 'ug.userid=' . $userid; $def_sql['where'][] = 'r.permission>=' . $perm; $def_sql['where'][] = 'NOT EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups gg ' . ' WHERE hgg.hostid=hg.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $perm . ')'; } // nodes if (ZBX_DISTRIBUTED) { $def_sql['select'][] = 'n.name'; $def_sql['from'][] = 'nodes n'; $def_sql['where'][] = 'n.nodeid=' . DBid2nodeid('h.hostid'); $def_sql['order'][] = 'n.name'; } // hosts if ($def_options['monitored_hosts']) { $def_sql['where'][] = 'h.status=' . HOST_STATUS_MONITORED; } else { if ($def_options['real_hosts']) { $def_sql['where'][] = 'h.status IN(' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')'; } else { if ($def_options['templated_hosts']) { $def_sql['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE; } else { if ($def_options['not_proxy_hosts']) { $def_sql['where'][] = 'h.status<>' . HOST_STATUS_PROXY; } } } } // items if ($def_options['with_items']) { $def_sql['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid )'; } else { if ($def_options['with_monitored_items']) { $def_sql['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND i.status=' . ITEM_STATUS_ACTIVE . ')'; } else { if ($def_options['with_historical_items']) { $def_sql['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND (i.status=' . ITEM_STATUS_ACTIVE . ' OR i.status=' . ITEM_STATUS_NOTSUPPORTED . ') AND i.lastvalue IS NOT NULL)'; } } } // triggers if ($def_options['with_triggers']) { $def_sql['where'][] = 'EXISTS( SELECT i.itemid ' . ' FROM items i, functions f, triggers t' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid)'; } else { if ($def_options['with_monitored_triggers']) { $def_sql['where'][] = 'EXISTS( SELECT i.itemid ' . ' FROM items i, functions f, triggers t' . ' WHERE i.hostid=h.hostid ' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid ' . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')'; } } // httptests if ($def_options['with_httptests']) { $def_sql['where'][] = 'EXISTS( SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid)'; } else { if ($def_options['with_monitored_httptests']) { $def_sql['where'][] = 'EXISTS( SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid ' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')'; } } // graphs if ($def_options['with_graphs']) { $def_sql['where'][] = 'EXISTS( SELECT DISTINCT i.itemid ' . ' FROM items i, graphs_items gi ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=gi.itemid)'; } //------ $def_sql['order'][] = 'h.host'; foreach ($sql as $key => $value) { zbx_value2array($value); if (isset($def_sql[$key])) { $def_sql[$key] = zbx_array_merge($def_sql[$key], $value); } else { $def_sql[$key] = $value; } } $def_sql['select'] = array_unique($def_sql['select']); $def_sql['from'] = array_unique($def_sql['from']); $def_sql['where'] = array_unique($def_sql['where']); $def_sql['order'] = array_unique($def_sql['order']); $sql_select = ''; $sql_from = ''; $sql_where = ''; $sql_order = ''; if (!empty($def_sql['select'])) { $sql_select .= implode(',', $def_sql['select']); } if (!empty($def_sql['from'])) { $sql_from .= implode(',', $def_sql['from']); } if (!empty($def_sql['where'])) { $sql_where .= ' AND ' . implode(' AND ', $def_sql['where']); } if (!empty($def_sql['order'])) { $sql_order .= implode(',', $def_sql['order']); } $sql = 'SELECT DISTINCT ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . DBin_node('h.hostid', $nodeid) . $sql_where . ' ORDER BY ' . $sql_order; $res = DBselect($sql); while ($host = DBfetch($res)) { $hosts[$host['hostid']] = $host['host']; $hostids[$host['hostid']] = $host['hostid']; if (bccomp($_REQUEST['hostid'], $host['hostid']) == 0) { $result['selected'] = $host['hostid']; } } $profile_hostid = CProfile::get('web.' . $page['menu'] . '.hostid'); //----- if ($def_options['do_not_select']) { $_REQUEST['hostid'] = $result['selected'] = 0; } else { if ($def_options['do_not_select_if_empty'] && $_REQUEST['hostid'] == -1) { $_REQUEST['hostid'] = $result['selected'] = 0; } else { if ($def_options['select_first_host'] || $def_options['select_first_host_if_empty'] && $_REQUEST['hostid'] == -1 && is_null($profile_hostid) || $def_options['select_host_on_group_switch'] && $_REQUEST['hostid'] != -1 && bccomp($_REQUEST['hostid'], $result['selected']) != 0) { $first_hostid = next($hostids); reset($hostids); if ($first_hostid !== FALSE) { $_REQUEST['hostid'] = $result['selected'] = $first_hostid; } else { $_REQUEST['hostid'] = $result['selected'] = 0; } } else { if ($config['dropdown_first_remember']) { if ($_REQUEST['hostid'] == -1) { $_REQUEST['hostid'] = is_null($profile_hostid) ? '0' : $profile_hostid; } if (isset($hostids[$_REQUEST['hostid']])) { $result['selected'] = $_REQUEST['hostid']; } else { $_REQUEST['hostid'] = $result['selected']; } } else { $_REQUEST['hostid'] = $result['selected']; } } } } return $result; }
/** * Get items data. * * @param array $options * @param array $options['itemids'] * @param array $options['hostids'] * @param array $options['groupids'] * @param array $options['triggerids'] * @param array $options['applicationids'] * @param bool $options['status'] * @param bool $options['templated_items'] * @param bool $options['editable'] * @param bool $options['count'] * @param string $options['pattern'] * @param int $options['limit'] * @param string $options['order'] * * @return array|int item data as array or false if error */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = array('select' => array('items' => 'i.itemid'), 'from' => array('items' => 'items i'), 'where' => array('webtype' => 'i.type<>' . ITEM_TYPE_HTTPTEST, 'flags' => 'i.flags IN (' . ZBX_FLAG_DISCOVERY_NORMAL . ',' . ZBX_FLAG_DISCOVERY_CREATED . ')'), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('groupids' => null, 'templateids' => null, 'hostids' => null, 'proxyids' => null, 'itemids' => null, 'interfaceids' => null, 'graphids' => null, 'triggerids' => null, 'applicationids' => null, 'webitems' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'editable' => null, 'nopermissions' => null, 'group' => null, 'host' => null, 'application' => null, 'with_triggers' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => null, 'selectInterfaces' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectApplications' => null, 'selectDiscoveryRule' => null, 'selectItemDiscovery' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); // 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 hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE i.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')'; } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); $sqlParts['where']['itemid'] = dbConditionInt('i.itemid', $options['itemids']); } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $options['hostids'] = array_merge($options['hostids'], $options['templateids']); } else { $options['hostids'] = $options['templateids']; } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['hostids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['i'] = 'i.hostid'; } } // interfaceids if (!is_null($options['interfaceids'])) { zbx_value2array($options['interfaceids']); $sqlParts['where']['interfaceid'] = dbConditionInt('i.interfaceid', $options['interfaceids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['i'] = 'i.interfaceid'; } } // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where'][] = 'hg.hostid=i.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['hg'] = 'hg.groupid'; } } // proxyids if (!is_null($options['proxyids'])) { zbx_value2array($options['proxyids']); $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where'][] = dbConditionInt('h.proxy_hostid', $options['proxyids']); $sqlParts['where'][] = 'h.hostid=i.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['h'] = 'h.proxy_hostid'; } } // triggerids if (!is_null($options['triggerids'])) { zbx_value2array($options['triggerids']); $sqlParts['from']['functions'] = 'functions f'; $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']); $sqlParts['where']['if'] = 'i.itemid=f.itemid'; } // applicationids if (!is_null($options['applicationids'])) { zbx_value2array($options['applicationids']); $sqlParts['from']['items_applications'] = 'items_applications ia'; $sqlParts['where'][] = dbConditionInt('ia.applicationid', $options['applicationids']); $sqlParts['where']['ia'] = 'ia.itemid=i.itemid'; } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']); $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; } // webitems if (!is_null($options['webitems'])) { unset($sqlParts['where']['webtype']); } // inherited if (!is_null($options['inherited'])) { if ($options['inherited']) { $sqlParts['where'][] = 'i.templateid IS NOT NULL'; } else { $sqlParts['where'][] = 'i.templateid IS NULL'; } } // templated if (!is_null($options['templated'])) { $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if ($options['templated']) { $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE; } else { $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE; } } // monitored if (!is_null($options['monitored'])) { $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if ($options['monitored']) { $sqlParts['where'][] = 'h.status=' . HOST_STATUS_MONITORED; $sqlParts['where'][] = 'i.status=' . ITEM_STATUS_ACTIVE; } else { $sqlParts['where'][] = '(h.status<>' . HOST_STATUS_MONITORED . ' OR i.status<>' . ITEM_STATUS_ACTIVE . ')'; } } // search if (is_array($options['search'])) { zbx_db_search('items i', $options, $sqlParts); } // filter if (is_array($options['filter'])) { $this->dbFilter('items i', $options, $sqlParts); if (isset($options['filter']['host'])) { zbx_value2array($options['filter']['host']); $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; $sqlParts['where']['h'] = dbConditionString('h.host', $options['filter']['host'], false, true); } if (array_key_exists('flags', $options['filter']) && (is_null($options['filter']['flags']) || !zbx_empty($options['filter']['flags']))) { unset($sqlParts['where']['flags']); } } // group if (!is_null($options['group'])) { $sqlParts['from']['groups'] = 'groups g'; $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where']['ghg'] = 'g.groupid=hg.groupid'; $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid'; $sqlParts['where'][] = ' g.name=' . zbx_dbstr($options['group']); } // host if (!is_null($options['host'])) { $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; $sqlParts['where'][] = ' h.host=' . zbx_dbstr($options['host']); } // application if (!is_null($options['application'])) { $sqlParts['from']['applications'] = 'applications a'; $sqlParts['from']['items_applications'] = 'items_applications ia'; $sqlParts['where']['aia'] = 'a.applicationid = ia.applicationid'; $sqlParts['where']['iai'] = 'ia.itemid=i.itemid'; $sqlParts['where'][] = ' a.name=' . zbx_dbstr($options['application']); } // with_triggers if (!is_null($options['with_triggers'])) { if ($options['with_triggers'] == 1) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM functions ff,triggers t' . ' WHERE i.itemid=ff.itemid' . ' AND ff.triggerid=t.triggerid' . ' AND t.flags IN (' . ZBX_FLAG_DISCOVERY_NORMAL . ',' . ZBX_FLAG_DISCOVERY_CREATED . ')' . ')'; } else { $sqlParts['where'][] = 'NOT EXISTS (' . 'SELECT NULL' . ' FROM functions ff,triggers t' . ' WHERE i.itemid=ff.itemid' . ' AND ff.triggerid=t.triggerid' . ' AND t.flags IN (' . ZBX_FLAG_DISCOVERY_NORMAL . ',' . ZBX_FLAG_DISCOVERY_CREATED . ')' . ')'; } } // 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 ($item = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $item; } else { $result = $item['rowscount']; } } else { $result[$item['itemid']] = $item; } } if (!is_null($options['countOutput'])) { return $result; } // add other related objects if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, array('hostid', 'interfaceid', 'value_type'), $options['output']); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
$i['value_type'] = $item['value_type']; //ZBX-3059: So it would be possible to show different caption for history for chars and numbers (KB) $i['action'] = str_in_array($item['value_type'], array(ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64)) ? 'showgraph' : 'showvalues'; $i['description'] = item_description($item); $items[] = $i; } // Actions $actions = get_event_actions_status($event['eventid']); if ($config['event_ack_enable']) { if ($event['acknowledged'] == 1) { $ack = new CLink(S_YES, 'acknow.php?eventid=' . $event['eventid'] . '&backurl=' . $page['file']); } else { $ack = new CLink(S_NO, 'acknow.php?eventid=' . $event['eventid'] . '&backurl=' . $page['file'], 'on'); } } $description = expand_trigger_description_by_data(zbx_array_merge($trigger, array('clock' => $event['clock'])), ZBX_FLAG_EVENT); $tr_desc = new CSpan($description, 'pointer'); $tr_desc->addAction('onclick', "create_mon_trigger_menu(event, " . " new Array({'triggerid': '" . $trigger['triggerid'] . "', 'lastchange': '" . $event['clock'] . "'})," . zbx_jsvalue($items, true) . ");"); // Duration $tr_event = $event + $trigger; if ($next_event = get_next_event($tr_event, $events, $_REQUEST['hide_unknown'])) { $event['duration'] = zbx_date2age($tr_event['clock'], $next_event['clock']); } else { $event['duration'] = zbx_date2age($tr_event['clock']); } $table->addRow(array(new CLink(zbx_date2str(S_EVENTS_ACTION_TIME_FORMAT, $event['clock']), 'tr_events.php?triggerid=' . $event['objectid'] . '&eventid=' . $event['eventid'], 'action'), is_show_all_nodes() ? get_node_name_by_elid($event['objectid']) : null, $_REQUEST['hostid'] == 0 ? $host['host'] : null, new CSpan($tr_desc, 'link_menu'), new CCol(trigger_value2str($event['value']), get_trigger_value_style($event['value'])), new CCol(get_severity_description($trigger['priority']), get_severity_style($trigger['priority'], $event['value'])), $event['duration'], $config['event_ack_enable'] ? $ack : NULL, $actions)); } } $table = array($paging, $table, $paging); $jsmenu = new CPUMenu(null, 170); $jsmenu->InsertJavaScript();
/** * Get data for item edit page. * * @param array $item item, item prototype or LLD rule to take the data from * @param bool $options['is_discovery_rule'] * * @return array */ function getItemFormData(array $item = array(), array $options = array()) { $data = array('form' => getRequest('form'), 'form_refresh' => getRequest('form_refresh'), 'is_discovery_rule' => !empty($options['is_discovery_rule']), 'parent_discoveryid' => getRequest('parent_discoveryid', !empty($options['is_discovery_rule']) ? getRequest('itemid') : null), 'itemid' => getRequest('itemid'), 'limited' => false, 'interfaceid' => getRequest('interfaceid', 0), 'name' => getRequest('name', ''), 'description' => getRequest('description', ''), 'key' => getRequest('key', ''), 'hostname' => getRequest('hostname'), 'delay' => getRequest('delay', ZBX_ITEM_DELAY_DEFAULT), 'history' => getRequest('history', 90), 'status' => getRequest('status', isset($_REQUEST['form_refresh']) ? 1 : 0), 'type' => getRequest('type', 0), 'snmp_community' => getRequest('snmp_community', 'public'), 'snmp_oid' => getRequest('snmp_oid', 'interfaces.ifTable.ifEntry.ifInOctets.1'), 'port' => getRequest('port', ''), 'value_type' => getRequest('value_type', ITEM_VALUE_TYPE_UINT64), 'data_type' => getRequest('data_type', ITEM_DATA_TYPE_DECIMAL), 'trapper_hosts' => getRequest('trapper_hosts', ''), 'units' => getRequest('units', ''), 'valuemapid' => getRequest('valuemapid', 0), 'params' => getRequest('params', ''), 'multiplier' => getRequest('multiplier', 0), 'delta' => getRequest('delta', 0), 'trends' => getRequest('trends', DAY_IN_YEAR), 'new_application' => getRequest('new_application', ''), 'applications' => getRequest('applications', array()), 'delay_flex' => getRequest('delay_flex', array()), 'new_delay_flex' => getRequest('new_delay_flex', array('delay' => 50, 'period' => ZBX_DEFAULT_INTERVAL)), 'snmpv3_contextname' => getRequest('snmpv3_contextname', ''), 'snmpv3_securityname' => getRequest('snmpv3_securityname', ''), 'snmpv3_securitylevel' => getRequest('snmpv3_securitylevel', 0), 'snmpv3_authprotocol' => getRequest('snmpv3_authprotocol', ITEM_AUTHPROTOCOL_MD5), 'snmpv3_authpassphrase' => getRequest('snmpv3_authpassphrase', ''), 'snmpv3_privprotocol' => getRequest('snmpv3_privprotocol', ITEM_PRIVPROTOCOL_DES), 'snmpv3_privpassphrase' => getRequest('snmpv3_privpassphrase', ''), 'ipmi_sensor' => getRequest('ipmi_sensor', ''), 'authtype' => getRequest('authtype', 0), 'username' => getRequest('username', ''), 'password' => getRequest('password', ''), 'publickey' => getRequest('publickey', ''), 'privatekey' => getRequest('privatekey', ''), 'formula' => getRequest('formula', 1), 'logtimefmt' => getRequest('logtimefmt', ''), 'add_groupid' => getRequest('add_groupid', getRequest('groupid', 0)), 'valuemaps' => null, 'possibleHostInventories' => null, 'alreadyPopulated' => null, 'initial_item_type' => null, 'templates' => array()); // hostid if (!empty($data['parent_discoveryid'])) { $discoveryRule = API::DiscoveryRule()->get(array('itemids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true)); $discoveryRule = reset($discoveryRule); $data['hostid'] = $discoveryRule['hostid']; } else { $data['hostid'] = getRequest('hostid', 0); } // types, http items only for internal processes $data['types'] = item_type2str(); unset($data['types'][ITEM_TYPE_HTTPTEST]); if (!empty($options['is_discovery_rule'])) { unset($data['types'][ITEM_TYPE_AGGREGATE], $data['types'][ITEM_TYPE_CALCULATED], $data['types'][ITEM_TYPE_SNMPTRAP]); } // item if ($item) { $data['item'] = $item; $data['hostid'] = !empty($data['hostid']) ? $data['hostid'] : $data['item']['hostid']; $data['limited'] = $data['item']['templateid'] != 0; // get templates $itemid = $item['itemid']; do { $params = array('itemids' => $itemid, 'output' => array('itemid', 'templateid'), 'selectHosts' => array('name')); if ($data['is_discovery_rule']) { $item = API::DiscoveryRule()->get($params); } else { $params['selectDiscoveryRule'] = array('itemid'); $params['filter'] = array('flags' => null); $item = API::Item()->get($params); } $item = reset($item); if (!empty($item)) { $host = reset($item['hosts']); if (!empty($item['hosts'])) { $host['name'] = CHtml::encode($host['name']); if (bccomp($data['itemid'], $itemid) == 0) { } elseif ($data['is_discovery_rule']) { $data['templates'][] = new CLink($host['name'], 'host_discovery.php?form=update&itemid=' . $item['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } elseif ($item['discoveryRule']) { $data['templates'][] = new CLink($host['name'], 'disc_prototypes.php?form=update&itemid=' . $item['itemid'] . '&parent_discoveryid=' . $item['discoveryRule']['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } else { $data['templates'][] = new CLink($host['name'], 'items.php?form=update&itemid=' . $item['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } } $itemid = $item['templateid']; } else { break; } } while ($itemid != 0); $data['templates'] = array_reverse($data['templates']); array_shift($data['templates']); } // caption if (!empty($data['is_discovery_rule'])) { $data['caption'] = _('Discovery rule'); } else { $data['caption'] = !empty($data['parent_discoveryid']) ? _('Item prototype') : _('Item'); } // hostname if (empty($data['is_discovery_rule']) && empty($data['hostname'])) { if (!empty($data['hostid'])) { $hostInfo = API::Host()->get(array('hostids' => $data['hostid'], 'output' => array('name'), 'templated_hosts' => true)); $hostInfo = reset($hostInfo); $data['hostname'] = $hostInfo['name']; } else { $data['hostname'] = _('not selected'); } } // fill data from item if (!hasRequest('form_refresh') && ($item || $data['limited'])) { $data['name'] = $data['item']['name']; $data['description'] = $data['item']['description']; $data['key'] = $data['item']['key_']; $data['interfaceid'] = $data['item']['interfaceid']; $data['type'] = $data['item']['type']; $data['snmp_community'] = $data['item']['snmp_community']; $data['snmp_oid'] = $data['item']['snmp_oid']; $data['port'] = $data['item']['port']; $data['value_type'] = $data['item']['value_type']; $data['data_type'] = $data['item']['data_type']; $data['trapper_hosts'] = $data['item']['trapper_hosts']; $data['units'] = $data['item']['units']; $data['valuemapid'] = $data['item']['valuemapid']; $data['multiplier'] = $data['item']['multiplier']; $data['hostid'] = $data['item']['hostid']; $data['params'] = $data['item']['params']; $data['snmpv3_contextname'] = $data['item']['snmpv3_contextname']; $data['snmpv3_securityname'] = $data['item']['snmpv3_securityname']; $data['snmpv3_securitylevel'] = $data['item']['snmpv3_securitylevel']; $data['snmpv3_authprotocol'] = $data['item']['snmpv3_authprotocol']; $data['snmpv3_authpassphrase'] = $data['item']['snmpv3_authpassphrase']; $data['snmpv3_privprotocol'] = $data['item']['snmpv3_privprotocol']; $data['snmpv3_privpassphrase'] = $data['item']['snmpv3_privpassphrase']; $data['ipmi_sensor'] = $data['item']['ipmi_sensor']; $data['authtype'] = $data['item']['authtype']; $data['username'] = $data['item']['username']; $data['password'] = $data['item']['password']; $data['publickey'] = $data['item']['publickey']; $data['privatekey'] = $data['item']['privatekey']; $data['logtimefmt'] = $data['item']['logtimefmt']; $data['new_application'] = getRequest('new_application', ''); if (!$data['is_discovery_rule']) { $data['formula'] = $data['item']['formula']; } if (!$data['limited'] || !isset($_REQUEST['form_refresh'])) { $data['delay'] = $data['item']['delay']; if (($data['type'] == ITEM_TYPE_TRAPPER || $data['type'] == ITEM_TYPE_SNMPTRAP) && $data['delay'] == 0) { $data['delay'] = ZBX_ITEM_DELAY_DEFAULT; } $data['history'] = $data['item']['history']; $data['status'] = $data['item']['status']; $data['delta'] = $data['item']['delta']; $data['trends'] = $data['item']['trends']; $db_delay_flex = $data['item']['delay_flex']; if (isset($db_delay_flex)) { $arr_of_dellays = explode(';', $db_delay_flex); foreach ($arr_of_dellays as $one_db_delay) { $arr_of_delay = explode('/', $one_db_delay); if (!isset($arr_of_delay[0]) || !isset($arr_of_delay[1])) { continue; } array_push($data['delay_flex'], array('delay' => $arr_of_delay[0], 'period' => $arr_of_delay[1])); } } $data['applications'] = array_unique(zbx_array_merge($data['applications'], get_applications_by_itemid($data['itemid']))); } } // applications if (count($data['applications']) == 0) { array_push($data['applications'], 0); } $data['db_applications'] = DBfetchArray(DBselect('SELECT DISTINCT a.applicationid,a.name' . ' FROM applications a' . ' WHERE a.hostid=' . zbx_dbstr($data['hostid']))); order_result($data['db_applications'], 'name'); // interfaces $data['interfaces'] = API::HostInterface()->get(array('hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND)); // valuemapid if ($data['limited']) { if (!empty($data['valuemapid'])) { if ($map_data = DBfetch(DBselect('SELECT v.name FROM valuemaps v WHERE v.valuemapid=' . zbx_dbstr($data['valuemapid'])))) { $data['valuemaps'] = $map_data['name']; } } } else { $data['valuemaps'] = DBfetchArray(DBselect('SELECT v.* FROM valuemaps v')); order_result($data['valuemaps'], 'name'); } // possible host inventories if (empty($data['parent_discoveryid'])) { $data['possibleHostInventories'] = getHostInventories(); // get already populated fields by other items $data['alreadyPopulated'] = API::item()->get(array('output' => array('inventory_link'), 'filter' => array('hostid' => $data['hostid']), 'nopermissions' => true)); $data['alreadyPopulated'] = zbx_toHash($data['alreadyPopulated'], 'inventory_link'); } // template $data['is_template'] = isTemplate($data['hostid']); // unset snmpv3 fields if ($data['type'] != ITEM_TYPE_SNMPV3) { $data['snmpv3_contextname'] = ''; $data['snmpv3_securityname'] = ''; $data['snmpv3_securitylevel'] = ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV; $data['snmpv3_authprotocol'] = ITEM_AUTHPROTOCOL_MD5; $data['snmpv3_authpassphrase'] = ''; $data['snmpv3_privprotocol'] = ITEM_PRIVPROTOCOL_DES; $data['snmpv3_privpassphrase'] = ''; } // unset ssh auth fields if ($data['type'] != ITEM_TYPE_SSH) { $data['authtype'] = ITEM_AUTHTYPE_PASSWORD; $data['publickey'] = ''; $data['privatekey'] = ''; } return $data; }
private function getUserData($user) { if (!$this->connect()) { return false; } // force superuser bind if wanted and not bound as superuser yet if (!empty($this->cnf['bind_dn']) && !empty($this->cnf['bind_password']) && $this->bound < 2) { if (!ldap_bind($this->ds, $this->cnf['bind_dn'], $this->cnf['bind_password'])) { return false; } $this->bound = 2; } // with no superuser creds we continue as user or anonymous here $info['user'] = $user; $info['host'] = $this->cnf['host']; // get info for given user $base = $this->makeFilter($this->cnf['base_dn'], $info); if (isset($this->cnf['userfilter']) && !empty($this->cnf['userfilter'])) { $filter = $this->makeFilter($this->cnf['userfilter'], $info); } else { $filter = '(ObjectClass=*)'; } $sr = ldap_search($this->ds, $base, $filter); $result = ldap_get_entries($this->ds, $sr); // don't accept more or less than one response if ($result['count'] != 1) { error('LDAP: User not found.'); return false; } $user_result = $result[0]; ldap_free_result($sr); // general user info $info['dn'] = $user_result['dn']; $info['name'] = $user_result['cn'][0]; $info['grps'] = array(); // overwrite if other attribs are specified. if (is_array($this->cnf['mapping'])) { foreach ($this->cnf['mapping'] as $localkey => $key) { $info[$localkey] = isset($user_result[$key]) ? $user_result[$key][0] : null; } } $user_result = zbx_array_merge($info, $user_result); // get groups for given user if grouptree is given if (isset($this->cnf['grouptree']) && isset($this->cnf['groupfilter'])) { $base = $this->makeFilter($this->cnf['grouptree'], $user_result); $filter = $this->makeFilter($this->cnf['groupfilter'], $user_result); $sr = ldap_search($this->ds, $base, $filter, array($this->cnf['groupkey'])); if (!$sr) { error('LDAP: Reading group memberships failed.'); return false; } $result = ldap_get_entries($this->ds, $sr); foreach ($result as $grp) { if (!empty($grp[$this->cnf['groupkey']][0])) { $info['grps'][] = $grp[$this->cnf['groupkey']][0]; } } } // always add the default group to the list of groups if (isset($conf['defaultgroup']) && !str_in_array($conf['defaultgroup'], $info['grps'])) { $info['grps'][] = $conf['defaultgroup']; } return $info; }
/** * Delete Applications * * @param array $applicationids * @return array */ public function delete($applicationids, $nopermissions = false) { $applicationids = zbx_toArray($applicationids); // TODO: remove $nopermissions hack $options = array('applicationids' => $applicationids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'selectHosts' => array('name', 'hostid')); $delApplications = $this->get($options); if (!$nopermissions) { foreach ($applicationids as $applicationid) { if (!isset($delApplications[$applicationid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } if ($delApplications[$applicationid]['templateid'] != 0) { self::exception(ZBX_API_ERROR_PERMISSIONS, 'Cannot delete templated application.'); } } } $parentApplicationids = $applicationids; $childApplicationids = array(); do { $dbApplications = DBselect('SELECT a.applicationid FROM applications a WHERE ' . dbConditionInt('a.templateid', $parentApplicationids)); $parentApplicationids = array(); while ($dbApplication = DBfetch($dbApplications)) { $parentApplicationids[] = $dbApplication['applicationid']; $childApplicationids[$dbApplication['applicationid']] = $dbApplication['applicationid']; } } while (!empty($parentApplicationids)); $options = array('applicationids' => $childApplicationids, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => array('name', 'hostid')); $delApplicationChilds = $this->get($options); $delApplications = zbx_array_merge($delApplications, $delApplicationChilds); $applicationids = array_merge($applicationids, $childApplicationids); // check if app is used by web scenario $sql = 'SELECT ht.name,ht.applicationid' . ' FROM httptest ht' . ' WHERE ' . dbConditionInt('ht.applicationid', $applicationids); $res = DBselect($sql); if ($info = DBfetch($res)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Application "%1$s" used by scenario "%2$s" and can\'t be deleted.', $delApplications[$info['applicationid']]['name'], $info['name'])); } DB::delete('applications', array('applicationid' => $applicationids)); // TODO: remove info from API foreach ($delApplications as $delApplication) { $host = reset($delApplication['hosts']); info(_s('Deleted: Application "%1$s" on "%2$s".', $delApplication['name'], $host['name'])); } return array('applicationids' => $applicationids); }
/** * Get GraphPrototype data * * @param array $options * @return array */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; // allowed columns for sorting $sortColumns = array('graphid', 'name', 'graphtype'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM); $sqlParts = array('select' => array('graphs' => 'g.graphid'), 'from' => array('graphs' => 'graphs g'), 'where' => array('g.flags=' . ZBX_FLAG_DISCOVERY_CHILD), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'graphids' => null, 'itemids' => null, 'discoveryids' => null, 'type' => null, 'templated' => null, 'inherited' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectTemplates' => null, 'selectHosts' => null, 'selectItems' => null, 'selectGraphItems' => null, 'selectDiscoveryRule' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); if (is_array($options['output'])) { unset($sqlParts['select']['graphs']); $dbTable = DB::getSchema('graphs'); foreach ($options['output'] as $field) { if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 'g.' . $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 graphs_items gi,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE g.graphid=gi.graphid' . ' AND gi.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY gi.graphid' . ' 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']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where'][] = 'hg.hostid=i.hostid'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['hg'] = 'hg.groupid'; } } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $options['hostids'] = array_merge($options['hostids'], $options['templateids']); } else { $options['hostids'] = $options['templateids']; } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['hostid'] = 'i.hostid'; } $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('i.hostid', $options['hostids']); $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['i'] = 'i.hostid'; } } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); $sqlParts['where'][] = dbConditionInt('g.graphid', $options['graphids']); } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['itemid'] = 'gi.itemid'; } $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where'][] = dbConditionInt('gi.itemid', $options['itemids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['gi'] = 'gi.itemid'; } } // discoveryids if (!is_null($options['discoveryids'])) { zbx_value2array($options['discoveryids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['itemid'] = 'id.parent_itemid'; } $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['item_discovery'] = 'item_discovery id'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['giid'] = 'gi.itemid=id.itemid'; $sqlParts['where'][] = dbConditionInt('id.parent_itemid', $options['discoveryids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['id'] = 'id.parent_itemid'; } } // type if (!is_null($options['type'])) { $sqlParts['where'][] = 'g.type=' . zbx_dbstr($options['type']); } // templated if (!is_null($options['templated'])) { $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['ggi'] = 'g.graphid=gi.graphid'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if ($options['templated']) { $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE; } else { $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE; } } // inherited if (!is_null($options['inherited'])) { if ($options['inherited']) { $sqlParts['where'][] = 'g.templateid IS NOT NULL'; } else { $sqlParts['where'][] = 'g.templateid IS NULL'; } } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['graphs'] = 'g.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('count(DISTINCT g.graphid) as rowscount'); // groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // search if (is_array($options['search'])) { zbx_db_search('graphs g', $options, $sqlParts); } // filter if (is_array($options['filter'])) { $this->dbFilter('graphs g', $options, $sqlParts); if (isset($options['filter']['host'])) { zbx_value2array($options['filter']['host']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; $sqlParts['where']['host'] = dbConditionString('h.host', $options['filter']['host']); } if (isset($options['filter']['hostid'])) { zbx_value2array($options['filter']['hostid']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['filter']['hostid']); } } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'g'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $graphids = 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 .= ' AND ' . 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 ' . DBin_node('g.graphid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder; $dbRes = DBselect($sql, $sqlLimit); while ($graph = DBfetch($dbRes)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $graph; } else { $result = $graph['rowscount']; } } else { $graphids[$graph['graphid']] = $graph['graphid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$graph['graphid']] = array('graphid' => $graph['graphid']); } else { if (!isset($result[$graph['graphid']])) { $result[$graph['graphid']] = array(); } if (!is_null($options['selectHosts']) && !isset($result[$graph['graphid']]['hosts'])) { $result[$graph['graphid']]['hosts'] = array(); } if (!is_null($options['selectGraphItems']) && !isset($result[$graph['graphid']]['gitems'])) { $result[$graph['graphid']]['gitems'] = array(); } if (!is_null($options['selectTemplates']) && !isset($result[$graph['graphid']]['templates'])) { $result[$graph['graphid']]['templates'] = array(); } if (!is_null($options['selectItems']) && !isset($result[$graph['graphid']]['items'])) { $result[$graph['graphid']]['items'] = array(); } if (!is_null($options['selectDiscoveryRule']) && !isset($result[$graph['graphid']]['discoveryRule'])) { $result[$graph['graphid']]['discoveryRule'] = array(); } // hostids if (isset($graph['hostid']) && is_null($options['selectHosts'])) { if (!isset($result[$graph['graphid']]['hosts'])) { $result[$graph['graphid']]['hosts'] = array(); } $result[$graph['graphid']]['hosts'][] = array('hostid' => $graph['hostid']); unset($graph['hostid']); } // itemids if (isset($graph['itemid']) && is_null($options['selectItems'])) { if (!isset($result[$graph['graphid']]['items'])) { $result[$graph['graphid']]['items'] = array(); } $result[$graph['graphid']]['items'][] = array('itemid' => $graph['itemid']); unset($graph['itemid']); } $result[$graph['graphid']] += $graph; } } } if (!is_null($options['countOutput'])) { return $result; } // adding GraphItems if (!is_null($options['selectGraphItems']) && str_in_array($options['selectGraphItems'], $subselectsAllowedOutputs)) { $gitems = API::GraphItem()->get(array('nodeids' => $nodeids, 'output' => $options['selectGraphItems'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true)); foreach ($gitems as $gitem) { $ggraphs = $gitem['graphs']; unset($gitem['graphs']); foreach ($ggraphs as $graph) { $result[$graph['graphid']]['gitems'][$gitem['gitemid']] = $gitem; } } } // adding Hostgroups if (!is_null($options['selectGroups'])) { if (is_array($options['selectGroups']) || str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) { $groups = API::HostGroup()->get(array('nodeids' => $nodeids, 'output' => $options['selectGroups'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true)); foreach ($groups as $group) { $ggraphs = $group['graphs']; unset($group['graphs']); foreach ($ggraphs as $graph) { $result[$graph['graphid']]['groups'][] = $group; } } } } // adding Hosts if (!is_null($options['selectHosts'])) { if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) { $hosts = API::Host()->get(array('nodeids' => $nodeids, 'output' => $options['selectHosts'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true)); foreach ($hosts as $host) { $hgraphs = $host['graphs']; unset($host['graphs']); foreach ($hgraphs as $graph) { $result[$graph['graphid']]['hosts'][] = $host; } } } } // adding Templates if (!is_null($options['selectTemplates']) && str_in_array($options['selectTemplates'], $subselectsAllowedOutputs)) { $templates = API::Template()->get(array('nodeids' => $nodeids, 'output' => $options['selectTemplates'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true)); foreach ($templates as $template) { $tgraphs = $template['graphs']; unset($template['graphs']); foreach ($tgraphs as $graph) { $result[$graph['graphid']]['templates'][] = $template; } } } // adding Items if (!is_null($options['selectItems']) && str_in_array($options['selectItems'], $subselectsAllowedOutputs)) { $items = API::Item()->get(array('nodeids' => $nodeids, 'output' => $options['selectItems'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true, 'filter' => array('flags' => null))); foreach ($items as $item) { $igraphs = $item['graphs']; unset($item['graphs']); foreach ($igraphs as $graph) { $result[$graph['graphid']]['items'][] = $item; } } } // adding discoveryRule if (!is_null($options['selectDiscoveryRule'])) { $ruleids = $ruleMap = array(); $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'); while ($rule = DBfetch($dbRules)) { $ruleids[$rule['parent_itemid']] = $rule['parent_itemid']; $ruleMap[$rule['graphid']] = $rule['parent_itemid']; } $objParams = array('nodeids' => $nodeids, 'itemids' => $ruleids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectDiscoveryRule']) || str_in_array($options['selectDiscoveryRule'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDiscoveryRule']; $discoveryRules = API::DiscoveryRule()->get($objParams); foreach ($result as $graphid => $graph) { if (isset($ruleMap[$graphid]) && isset($discoveryRules[$ruleMap[$graphid]])) { $result[$graphid]['discoveryRule'] = $discoveryRules[$ruleMap[$graphid]]; } } } } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Get events data. * * @param _array $options * @param array $options['itemids'] * @param array $options['hostids'] * @param array $options['groupids'] * @param array $options['eventids'] * @param array $options['applicationids'] * @param array $options['status'] * @param array $options['editable'] * @param array $options['count'] * @param array $options['pattern'] * @param array $options['limit'] * @param array $options['order'] * * @return array|int item data as array or false if error */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = array('select' => array($this->fieldId('eventid')), 'from' => array('events' => 'events e'), 'where' => array(), 'order' => array(), 'group' => array(), 'limit' => null); $defOptions = array('groupids' => null, 'hostids' => null, 'objectids' => null, 'eventids' => null, 'editable' => null, 'object' => EVENT_OBJECT_TRIGGER, 'source' => EVENT_SOURCE_TRIGGERS, 'acknowledged' => null, 'nopermissions' => null, 'value' => null, 'time_from' => null, 'time_till' => null, 'eventid_from' => null, 'eventid_till' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => null, 'selectRelatedObject' => null, 'select_alerts' => null, 'select_acknowledges' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); $this->validateGet($options); // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { // triggers if ($options['object'] == EVENT_OBJECT_TRIGGER) { // specific triggers if ($options['objectids'] !== null) { $triggers = API::Trigger()->get(array('output' => array('triggerid'), 'triggerids' => $options['objectids'], 'editable' => $options['editable'])); $options['objectids'] = zbx_objectValues($triggers, 'triggerid'); } else { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ; $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', getUserGroupsByUserId($userid)) . ' WHERE e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY f.triggerid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')'; } } elseif ($options['object'] == EVENT_OBJECT_ITEM || $options['object'] == EVENT_OBJECT_LLDRULE) { // specific items or LLD rules if ($options['objectids'] !== null) { if ($options['object'] == EVENT_OBJECT_ITEM) { $items = API::Item()->get(array('output' => array('itemid'), 'itemids' => $options['objectids'], 'editable' => $options['editable'])); $options['objectids'] = zbx_objectValues($items, 'itemid'); } elseif ($options['object'] == EVENT_OBJECT_LLDRULE) { $items = API::DiscoveryRule()->get(array('output' => array('itemid'), 'itemids' => $options['objectids'], 'editable' => $options['editable'])); $options['objectids'] = zbx_objectValues($items, 'itemid'); } } else { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ; $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', getUserGroupsByUserId($userid)) . ' WHERE e.objectid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')'; } } } // eventids if (!is_null($options['eventids'])) { zbx_value2array($options['eventids']); $sqlParts['where'][] = dbConditionInt('e.eventid', $options['eventids']); } // objectids if ($options['objectids'] !== null && in_array($options['object'], array(EVENT_OBJECT_TRIGGER, EVENT_OBJECT_ITEM, EVENT_OBJECT_LLDRULE))) { zbx_value2array($options['objectids']); $sqlParts['where'][] = dbConditionInt('e.objectid', $options['objectids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['objectid'] = 'e.objectid'; } } // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); // triggers if ($options['object'] == EVENT_OBJECT_TRIGGER) { $sqlParts['from']['functions'] = 'functions f'; $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where']['hg'] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid'; $sqlParts['where']['fe'] = 'f.triggerid=e.objectid'; $sqlParts['where']['fi'] = 'f.itemid=i.itemid'; } elseif ($options['object'] == EVENT_OBJECT_LLDRULE || $options['object'] == EVENT_OBJECT_ITEM) { $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where']['hg'] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid'; $sqlParts['where']['fi'] = 'e.objectid=i.itemid'; } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); // triggers if ($options['object'] == EVENT_OBJECT_TRIGGER) { $sqlParts['from']['functions'] = 'functions f'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']); $sqlParts['where']['ft'] = 'f.triggerid=e.objectid'; $sqlParts['where']['fi'] = 'f.itemid=i.itemid'; } elseif ($options['object'] == EVENT_OBJECT_LLDRULE || $options['object'] == EVENT_OBJECT_ITEM) { $sqlParts['from']['items'] = 'items i'; $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']); $sqlParts['where']['fi'] = 'e.objectid=i.itemid'; } } // object if (!is_null($options['object'])) { $sqlParts['where']['o'] = 'e.object=' . zbx_dbstr($options['object']); } // source if (!is_null($options['source'])) { $sqlParts['where'][] = 'e.source=' . zbx_dbstr($options['source']); } // acknowledged if (!is_null($options['acknowledged'])) { $sqlParts['where'][] = 'e.acknowledged=' . ($options['acknowledged'] ? 1 : 0); } // time_from if (!is_null($options['time_from'])) { $sqlParts['where'][] = 'e.clock>=' . zbx_dbstr($options['time_from']); } // time_till if (!is_null($options['time_till'])) { $sqlParts['where'][] = 'e.clock<=' . zbx_dbstr($options['time_till']); } // eventid_from if (!is_null($options['eventid_from'])) { $sqlParts['where'][] = 'e.eventid>=' . zbx_dbstr($options['eventid_from']); } // eventid_till if (!is_null($options['eventid_till'])) { $sqlParts['where'][] = 'e.eventid<=' . zbx_dbstr($options['eventid_till']); } // value if (!is_null($options['value'])) { zbx_value2array($options['value']); $sqlParts['where'][] = dbConditionInt('e.value', $options['value']); } // search if (is_array($options['search'])) { zbx_db_search('events e', $options, $sqlParts); } // filter if (is_array($options['filter'])) { $this->dbFilter('events e', $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 ($event = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $event; } else { $result = $event['rowscount']; } } else { $result[$event['eventid']] = $event; } } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, array('object', 'objectid'), $options['output']); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Get GraphPrototype data * * @param array $options * @return array */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = array('select' => array('graphs' => 'g.graphid'), 'from' => array('graphs' => 'graphs g'), 'where' => array('g.flags=' . ZBX_FLAG_DISCOVERY_PROTOTYPE), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('groupids' => null, 'templateids' => null, 'hostids' => null, 'graphids' => null, 'itemids' => null, 'discoveryids' => null, 'templated' => null, 'inherited' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectGroups' => null, 'selectTemplates' => null, 'selectHosts' => null, 'selectItems' => null, 'selectGraphItems' => null, 'selectDiscoveryRule' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ; $userGroups = getUserGroupsByUserId($userid); // check permissions by graph items $sqlParts['where'][] = 'NOT EXISTS (' . 'SELECT NULL' . ' FROM graphs_items gi,items i,hosts_groups hgg' . ' LEFT JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE g.graphid=gi.graphid' . ' AND gi.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY i.hostid' . ' HAVING MAX(permission)<' . zbx_dbstr($permission) . ' OR MIN(permission) IS NULL' . ' OR MIN(permission)=' . PERM_DENY . ')'; // check permissions by Y min item $sqlParts['where'][] = 'NOT EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts_groups hgg' . ' LEFT JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE g.ymin_type=' . GRAPH_YAXIS_TYPE_ITEM_VALUE . ' AND g.ymin_itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY i.hostid' . ' HAVING MAX(permission)<' . $permission . ' OR MIN(permission) IS NULL' . ' OR MIN(permission)=' . PERM_DENY . ')'; // check permissions by Y max item $sqlParts['where'][] = 'NOT EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts_groups hgg' . ' LEFT JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE g.ymax_type=' . GRAPH_YAXIS_TYPE_ITEM_VALUE . ' AND g.ymax_itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY i.hostid' . ' HAVING MAX(permission)<' . $permission . ' OR MIN(permission) IS NULL' . ' OR MIN(permission)=' . PERM_DENY . ')'; } // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where'][] = 'hg.hostid=i.hostid'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['hg'] = 'hg.groupid'; } } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $options['hostids'] = array_merge($options['hostids'], $options['templateids']); } else { $options['hostids'] = $options['templateids']; } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('i.hostid', $options['hostids']); $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['i'] = 'i.hostid'; } } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); $sqlParts['where'][] = dbConditionInt('g.graphid', $options['graphids']); } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where'][] = dbConditionInt('gi.itemid', $options['itemids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['gi'] = 'gi.itemid'; } } // discoveryids if (!is_null($options['discoveryids'])) { zbx_value2array($options['discoveryids']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['item_discovery'] = 'item_discovery id'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['giid'] = 'gi.itemid=id.itemid'; $sqlParts['where'][] = dbConditionInt('id.parent_itemid', $options['discoveryids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['id'] = 'id.parent_itemid'; } } // templated if (!is_null($options['templated'])) { $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['ggi'] = 'g.graphid=gi.graphid'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if ($options['templated']) { $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE; } else { $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE; } } // inherited if (!is_null($options['inherited'])) { if ($options['inherited']) { $sqlParts['where'][] = 'g.templateid IS NOT NULL'; } else { $sqlParts['where'][] = 'g.templateid IS NULL'; } } // search if (is_array($options['search'])) { zbx_db_search('graphs g', $options, $sqlParts); } // filter if (is_array($options['filter'])) { $this->dbFilter('graphs g', $options, $sqlParts); if (isset($options['filter']['host'])) { zbx_value2array($options['filter']['host']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; $sqlParts['where']['host'] = dbConditionString('h.host', $options['filter']['host']); } if (isset($options['filter']['hostid'])) { zbx_value2array($options['filter']['hostid']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where']['gig'] = 'gi.graphid=g.graphid'; $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['filter']['hostid']); } } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $dbRes = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($graph = DBfetch($dbRes)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $graph; } else { $result = $graph['rowscount']; } } else { $result[$graph['graphid']] = $graph; } } 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; }
/** * Validates the input parameters for the update() method. * * @param array $hosts hosts data array * @param array $db_hosts db hosts data array * * @throws APIException if the input is invalid. */ protected function validateUpdate(array $hosts, array $db_hosts) { $host_db_fields = ['hostid' => null]; $hosts_full = []; foreach ($hosts as $host) { // Validate mandatory fields. if (!check_db_fields($host_db_fields, $host)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Wrong fields for host "%1$s".', array_key_exists('host', $host) ? $host['host'] : '')); } // Validate host permissions. if (!array_key_exists($host['hostid'], $db_hosts)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } // Validate "groups" field. if (array_key_exists('groups', $host) && (!is_array($host['groups']) || !$host['groups'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('No groups for host "%1$s".', $db_hosts[$host['hostid']]['host'])); } // Permissions to host groups is validated in massUpdate(). } $inventory_fields = zbx_objectValues(getHostInventories(), 'db_field'); $status_validator = new CLimitedSetValidator(['values' => [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED], 'messageInvalid' => _('Incorrect status for host "%1$s".')]); $update_discovered_validator = new CUpdateDiscoveredValidator(['allowed' => ['hostid', 'status', 'inventory', 'description'], 'messageAllowedField' => _('Cannot update "%2$s" for a discovered host "%1$s".')]); $host_names = []; foreach ($hosts as &$host) { $db_host = $db_hosts[$host['hostid']]; $host_name = array_key_exists('host', $host) ? $host['host'] : $db_host['host']; if (array_key_exists('status', $host)) { $status_validator->setObjectName($host_name); $this->checkValidator($host['status'], $status_validator); } if (array_key_exists('inventory', $host) && $host['inventory']) { if (array_key_exists('inventory_mode', $host) && $host['inventory_mode'] == HOST_INVENTORY_DISABLED) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set inventory fields for disabled inventory.')); } $fields = array_keys($host['inventory']); foreach ($fields as $field) { if (!in_array($field, $inventory_fields)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect inventory field "%s".', $field)); } } } // cannot update certain fields for discovered hosts $update_discovered_validator->setObjectName($host_name); $this->checkPartialValidator($host, $update_discovered_validator, $db_host); if (array_key_exists('interfaces', $host)) { if (!is_array($host['interfaces']) || !$host['interfaces']) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('No interfaces for host "%s".', $host['host'])); } } if (array_key_exists('host', $host)) { if (!preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/', $host['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for host name "%s".', $host['host'])); } if (array_key_exists('host', $host_names) && array_key_exists($host['host'], $host_names['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate host. Host with the same host name "%s" already exists in data.', $host['host'])); } $host_names['host'][$host['host']] = $host['hostid']; } if (array_key_exists('name', $host)) { // if visible name is empty replace it with host name if (zbx_empty(trim($host['name']))) { if (!array_key_exists('host', $host)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Visible name cannot be empty if host name is missing.')); } $host['name'] = $host['host']; } if (array_key_exists('name', $host_names) && array_key_exists($host['name'], $host_names['name'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate host. Host with the same visible name "%s" already exists in data.', $host['name'])); } $host_names['name'][$host['name']] = $host['hostid']; } $hosts_full[] = zbx_array_merge($db_host, $host); } unset($host); if (array_key_exists('host', $host_names) || array_key_exists('name', $host_names)) { $filter = []; if (array_key_exists('host', $host_names)) { $filter['host'] = array_keys($host_names['host']); } if (array_key_exists('name', $host_names)) { $filter['name'] = array_keys($host_names['name']); } $hosts_exists = $this->get(['output' => ['hostid', 'host', 'name'], 'filter' => $filter, 'searchByAny' => true, 'nopermissions' => true, 'preservekeys' => true]); foreach ($hosts_exists as $host_exists) { if (array_key_exists('host', $host_names) && array_key_exists($host_exists['host'], $host_names['host']) && bccomp($host_exists['hostid'], $host_names['host'][$host_exists['host']]) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same name "%s" already exists.', $host_exists['host'])); } if (array_key_exists('name', $host_names) && array_key_exists($host_exists['name'], $host_names['name']) && bccomp($host_exists['hostid'], $host_names['name'][$host_exists['name']]) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same visible name "%s" already exists.', $host_exists['name'])); } } $templates_exists = API::Template()->get(['output' => ['hostid', 'host', 'name'], 'filter' => $filter, 'searchByAny' => true, 'nopermissions' => true, 'preservekeys' => true]); foreach ($templates_exists as $template_exists) { if (array_key_exists('host', $host_names) && array_key_exists($template_exists['host'], $host_names['host']) && bccomp($template_exists['templateid'], $host_names['host'][$template_exists['host']]) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same name "%s" already exists.', $template_exists['host'])); } if (array_key_exists('name', $host_names) && array_key_exists($template_exists['name'], $host_names['name']) && bccomp($template_exists['templateid'], $host_names['name'][$template_exists['name']]) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same visible name "%s" already exists.', $template_exists['name'])); } } } $this->validateEncryption($hosts_full); }
/** * Builds an SQL parts array from the given options. * * @param string $tableName * @param string $tableAlias * @param array $options * * @return array The resulting SQL parts array */ protected function createSelectQueryParts($tableName, $tableAlias, array $options) { // extend default options $options = zbx_array_merge($this->globalGetOptions, $options); $sqlParts = ['select' => [$this->fieldId($this->pk($tableName), $tableAlias)], 'from' => [$this->tableId($tableName, $tableAlias)], 'where' => [], 'group' => [], 'order' => [], 'limit' => null]; // add filter options $sqlParts = $this->applyQueryFilterOptions($tableName, $tableAlias, $options, $sqlParts); // add output options $sqlParts = $this->applyQueryOutputOptions($tableName, $tableAlias, $options, $sqlParts); // add sort options $sqlParts = $this->applyQuerySortOptions($tableName, $tableAlias, $options, $sqlParts); return $sqlParts; }
/** * Delete web scenario. * * @param array $httpTestIds * @param bool $nopermissions * * @return array */ public function delete(array $httpTestIds, $nopermissions = false) { if (empty($httpTestIds)) { return true; } $delHttpTests = $this->get(array('httptestids' => $httpTestIds, 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'selectHosts' => API_OUTPUT_EXTEND, 'preservekeys' => true)); if (!$nopermissions) { foreach ($httpTestIds as $httpTestId) { if (!empty($delHttpTests[$httpTestId]['templateid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot delete templated web scenario "%1$s".', $delHttpTests[$httpTestId]['name'])); } if (!isset($delHttpTests[$httpTestId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } } } $parentHttpTestIds = $httpTestIds; $childHttpTestIds = array(); do { $dbTests = DBselect('SELECT ht.httptestid FROM httptest ht WHERE ' . dbConditionInt('ht.templateid', $parentHttpTestIds)); $parentHttpTestIds = array(); while ($dbTest = DBfetch($dbTests)) { $parentHttpTestIds[] = $dbTest['httptestid']; $childHttpTestIds[$dbTest['httptestid']] = $dbTest['httptestid']; } } while (!empty($parentHttpTestIds)); $options = array('httptestids' => $childHttpTestIds, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => API_OUTPUT_EXTEND); $delHttpTestChilds = $this->get($options); $delHttpTests = zbx_array_merge($delHttpTests, $delHttpTestChilds); $httpTestIds = array_merge($httpTestIds, $childHttpTestIds); $itemidsDel = array(); $dbTestItems = DBselect('SELECT hsi.itemid' . ' FROM httptestitem hsi' . ' WHERE ' . dbConditionInt('hsi.httptestid', $httpTestIds)); while ($testitem = DBfetch($dbTestItems)) { $itemidsDel[] = $testitem['itemid']; } $dbStepItems = DBselect('SELECT DISTINCT hsi.itemid' . ' FROM httpstepitem hsi,httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', $httpTestIds) . ' AND hs.httpstepid=hsi.httpstepid'); while ($stepitem = DBfetch($dbStepItems)) { $itemidsDel[] = $stepitem['itemid']; } if (!empty($itemidsDel)) { API::Item()->delete($itemidsDel, true); } DB::delete('httptest', array('httptestid' => $httpTestIds)); // TODO: REMOVE foreach ($delHttpTests as $httpTest) { $host = reset($httpTest['hosts']); info(_s('Deleted: Web scenario "%1$s" on "%2$s".', $httpTest['name'], $host['host'])); add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_SCENARIO, 'Web scenario [' . $httpTest['name'] . '] [' . $httpTest['httptestid'] . '] Host [' . $host['name'] . ']'); } return array('httptestids' => $httpTestIds); }
/** * Get Host data * * {@source} * @access public * @static * @since 1.8 * @version 1 * * @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 int $options['extendoutput'] return all fields for Hosts * @param boolean $options['select_groups'] select HostGroups * @param boolean $options['select_templates'] select Templates * @param boolean $options['select_items'] select Items * @param boolean $options['select_triggers'] select Triggers * @param boolean $options['select_graphs'] select Graphs * @param boolean $options['select_applications'] select Applications * @param boolean $options['select_macros'] select Macros * @param boolean $options['select_profile'] select Profile * @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 static function get($options = array()) { global $USER_DETAILS; $result = array(); $nodeCheck = false; $user_type = $USER_DETAILS['type']; $userid = $USER_DETAILS['userid']; $sort_columns = array('hostid', 'host', 'status', 'dns', 'ip'); // allowed columns for sorting $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM); // allowed output options for [ select_* ] params $sql_parts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $def_options = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'proxyids' => null, 'templateids' => null, 'itemids' => null, 'triggerids' => null, 'maintenanceids' => null, 'graphids' => null, 'dhostids' => null, 'dserviceids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'proxy_hosts' => null, 'with_items' => null, 'with_monitored_items' => null, 'with_historical_items' => null, 'with_triggers' => null, 'with_monitored_triggers' => null, 'with_httptests' => null, 'with_monitored_httptests' => null, 'with_graphs' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_groups' => null, 'selectParentTemplates' => null, 'select_items' => null, 'select_triggers' => null, 'select_graphs' => null, 'select_dhosts' => null, 'select_dservices' => null, 'select_applications' => null, 'select_macros' => null, 'select_profile' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($def_options, $options); if (!is_null($options['extendoutput'])) { $options['output'] = API_OUTPUT_EXTEND; if (!is_null($options['select_groups'])) { $options['select_groups'] = API_OUTPUT_EXTEND; } if (!is_null($options['selectParentTemplates'])) { $options['selectParentTemplates'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_items'])) { $options['select_items'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_triggers'])) { $options['select_triggers'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_graphs'])) { $options['select_graphs'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_applications'])) { $options['select_applications'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_macros'])) { $options['select_macros'] = API_OUTPUT_EXTEND; } } if (is_array($options['output'])) { unset($sql_parts['select']['hosts']); $sql_parts['select']['hostid'] = ' h.hostid'; foreach ($options['output'] as $key => $field) { $sql_parts['select'][$field] = ' h.' . $field; } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) { } else { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY; $sql_parts['where'][] = 'EXISTS (' . ' SELECT hh.hostid ' . ' FROM hosts hh, hosts_groups hgg, rights r, users_groups ug ' . ' WHERE hh.hostid=h.hostid ' . ' AND hh.hostid=hgg.hostid ' . ' AND r.id=hgg.groupid ' . ' AND r.groupid=ug.usrgrpid ' . ' AND ug.userid=' . $userid . ' AND r.permission>=' . $permission . ' AND NOT EXISTS( ' . ' SELECT hggg.groupid ' . ' FROM hosts_groups hggg, rights rr, users_groups gg ' . ' WHERE hggg.hostid=hgg.hostid ' . ' AND rr.id=hggg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . ' )) '; } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sql_parts['where']['hostid'] = DBcondition('h.hostid', $options['hostids']); if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.hostid', $nodeids); } } // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['groupid'] = 'hg.groupid'; } $sql_parts['from']['hosts_groups'] = 'hosts_groups hg'; $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']); $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid'; if (!is_null($options['groupCount'])) { $sql_parts['group']['groupid'] = 'hg.groupid'; } if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('hg.groupid', $nodeids); } } // proxyids if (!is_null($options['proxyids'])) { zbx_value2array($options['proxyids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['proxy_hostid'] = 'h.proxy_hostid'; } $sql_parts['where'][] = DBcondition('h.proxy_hostid', $options['proxyids']); } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['templateid'] = 'ht.templateid'; } $sql_parts['from']['hosts_templates'] = 'hosts_templates ht'; $sql_parts['where'][] = DBcondition('ht.templateid', $options['templateids']); $sql_parts['where']['hht'] = 'h.hostid=ht.hostid'; if (!is_null($options['groupCount'])) { $sql_parts['group']['templateid'] = 'ht.templateid'; } if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('ht.templateid', $nodeids); } } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['itemid'] = 'i.itemid'; } $sql_parts['from']['items'] = 'items i'; $sql_parts['where'][] = DBcondition('i.itemid', $options['itemids']); $sql_parts['where']['hi'] = 'h.hostid=i.hostid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('i.itemid', $nodeids); } } // triggerids if (!is_null($options['triggerids'])) { zbx_value2array($options['triggerids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['triggerid'] = 'f.triggerid'; } $sql_parts['from']['functions'] = 'functions f'; $sql_parts['from']['items'] = 'items i'; $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']); $sql_parts['where']['hi'] = 'h.hostid=i.hostid'; $sql_parts['where']['fi'] = 'f.itemid=i.itemid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('f.triggerid', $nodeids); } } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['graphid'] = 'gi.graphid'; } $sql_parts['from']['graphs_items'] = 'graphs_items gi'; $sql_parts['from']['items'] = 'items i'; $sql_parts['where'][] = DBcondition('gi.graphid', $options['graphids']); $sql_parts['where']['igi'] = 'i.itemid=gi.itemid'; $sql_parts['where']['hi'] = 'h.hostid=i.hostid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('gi.graphid', $nodeids); } } // dhostids if (!is_null($options['dhostids'])) { zbx_value2array($options['dhostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['dhostid'] = 'ds.dhostid'; } $sql_parts['from']['dservices'] = 'dservices ds'; $sql_parts['where'][] = DBcondition('ds.dhostid', $options['dhostids']); $sql_parts['where']['dsh'] = 'ds.ip=h.ip'; if (!is_null($options['groupCount'])) { $sql_parts['group']['dhostid'] = 'ds.dhostid'; } } // dserviceids if (!is_null($options['dserviceids'])) { zbx_value2array($options['dserviceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['dserviceid'] = 'ds.dserviceid'; } $sql_parts['from']['dservices'] = 'dservices ds'; $sql_parts['where'][] = DBcondition('ds.dserviceid', $options['dserviceids']); $sql_parts['where']['dsh'] = 'ds.ip=h.ip'; if (!is_null($options['groupCount'])) { $sql_parts['group']['dserviceid'] = 'ds.dserviceid'; } } // maintenanceids if (!is_null($options['maintenanceids'])) { zbx_value2array($options['maintenanceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['maintenanceid'] = 'mh.maintenanceid'; } $sql_parts['from']['maintenances_hosts'] = 'maintenances_hosts mh'; $sql_parts['where'][] = DBcondition('mh.maintenanceid', $options['maintenanceids']); $sql_parts['where']['hmh'] = 'h.hostid=mh.hostid'; if (!is_null($options['groupCount'])) { $sql_parts['group']['maintenanceid'] = 'mh.maintenanceid'; } } // node check !!!!! // should last, after all ****IDS checks if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.hostid', $nodeids); } // monitored_hosts, templated_hosts if (!is_null($options['monitored_hosts'])) { $sql_parts['where']['status'] = 'h.status=' . HOST_STATUS_MONITORED; } else { if (!is_null($options['templated_hosts'])) { $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')'; } else { if (!is_null($options['proxy_hosts'])) { $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')'; } else { $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')'; } } } // with_items, with_monitored_items, with_historical_items if (!is_null($options['with_items'])) { $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid )'; } else { if (!is_null($options['with_monitored_items'])) { $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND i.status=' . ITEM_STATUS_ACTIVE . ')'; } else { if (!is_null($options['with_historical_items'])) { $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND (i.status=' . ITEM_STATUS_ACTIVE . ' OR i.status=' . ITEM_STATUS_NOTSUPPORTED . ') AND i.lastvalue IS NOT NULL)'; } } } // with_triggers, with_monitored_triggers if (!is_null($options['with_triggers'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid)'; } else { if (!is_null($options['with_monitored_triggers'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid ' . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')'; } } // with_httptests, with_monitored_httptests if (!is_null($options['with_httptests'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid)'; } else { if (!is_null($options['with_monitored_httptests'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid ' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')'; } } // with_graphs if (!is_null($options['with_graphs'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT DISTINCT i.itemid ' . ' FROM items i, graphs_items gi ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=gi.itemid)'; } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sql_parts['select']['hosts'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sql_parts['select'] = array('count(DISTINCT h.hostid) as rowscount'); //groupCount if (!is_null($options['groupCount'])) { foreach ($sql_parts['group'] as $key => $fields) { $sql_parts['select'][$key] = $fields; } } } // search if (is_array($options['search'])) { zbx_db_search('hosts h', $options, $sql_parts); } // filter if (is_array($options['filter'])) { zbx_db_filter('hosts h', $options, $sql_parts); } // order // restrict not allowed columns for sorting $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : ''; if (!zbx_empty($options['sortfield'])) { $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP; $sql_parts['order'][$options['sortfield']] = 'h.' . $options['sortfield'] . ' ' . $sortorder; if (!str_in_array('h.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('h.*', $sql_parts['select'])) { $sql_parts['select'][$options['sortfield']] = 'h.' . $options['sortfield']; } } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sql_parts['limit'] = $options['limit']; } //------- $hostids = array(); $sql_parts['select'] = array_unique($sql_parts['select']); $sql_parts['from'] = array_unique($sql_parts['from']); $sql_parts['where'] = array_unique($sql_parts['where']); $sql_parts['group'] = array_unique($sql_parts['group']); $sql_parts['order'] = array_unique($sql_parts['order']); $sql_select = ''; $sql_from = ''; $sql_where = ''; $sql_group = ''; $sql_order = ''; if (!empty($sql_parts['select'])) { $sql_select .= implode(',', $sql_parts['select']); } if (!empty($sql_parts['from'])) { $sql_from .= implode(',', $sql_parts['from']); } if (!empty($sql_parts['where'])) { $sql_where .= implode(' AND ', $sql_parts['where']); } if (!empty($sql_parts['group'])) { $sql_where .= ' GROUP BY ' . implode(',', $sql_parts['group']); } if (!empty($sql_parts['order'])) { $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']); } $sql_limit = $sql_parts['limit']; $sql = 'SELECT ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_group . $sql_order; //SDI($sql); $res = DBselect($sql, $sql_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['select_groups']) && !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['select_items']) && !isset($result[$host['hostid']]['items'])) { $result[$host['hostid']]['items'] = array(); } if (!is_null($options['select_profile']) && !isset($result[$host['hostid']]['profile'])) { $result[$host['hostid']]['profile'] = array(); $result[$host['hostid']]['profile_ext'] = array(); } if (!is_null($options['select_triggers']) && !isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } if (!is_null($options['select_graphs']) && !isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } if (!is_null($options['select_dhosts']) && !isset($result[$host['hostid']]['dhosts'])) { $result[$host['hostid']]['dhosts'] = array(); } if (!is_null($options['select_dservices']) && !isset($result[$host['hostid']]['dservices'])) { $result[$host['hostid']]['dservices'] = array(); } if (!is_null($options['select_applications']) && !isset($result[$host['hostid']]['applications'])) { $result[$host['hostid']]['applications'] = array(); } if (!is_null($options['select_macros']) && !isset($result[$host['hostid']]['macros'])) { $result[$host['hostid']]['macros'] = array(); } // if(!is_null($options['select_maintenances']) && !isset($result[$host['hostid']]['maintenances'])){ // $result[$host['hostid']]['maintenances'] = array(); // } // groupids if (isset($host['groupid']) && is_null($options['select_groups'])) { 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']); unset($host['templateid']); } // triggerids if (isset($host['triggerid']) && is_null($options['select_triggers'])) { if (!isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } $result[$host['hostid']]['triggers'][] = array('triggerid' => $host['triggerid']); unset($host['triggerid']); } // itemids if (isset($host['itemid']) && is_null($options['select_items'])) { 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['select_graphs'])) { if (!isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } $result[$host['hostid']]['graphs'][] = array('graphid' => $host['graphid']); unset($host['graphid']); } // dhostids if (isset($host['dhostid']) && is_null($options['select_dhosts'])) { 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['select_dservices'])) { 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']]['maintenanceid'])) { $result[$host['hostid']]['maintenances'] = array(); } $result[$host['hostid']]['maintenances'][] = array('maintenanceid' => $host['maintenanceid']); // unset($host['maintenanceid']); } //--- $result[$host['hostid']] += $host; } } } Copt::memoryPick(); if (!is_null($options['countOutput'])) { if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; } // Adding Objects // Adding Groups if (!is_null($options['select_groups']) && str_in_array($options['select_groups'], $subselects_allowed_outputs)) { $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_groups'], 'hostids' => $hostids, 'preservekeys' => 1); $groups = CHostgroup::get($obj_params); foreach ($groups as $groupid => $group) { $ghosts = $group['hosts']; unset($group['hosts']); foreach ($ghosts as $num => $host) { $result[$host['hostid']]['groups'][] = $group; } } } // Adding Profiles if (!is_null($options['select_profile'])) { $sql = 'SELECT hp.* ' . ' FROM hosts_profiles hp ' . ' WHERE ' . DBcondition('hp.hostid', $hostids); $db_profile = DBselect($sql); while ($profile = DBfetch($db_profile)) { $result[$profile['hostid']]['profile'] = $profile; } $sql = 'SELECT hpe.* ' . ' FROM hosts_profiles_ext hpe ' . ' WHERE ' . DBcondition('hpe.hostid', $hostids); $db_profile_ext = DBselect($sql); while ($profile_ext = DBfetch($db_profile_ext)) { $result[$profile_ext['hostid']]['profile_ext'] = $profile_ext; } } // Adding Templates if (!is_null($options['selectParentTemplates'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'preservekeys' => 1); if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['selectParentTemplates']; $templates = CTemplate::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['hosts']); $count = array(); 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]; } } } else { if (API_OUTPUT_COUNT == $options['selectParentTemplates']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $templates = CTemplate::get($obj_params); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $hostid => $host) { if (isset($templates[$hostid])) { $result[$hostid]['templates'] = $templates[$hostid]['rowscount']; } else { $result[$hostid]['templates'] = 0; } } } } } // Adding Items if (!is_null($options['select_items'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_items']) || str_in_array($options['select_items'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_items']; $items = CItem::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($items, 'description'); } 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']]['items'][] =& $items[$itemid]; } } } else { if (API_OUTPUT_COUNT == $options['select_items']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $items = CItem::get($obj_params); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { if (isset($items[$hostid])) { $result[$hostid]['items'] = $items[$hostid]['rowscount']; } else { $result[$hostid]['items'] = 0; } } } } } // Adding triggers if (!is_null($options['select_triggers'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_triggers']) || str_in_array($options['select_triggers'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_triggers']; $triggers = CTrigger::get($obj_params); 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]; } } } else { if (API_OUTPUT_COUNT == $options['select_triggers']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $triggers = CTrigger::get($obj_params); $triggers = zbx_toHash($triggers, 'hostid'); foreach ($result as $hostid => $host) { if (isset($triggers[$hostid])) { $result[$hostid]['triggers'] = $triggers[$hostid]['rowscount']; } else { $result[$hostid]['triggers'] = 0; } } } } } // Adding graphs if (!is_null($options['select_graphs'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_graphs']) || str_in_array($options['select_graphs'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_graphs']; $graphs = CGraph::get($obj_params); 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]; } } } else { if (API_OUTPUT_COUNT == $options['select_graphs']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $graphs = CGraph::get($obj_params); $graphs = zbx_toHash($graphs, 'hostid'); foreach ($result as $hostid => $host) { if (isset($graphs[$hostid])) { $result[$hostid]['graphs'] = $graphs[$hostid]['rowscount']; } else { $result[$hostid]['graphs'] = 0; } } } } } // Adding discovery hosts if (!is_null($options['select_dhosts'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_dhosts']) || str_in_array($options['select_dhosts'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_dhosts']; $dhosts = CDHost::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($dhosts, 'dhostid'); } foreach ($dhosts as $dhostid => $dhost) { unset($dhosts[$dhostid]['hosts']); foreach ($dhost['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']]['dhosts'][] =& $dhosts[$dhostid]; } } } else { if (API_OUTPUT_COUNT == $options['select_dhosts']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $dhosts = CDHost::get($obj_params); $dhosts = zbx_toHash($dhosts, 'hostid'); foreach ($result as $hostid => $host) { if (isset($dhosts[$hostid])) { $result[$hostid]['dhosts'] = $dhosts[$hostid]['rowscount']; } else { $result[$hostid]['dhosts'] = 0; } } } } } // Adding applications if (!is_null($options['select_applications'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_applications']) || str_in_array($options['select_applications'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_applications']; $applications = CApplication::get($obj_params); 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]; } } } else { if (API_OUTPUT_COUNT == $options['select_applications']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $applications = CApplication::get($obj_params); $applications = zbx_toHash($applications, 'hostid'); foreach ($result as $hostid => $host) { if (isset($applications[$hostid])) { $result[$hostid]['applications'] = $applications[$hostid]['rowscount']; } else { $result[$hostid]['applications'] = 0; } } } } } // Adding macros if (!is_null($options['select_macros']) && str_in_array($options['select_macros'], $subselects_allowed_outputs)) { $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_macros'], 'hostids' => $hostids, 'preservekeys' => 1); $macros = CUserMacro::get($obj_params); foreach ($macros as $macroid => $macro) { $mhosts = $macro['hosts']; unset($macro['hosts']); foreach ($mhosts as $num => $host) { $result[$host['hostid']]['macros'][] = $macro; } } } Copt::memoryPick(); // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Resolves and retrieves effective item prototype used in this screen item. * * @return array|bool */ protected function getItemPrototype() { if ($this->itemPrototype === null) { $defaultOptions = array('output' => array('itemid', 'name'), 'selectHosts' => array('name'), 'selectDiscoveryRule' => array('hostid')); $options = array(); /* * If screen item is dynamic or is templated screen, real item prototype is looked up by "key" * used as resource ID for this screen item and by current host. */ if (($this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM || $this->isTemplatedScreen) && $this->hostid) { $currentItemPrototype = API::ItemPrototype()->get(array('output' => array('key_'), 'itemids' => array($this->screenitem['resourceid']))); $currentItemPrototype = reset($currentItemPrototype); $options['hostids'] = array($this->hostid); $options['filter'] = array('key_' => $currentItemPrototype['key_']); } else { $options['itemids'] = array($this->screenitem['resourceid']); } $options = zbx_array_merge($defaultOptions, $options); $selectedItemPrototype = API::ItemPrototype()->get($options); $this->itemPrototype = reset($selectedItemPrototype); } return $this->itemPrototype; }
function drawMapLinkLabels(&$im, $map, $mapInfo, $resolveMacros = true) { global $colors; $links = $map['links']; $selements = $map['selements']; foreach ($links as $link) { if (empty($link['label'])) { continue; } $selement1 = $selements[$link['selementid1']]; list($x1, $y1) = get_icon_center_by_selement($selement1, $mapInfo[$link['selementid1']], $map); $selement2 = $selements[$link['selementid2']]; list($x2, $y2) = get_icon_center_by_selement($selement2, $mapInfo[$link['selementid2']], $map); if (isset($selement1['elementsubtype']) && $selement1['elementsubtype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) { if ($selement1['areatype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) { $w = $selement1['width']; $h = $selement1['height']; } else { $w = $map['width']; $h = $map['height']; } list($x1, $y1) = calculateMapAreaLinkCoord($x1, $y1, $w, $h, $x2, $y2); } if (isset($selement2['elementsubtype']) && $selement2['elementsubtype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) { if ($selement2['areatype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) { $w = $selement2['width']; $h = $selement2['height']; } else { $w = $map['width']; $h = $map['height']; } list($x2, $y2) = calculateMapAreaLinkCoord($x2, $y2, $w, $h, $x1, $y1); } $drawtype = $link['drawtype']; $color = convertColor($im, $link['color']); $linktriggers = $link['linktriggers']; order_result($linktriggers, 'triggerid'); if (!empty($linktriggers)) { $max_severity = 0; $triggers = array(); foreach ($linktriggers as $link_trigger) { if ($link_trigger['triggerid'] == 0) { continue; } $id = $link_trigger['linktriggerid']; $triggers[$id] = zbx_array_merge($link_trigger, get_trigger_by_triggerid($link_trigger['triggerid'])); if ($triggers[$id]['status'] == TRIGGER_STATUS_ENABLED && $triggers[$id]['value'] == TRIGGER_VALUE_TRUE) { if ($triggers[$id]['priority'] >= $max_severity) { $drawtype = $triggers[$id]['drawtype']; $color = convertColor($im, $triggers[$id]['color']); $max_severity = $triggers[$id]['priority']; } } } } $label = $link['label']; $label = str_replace("\r", '', $label); $strings = explode("\n", $label); $box_width = 0; $box_height = 0; foreach ($strings as $snum => $str) { $strings[$snum] = $resolveMacros ? CMacrosResolverHelper::resolveMapLabelMacros($str) : $str; } foreach ($strings as $str) { $dims = imageTextSize(8, 0, $str); $box_width = $box_width > $dims['width'] ? $box_width : $dims['width']; $box_height += $dims['height'] + 2; } $boxX_left = round(($x1 + $x2) / 2 - $box_width / 2 - 6); $boxX_right = round(($x1 + $x2) / 2 + $box_width / 2 + 6); $boxY_top = round(($y1 + $y2) / 2 - $box_height / 2 - 4); $boxY_bottom = round(($y1 + $y2) / 2 + $box_height / 2 + 2); switch ($drawtype) { case MAP_LINK_DRAWTYPE_DASHED_LINE: case MAP_LINK_DRAWTYPE_DOT: dashedRectangle($im, $boxX_left, $boxY_top, $boxX_right, $boxY_bottom, $color); break; case MAP_LINK_DRAWTYPE_BOLD_LINE: imagerectangle($im, $boxX_left - 1, $boxY_top - 1, $boxX_right + 1, $boxY_bottom + 1, $color); // break; is not ne // break; is not ne case MAP_LINK_DRAWTYPE_LINE: default: imagerectangle($im, $boxX_left, $boxY_top, $boxX_right, $boxY_bottom, $color); } imagefilledrectangle($im, $boxX_left + 1, $boxY_top + 1, $boxX_right - 1, $boxY_bottom - 1, $colors['White']); $increasey = 4; foreach ($strings as $str) { $dims = imageTextSize(8, 0, $str); $labelx = ($x1 + $x2) / 2 - $dims['width'] / 2; $labely = $boxY_top + $increasey; imagetext($im, 8, 0, $labelx, $labely + $dims['height'], $colors['Black'], $str); $increasey += $dims['height'] + 2; } } }
/** * Get proxy data. * * @param array $options * @param array $options['nodeids'] * @param array $options['proxyids'] * @param bool $options['editable'] only with read-write permission. Ignored for SuperAdmins * @param int $options['count'] returns value in rowscount * @param string $options['pattern'] * @param int $options['limit'] * @param string $options['sortfield'] * @param string $options['sortorder'] * * @return array */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $sqlParts = array('select' => array('hostid' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array('h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')'), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'proxyids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'preservekeys' => null, 'selectHosts' => null, 'selectInterface' => null, 'selectInterfaces' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); // deprecated $this->checkDeprecatedParam($options, 'selectInterfaces'); // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ; if ($permission == PERM_READ_WRITE) { return array(); } } // proxyids if (!is_null($options['proxyids'])) { zbx_value2array($options['proxyids']); $sqlParts['where'][] = dbConditionInt('h.hostid', $options['proxyids']); } // 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']['hostid'] = 'h.hostid'; $sqlParts['select']['host'] = 'h.host'; $sqlParts['select']['status'] = 'h.status'; $sqlParts['select']['lastaccess'] = 'h.lastaccess'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('COUNT(DISTINCT h.hostid) AS rowscount'); } // 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); $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($proxy = DBfetch($res)) { if ($options['countOutput']) { $result = $proxy['rowscount']; } else { $proxy['proxyid'] = $proxy['hostid']; unset($proxy['hostid']); if (!isset($result[$proxy['proxyid']])) { $result[$proxy['proxyid']] = array(); } $result[$proxy['proxyid']] += $proxy; } } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, array('hostid'), $options['output']); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Get Itemprototype data. */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = array('select' => array('items' => 'i.itemid'), 'from' => array('items' => 'items i'), 'where' => array('i.flags=' . ZBX_FLAG_DISCOVERY_PROTOTYPE), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('groupids' => null, 'templateids' => null, 'hostids' => null, 'itemids' => null, 'discoveryids' => null, 'graphids' => null, 'triggerids' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => null, 'selectApplications' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectDiscoveryRule' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); // 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 hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE i.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')'; } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $options['hostids'] = array_merge($options['hostids'], $options['templateids']); } else { $options['hostids'] = $options['templateids']; } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['hostids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['i'] = 'i.hostid'; } } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); $sqlParts['where']['itemid'] = dbConditionInt('i.itemid', $options['itemids']); } // discoveryids if (!is_null($options['discoveryids'])) { zbx_value2array($options['discoveryids']); $sqlParts['from']['item_discovery'] = 'item_discovery id'; $sqlParts['where'][] = dbConditionInt('id.parent_itemid', $options['discoveryids']); $sqlParts['where']['idi'] = 'i.itemid=id.itemid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['id'] = 'id.parent_itemid'; } } // triggerids if (!is_null($options['triggerids'])) { zbx_value2array($options['triggerids']); $sqlParts['from']['functions'] = 'functions f'; $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']); $sqlParts['where']['if'] = 'i.itemid=f.itemid'; } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']); $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; } // inherited if (!is_null($options['inherited'])) { if ($options['inherited']) { $sqlParts['where'][] = 'i.templateid IS NOT NULL'; } else { $sqlParts['where'][] = 'i.templateid IS NULL'; } } // templated if (!is_null($options['templated'])) { $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if ($options['templated']) { $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE; } else { $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE; } } // monitored if (!is_null($options['monitored'])) { $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if ($options['monitored']) { $sqlParts['where'][] = 'h.status=' . HOST_STATUS_MONITORED; $sqlParts['where'][] = 'i.status=' . ITEM_STATUS_ACTIVE; } else { $sqlParts['where'][] = '(h.status<>' . HOST_STATUS_MONITORED . ' OR i.status<>' . ITEM_STATUS_ACTIVE . ')'; } } // search if (is_array($options['search'])) { zbx_db_search('items i', $options, $sqlParts); } // --- FILTER --- if (is_array($options['filter'])) { $this->dbFilter('items i', $options, $sqlParts); if (isset($options['filter']['host'])) { zbx_value2array($options['filter']['host']); $sqlParts['from']['hosts'] = 'hosts h'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; $sqlParts['where']['h'] = dbConditionString('h.host', $options['filter']['host']); } } // 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 ($item = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $item; } else { $result = $item['rowscount']; } } else { $result[$item['itemid']] = $item; } } if (!is_null($options['countOutput'])) { return $result; } // add other related objects if ($result) { $result = $this->addRelatedObjects($options, $result); $result = $this->unsetExtraFields($result, array('hostid'), $options['output']); } 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; }
/** * 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; }
/** * Get maintenances data. * * @param array $options * @param array $options['itemids'] * @param array $options['hostids'] * @param array $options['groupids'] * @param array $options['triggerids'] * @param array $options['maintenanceids'] * @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 = []; $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = ['select' => ['maintenance' => 'm.maintenanceid'], 'from' => ['maintenances' => 'maintenances m'], 'where' => [], 'group' => [], 'order' => [], 'limit' => null]; $defOptions = ['groupids' => null, 'hostids' => null, 'maintenanceids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'filter' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectGroups' => null, 'selectHosts' => null, 'selectTimeperiods' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null]; $options = zbx_array_merge($defOptions, $options); // editable + PERMISSION CHECK $maintenanceids = []; if ($userType == USER_TYPE_SUPER_ADMIN || $options['nopermissions']) { if (!is_null($options['groupids']) || !is_null($options['hostids'])) { if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); $res = DBselect('SELECT mmg.maintenanceid' . ' FROM maintenances_groups mmg' . ' WHERE ' . dbConditionInt('mmg.groupid', $options['groupids'])); while ($maintenance = DBfetch($res)) { $maintenanceids[] = $maintenance['maintenanceid']; } } $sql = 'SELECT mmh.maintenanceid' . ' FROM maintenances_hosts mmh,hosts_groups hg' . ' WHERE hg.hostid=mmh.hostid'; if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); $sql .= ' AND ' . dbConditionInt('hg.groupid', $options['groupids']); } if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sql .= ' AND ' . dbConditionInt('hg.hostid', $options['hostids']); } $res = DBselect($sql); while ($maintenance = DBfetch($res)) { $maintenanceids[] = $maintenance['maintenanceid']; } $sqlParts['where'][] = dbConditionInt('m.maintenanceid', $maintenanceids); } } else { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ; $userGroups = getUserGroupsByUserId($userid); $sql = 'SELECT m.maintenanceid' . ' FROM maintenances m' . ' WHERE NOT EXISTS (' . 'SELECT NULL' . ' FROM maintenances_hosts mh,hosts_groups hg' . ' LEFT JOIN rights r' . ' ON r.id=hg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE m.maintenanceid=mh.maintenanceid' . ' AND mh.hostid=hg.hostid' . ' GROUP by mh.hostid' . ' HAVING MIN(r.permission) IS NULL' . ' OR MIN(r.permission)=' . PERM_DENY . ' OR MAX(r.permission)<' . zbx_dbstr($permission) . ')' . ' AND NOT EXISTS (' . 'SELECT NULL' . ' FROM maintenances_groups mg' . ' LEFT JOIN rights r' . ' ON r.id=mg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE m.maintenanceid=mg.maintenanceid' . ' GROUP by mg.groupid' . ' HAVING MIN(r.permission) IS NULL' . ' OR MIN(r.permission)=' . PERM_DENY . ' OR MAX(r.permission)<' . zbx_dbstr($permission) . ')'; if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); $sql .= ' AND (' . 'EXISTS (' . 'SELECT NULL' . ' FROM maintenances_groups mg' . ' WHERE m.maintenanceid=mg.maintenanceid' . ' AND ' . dbConditionInt('mg.groupid', $options['groupids']) . ')' . ' OR EXISTS (' . 'SELECT NULL' . ' FROM maintenances_hosts mh,hosts_groups hg' . ' WHERE m.maintenanceid=mh.maintenanceid' . ' AND mh.hostid=hg.hostid' . ' AND ' . dbConditionInt('hg.groupid', $options['groupids']) . ')' . ')'; } if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sql .= ' AND EXISTS (' . 'SELECT NULL' . ' FROM maintenances_hosts mh' . ' WHERE m.maintenanceid=mh.maintenanceid' . ' AND ' . dbConditionInt('mh.hostid', $options['hostids']) . ')'; } if (!is_null($options['maintenanceids'])) { zbx_value2array($options['maintenanceids']); $sql .= ' AND ' . dbConditionInt('m.maintenanceid', $options['maintenanceids']); } $res = DBselect($sql); while ($maintenance = DBfetch($res)) { $maintenanceids[] = $maintenance['maintenanceid']; } $sqlParts['where'][] = dbConditionInt('m.maintenanceid', $maintenanceids); } // maintenanceids if (!is_null($options['maintenanceids'])) { zbx_value2array($options['maintenanceids']); $sqlParts['where'][] = dbConditionInt('m.maintenanceid', $options['maintenanceids']); } // filter if (is_array($options['filter'])) { $this->dbFilter('maintenances m', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('maintenances m', $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 ($maintenance = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $maintenance; } else { $result = $maintenance['rowscount']; } } else { $result[$maintenance['maintenanceid']] = $maintenance; } } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->addRelatedObjects($options, $result); } if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }