/** * Retrieves graphs created for graph prototype given as resource for this screen item * and returns array of the graph IDs. * * @return array */ protected function getCreatedGraphIds() { if (!$this->createdGraphIds) { $graphPrototype = $this->getGraphPrototype(); if ($graphPrototype) { // Get all created (discovered) graphs for host of graph prototype. $allCreatedGraphs = API::Graph()->get(['output' => ['graphid', 'name'], 'hostids' => [$graphPrototype['discoveryRule']['hostid']], 'selectGraphDiscovery' => ['graphid', 'parent_graphid'], 'expandName' => true, 'filter' => ['flags' => ZBX_FLAG_DISCOVERY_CREATED]]); // Collect those graph IDs where parent graph is graph prototype selected for // this screen item as resource. foreach ($allCreatedGraphs as $graph) { if ($graph['graphDiscovery']['parent_graphid'] == $graphPrototype['graphid']) { $this->createdGraphIds[$graph['graphid']] = $graph['name']; } } natsort($this->createdGraphIds); $this->createdGraphIds = array_keys($this->createdGraphIds); } } return $this->createdGraphIds; }
/** * Prepare data for favourite graphs menu popup. * * @return array */ public static function getFavouriteGraphs() { $graphs = []; $simple_graphs = []; $favourites = CFavorite::get('web.favorite.graphids'); if ($favourites) { $graphids = []; $itemids = []; $db_graphs = []; $db_items = []; foreach ($favourites as $favourite) { if ($favourite['source'] === 'itemid') { $itemids[$favourite['value']] = true; } else { $graphids[$favourite['value']] = true; } } if ($graphids) { $db_graphs = API::Graph()->get(['output' => ['graphid', 'name'], 'selectHosts' => ['hostid', 'name'], 'expandName' => true, 'graphids' => array_keys($graphids), 'preservekeys' => true]); } if ($itemids) { $db_items = API::Item()->get(['output' => ['itemid', 'hostid', 'name', 'key_'], 'selectHosts' => ['hostid', 'name'], 'itemids' => array_keys($itemids), 'webitems' => true, 'preservekeys' => true]); $db_items = CMacrosResolverHelper::resolveItemNames($db_items); } foreach ($favourites as $favourite) { $sourceid = $favourite['value']; if ($favourite['source'] === 'itemid') { if (array_key_exists($sourceid, $db_items)) { $db_item = $db_items[$sourceid]; $simple_graphs[] = ['id' => $sourceid, 'label' => $db_item['hosts'][0]['name'] . NAME_DELIMITER . $db_item['name_expanded']]; } } else { if (array_key_exists($sourceid, $db_graphs)) { $db_graph = $db_graphs[$sourceid]; $graphs[] = ['id' => $sourceid, 'label' => $db_graph['hosts'][0]['name'] . NAME_DELIMITER . $db_graph['name']]; } } } } return ['type' => 'favouriteGraphs', 'graphs' => $graphs, 'simpleGraphs' => $simple_graphs]; }
/** * Prepare data for favourite graphs menu popup. * * @return array */ public static function getFavouriteGraphs() { $graphs = $simpeGraphs = array(); $favourites = CFavorite::get('web.favorite.graphids'); if ($favourites) { $graphIds = $itemIds = $dbGraphs = $dbItems = array(); foreach ($favourites as $favourite) { if ($favourite['source'] === 'itemid') { $itemIds[$favourite['value']] = $favourite['value']; } else { $graphIds[$favourite['value']] = $favourite['value']; } } if ($graphIds) { $dbGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'selectHosts' => array('hostid', 'host'), 'expandName' => true, 'graphids' => $graphIds, 'preservekeys' => true)); } if ($itemIds) { $dbItems = API::Item()->get(array('output' => array('itemid', 'hostid', 'name', 'key_'), 'selectHosts' => array('hostid', 'host'), 'itemids' => $itemIds, 'webitems' => true, 'preservekeys' => true)); $dbItems = CMacrosResolverHelper::resolveItemNames($dbItems); } foreach ($favourites as $favourite) { $sourceId = $favourite['value']; if ($favourite['source'] === 'itemid') { if (isset($dbItems[$sourceId])) { $dbItem = $dbItems[$sourceId]; $dbHost = reset($dbItem['hosts']); $simpeGraphs[] = array('id' => $sourceId, 'label' => $dbHost['host'] . NAME_DELIMITER . $dbItem['name_expanded']); } } else { if (isset($dbGraphs[$sourceId])) { $dbGraph = $dbGraphs[$sourceId]; $dbHost = reset($dbGraph['hosts']); $graphs[] = array('id' => $sourceId, 'label' => $dbHost['host'] . NAME_DELIMITER . $dbGraph['name']); } } } } return array('type' => 'favouriteGraphs', 'graphs' => $graphs, 'simpleGraphs' => $simpeGraphs); }
// clone triggers $triggers = API::Trigger()->get(array('output' => array('triggerid'), 'hostids' => $srcHostId, 'inherited' => false)); if ($triggers) { if (!copyTriggersToHosts(zbx_objectValues($triggers, 'triggerid'), $hostId, $srcHostId)) { throw new Exception(); } } // clone discovery rules $discoveryRules = API::DiscoveryRule()->get(array('output' => array('itemid'), 'hostids' => $srcHostId, 'inherited' => false)); if ($discoveryRules) { $copyDiscoveryRules = API::DiscoveryRule()->copy(array('discoveryids' => zbx_objectValues($discoveryRules, 'itemid'), 'hostids' => array($hostId))); if (!$copyDiscoveryRules) { throw new Exception(); } } $graphs = API::Graph()->get(array('hostids' => $srcHostId, 'selectItems' => array('type'), 'output' => API_OUTPUT_EXTEND, 'inherited' => false, 'selectHosts' => array('hostid'), 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); foreach ($graphs as $graph) { if (count($graph['hosts']) > 1) { continue; } if (httpItemExists($graph['items'])) { continue; } if (!copyGraphToHost($graph['graphid'], $hostId)) { throw new Exception(); } } } $result = DBend(true); show_messages($result, $msgOk, $msgFail); clearCookies($result);
/** * Copies all of the graphs from the source discovery to the target discovery rule. * * @throws APIException if graph saving fails * * @param array $srcDiscovery The source discovery rule to copy from * @param array $dstDiscovery The target discovery rule to copy to * * @return array */ protected function copyGraphPrototypes(array $srcDiscovery, array $dstDiscovery) { // fetch source graphs $srcGraphs = API::GraphPrototype()->get(array('discoveryids' => $srcDiscovery['itemid'], 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'selectHosts' => API_OUTPUT_REFER, 'preservekeys' => true)); if (!$srcGraphs) { return array(); } $srcItemIds = array(); foreach ($srcGraphs as $key => $graph) { // skip graphs with items from multiple hosts if (count($graph['hosts']) > 1) { unset($srcGraphs[$key]); continue; } // skip graphs with http items if (httpItemExists($graph['gitems'])) { unset($srcGraphs[$key]); continue; } // save all used item ids to map them to the new items foreach ($graph['gitems'] as $item) { $srcItemIds[$item['itemid']] = $item['itemid']; } if ($graph['ymin_itemid']) { $srcItemIds[$graph['ymin_itemid']] = $graph['ymin_itemid']; } if ($graph['ymax_itemid']) { $srcItemIds[$graph['ymax_itemid']] = $graph['ymax_itemid']; } } // fetch source items $items = API::Item()->get(array('itemids' => $srcItemIds, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'filter' => array('flags' => null))); $srcItems = array(); $itemKeys = array(); foreach ($items as $item) { $srcItems[$item['itemid']] = $item; $itemKeys[$item['key_']] = $item['key_']; } // fetch newly cloned items $newItems = API::Item()->get(array('hostids' => $dstDiscovery['hostid'], 'filter' => array('key_' => $itemKeys, 'flags' => null), 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); $items = array_merge($dstDiscovery['items'], $newItems); $dstItems = array(); foreach ($items as $item) { $dstItems[$item['key_']] = $item; } $dstGraphs = $srcGraphs; foreach ($dstGraphs as &$graph) { unset($graph['graphid']); unset($graph['templateid']); foreach ($graph['gitems'] as &$gitem) { // replace the old item with the new one with the same key $item = $srcItems[$gitem['itemid']]; $gitem['itemid'] = $dstItems[$item['key_']]['itemid']; unset($gitem['gitemid'], $gitem['graphid']); } // replace the old axis items with the new one with the same key if ($graph['ymin_itemid']) { $yMinSrcItem = $srcItems[$graph['ymin_itemid']]; $graph['ymin_itemid'] = $dstItems[$yMinSrcItem['key_']]['itemid']; } if ($graph['ymax_itemid']) { $yMaxSrcItem = $srcItems[$graph['ymax_itemid']]; $graph['ymax_itemid'] = $dstItems[$yMaxSrcItem['key_']]['itemid']; } } // save graphs $rs = API::Graph()->create($dstGraphs); if (!$rs) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot clone graph prototypes.')); } return $rs; }
function make_graph_submenu() { $graphids = array(); $itemids = array(); $favGraphs = array(); $fav_graphs = CFavorite::get('web.favorite.graphids'); if (!$fav_graphs) { return $favGraphs; } foreach ($fav_graphs as $favorite) { if ('itemid' == $favorite['source']) { $itemids[$favorite['value']] = $favorite['value']; } else { $graphids[$favorite['value']] = $favorite['value']; } } if ($graphids) { $options = array('graphids' => $graphids, 'selectHosts' => array('hostid', 'host'), 'output' => array('graphid', 'name'), 'expandName' => true); $graphs = API::Graph()->get($options); $graphs = zbx_toHash($graphs, 'graphid'); } if ($itemids) { $options = array('itemids' => $itemids, 'selectHosts' => array('hostid', 'host'), 'output' => array('itemid', 'name', 'key_'), 'webitems' => 1); $items = API::Item()->get($options); $items = zbx_toHash($items, 'itemid'); } foreach ($fav_graphs as $favorite) { $source = $favorite['source']; $sourceid = $favorite['value']; if ('itemid' == $source) { if (!isset($items[$sourceid])) { continue; } $item_added = true; $item = $items[$sourceid]; $host = reset($item['hosts']); $item['name'] = itemName($item); $favGraphs[] = array('name' => $host['host'] . NAME_DELIMITER . $item['name'], 'favobj' => 'itemid', 'favid' => $sourceid, 'favaction' => 'remove'); } else { if (!isset($graphs[$sourceid])) { continue; } $graph_added = true; $graph = $graphs[$sourceid]; $ghost = reset($graph['hosts']); $favGraphs[] = array('name' => $ghost['host'] . NAME_DELIMITER . $graph['name'], 'favobj' => 'graphid', 'favid' => $sourceid, 'favaction' => 'remove'); } } if (isset($graph_added)) { $favGraphs[] = array('name' => _('Remove') . ' ' . _('All') . ' ' . _('Graphs'), 'favobj' => 'graphid', 'favid' => 0, 'favaction' => 'remove'); } if (isset($item_added)) { $favGraphs[] = array('name' => _('Remove') . ' ' . _('All') . ' ' . _('Simple graphs'), 'favobj' => 'itemid', 'favid' => 0, 'favaction' => 'remove'); } return $favGraphs; }
throw new Exception(); } // copy web scenarios if (!copyHttpTests($cloneTemplateId, $templateId)) { throw new Exception(); } // copy triggers $dbTriggers = API::Trigger()->get(array('output' => array('triggerid'), 'hostids' => $cloneTemplateId, 'inherited' => false)); if ($dbTriggers) { $result &= copyTriggersToHosts(zbx_objectValues($dbTriggers, 'triggerid'), $templateId, $cloneTemplateId); if (!$result) { throw new Exception(); } } // copy graphs $dbGraphs = API::Graph()->get(array('output' => array('graphid'), 'hostids' => $cloneTemplateId, 'inherited' => false)); foreach ($dbGraphs as $dbGraph) { copyGraphToHost($dbGraph['graphid'], $templateId); } // copy discovery rules $dbDiscoveryRules = API::DiscoveryRule()->get(array('output' => array('itemid'), 'hostids' => $cloneTemplateId, 'inherited' => false)); if ($dbDiscoveryRules) { $result &= API::DiscoveryRule()->copy(array('discoveryids' => zbx_objectValues($dbDiscoveryRules, 'itemid'), 'hostids' => array($templateId))); if (!$result) { throw new Exception(); } } // copy template screens $dbTemplateScreens = API::TemplateScreen()->get(array('output' => array('screenid'), 'templateids' => $cloneTemplateId, 'preservekeys' => true, 'inherited' => false)); if ($dbTemplateScreens) { $result &= API::TemplateScreen()->copy(array('screenIds' => zbx_objectValues($dbTemplateScreens, 'screenid'), 'templateIds' => $templateId));
/** * Copy specified graph to specified host. * * @param $graphid * @param $hostid * @return array|bool */ function copy_graph_to_host($graphid, $hostid) { $graphs = API::Graph()->get(array('graphids' => $graphid, 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND)); $graph = reset($graphs); $new_gitems = get_same_graphitems_for_host($graph['gitems'], $hostid); if (!$new_gitems) { $host = get_host_by_hostid($hostid); info(_s('Skipped copying of graph "%1$s" to host "%2$s".', $graph['name'], $host['host'])); return false; } // retrieve actual ymax_itemid and ymin_itemid if ($graph['ymax_itemid']) { if ($itemid = get_same_item_for_host($graph['ymax_itemid'], $hostid)) { $graph['ymax_itemid'] = $itemid; } } if ($graph['ymin_itemid']) { if ($itemid = get_same_item_for_host($graph['ymin_itemid'], $hostid)) { $graph['ymin_itemid'] = $itemid; } } $graph['gitems'] = $new_gitems; unset($graph['templateid']); $result = API::Graph()->create($graph); return $result; }
/** * Delete GraphPrototype. * * @param array $graphids * @param bool $nopermissions * * @return array */ public function delete(array $graphids, $nopermissions = false) { if (empty($graphids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $delGraphs = $this->get(array('graphids' => $graphids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); if (!$nopermissions) { foreach ($graphids as $graphid) { if (!isset($delGraphs[$graphid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } if ($delGraphs[$graphid]['templateid'] != 0) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('Cannot delete templated graphs.')); } } } $parentGraphids = $graphids; do { $dbGraphs = DBselect('SELECT g.graphid FROM graphs g WHERE ' . dbConditionInt('g.templateid', $parentGraphids)); $parentGraphids = array(); while ($dbGraph = DBfetch($dbGraphs)) { $parentGraphids[] = $dbGraph['graphid']; $graphids[] = $dbGraph['graphid']; } } while (!empty($parentGraphids)); $graphids = array_unique($graphids); $createdGraphs = array(); $dbGraphs = DBselect('SELECT gd.graphid FROM graph_discovery gd WHERE ' . dbConditionInt('gd.parent_graphid', $graphids)); while ($graph = DBfetch($dbGraphs)) { $createdGraphs[$graph['graphid']] = $graph['graphid']; } if (!empty($createdGraphs)) { $result = API::Graph()->delete($createdGraphs, true); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete graphs created by low level discovery.')); } } DB::delete('screens_items', array('resourceid' => $graphids, 'resourcetype' => SCREEN_RESOURCE_LLD_GRAPH)); DB::delete('graphs', array('graphid' => $graphids)); foreach ($delGraphs as $graph) { info(_s('Graph prototype "%s" deleted.', $graph['name'])); } return array('graphids' => $graphids); }
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__) . '/include/config.inc.php'; require_once dirname(__FILE__) . '/include/graphs.inc.php'; $page['file'] = 'chart6.php'; $page['type'] = PAGE_TYPE_IMAGE; require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('graphid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, null), 'period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'profileIdx' => array(T_ZBX_STR, O_OPT, null, null, null), 'profileIdx2' => array(T_ZBX_STR, O_OPT, null, null, null), 'updateProfile' => array(T_ZBX_STR, O_OPT, null, null, null), 'border' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'width' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(20, 65535), null), 'height' => array(T_ZBX_INT, O_OPT, P_NZERO, '{}>0', null), 'graph3d' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'legend' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null)); if (!check_fields($fields)) { exit; } /* * Permissions */ $dbGraph = API::Graph()->get(array('output' => API_OUTPUT_EXTEND, 'selectGraphItems' => array('itemid', 'calc_fnc', 'color', 'type'), 'selectHosts' => array('name'), 'graphids' => $_REQUEST['graphid'])); if (!$dbGraph) { access_deny(); } else { $dbGraph = reset($dbGraph); } /* * Display */ $timeline = CScreenBase::calculateTime(array('profileIdx' => getRequest('profileIdx', 'web.screens'), 'profileIdx2' => getRequest('profileIdx2'), 'updateProfile' => getRequest('updateProfile', true), 'period' => getRequest('period'), 'stime' => getRequest('stime'))); $graph = new CPieGraphDraw($dbGraph['graphtype']); $graph->setPeriod($timeline['period']); $graph->setSTime($timeline['stime']); if (isset($_REQUEST['border'])) { $graph->setBorder(0); }
/** * Checks if any of the given items are used as min/max Y values in a graph. * * if there are graphs, that have an y*_itemid column set, but the * y*_type column is not set to GRAPH_YAXIS_TYPE_ITEM_VALUE, the y*_itemid * column will be set to NULL. * * If the $checkMax parameter is set to true, the items will be checked against * max Y values, otherwise, they will be checked against min Y values. * * @throws APIException if any of the given items are used as min/max Y values in a graph. * * @param array $itemids An array of items IDs * @param type $checkMax */ protected function checkUseInGraphAxis(array $itemids, $checkMax = false) { if ($checkMax) { $filter = array('ymax_itemid' => $itemids); $itemIdColumn = 'ymax_itemid'; $typeColumn = 'ymax_type'; } else { $filter = array('ymin_itemid' => $itemids); $itemIdColumn = 'ymin_itemid'; $typeColumn = 'ymin_type'; } // make it work for both graphs and graph prototypes $filter['flags'] = array(ZBX_FLAG_DISCOVERY_PROTOTYPE, ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED); // check if the items are used in Y axis min/max values in any graphs $graphs = API::Graph()->get(array('output' => array($itemIdColumn, $typeColumn, 'graphtype'), 'filter' => $filter)); $updateGraphs = array(); foreach ($graphs as &$graph) { // check if Y type is actually set to GRAPH_YAXIS_TYPE_ITEM_VALUE if ($graph[$typeColumn] == GRAPH_YAXIS_TYPE_ITEM_VALUE) { if ($checkMax) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Could not delete these items because some of them are used as MAX values for graphs.'); } else { self::exception(ZBX_API_ERROR_PARAMETERS, 'Could not delete these items because some of them are used as MIN values for graphs.'); } } else { $graph[$itemIdColumn] = null; $updateGraphs[] = $graph; } } // if there are graphs, that have an y*_itemid column set, but the // y*_type column is not set to GRAPH_YAXIS_TYPE_ITEM_VALUE, set y*_itemid to NULL. // Otherwise we won't be able to delete them. if ($updateGraphs) { API::Graph()->update($updateGraphs); } }
/** * Select graph IDs for previously added graph names. */ protected function selectGraphs() { if ($this->graphs) { $this->graphsRefs = array(); $graphNames = array(); foreach ($this->graphs as $graphs) { foreach ($graphs as $graph) { $graphNames[$graph] = $graph; } } $dbGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'selectHosts' => array('hostid'), 'filter' => array('name' => $graphNames, 'flags' => null), 'editable' => true)); foreach ($dbGraphs as $dbGraph) { foreach ($dbGraph['hosts'] as $host) { $this->graphsRefs[$host['hostid']][$dbGraph['name']] = $dbGraph['graphid']; } } } }
/** * Get Template data * * @param array $options * @return array|boolean Template data as array or false if error */ public function get($options = array()) { $result = array(); $nodeCheck = false; $userType = self::$userData['type']; $userid = self::$userData['userid']; // allowed columns for sorting $sortColumns = array('hostid', 'host', 'name'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND); $sqlParts = array('select' => array('templates' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array('h.status=' . HOST_STATUS_TEMPLATE), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'parentTemplateids' => null, 'hostids' => null, 'graphids' => null, 'itemids' => null, 'triggerids' => null, 'with_items' => null, 'with_triggers' => null, 'with_graphs' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => '', 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectHosts' => null, 'selectTemplates' => null, 'selectParentTemplates' => null, 'selectItems' => null, 'selectDiscoveries' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectApplications' => null, 'selectMacros' => null, 'selectScreens' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); if (is_array($options['output'])) { unset($sqlParts['select']['templates']); $dbTable = DB::getSchema('hosts'); $sqlParts['select']['hostid'] = 'h.hostid'; foreach ($options['output'] as $field) { if ($field == 'templateid') { continue; } if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 'h.' . $field; } } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY; $userGroups = getUserGroupsByUserId($userid); $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE h.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')'; } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['groupid'] = 'hg.groupid'; } $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where']['hgh'] = 'hg.hostid=h.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['hg'] = 'hg.groupid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('hg.groupid', $nodeids); } } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); $sqlParts['where']['templateid'] = dbConditionInt('h.hostid', $options['templateids']); if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('h.hostid', $nodeids); } } // parentTemplateids if (!is_null($options['parentTemplateids'])) { zbx_value2array($options['parentTemplateids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['parentTemplateid'] = 'ht.templateid as parentTemplateid'; } $sqlParts['from']['hosts_templates'] = 'hosts_templates ht'; $sqlParts['where'][] = dbConditionInt('ht.templateid', $options['parentTemplateids']); $sqlParts['where']['hht'] = 'h.hostid=ht.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['templateid'] = 'ht.templateid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ht.templateid', $nodeids); } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['linked_hostid'] = 'ht.hostid as linked_hostid'; } $sqlParts['from']['hosts_templates'] = 'hosts_templates ht'; $sqlParts['where'][] = dbConditionInt('ht.hostid', $options['hostids']); $sqlParts['where']['hht'] = 'h.hostid=ht.templateid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['ht'] = 'ht.hostid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ht.hostid', $nodeids); } } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['itemid'] = 'i.itemid'; } $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('i.itemid', $options['itemids']); $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('i.itemid', $nodeids); } } // triggerids if (!is_null($options['triggerids'])) { zbx_value2array($options['triggerids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['triggerid'] = 'f.triggerid'; } $sqlParts['from']['functions'] = 'functions f'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']); $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; $sqlParts['where']['fi'] = 'f.itemid=i.itemid'; if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('f.triggerid', $nodeids); } } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['graphid'] = 'gi.graphid'; } $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']); $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('gi.graphid', $nodeids); } } // node check !!!! // should last, after all ****IDS checks if (!$nodeCheck) { $sqlParts['where'][] = DBin_node('h.hostid', $nodeids); } // with_items if (!is_null($options['with_items'])) { $sqlParts['where'][] = 'EXISTS (SELECT NULL FROM items i WHERE h.hostid=i.hostid )'; } // with_triggers if (!is_null($options['with_triggers'])) { $sqlParts['where'][] = 'EXISTS(' . 'SELECT NULL' . ' FROM items i,functions f,triggers t' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid)'; } // with_graphs if (!is_null($options['with_graphs'])) { $sqlParts['where'][] = 'EXISTS(' . 'SELECT NULL' . ' FROM items i,graphs_items gi' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=gi.itemid)'; } // filter if (is_array($options['filter'])) { $this->dbFilter('hosts h', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('hosts h', $options, $sqlParts); } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['templates'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('count(DISTINCT h.hostid) as rowscount'); // groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'h'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } //------------- $templateids = array(); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($template = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $template; } else { $result = $template['rowscount']; } } else { $template['templateid'] = $template['hostid']; $templateids[$template['templateid']] = $template['templateid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$template['templateid']] = array('templateid' => $template['templateid']); } else { if (!isset($result[$template['templateid']])) { $result[$template['templateid']] = array(); } if (!is_null($options['selectGroups']) && !isset($result[$template['templateid']]['groups'])) { $template['groups'] = array(); } if (!is_null($options['selectTemplates']) && !isset($result[$template['templateid']]['templates'])) { $template['templates'] = array(); } if (!is_null($options['selectHosts']) && !isset($result[$template['templateid']]['hosts'])) { $template['hosts'] = array(); } if (!is_null($options['selectParentTemplates']) && !isset($result[$template['templateid']]['parentTemplates'])) { $template['parentTemplates'] = array(); } if (!is_null($options['selectItems']) && !isset($result[$template['templateid']]['items'])) { $template['items'] = array(); } if (!is_null($options['selectDiscoveries']) && !isset($result[$template['hostid']]['discoveries'])) { $result[$template['hostid']]['discoveries'] = array(); } if (!is_null($options['selectTriggers']) && !isset($result[$template['templateid']]['triggers'])) { $template['triggers'] = array(); } if (!is_null($options['selectGraphs']) && !isset($result[$template['templateid']]['graphs'])) { $template['graphs'] = array(); } if (!is_null($options['selectApplications']) && !isset($result[$template['templateid']]['applications'])) { $template['applications'] = array(); } if (!is_null($options['selectMacros']) && !isset($result[$template['templateid']]['macros'])) { $template['macros'] = array(); } if (!is_null($options['selectScreens']) && !isset($result[$template['templateid']]['screens'])) { $template['screens'] = array(); } // groupids if (isset($template['groupid']) && is_null($options['selectGroups'])) { if (!isset($result[$template['templateid']]['groups'])) { $result[$template['templateid']]['groups'] = array(); } $result[$template['templateid']]['groups'][] = array('groupid' => $template['groupid']); unset($template['groupid']); } // hostids if (isset($template['linked_hostid']) && is_null($options['selectHosts'])) { if (!isset($result[$template['templateid']]['hosts'])) { $result[$template['templateid']]['hosts'] = array(); } $result[$template['templateid']]['hosts'][] = array('hostid' => $template['linked_hostid']); unset($template['linked_hostid']); } // parentTemplateids if (isset($template['parentTemplateid']) && is_null($options['selectParentTemplates'])) { if (!isset($result[$template['templateid']]['parentTemplates'])) { $result[$template['templateid']]['parentTemplates'] = array(); } $result[$template['templateid']]['parentTemplates'][] = array('templateid' => $template['parentTemplateid']); unset($template['parentTemplateid']); } // itemids if (isset($template['itemid']) && is_null($options['selectItems'])) { if (!isset($result[$template['templateid']]['items'])) { $result[$template['templateid']]['items'] = array(); } $result[$template['templateid']]['items'][] = array('itemid' => $template['itemid']); unset($template['itemid']); } // triggerids if (isset($template['triggerid']) && is_null($options['selectTriggers'])) { if (!isset($result[$template['hostid']]['triggers'])) { $result[$template['hostid']]['triggers'] = array(); } $result[$template['hostid']]['triggers'][] = array('triggerid' => $template['triggerid']); unset($template['triggerid']); } // graphids if (isset($template['graphid']) && is_null($options['selectGraphs'])) { if (!isset($result[$template['templateid']]['graphs'])) { $result[$template['templateid']]['graphs'] = array(); } $result[$template['templateid']]['graphs'][] = array('graphid' => $template['graphid']); unset($template['graphid']); } $result[$template['templateid']] += $template; } } } if (!is_null($options['countOutput'])) { return $result; } // Adding Objects // Adding Groups if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) { $objParams = array('nodeids' => $nodeids, 'output' => $options['selectGroups'], 'hostids' => $templateids, 'preservekeys' => 1); $groups = API::HostGroup()->get($objParams); foreach ($groups as $groupid => $group) { $ghosts = $group['hosts']; unset($group['hosts']); foreach ($ghosts as $hnum => $template) { $result[$template['hostid']]['groups'][] = $group; } } } // Adding Templates if (!is_null($options['selectTemplates'])) { $objParams = array('nodeids' => $nodeids, 'parentTemplateids' => $templateids, 'preservekeys' => 1); if (is_array($options['selectTemplates']) || str_in_array($options['selectTemplates'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectTemplates']; $templates = API::Template()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['parentTemplates']); if (isset($template['parentTemplates']) && is_array($template['parentTemplates'])) { $count = array(); foreach ($template['parentTemplates'] as $parentTemplate) { if (!is_null($options['limitSelects'])) { if (!isset($count[$parentTemplate['templateid']])) { $count[$parentTemplate['templateid']] = 0; } $count[$parentTemplate['hostid']]++; if ($count[$parentTemplate['templateid']] > $options['limitSelects']) { continue; } } $result[$parentTemplate['templateid']]['templates'][] =& $templates[$templateid]; } } } } elseif (API_OUTPUT_COUNT == $options['selectTemplates']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $templates = API::Template()->get($objParams); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $templateid => $template) { if (isset($templates[$groupid])) { $result[$templateid]['templates'] = $templates[$templateid]['rowscount']; } else { $result[$templateid]['templates'] = 0; } } } } // Adding Hosts if (!is_null($options['selectHosts'])) { $objParams = array('nodeids' => $nodeids, 'templateids' => $templateids, 'preservekeys' => 1); if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectHosts']; $hosts = API::Host()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($hosts, 'host'); } foreach ($hosts as $hostid => $host) { unset($hosts[$hostid]['templates']); foreach ($host['templates'] as $tnum => $template) { if (!is_null($options['limitSelects'])) { if (!isset($count[$template['templateid']])) { $count[$template['templateid']] = 0; } $count[$template['templateid']]++; if ($count[$template['templateid']] > $options['limitSelects']) { continue; } } $result[$template['templateid']]['hosts'][] =& $hosts[$hostid]; } } } elseif (API_OUTPUT_COUNT == $options['selectHosts']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $hosts = API::Host()->get($objParams); $hosts = zbx_toHash($hosts, 'hostid'); foreach ($result as $templateid => $template) { if (isset($hosts[$templateid])) { $result[$templateid]['hosts'] = $hosts[$templateid]['rowscount']; } else { $result[$templateid]['hosts'] = 0; } } } } // Adding parentTemplates if (!is_null($options['selectParentTemplates'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => 1); if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectParentTemplates']; $templates = API::Template()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['hosts']); foreach ($template['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['parentTemplates'][] =& $templates[$templateid]; } } } elseif (API_OUTPUT_COUNT == $options['selectTemplates']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $templates = API::Template()->get($objParams); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $templateid => $template) { if (isset($templates[$groupid])) { $result[$templateid]['parentTemplates'] = $templates[$templateid]['rowscount']; } else { $result[$templateid]['parentTemplates'] = 0; } } } } // Adding Items if (!is_null($options['selectItems'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectItems']; $items = API::Item()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } $count = array(); foreach ($items as $itemid => $item) { if (!is_null($options['limitSelects'])) { if (!isset($count[$item['hostid']])) { $count[$item['hostid']] = 0; } $count[$item['hostid']]++; if ($count[$item['hostid']] > $options['limitSelects']) { continue; } } $result[$item['hostid']]['items'][] =& $items[$itemid]; } } elseif (API_OUTPUT_COUNT == $options['selectItems']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::Item()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $templateid => $template) { if (isset($items[$templateid])) { $result[$templateid]['items'] = $items[$templateid]['rowscount']; } else { $result[$templateid]['items'] = 0; } } } } // Adding Discoveries if (!is_null($options['selectDiscoveries'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectDiscoveries']) || str_in_array($options['selectDiscoveries'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDiscoveries']; $items = API::DiscoveryRule()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } foreach ($items as $itemid => $item) { unset($items[$itemid]['hosts']); foreach ($item['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['discoveries'][] =& $items[$itemid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDiscoveries']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::DiscoveryRule()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { if (isset($items[$hostid])) { $result[$hostid]['discoveries'] = $items[$hostid]['rowscount']; } else { $result[$hostid]['discoveries'] = 0; } } } } // Adding triggers if (!is_null($options['selectTriggers'])) { if (is_array($options['selectTriggers']) || str_in_array($options['selectTriggers'], $subselectsAllowedOutputs)) { $triggers = API::Trigger()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => true, 'output' => $options['selectTriggers'])); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } foreach ($triggers as $triggerid => $trigger) { unset($triggers[$triggerid]['hosts']); foreach ($trigger['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['triggers'][] =& $triggers[$triggerid]; } } } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) { $triggers = API::Trigger()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'countOutput' => true, 'groupCount' => true)); $triggers = zbx_toHash($triggers, 'hostid'); foreach ($result as $templateid => $template) { if (isset($triggers[$templateid])) { $result[$templateid]['triggers'] = $triggers[$templateid]['rowscount']; } else { $result[$templateid]['triggers'] = 0; } } } } // Adding graphs if (!is_null($options['selectGraphs'])) { if (is_array($options['selectGraphs']) || str_in_array($options['selectGraphs'], $subselectsAllowedOutputs)) { $graphs = API::Graph()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => true, 'output' => $options['selectGraphs'])); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } foreach ($graphs as $graphid => $graph) { unset($graphs[$graphid]['hosts']); foreach ($graph['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['graphs'][] =& $graphs[$graphid]; } } } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) { $graphs = API::Graph()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'countOutput' => true, 'groupCount' => true)); $graphs = zbx_toHash($graphs, 'hostid'); foreach ($result as $templateid => $template) { if (isset($graphs[$templateid])) { $result[$templateid]['graphs'] = $graphs[$templateid]['rowscount']; } else { $result[$templateid]['graphs'] = 0; } } } } // Adding applications if (!is_null($options['selectApplications'])) { $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectApplications']) || str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectApplications']; $applications = API::Application()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($applications, 'name'); } foreach ($applications as $applicationid => $application) { unset($applications[$applicationid]['hosts']); foreach ($application['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['applications'][] =& $applications[$applicationid]; } } } elseif (API_OUTPUT_COUNT == $options['selectApplications']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $applications = API::Application()->get($objParams); $applications = zbx_toHash($applications, 'hostid'); foreach ($result as $templateid => $template) { if (isset($applications[$templateid])) { $result[$templateid]['applications'] = $applications[$templateid]['rowscount']; } else { $result[$templateid]['applications'] = 0; } } } } // Adding screens if (!is_null($options['selectScreens'])) { $objParams = array('nodeids' => $nodeids, 'templateids' => $templateids, 'editable' => $options['editable'], 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['selectScreens']) || str_in_array($options['selectScreens'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectScreens']; $screens = API::TemplateScreen()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } foreach ($screens as $screenid => $screen) { if (!is_null($options['limitSelects'])) { if (count($result[$screen['hostid']]['screens']) >= $options['limitSelects']) { continue; } } unset($screens[$screenid]['templates']); $result[$screen['hostid']]['screens'][] =& $screens[$screenid]; } } elseif (API_OUTPUT_COUNT == $options['selectScreens']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $screens = API::TemplateScreen()->get($objParams); $screens = zbx_toHash($screens, 'hostid'); foreach ($result as $templateid => $template) { if (isset($screens[$templateid])) { $result[$templateid]['screens'] = $screens[$templateid]['rowscount']; } else { $result[$templateid]['screens'] = 0; } } } } // Adding macros if (!is_null($options['selectMacros']) && str_in_array($options['selectMacros'], $subselectsAllowedOutputs)) { $objParams = array('nodeids' => $nodeids, 'output' => $options['selectMacros'], 'hostids' => $templateids, 'preservekeys' => 1); $macros = API::UserMacro()->get($objParams); foreach ($macros as $macroid => $macro) { unset($macros[$macroid]['hosts']); foreach ($macro['hosts'] as $hnum => $host) { $result[$host['hostid']]['macros'][] = $macros[$macroid]; } } } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
} // append resource types to form list $resourceTypeComboBox = new CComboBox('resourcetype', $resourceType, 'submit()'); $screenResources = screen_resources(); if ($this->data['screen']['templateid']) { unset($screenResources[SCREEN_RESOURCE_DATA_OVERVIEW], $screenResources[SCREEN_RESOURCE_ACTIONS], $screenResources[SCREEN_RESOURCE_EVENTS], $screenResources[SCREEN_RESOURCE_HOSTS_INFO], $screenResources[SCREEN_RESOURCE_MAP], $screenResources[SCREEN_RESOURCE_SCREEN], $screenResources[SCREEN_RESOURCE_SERVER_INFO], $screenResources[SCREEN_RESOURCE_HOSTGROUP_TRIGGERS], $screenResources[SCREEN_RESOURCE_HOST_TRIGGERS], $screenResources[SCREEN_RESOURCE_SYSTEM_STATUS], $screenResources[SCREEN_RESOURCE_TRIGGERS_INFO], $screenResources[SCREEN_RESOURCE_TRIGGERS_OVERVIEW]); } $resourceTypeComboBox->addItems($screenResources); $screenFormList->addRow(_('Resource'), $resourceTypeComboBox); /* * Screen item: Graph */ if ($resourceType == SCREEN_RESOURCE_GRAPH) { $caption = ''; $id = 0; $graphs = API::Graph()->get(array('graphids' => $resourceId, 'selectHosts' => array('hostid', 'name', 'status'), 'output' => API_OUTPUT_EXTEND)); if (!empty($graphs)) { $id = $resourceId; $graph = reset($graphs); order_result($graph['hosts'], 'name'); $graph['host'] = reset($graph['hosts']); $caption = $graph['host']['name'] . NAME_DELIMITER . $graph['name']; $nodeName = get_node_name_by_elid($graph['host']['hostid']); if (!zbx_empty($nodeName)) { $caption = '(' . $nodeName . ') ' . $caption; } } if ($this->data['screen']['templateid']) { $selectButton = new CButton('select', _('Select'), 'javascript: return PopUp("popup.php?srctbl=graphs&srcfld1=graphid&srcfld2=name' . '&dstfrm=' . $screenForm->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&templated_hosts=1&only_hostid=' . $this->data['screen']['templateid'] . '&writeonly=1", 800, 450);', 'formlist'); } else { $selectButton = new CButton('select', _('Select'), 'javascript: return PopUp("popup.php?srctbl=graphs&srcfld1=graphid&srcfld2=name' . '&dstfrm=' . $screenForm->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&real_hosts=1&with_graphs=1&writeonly=1", 800, 450);', 'formlist');
/** * Get Screen data * * @param array $options * @param array $options['nodeids'] Node IDs * @param boolean $options['with_items'] only with items * @param boolean $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['order'] deprecated parameter (for now) * @return array|boolean Host data as array or false if error */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; // allowed columns for sorting $sortColumns = array('screenid', 'name'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND); $sqlParts = array('select' => array('screens' => 's.screenid,s.templateid'), 'from' => array('screens' => 'screens s'), 'where' => array('template' => 's.templateid IS NOT NULL'), 'order' => array(), 'group' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'screenids' => null, 'screenitemids' => null, 'templateids' => null, 'hostids' => null, 'editable' => null, 'noInheritance' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectScreenItems' => 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']['screens']); $dbTable = DB::getSchema('screens'); foreach ($options['output'] as $field) { if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 's.' . $field; } } $options['output'] = API_OUTPUT_CUSTOM; } if (!is_null($options['editable']) || is_null($options['hostids']) && is_null($options['templateids'])) { $options['noInheritance'] = 1; } // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { // TODO: think how we could combine templateids && hostids options if (!is_null($options['templateids'])) { unset($options['hostids']); $options['templateids'] = API::Template()->get(array('templateids' => $options['templateids'], 'editable' => $options['editable'], 'preservekeys' => true)); $options['templateids'] = array_keys($options['templateids']); } elseif (!is_null($options['hostids'])) { $options['templateids'] = API::Host()->get(array('hostids' => $options['hostids'], 'editable' => $options['editable'], 'preservekeys' => true)); $options['templateids'] = array_keys($options['templateids']); } else { // TODO: get screen $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY; $userGroups = getUserGroupsByUserId($userid); $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE s.templateid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')'; } } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // screenids if (!is_null($options['screenids'])) { zbx_value2array($options['screenids']); $sqlParts['where'][] = dbConditionInt('s.screenid', $options['screenids']); } // screenitemids if (!is_null($options['screenitemids'])) { zbx_value2array($options['screenitemids']); if ($options['output'] != API_OUTPUT_EXTEND) { $sqlParts['select']['screenitemid'] = 'si.screenitemid'; } $sqlParts['from']['screens_items'] = 'screens_items si'; $sqlParts['where']['ssi'] = 'si.screenid=s.screenid'; $sqlParts['where'][] = dbConditionInt('si.screenitemid', $options['screenitemids']); } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if (isset($options['hostids']) && !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']); // collecting template chain $templatesChain = array(); $linkedTemplateids = $options['hostids']; $childTemplateids = $options['hostids']; while (is_null($options['noInheritance']) && !empty($childTemplateids)) { $sql = 'SELECT ht.*' . ' FROM hosts_templates ht' . ' WHERE ' . dbConditionInt('hostid', $childTemplateids); $dbTemplates = DBselect($sql); $childTemplateids = array(); while ($link = DBfetch($dbTemplates)) { $childTemplateids[$link['templateid']] = $link['templateid']; $linkedTemplateids[$link['templateid']] = $link['templateid']; createParentToChildRelation($templatesChain, $link, 'templateid', 'hostid'); } } if ($options['output'] != API_OUTPUT_EXTEND) { $sqlParts['select']['templateid'] = 's.templateid'; } if (!is_null($options['groupCount'])) { $sqlParts['group']['templateid'] = 's.templateid'; } $sqlParts['where']['templateid'] = dbConditionInt('s.templateid', $linkedTemplateids); } // filter if (is_array($options['filter'])) { $this->dbFilter('screens s', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('screens s', $options, $sqlParts); } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['screens'] = 's.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('count(DISTINCT s.screenid) as rowscount'); // groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 's'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $screenids = 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'])) { $sqlGroup .= ' 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('s.screenid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder; $res = DBselect($sql, $sqlLimit); while ($screen = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $screen; } else { $result = $screen['rowscount']; } } else { $screenids[$screen['screenid']] = $screen['screenid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$screen['screenid']] = array('screenid' => $screen['screenid'], 'templateid' => $screen['templateid']); } else { if (!isset($result[$screen['screenid']])) { $result[$screen['screenid']] = array(); } if (!is_null($options['selectScreenItems']) && !isset($result[$screen['screenid']]['screenitems'])) { $result[$screen['screenid']]['screenitems'] = array(); } if (isset($screen['screenitemid']) && is_null($options['selectScreenItems'])) { if (!isset($result[$screen['screenid']]['screenitems'])) { $result[$screen['screenid']]['screenitems'] = array(); } $result[$screen['screenid']]['screenitems'][] = array('screenitemid' => $screen['screenitemid']); unset($screen['screenitemid']); } $result[$screen['screenid']] += $screen; } } } // hashing $options['hostids'] = zbx_toHash($options['hostids']); // adding screenitems if (!is_null($options['selectScreenItems']) && str_in_array($options['selectScreenItems'], $subselectsAllowedOutputs)) { $screensItems = array(); $dbSitems = DBselect('SELECT si.* FROM screens_items si WHERE ' . dbConditionInt('si.screenid', $screenids)); while ($sitem = DBfetch($dbSitems)) { // sorting $screensItems[$sitem['screenitemid']] = $sitem; switch ($sitem['resourcetype']) { case SCREEN_RESOURCE_GRAPH: $graphids[$sitem['resourceid']] = $sitem['resourceid']; break; case SCREEN_RESOURCE_SIMPLE_GRAPH: case SCREEN_RESOURCE_PLAIN_TEXT: $itemids[$sitem['resourceid']] = $sitem['resourceid']; break; } } foreach ($screensItems as $sitem) { if (!isset($result[$sitem['screenid']]['screenitems'])) { $result[$sitem['screenid']]['screenitems'] = array(); } $result[$sitem['screenid']]['screenitems'][] = $sitem; } } // creating linkage of template -> real objects if (!is_null($options['selectScreenItems']) && !is_null($options['hostids'])) { // prepare graphs if (!empty($graphids)) { $tplGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true)); $dbGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'hostids' => $options['hostids'], 'filter' => array('name' => zbx_objectValues($tplGraphs, 'name')), 'nopermissions' => true, 'preservekeys' => true)); $realGraphs = array(); foreach ($dbGraphs as $graph) { $host = reset($graph['hosts']); unset($graph['hosts']); if (!isset($realGraphs[$host['hostid']])) { $realGraphs[$host['hostid']] = array(); } $realGraphs[$host['hostid']][$graph['name']] = $graph; } } // prepare items if (!empty($itemids)) { $tplItems = API::Item()->get(array('output' => array('itemid', 'key_'), 'itemids' => $itemids, 'nopermissions' => true, 'preservekeys' => true)); $dbItems = API::Item()->get(array('output' => array('itemid', 'key_'), 'hostids' => $options['hostids'], 'filter' => array('key_' => zbx_objectValues($tplItems, 'key_')), 'nopermissions' => true, 'preservekeys' => true)); $realItems = array(); foreach ($dbItems as $item) { unset($item['hosts']); if (!isset($realItems[$item['hostid']])) { $realItems[$item['hostid']] = array(); } $realItems[$item['hostid']][$item['key_']] = $item; } } } if (is_null($options['countOutput']) || !is_null($options['countOutput']) && !is_null($options['groupCount'])) { // creating copies of templated screens (inheritance) // screenNum is needed due to we can't refer to screenid/hostid/templateid as they will repeat $screenNum = 0; $vrtResult = array(); foreach ($result as $screen) { if (is_null($options['hostids']) || isset($options['hostids'][$screen['templateid']])) { $screenNum++; $vrtResult[$screenNum] = $screen; $vrtResult[$screenNum]['hostid'] = $screen['templateid']; } if (!isset($templatesChain[$screen['templateid']])) { continue; } foreach ($templatesChain[$screen['templateid']] as $hostid) { if (!isset($options['hostids'][$hostid])) { continue; } $screenNum++; $vrtResult[$screenNum] = $screen; $vrtResult[$screenNum]['hostid'] = $hostid; if (!isset($vrtResult[$screenNum]['screenitems'])) { continue; } foreach ($vrtResult[$screenNum]['screenitems'] as &$screenitem) { switch ($screenitem['resourcetype']) { case SCREEN_RESOURCE_GRAPH: $graphName = $tplGraphs[$screenitem['resourceid']]['name']; $screenitem['real_resourceid'] = $realGraphs[$hostid][$graphName]['graphid']; break; case SCREEN_RESOURCE_SIMPLE_GRAPH: case SCREEN_RESOURCE_PLAIN_TEXT: $itemKey = $tplItems[$screenitem['resourceid']]['key_']; $screenitem['real_resourceid'] = $realItems[$hostid][$itemKey]['itemid']; break; } } unset($screenitem); } } $result = array_values($vrtResult); } if (!is_null($options['countOutput'])) { return $result; } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } elseif (!is_null($options['noInheritance'])) { $result = zbx_toHash($result, 'screenid'); } return $result; }
/** * Get graphs references by graph ids. * * @param array $graphIds * * @return array */ protected function getGraphsReferences(array $graphIds) { $idents = array(); $graphs = API::Graph()->get(array('graphids' => $graphIds, 'selectHosts' => array('host'), 'output' => array('name'), 'nodeids' => get_current_nodeid(true), 'preservekeys' => true)); foreach ($graphs as $id => $graph) { $host = reset($graph['hosts']); $idents[$id] = array('name' => $graph['name'], 'host' => $host['host']); } return $idents; }
/** * Deletes graphs from DB that are missing in XML. * * @return null */ protected function deleteMissingGraphs() { if (!$this->options['graphs']['deleteMissing']) { return; } $processedHostIds = $this->importedObjectContainer->getHostIds(); $processedTemplateIds = $this->importedObjectContainer->getTemplateIds(); $processedHostIds = array_merge($processedHostIds, $processedTemplateIds); // no hosts or templates have been processed if (!$processedHostIds) { return; } $graphsIdsXML = array(); // gather host IDs for graphs that exist in XML $allGraphs = $this->getFormattedGraphs(); if ($allGraphs) { foreach ($allGraphs as $graph) { if (isset($graph['gitems']) && $graph['gitems']) { foreach ($graph['gitems'] as $gitem) { $gitemHostId = $this->referencer->resolveHostOrTemplate($gitem['item']['host']); $graphId = $this->referencer->resolveGraph($gitemHostId, $graph['name']); if ($graphId) { $graphsIdsXML[$graphId] = $graphId; } } } } } $dbGraphIds = API::Graph()->get(array('output' => array('graphid'), 'hostids' => $processedHostIds, 'selectHosts' => array('hostid'), 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); // check that potentially deletable graph belongs to same hosts that are in XML // if some graphs belong to more hosts than current XML contains, don't delete them $graphsToDelete = array_diff_key($dbGraphIds, $graphsIdsXML); $graphIdsToDelete = array(); $processedHostIds = array_flip($processedHostIds); foreach ($graphsToDelete as $graphId => $graph) { $graphHostIds = array_flip(zbx_objectValues($graph['hosts'], 'hostid')); if (!array_diff_key($graphHostIds, $processedHostIds)) { $graphIdsToDelete[] = $graphId; } } if ($graphIdsToDelete) { API::Graph()->delete($graphIdsToDelete); } $this->referencer->refreshGraphs(); }
/** * Import graphs. * * @throws Exception */ protected function processGraphs() { $allGraphs = $this->getFormattedGraphs(); if (empty($allGraphs)) { return; } $graphsToCreate = array(); $graphsToUpdate = array(); foreach ($allGraphs as $graph) { $graphHostIds = array(); if ($graph['ymin_item_1']) { $hostId = $this->referencer->resolveHostOrTemplate($graph['ymin_item_1']['host']); $itemId = $hostId ? $this->referencer->resolveItem($hostId, $graph['ymin_item_1']['key']) : false; if (!$itemId) { throw new Exception(_s('Cannot find item "%1$s" on "%2$s" used as the Y axis MIN value for graph "%3$s".', $graph['ymin_item_1']['key'], $graph['ymin_item_1']['host'], $graph['name'])); } $graph['ymin_itemid'] = $itemId; } if ($graph['ymax_item_1']) { $hostId = $this->referencer->resolveHostOrTemplate($graph['ymax_item_1']['host']); $itemId = $hostId ? $this->referencer->resolveItem($hostId, $graph['ymax_item_1']['key']) : false; if (!$itemId) { throw new Exception(_s('Cannot find item "%1$s" on "%2$s" used as the Y axis MAX value for graph "%3$s".', $graph['ymax_item_1']['key'], $graph['ymax_item_1']['host'], $graph['name'])); } $graph['ymax_itemid'] = $itemId; } if (isset($graph['gitems']) && $graph['gitems']) { foreach ($graph['gitems'] as &$gitem) { $gitemHostId = $this->referencer->resolveHostOrTemplate($gitem['item']['host']); if (!$gitemHostId) { throw new Exception(_s('Cannot find host or template "%1$s" used in graph "%2$s".', $gitem['item']['host'], $graph['name'])); } $gitem['itemid'] = $this->referencer->resolveItem($gitemHostId, $gitem['item']['key']); $graphHostIds[$gitemHostId] = $gitemHostId; } unset($gitem); } // TODO: do this for all graphs at once $sql = 'SELECT g.graphid' . ' FROM graphs g,graphs_items gi,items i' . ' WHERE g.graphid=gi.graphid' . ' AND gi.itemid=i.itemid' . ' AND g.name=' . zbx_dbstr($graph['name']) . ' AND ' . dbConditionInt('i.hostid', $graphHostIds); $graphExists = DBfetch(DBselect($sql)); if ($graphExists) { $dbGraph = API::Graph()->get(array('graphids' => $graphExists['graphid'], 'output' => array('graphid'), 'editable' => true)); if (empty($dbGraph)) { throw new Exception(_s('No permission for graph "%1$s".', $graph['name'])); } $graph['graphid'] = $graphExists['graphid']; $graphsToUpdate[] = $graph; } else { $graphsToCreate[] = $graph; } } if ($this->options['graphs']['createMissing'] && $graphsToCreate) { API::Graph()->create($graphsToCreate); } if ($this->options['graphs']['updateExisting'] && $graphsToUpdate) { API::Graph()->update($graphsToUpdate); } }
foreach ($hostTriggers as $hostTrigger) { if (httpItemExists($hostTrigger['items'])) { continue; } $triggersList[$hostTrigger['triggerid']] = $hostTrigger['description']; } if (!empty($triggersList)) { order_result($triggersList); $listBox = new CListBox('triggers', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($triggersList); $hostList->addRow(_('Triggers'), $listBox); } } // host graphs $hostGraphs = API::Graph()->get(array('inherited' => false, 'hostids' => $_REQUEST['hostid'], 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL)), 'selectHosts' => array('hostid'), 'selectItems' => array('type'), 'output' => array('graphid', 'name'))); if (!empty($hostGraphs)) { $graphsList = array(); foreach ($hostGraphs as $hostGraph) { if (count($hostGraph['hosts']) > 1) { continue; } if (httpItemExists($hostGraph['items'])) { continue; } $graphsList[$hostGraph['graphid']] = $hostGraph['name']; } if (!empty($graphsList)) { order_result($graphsList); $listBox = new CListBox('graphs', null, 8); $listBox->setAttribute('disabled', 'disabled');
public function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $itemids = array_keys($result); // adding applications if ($options['selectApplications'] !== null && $options['selectApplications'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'applicationid', 'items_applications'); $applications = API::Application()->get(array('output' => $options['selectApplications'], 'applicationids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $applications, 'applications'); } // adding interfaces if ($options['selectInterfaces'] !== null && $options['selectInterfaces'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'interfaceid'); $interfaces = API::HostInterface()->get(array('output' => $options['selectInterfaces'], 'interfaceids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $interfaces, 'interfaces'); } // adding triggers if (!is_null($options['selectTriggers'])) { if ($options['selectTriggers'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'triggerid', 'functions'); $triggers = API::Trigger()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']); } else { $triggers = API::Trigger()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $triggers = zbx_toHash($triggers, 'itemid'); foreach ($result as $itemid => $item) { if (isset($triggers[$itemid])) { $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount']; } else { $result[$itemid]['triggers'] = 0; } } } } // adding graphs if (!is_null($options['selectGraphs'])) { if ($options['selectGraphs'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'graphid', 'graphs_items'); $graphs = API::Graph()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']); } else { $graphs = API::Graph()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $graphs = zbx_toHash($graphs, 'itemid'); foreach ($result as $itemid => $item) { if (isset($graphs[$itemid])) { $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount']; } else { $result[$itemid]['graphs'] = 0; } } } } // adding discoveryrule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { $relationMap = new CRelationMap(); // discovered items $dbRules = DBselect('SELECT id1.itemid,id2.parent_itemid' . ' FROM item_discovery id1,item_discovery id2,items i' . ' WHERE ' . dbConditionInt('id1.itemid', $itemids) . ' AND id1.parent_itemid=id2.itemid' . ' AND i.itemid=id1.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_CREATED); while ($rule = DBfetch($dbRules)) { $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']); } // item prototypes // TODO: this should not be in the item API $dbRules = DBselect('SELECT id.parent_itemid,id.itemid' . ' FROM item_discovery id,items i' . ' WHERE ' . dbConditionInt('id.itemid', $itemids) . ' AND i.itemid=id.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_PROTOTYPE); while ($rule = DBfetch($dbRules)) { $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']); } $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding item discovery if ($options['selectItemDiscovery'] !== null) { $itemDiscoveries = API::getApiService()->select('item_discovery', array('output' => $this->outputExtend($options['selectItemDiscovery'], array('itemdiscoveryid', 'itemid')), 'filter' => array('itemid' => array_keys($result)), 'preservekeys' => true)); $relationMap = $this->createRelationMap($itemDiscoveries, 'itemid', 'itemdiscoveryid'); $itemDiscoveries = $this->unsetExtraFields($itemDiscoveries, array('itemid', 'itemdiscoveryid'), $options['selectItemDiscovery']); $result = $relationMap->mapOne($result, $itemDiscoveries, 'itemDiscovery'); } // adding history data $requestedOutput = array(); if ($this->outputIsRequested('lastclock', $options['output'])) { $requestedOutput['lastclock'] = true; } if ($this->outputIsRequested('lastns', $options['output'])) { $requestedOutput['lastns'] = true; } if ($this->outputIsRequested('lastvalue', $options['output'])) { $requestedOutput['lastvalue'] = true; } if ($this->outputIsRequested('prevvalue', $options['output'])) { $requestedOutput['prevvalue'] = true; } if ($requestedOutput) { $history = Manager::History()->getLast($result, 2, ZBX_HISTORY_PERIOD); foreach ($result as &$item) { $lastHistory = isset($history[$item['itemid']][0]) ? $history[$item['itemid']][0] : null; $prevHistory = isset($history[$item['itemid']][1]) ? $history[$item['itemid']][1] : null; if (isset($requestedOutput['lastclock'])) { $item['lastclock'] = $lastHistory ? $lastHistory['clock'] : '0'; } if (isset($requestedOutput['lastns'])) { $item['lastns'] = $lastHistory ? $lastHistory['ns'] : '0'; } if (isset($requestedOutput['lastvalue'])) { $item['lastvalue'] = $lastHistory ? $lastHistory['value'] : '0'; } if (isset($requestedOutput['prevvalue'])) { $item['prevvalue'] = $prevHistory ? $prevHistory['value'] : '0'; } } unset($item); } return $result; }
**/ require_once 'include/config.inc.php'; require_once 'include/graphs.inc.php'; $page['file'] = 'chart6.php'; $page['type'] = PAGE_TYPE_IMAGE; require_once 'include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('graphid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, null), 'screenid' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'profileIdx' => array(T_ZBX_STR, O_OPT, null, null, null), 'profileIdx2' => array(T_ZBX_STR, O_OPT, null, null, null), 'updateProfile' => array(T_ZBX_STR, O_OPT, null, null, null), 'border' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'width' => array(T_ZBX_INT, O_OPT, P_NZERO, '{}>0', null), 'height' => array(T_ZBX_INT, O_OPT, P_NZERO, '{}>0', null), 'graph3d' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'legend' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null)); check_fields($fields); /* * Permissions */ if (!DBfetch(DBselect('SELECT g.graphid FROM graphs g WHERE g.graphid=' . $_REQUEST['graphid']))) { show_error_message(_('No graphs defined.')); } $db_data = API::Graph()->get(array('graphids' => $_REQUEST['graphid'], 'selectHosts' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND)); if (empty($db_data)) { access_deny(); } else { $db_data = reset($db_data); } $host = reset($db_data['hosts']); /* * Display */ $timeline = CScreenBase::calculateTime(array('profileIdx' => get_request('profileIdx', 'web.screens'), 'profileIdx2' => get_request('profileIdx2'), 'updateProfile' => get_request('updateProfile', true), 'period' => get_request('period'), 'stime' => get_request('stime'))); $graph = new CPie($db_data['graphtype']); $graph->setPeriod($timeline['period']); $graph->setSTime($timeline['stime']); if (isset($_REQUEST['border'])) { $graph->setBorder(0);
** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__) . '/include/config.inc.php'; require_once dirname(__FILE__) . '/include/graphs.inc.php'; $page['file'] = 'chart2.php'; $page['type'] = PAGE_TYPE_IMAGE; require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('graphid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, null), 'period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'profileIdx' => array(T_ZBX_STR, O_OPT, null, null, null), 'profileIdx2' => array(T_ZBX_STR, O_OPT, null, null, null), 'updateProfile' => array(T_ZBX_STR, O_OPT, null, null, null), 'border' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'width' => array(T_ZBX_INT, O_OPT, P_NZERO, '{} > 0', null), 'height' => array(T_ZBX_INT, O_OPT, P_NZERO, '{} > 0', null)); check_fields($fields); /* * Permissions */ $dbGraph = API::Graph()->get(array('output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'selectHosts' => array('name'), 'graphids' => $_REQUEST['graphid'])); if (!$dbGraph) { access_deny(); } else { $dbGraph = reset($dbGraph); } /* * Display */ $timeline = CScreenBase::calculateTime(array('profileIdx' => getRequest('profileIdx', 'web.screens'), 'profileIdx2' => getRequest('profileIdx2'), 'updateProfile' => getRequest('updateProfile', true), 'period' => getRequest('period'), 'stime' => getRequest('stime'))); CProfile::update('web.screens.graphid', $_REQUEST['graphid'], PROFILE_TYPE_ID); $graph = new CLineGraphDraw($dbGraph['graphtype']); // array sorting CArrayHelper::sort($dbGraph['gitems'], array(array('field' => 'sortorder', 'order' => ZBX_SORT_UP), array('field' => 'itemid', 'order' => ZBX_SORT_DOWN))); // get graph items foreach ($dbGraph['gitems'] as $gItem) {
$graphs = API::Graph()->get(array("hostids" => array($hostid), "output" => "extend", "expandName" => 1, "sortfield" => "name")); foreach ($graphs as &$each) { $graphids[] = $each['graphid']; } if (!is_null($graphids)) { $items_list = API::GraphItem()->get(array("graphids" => $graphids, "output" => "extend")); } } else { //查询分组里面的所有机器 $host_ids = array(); $hosts = API::Host()->get(array("output" => "extend", "monitored_hosts" => true, "with_monitored_items" => 1, "groupids" => array($group_class))); foreach ($hosts as $each_host) { $host_ids[] = $each_host['hostid']; } //查询分组下的所有机器的所有图形 $graphs = API::Graph()->get(array("hostids" => $host_ids, "output" => "extend", "sortfield" => "name")); foreach ($graphs as &$each) { $graphids[] = $each['graphid']; } if (!is_null($graphids)) { $items_list = API::GraphItem()->get(array("graphids" => $graphids, "output" => "extend")); } } $list = array('list_item' => $items_list, 'parame' => array('stime' => strtotime($stime), 'period' => $period, 'sizeX' => $width, 'item_name_search' => $itemkey)); $format_list = API::ItemValue()->getItemListFormat($list); $format_list = (array) $format_list; foreach ($format_list as &$format) { $format = (array) $format; if (is_array($format)) { foreach ($format as $key_obj => &$value_obj) { if (is_object($value_obj)) {
} // Triggers $hostTriggers = API::Trigger()->get(array('inherited' => false, 'hostids' => $templateid, 'output' => API_OUTPUT_EXTEND, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL)))); if (!empty($hostTriggers)) { $triggersList = array(); foreach ($hostTriggers as $hostTrigger) { $triggersList[$hostTrigger['triggerid']] = $hostTrigger['description']; } order_result($triggersList); $listBox = new CListBox('triggers', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($triggersList); $templateList->addRow(_('Triggers'), $listBox); } // Graphs $hostGraphs = API::Graph()->get(array('inherited' => false, 'hostids' => $templateid, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL)), 'output' => API_OUTPUT_EXTEND)); if (!empty($hostGraphs)) { $graphsList = array(); foreach ($hostGraphs as $hostGraph) { $graphsList[$hostGraph['graphid']] = $hostGraph['name']; } order_result($graphsList); $listBox = new CListBox('graphs', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($graphsList); $templateList->addRow(_('Graphs'), $listBox); } // discovery rules $hostDiscoveryRules = API::DiscoveryRule()->get(array('inherited' => false, 'hostids' => $templateid, 'output' => API_OUTPUT_EXTEND)); if ($hostDiscoveryRules) { $hostDiscoveryRules = CMacrosResolverHelper::resolveItemNames($hostDiscoveryRules);
** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__) . '/include/config.inc.php'; require_once dirname(__FILE__) . '/include/graphs.inc.php'; $page['file'] = 'chart2.php'; $page['type'] = PAGE_TYPE_IMAGE; //PAGE_TYPE_IMAGE; require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('graphid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, null), 'period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'profileIdx' => array(T_ZBX_STR, O_OPT, null, null, null), 'profileIdx2' => array(T_ZBX_STR, O_OPT, null, null, null), 'updateProfile' => array(T_ZBX_STR, O_OPT, null, null, null), 'border' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'width' => array(T_ZBX_INT, O_OPT, P_NZERO, '{}>0', null), 'height' => array(T_ZBX_INT, O_OPT, P_NZERO, '{}>0', null)); check_fields($fields); /* * Permissions */ $dbGraph = API::Graph()->get(array('graphids' => $_REQUEST['graphid'], 'output' => API_OUTPUT_EXTEND, 'expandName' => 1)); // _ex($dbGraph,0); if (!$dbGraph) { access_deny(); } else { $dbGraph = reset($dbGraph); } $host = API::Host()->get(array('nodeids' => get_current_nodeid(true), 'graphids' => $_REQUEST['graphid'], 'output' => API_OUTPUT_EXTEND, 'templated_hosts' => true)); $host = reset($host); /* * Display */ $timeline = CScreenBase::calculateTime(array('profileIdx' => get_request('profileIdx', 'web.screens'), 'profileIdx2' => get_request('profileIdx2'), 'updateProfile' => get_request('updateProfile', true), 'period' => get_request('period'), 'stime' => get_request('stime'))); CProfile::update('web.screens.graphid', $_REQUEST['graphid'], PROFILE_TYPE_ID); $chartHeader = ''; if (id2nodeid($dbGraph['graphid']) != get_current_nodeid()) {
/** * Get Host data * * @param array $options * @param array $options['nodeids'] Node IDs * @param array $options['groupids'] HostGroup IDs * @param array $options['hostids'] Host IDs * @param boolean $options['monitored_hosts'] only monitored Hosts * @param boolean $options['templated_hosts'] include templates in result * @param boolean $options['with_items'] only with items * @param boolean $options['with_monitored_items'] only with monitored items * @param boolean $options['with_historical_items'] only with historical items * @param boolean $options['with_triggers'] only with triggers * @param boolean $options['with_monitored_triggers'] only with monitored triggers * @param boolean $options['with_httptests'] only with http tests * @param boolean $options['with_monitored_httptests'] only with monitored http tests * @param boolean $options['with_graphs'] only with graphs * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins * @param boolean $options['selectGroups'] select HostGroups * @param boolean $options['selectItems'] select Items * @param boolean $options['selectTriggers'] select Triggers * @param boolean $options['selectGraphs'] select Graphs * @param boolean $options['selectApplications'] select Applications * @param boolean $options['selectMacros'] select Macros * @param boolean|array $options['selectInventory'] select Inventory * @param boolean $options['withInventory'] select only hosts with inventory * @param int $options['count'] count Hosts, returned column name is rowscount * @param string $options['pattern'] search hosts by pattern in Host name * @param string $options['extendPattern'] search hosts by pattern in Host name, ip and DNS * @param int $options['limit'] limit selection * @param string $options['sortfield'] field to sort by * @param string $options['sortorder'] sort order * * @return array|boolean Host data as array or false if error */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; // allowed columns for sorting $sortColumns = array('hostid', 'host', 'name', 'status'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM); $sqlParts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'proxyids' => null, 'templateids' => null, 'interfaceids' => null, 'itemids' => null, 'triggerids' => null, 'maintenanceids' => null, 'graphids' => null, 'applicationids' => null, 'dhostids' => null, 'dserviceids' => null, 'httptestids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'proxy_hosts' => null, 'with_items' => null, 'with_monitored_items' => null, 'with_historical_items' => null, 'with_simple_graph_items' => null, 'with_triggers' => null, 'with_monitored_triggers' => null, 'with_httptests' => null, 'with_monitored_httptests' => null, 'with_graphs' => null, 'with_applications' => null, 'withInventory' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectParentTemplates' => null, 'selectItems' => null, 'selectDiscoveries' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectDHosts' => null, 'selectDServices' => null, 'selectApplications' => null, 'selectMacros' => null, 'selectScreens' => null, 'selectInterfaces' => null, 'selectInventory' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); if (is_array($options['output'])) { unset($sqlParts['select']['hosts']); $dbTable = DB::getSchema('hosts'); $sqlParts['select']['hostid'] = 'h.hostid'; foreach ($options['output'] as $field) { if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 'h.' . $field; } } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY; $userGroups = getUserGroupsByUserId($userid); $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE h.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')'; } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sqlParts['where']['hostid'] = dbConditionInt('h.hostid', $options['hostids']); } // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['groupid'] = 'hg.groupid'; } $sqlParts['from']['hosts_groups'] = 'hosts_groups hg'; $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']); $sqlParts['where']['hgh'] = 'hg.hostid=h.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['groupid'] = 'hg.groupid'; } } // proxyids if (!is_null($options['proxyids'])) { zbx_value2array($options['proxyids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['proxy_hostid'] = 'h.proxy_hostid'; } $sqlParts['where'][] = dbConditionInt('h.proxy_hostid', $options['proxyids']); } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['templateid'] = 'ht.templateid'; } $sqlParts['from']['hosts_templates'] = 'hosts_templates ht'; $sqlParts['where'][] = dbConditionInt('ht.templateid', $options['templateids']); $sqlParts['where']['hht'] = 'h.hostid=ht.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['templateid'] = 'ht.templateid'; } } // interfaceids if (!is_null($options['interfaceids'])) { zbx_value2array($options['interfaceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['interfaceid'] = 'hi.interfaceid'; } $sqlParts['from']['interface'] = 'interface hi'; $sqlParts['where'][] = dbConditionInt('hi.interfaceid', $options['interfaceids']); $sqlParts['where']['hi'] = 'h.hostid=hi.hostid'; } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['itemid'] = 'i.itemid'; } $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('i.itemid', $options['itemids']); $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; } // triggerids if (!is_null($options['triggerids'])) { zbx_value2array($options['triggerids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['triggerid'] = 'f.triggerid'; } $sqlParts['from']['functions'] = 'functions f'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']); $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; $sqlParts['where']['fi'] = 'f.itemid=i.itemid'; } // httptestids if (!is_null($options['httptestids'])) { zbx_value2array($options['httptestids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['httptestid'] = 'ht.httptestid'; } $sqlParts['from']['applications'] = 'applications a'; $sqlParts['from']['httptest'] = 'httptest ht'; $sqlParts['where'][] = dbConditionInt('ht.httptestid', $options['httptestids']); $sqlParts['where']['aht'] = 'a.applicationid=ht.applicationid'; $sqlParts['where']['ah'] = 'a.hostid=h.hostid'; } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['graphid'] = 'gi.graphid'; } $sqlParts['from']['graphs_items'] = 'graphs_items gi'; $sqlParts['from']['items'] = 'items i'; $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']); $sqlParts['where']['igi'] = 'i.itemid=gi.itemid'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; } // applicationids if (!is_null($options['applicationids'])) { zbx_value2array($options['applicationids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['applicationid'] = 'a.applicationid'; } $sqlParts['from']['applications'] = 'applications a'; $sqlParts['where'][] = dbConditionInt('a.applicationid', $options['applicationids']); $sqlParts['where']['ah'] = 'a.hostid=h.hostid'; } // dhostids if (!is_null($options['dhostids'])) { zbx_value2array($options['dhostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dhostid'] = 'ds.dhostid'; } $sqlParts['from']['dservices'] = 'dservices ds'; $sqlParts['where'][] = dbConditionInt('ds.dhostid', $options['dhostids']); $sqlParts['where']['dsh'] = 'ds.ip=h.ip'; if (!is_null($options['groupCount'])) { $sqlParts['group']['dhostid'] = 'ds.dhostid'; } } // dserviceids if (!is_null($options['dserviceids'])) { zbx_value2array($options['dserviceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dserviceid'] = 'ds.dserviceid'; } $sqlParts['from']['dservices'] = 'dservices ds'; $sqlParts['from']['interface'] = 'interface i'; $sqlParts['where'][] = dbConditionInt('ds.dserviceid', $options['dserviceids']); $sqlParts['where']['dsh'] = 'ds.ip=i.ip'; $sqlParts['where']['hi'] = 'h.hostid=i.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['dserviceid'] = 'ds.dserviceid'; } } // maintenanceids if (!is_null($options['maintenanceids'])) { zbx_value2array($options['maintenanceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['maintenanceid'] = 'mh.maintenanceid'; } $sqlParts['from']['maintenances_hosts'] = 'maintenances_hosts mh'; $sqlParts['where'][] = dbConditionInt('mh.maintenanceid', $options['maintenanceids']); $sqlParts['where']['hmh'] = 'h.hostid=mh.hostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['maintenanceid'] = 'mh.maintenanceid'; } } // monitored_hosts, templated_hosts if (!is_null($options['monitored_hosts'])) { $sqlParts['where']['status'] = 'h.status=' . HOST_STATUS_MONITORED; } elseif (!is_null($options['templated_hosts'])) { $sqlParts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')'; } elseif (!is_null($options['proxy_hosts'])) { $sqlParts['where']['status'] = 'h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')'; } else { $sqlParts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')'; } // with_items, with_monitored_items, with_historical_items, with_simple_graph_items if (!is_null($options['with_items'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ')'; } elseif (!is_null($options['with_monitored_items'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ')'; } elseif (!is_null($options['with_historical_items'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ' AND i.status IN (' . ITEM_STATUS_ACTIVE . ',' . ITEM_STATUS_NOTSUPPORTED . ')' . ' AND i.lastvalue IS NOT NULL' . ')'; } elseif (!is_null($options['with_simple_graph_items'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ' AND i.value_type IN (' . ITEM_VALUE_TYPE_FLOAT . ',' . ITEM_VALUE_TYPE_UINT64 . ')' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.flags IN (' . ZBX_FLAG_DISCOVERY_NORMAL . ',' . ZBX_FLAG_DISCOVERY_CREATED . ')' . ')'; } // with_triggers, with_monitored_triggers if (!is_null($options['with_triggers'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,functions f,triggers t' . ' WHERE h.hostid=i.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid' . ')'; } elseif (!is_null($options['with_monitored_triggers'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,functions f,triggers t' . ' WHERE h.hostid=i.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')'; } // with_httptests, with_monitored_httptests if (!is_null($options['with_httptests'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,httptest ht' . ' WHERE h.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ')'; } elseif (!is_null($options['with_monitored_httptests'])) { $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,httptest ht' . ' WHERE h.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')'; } // with_graphs if (!is_null($options['with_graphs'])) { $sqlParts['where'][] = 'EXISTS (' . ' SELECT 1' . ' FROM items i,graphs_items gi' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=gi.itemid ' . zbx_limit(1) . ')'; } // with applications if (!is_null($options['with_applications'])) { $sqlParts['from']['applications'] = 'applications a'; $sqlParts['where'][] = 'a.hostid=h.hostid'; } // withInventory if (!is_null($options['withInventory']) && $options['withInventory']) { $sqlParts['where'][] = ' h.hostid IN (' . ' SELECT hin.hostid' . ' FROM host_inventory hin)'; } // search if (is_array($options['search'])) { zbx_db_search('hosts h', $options, $sqlParts); if (zbx_db_search('interface hi', $options, $sqlParts)) { $sqlParts['from']['interface'] = 'interface hi'; $sqlParts['where']['hi'] = 'h.hostid=hi.hostid'; } } // filter if (is_array($options['filter'])) { $this->dbFilter('hosts h', $options, $sqlParts); if ($this->dbFilter('interface hi', $options, $sqlParts)) { $sqlParts['from']['interface'] = 'interface hi'; $sqlParts['where']['hi'] = 'h.hostid=hi.hostid'; } } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['hosts'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('COUNT(DISTINCT h.hostid) AS rowscount'); // groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'h'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $hostids = array(); $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($host = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $host; } else { $result = $host['rowscount']; } } else { $hostids[$host['hostid']] = $host['hostid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$host['hostid']] = array('hostid' => $host['hostid']); } else { if (!isset($result[$host['hostid']])) { $result[$host['hostid']] = array(); } if (!is_null($options['selectGroups']) && !isset($result[$host['hostid']]['groups'])) { $result[$host['hostid']]['groups'] = array(); } if (!is_null($options['selectParentTemplates']) && !isset($result[$host['hostid']]['parentTemplates'])) { $result[$host['hostid']]['parentTemplates'] = array(); } if (!is_null($options['selectItems']) && !isset($result[$host['hostid']]['items'])) { $result[$host['hostid']]['items'] = array(); } if (!is_null($options['selectDiscoveries']) && !isset($result[$host['hostid']]['discoveries'])) { $result[$host['hostid']]['discoveries'] = array(); } if (!is_null($options['selectInventory']) && !isset($result[$host['hostid']]['inventory'])) { $result[$host['hostid']]['inventory'] = array(); } if (!is_null($options['selectTriggers']) && !isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } if (!is_null($options['selectGraphs']) && !isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } if (!is_null($options['selectDHosts']) && !isset($result[$host['hostid']]['dhosts'])) { $result[$host['hostid']]['dhosts'] = array(); } if (!is_null($options['selectDServices']) && !isset($result[$host['hostid']]['dservices'])) { $result[$host['hostid']]['dservices'] = array(); } if (!is_null($options['selectApplications']) && !isset($result[$host['hostid']]['applications'])) { $result[$host['hostid']]['applications'] = array(); } if (!is_null($options['selectMacros']) && !isset($result[$host['hostid']]['macros'])) { $result[$host['hostid']]['macros'] = array(); } if (!is_null($options['selectScreens']) && !isset($result[$host['hostid']]['screens'])) { $result[$host['hostid']]['screens'] = array(); } if (!is_null($options['selectInterfaces']) && !isset($result[$host['hostid']]['interfaces'])) { $result[$host['hostid']]['interfaces'] = array(); } // groupids if (isset($host['groupid']) && is_null($options['selectGroups'])) { if (!isset($result[$host['hostid']]['groups'])) { $result[$host['hostid']]['groups'] = array(); } $result[$host['hostid']]['groups'][] = array('groupid' => $host['groupid']); unset($host['groupid']); } // templateids if (isset($host['templateid'])) { if (!isset($result[$host['hostid']]['templates'])) { $result[$host['hostid']]['templates'] = array(); } $result[$host['hostid']]['templates'][] = array('templateid' => $host['templateid'], 'hostid' => $host['templateid']); unset($host['templateid']); } // triggerids if (isset($host['triggerid']) && is_null($options['selectTriggers'])) { if (!isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } $result[$host['hostid']]['triggers'][] = array('triggerid' => $host['triggerid']); unset($host['triggerid']); } // interfaceids if (isset($host['interfaceid']) && is_null($options['selectInterfaces'])) { if (!isset($result[$host['hostid']]['interfaces'])) { $result[$host['hostid']]['interfaces'] = array(); } $result[$host['hostid']]['interfaces'][] = array('interfaceid' => $host['interfaceid']); unset($host['interfaceid']); } // itemids if (isset($host['itemid']) && is_null($options['selectItems'])) { if (!isset($result[$host['hostid']]['items'])) { $result[$host['hostid']]['items'] = array(); } $result[$host['hostid']]['items'][] = array('itemid' => $host['itemid']); unset($host['itemid']); } // graphids if (isset($host['graphid']) && is_null($options['selectGraphs'])) { if (!isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } $result[$host['hostid']]['graphs'][] = array('graphid' => $host['graphid']); unset($host['graphid']); } // graphids if (isset($host['applicationid'])) { if (!isset($result[$host['hostid']]['applications'])) { $result[$host['hostid']]['applications'] = array(); } $result[$host['hostid']]['applications'][] = array('applicationid' => $host['applicationid']); unset($host['applicationid']); } // httptestids if (isset($host['httptestid'])) { if (!isset($result[$host['hostid']]['httptests'])) { $result[$host['hostid']]['httptests'] = array(); } $result[$host['hostid']]['httptests'][] = array('httptestid' => $host['httptestid']); unset($host['httptestid']); } // dhostids if (isset($host['dhostid']) && is_null($options['selectDHosts'])) { if (!isset($result[$host['hostid']]['dhosts'])) { $result[$host['hostid']]['dhosts'] = array(); } $result[$host['hostid']]['dhosts'][] = array('dhostid' => $host['dhostid']); unset($host['dhostid']); } // dserviceids if (isset($host['dserviceid']) && is_null($options['selectDServices'])) { if (!isset($result[$host['hostid']]['dservices'])) { $result[$host['hostid']]['dservices'] = array(); } $result[$host['hostid']]['dservices'][] = array('dserviceid' => $host['dserviceid']); unset($host['dserviceid']); } // maintenanceids if (isset($host['maintenanceid'])) { if (!isset($result[$host['hostid']]['maintenances'])) { $result[$host['hostid']]['maintenances'] = array(); } if ($host['maintenanceid'] > 0) { $result[$host['hostid']]['maintenances'][] = array('maintenanceid' => $host['maintenanceid']); } } $result[$host['hostid']] += $host; } } } if (!is_null($options['countOutput'])) { return $result; } /* * adding objects */ // adding groups if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) { $groups = API::HostGroup()->get(array('nodeids' => $options['nodeids'], 'output' => $options['selectGroups'], 'hostids' => $hostids, 'preservekeys' => true)); foreach ($groups as $group) { $ghosts = $group['hosts']; unset($group['hosts']); foreach ($ghosts as $host) { $result[$host['hostid']]['groups'][] = $group; } } } // adding inventories if (!is_null($options['selectInventory']) && $options['selectInventory'] !== false) { if (is_array($options['selectInventory'])) { // if we are given a list of fields that needs to be fetched $dbTable = DB::getSchema('host_inventory'); $selectHIn = array('hin.hostid'); foreach ($options['selectInventory'] as $field) { if (isset($dbTable['fields'][$field])) { $selectHIn[] = 'hin.' . $field; } } } else { // all fields are needed $selectHIn = array('hin.*'); } $dbInventory = DBselect('SELECT ' . implode(', ', $selectHIn) . ' FROM host_inventory hin' . ' WHERE ' . dbConditionInt('hin.hostid', $hostids)); while ($inventory = DBfetch($dbInventory)) { $result[$inventory['hostid']]['inventory'] = $inventory; } } // adding templates if (!is_null($options['selectParentTemplates'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true); if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectParentTemplates']; $templates = API::Template()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['hosts']); $count = array(); foreach ($template['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['parentTemplates'][] =& $templates[$templateid]; } } } elseif (API_OUTPUT_COUNT == $options['selectParentTemplates']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $templates = API::Template()->get($objParams); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['templates'] = isset($templates[$hostid]) ? $templates[$hostid]['rowscount'] : 0; } } } // adding hostinterfaces if (!is_null($options['selectInterfaces'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectInterfaces']) || str_in_array($options['selectInterfaces'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectInterfaces']; $interfaces = API::HostInterface()->get($objParams); // we need to order interfaces for proper linkage and viewing order_result($interfaces, 'interfaceid', ZBX_SORT_UP); $count = array(); foreach ($interfaces as $interfaceid => $interface) { if (!is_null($options['limitSelects'])) { if (!isset($count[$interface['hostid']])) { $count[$interface['hostid']] = 0; } $count[$interface['hostid']]++; if ($count[$interface['hostid']] > $options['limitSelects']) { continue; } } $result[$interface['hostid']]['interfaces'][$interfaceid] =& $interfaces[$interfaceid]; } } elseif (API_OUTPUT_COUNT == $options['selectInterfaces']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $interfaces = API::HostInterface()->get($objParams); $interfaces = zbx_toHash($interfaces, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['interfaces'] = isset($interfaces[$hostid]) ? $interfaces[$hostid]['rowscount'] : 0; } } } // adding items if (!is_null($options['selectItems'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectItems']; $items = API::Item()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } $count = array(); foreach ($items as $itemid => $item) { if (!is_null($options['limitSelects'])) { if (!isset($count[$item['hostid']])) { $count[$item['hostid']] = 0; } $count[$item['hostid']]++; if ($count[$item['hostid']] > $options['limitSelects']) { continue; } } $result[$item['hostid']]['items'][] =& $items[$itemid]; } } elseif (API_OUTPUT_COUNT == $options['selectItems']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::Item()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['items'] = isset($items[$hostid]) ? $items[$hostid]['rowscount'] : 0; } } } // adding discoveries if (!is_null($options['selectDiscoveries'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectDiscoveries']) || str_in_array($options['selectDiscoveries'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDiscoveries']; $items = API::DiscoveryRule()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($items, 'name'); } $count = array(); foreach ($items as $itemid => $item) { unset($items[$itemid]['hosts']); foreach ($item['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['discoveries'][] =& $items[$itemid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDiscoveries']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $items = API::DiscoveryRule()->get($objParams); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['discoveries'] = isset($items[$hostid]) ? $items[$hostid]['rowscount'] : 0; } } } // adding triggers if (!is_null($options['selectTriggers'])) { if (is_array($options['selectTriggers']) || str_in_array($options['selectTriggers'], $subselectsAllowedOutputs)) { $triggers = API::Trigger()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true, 'output' => $options['selectTriggers'])); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } $count = array(); foreach ($triggers as $triggerid => $trigger) { unset($triggers[$triggerid]['hosts']); foreach ($trigger['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['triggers'][] =& $triggers[$triggerid]; } } } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) { $triggers = API::Trigger()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'countOutput' => true, 'groupCount' => true)); $triggers = zbx_toHash($triggers, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['triggers'] = isset($triggers[$hostid]) ? $triggers[$hostid]['rowscount'] : 0; } } } // adding graphs if (!is_null($options['selectGraphs'])) { if (is_array($options['selectGraphs']) || str_in_array($options['selectGraphs'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectGraphs']; $graphs = API::Graph()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true, 'output' => $options['selectGraphs'])); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } $count = array(); foreach ($graphs as $graphid => $graph) { unset($graphs[$graphid]['hosts']); foreach ($graph['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['graphs'][] =& $graphs[$graphid]; } } } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) { $graphs = API::Graph()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'countOutput' => true, 'groupCount' => true)); $graphs = zbx_toHash($graphs, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['graphs'] = isset($graphs[$hostid]) ? $graphs[$hostid]['rowscount'] : 0; } } } // adding discovery hosts if (!is_null($options['selectDHosts'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectDHosts']) || str_in_array($options['selectDHosts'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDHosts']; $dhosts = API::DHost()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($dhosts, 'dhostid'); } $count = array(); foreach ($dhosts as $dhostid => $dhost) { unset($dhosts[$dhostid]['hosts']); foreach ($dhost['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['dhosts'][] =& $dhosts[$dhostid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDHosts']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $dhosts = API::DHost()->get($objParams); $dhosts = zbx_toHash($dhosts, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['dhosts'] = isset($dhosts[$hostid]) ? $dhosts[$hostid]['rowscount'] : 0; } } } // adding applications if (!is_null($options['selectApplications'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectApplications']) || str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectApplications']; $applications = API::Application()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($applications, 'name'); } $count = array(); foreach ($applications as $applicationid => $application) { unset($applications[$applicationid]['hosts']); foreach ($application['hosts'] as $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['applications'][] =& $applications[$applicationid]; } } } elseif (API_OUTPUT_COUNT == $options['selectApplications']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $applications = API::Application()->get($objParams); $applications = zbx_toHash($applications, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['applications'] = isset($applications[$hostid]) ? $applications[$hostid]['rowscount'] : 0; } } } // adding macros if (!is_null($options['selectMacros']) && str_in_array($options['selectMacros'], $subselectsAllowedOutputs)) { $objParams = array('nodeids' => $options['nodeids'], 'output' => $options['selectMacros'], 'hostids' => $hostids, 'preservekeys' => true); $macros = API::UserMacro()->get($objParams); foreach ($macros as $macroid => $macro) { $mhosts = $macro['hosts']; unset($macro['hosts']); foreach ($mhosts as $host) { $result[$host['hostid']]['macros'][$macroid] = $macro; } } } // adding screens if (!is_null($options['selectScreens'])) { $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'editable' => $options['editable'], 'nopermissions' => true, 'preservekeys' => true); if (is_array($options['selectScreens']) || str_in_array($options['selectScreens'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectScreens']; $screens = API::TemplateScreen()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } foreach ($screens as $snum => $screen) { if (!is_null($options['limitSelects'])) { if (count($result[$screen['hostid']]['screens']) >= $options['limitSelects']) { continue; } } unset($screens[$snum]['hosts']); $result[$screen['hostid']]['screens'][] =& $screens[$snum]; } } elseif (API_OUTPUT_COUNT == $options['selectScreens']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $screens = API::TemplateScreen()->get($objParams); $screens = zbx_toHash($screens, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['screens'] = isset($screens[$hostid]) ? $screens[$hostid]['rowscount'] : 0; } } } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); // adding graphs if ($options['selectGraphs'] !== null) { $relationMap = $this->createRelationMap($result, 'gitemid', 'graphid'); $graphs = API::Graph()->get(['output' => $options['selectGraphs'], 'gitemids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapMany($result, $graphs, 'graphs'); } return $result; }
public static function parseMain($rules) { $triggersForDependencies = array(); if (!empty($rules['hosts']['updateExisting']) || !empty($rules['hosts']['createMissing']) || !empty($rules['templates']['createMissing']) || !empty($rules['templates']['updateExisting'])) { $xpath = new DOMXPath(self::$xml); $hosts = $xpath->query('hosts/host'); foreach ($hosts as $host) { $host_db = self::mapXML2arr($host, XML_TAG_HOST); if (!isset($host_db['status'])) { $host_db['status'] = HOST_STATUS_TEMPLATE; } $current_host = $host_db['status'] == HOST_STATUS_TEMPLATE ? API::Template()->exists($host_db) : API::Host()->exists($host_db); if (!$current_host && ($host_db['status'] == HOST_STATUS_TEMPLATE && empty($rules['templates']['createMissing']) || $host_db['status'] != HOST_STATUS_TEMPLATE && empty($rules['hosts']['createMissing']))) { continue; } if ($current_host && ($host_db['status'] == HOST_STATUS_TEMPLATE && empty($rules['templates']['updateExisting']) || $host_db['status'] != HOST_STATUS_TEMPLATE && empty($rules['hosts']['updateExisting']))) { continue; } // there were no host visible names in 1.8 if (!isset($host_db['name'])) { $host_db['name'] = $host_db['host']; } // host will have no interfaces - we will be creating them separately $host_db['interfaces'] = null; // it is possible, that data is imported from 1.8, where there was only one network interface per host /** * @todo when new XML format will be introduced, this check should be changed to XML version check */ $old_version_input = $host_db['status'] != HOST_STATUS_TEMPLATE; if ($old_version_input) { // rearranging host structure, so it would look more like 2.0 host $interfaces = array(); // the main interface is always "agent" type if (!is_null($host_db['ip'])) { $interfaces[] = array('main' => INTERFACE_PRIMARY, 'type' => INTERFACE_TYPE_AGENT, 'useip' => $host_db['useip'], 'ip' => $host_db['ip'], 'dns' => $host_db['dns'], 'port' => $host_db['port']); } // now we need to check if host had SNMP items. If it had, we need and SNMP interface for every different port. $items = $xpath->query('items/item', $host); $snmp_interface_ports_created = array(); foreach ($items as $item) { $item_db = self::mapXML2arr($item, XML_TAG_ITEM); if (($item_db['type'] == ITEM_TYPE_SNMPV1 || $item_db['type'] == ITEM_TYPE_SNMPV2C || $item_db['type'] == ITEM_TYPE_SNMPV3) && !isset($snmp_interface_ports_created[$item_db['snmp_port']])) { $interfaces[] = array('main' => INTERFACE_PRIMARY, 'type' => INTERFACE_TYPE_SNMP, 'useip' => $host_db['useip'], 'ip' => $host_db['ip'], 'dns' => $host_db['dns'], 'port' => $item_db['snmp_port']); $snmp_interface_ports_created[$item_db['snmp_port']] = 1; } } unset($snmp_interface_ports_created); // it was a temporary variable // we ned to add ipmi interface if at least one ipmi item exists foreach ($items as $item) { $item_db = self::mapXML2arr($item, XML_TAG_ITEM); if ($item_db['type'] == ITEM_TYPE_IPMI) { // when saving a host in 1.8, it's possible to set useipmi=1 and not to fill an IP address // we were not really sure what to do with this host, // and decided to take host IP address instead and show info message about this if ($host_db['ipmi_ip'] == '') { $ipmi_ip = $host_db['ip']; info(_s('Host "%s" has "useipmi" parameter checked, but has no "ipmi_ip" parameter! Using host IP address as an address for IPMI interface.', $host_db['host'])); } else { $ipmi_ip = $host_db['ipmi_ip']; } $interfaces[] = array('main' => INTERFACE_PRIMARY, 'type' => INTERFACE_TYPE_IPMI, 'useip' => INTERFACE_USE_DNS, 'ip' => '', 'dns' => $ipmi_ip, 'port' => $host_db['ipmi_port']); // we need only one ipmi interface break; } } } if ($current_host) { $options = array('filter' => array('host' => $host_db['host']), 'output' => API_OUTPUT_EXTEND, 'editable' => 1, 'selectInterfaces' => API_OUTPUT_EXTEND); if ($host_db['status'] == HOST_STATUS_TEMPLATE) { $current_host = API::Template()->get($options); } else { $current_host = API::Host()->get($options); } if (empty($current_host)) { throw new Exception(_s('No permission for host "%1$s".', $host_db['host'])); } else { $current_host = reset($current_host); } // checking if host already exists - then some of the interfaces may not need to be created if ($host_db['status'] != HOST_STATUS_TEMPLATE) { // for every interface we got based on XML foreach ($interfaces as $i => $interface_db) { // checking every interface of current host foreach ($current_host['interfaces'] as $interface) { // if all parameters of interface are identical if ($interface['type'] == $interface_db['type'] && $interface['ip'] == $interface_db['ip'] && $interface['dns'] == $interface_db['dns'] && $interface['port'] == $interface_db['port'] && $interface['useip'] == $interface_db['useip']) { // this interface is the same as existing one! $interfaces[$i]['interfaceid'] = $interface['interfaceid']; break; } } } } $interfaces_created_with_host = false; } else { if ($host_db['status'] != HOST_STATUS_TEMPLATE) { $host_db['interfaces'] = $interfaces; $interfaces_created_with_host = true; } } // HOST GROUPS {{{ $groups = $xpath->query('groups/group', $host); $host_db['groups'] = array(); $groups_to_parse = array(); foreach ($groups as $group) { $groups_to_parse[] = array('name' => $group->nodeValue); } if (empty($groups_to_parse)) { $groups_to_parse[] = array('name' => ZBX_DEFAULT_IMPORT_HOST_GROUP); } foreach ($groups_to_parse as $group) { $current_group = API::HostGroup()->exists($group); if ($current_group) { $options = array('filter' => $group, 'output' => API_OUTPUT_EXTEND, 'editable' => 1); $current_group = API::HostGroup()->get($options); if (empty($current_group)) { throw new Exception(_s('No permissions for group "%1$s".', $group['name'])); } $host_db['groups'][] = reset($current_group); } else { $result = API::HostGroup()->create($group); if (!$result) { throw new Exception(); } $options = array('groupids' => $result['groupids'], 'output' => API_OUTPUT_EXTEND); $new_group = API::HostGroup()->get($options); $host_db['groups'][] = reset($new_group); } } // }}} HOST GROUPS // MACROS $macros = $xpath->query('macros/macro', $host); if ($macros->length > 0) { $host_db['macros'] = array(); foreach ($macros as $macro) { $host_db['macros'][] = self::mapXML2arr($macro, XML_TAG_MACRO); } } // }}} MACROS // host inventory if ($old_version_input) { if (!isset($host_db['inventory'])) { $host_db['inventory'] = array(); } $inventoryNode = $xpath->query('host_profile/*', $host); if ($inventoryNode->length > 0) { foreach ($inventoryNode as $field) { $newInventoryName = self::mapInventoryName($field->nodeName); $host_db['inventory'][$newInventoryName] = $field->nodeValue; } } $inventoryNodeExt = $xpath->query('host_profiles_ext/*', $host); if ($inventoryNodeExt->length > 0) { foreach ($inventoryNodeExt as $field) { $newInventoryName = self::mapInventoryName($field->nodeName); if (isset($host_db['inventory'][$newInventoryName]) && $field->nodeValue !== '') { $host_db['inventory'][$newInventoryName] .= "\r\n\r\n"; $host_db['inventory'][$newInventoryName] .= $field->nodeValue; } else { $host_db['inventory'][$newInventoryName] = $field->nodeValue; } } } $host_db['inventory_mode'] = isset($host_db['inventory']) ? HOST_INVENTORY_MANUAL : HOST_INVENTORY_DISABLED; } // HOSTS if (isset($host_db['proxy_hostid'])) { $proxy_exists = API::Proxy()->get(array('proxyids' => $host_db['proxy_hostid'])); if (empty($proxy_exists)) { $host_db['proxy_hostid'] = 0; } } if ($current_host && (!empty($rules['hosts']['updateExisting']) || !empty($rules['templates']['updateExisting']))) { if ($host_db['status'] == HOST_STATUS_TEMPLATE) { $host_db['templateid'] = $current_host['templateid']; $result = API::Template()->update($host_db); $current_hostid = $current_host['templateid']; } else { $host_db['hostid'] = $current_host['hostid']; $result = API::Host()->update($host_db); $current_hostid = $current_host['hostid']; } if (!$result) { throw new Exception(); } } if (!$current_host && (!empty($rules['hosts']['createMissing']) || !empty($rules['templates']['createMissing']))) { if ($host_db['status'] == HOST_STATUS_TEMPLATE) { $result = API::Template()->create($host_db); if (!$result) { throw new Exception(); } $current_hostid = reset($result['templateids']); } else { $result = API::Host()->create($host_db); if (!$result) { throw new Exception(); } $current_hostid = reset($result['hostids']); } } $current_hostname = $host_db['host']; // TEMPLATES {{{ if (!empty($rules['templateLinkage']['createMissing'])) { $templates = $xpath->query('templates/template', $host); $templateLinkage = array(); foreach ($templates as $template) { $options = array('filter' => array('host' => $template->nodeValue), 'output' => array('templateid'), 'editable' => true); $current_template = API::Template()->get($options); if (empty($current_template)) { throw new Exception(_s('No permission for template "%1$s".', $template->nodeValue)); } $current_template = reset($current_template); $templateLinkage[] = $current_template; } if ($templateLinkage) { $result = API::Template()->massAdd(array('hosts' => array('hostid' => $current_hostid), 'templates' => $templateLinkage)); if (!$result) { throw new Exception(); } } } // }}} TEMPLATES // ITEMS {{{ if (!empty($rules['items']['updateExisting']) || !empty($rules['items']['createMissing'])) { $items = $xpath->query('items/item', $host); // if this is an export from 1.8, we need to make some adjustments to items if ($old_version_input) { if (!$interfaces_created_with_host) { // if host had another interfaces, we are not touching them: they remain as is foreach ($interfaces as $i => $interface) { // interface was not already created if (!isset($interface['interfaceid'])) { // creating interface $interface['hostid'] = $current_hostid; $ids = API::HostInterface()->create($interface); if ($ids === false) { throw new Exception(); } $interfaces[$i]['interfaceid'] = reset($ids['interfaceids']); } } } else { $options = array('hostids' => $current_hostid, 'output' => API_OUTPUT_EXTEND); $interfaces = API::HostInterface()->get($options); } // we must know interface ids to assign them to items $agent_interface_id = null; $ipmi_interface_id = null; $snmp_interfaces = array(); // hash 'port' => 'iterfaceid' foreach ($interfaces as $interface) { switch ($interface['type']) { case INTERFACE_TYPE_AGENT: $agent_interface_id = $interface['interfaceid']; break; case INTERFACE_TYPE_IPMI: $ipmi_interface_id = $interface['interfaceid']; break; case INTERFACE_TYPE_SNMP: $snmp_interfaces[$interface['port']] = $interface['interfaceid']; break; } } } foreach ($items as $item) { $item_db = self::mapXML2arr($item, XML_TAG_ITEM); $item_db['hostid'] = $current_hostid; // item needs interfaces if ($old_version_input) { // 'snmp_port' column was renamed to 'port' if ($item_db['snmp_port'] != 0) { // zabbix agent items have no ports $item_db['port'] = $item_db['snmp_port']; } unset($item_db['snmp_port']); // assigning appropriate interface depending on item type switch ($item_db['type']) { // zabbix agent interface case ITEM_TYPE_ZABBIX: case ITEM_TYPE_SIMPLE: case ITEM_TYPE_EXTERNAL: case ITEM_TYPE_SSH: case ITEM_TYPE_TELNET: $item_db['interfaceid'] = $agent_interface_id; break; // snmp interface // snmp interface case ITEM_TYPE_SNMPV1: case ITEM_TYPE_SNMPV2C: case ITEM_TYPE_SNMPV3: // for an item with different port - different interface $item_db['interfaceid'] = $snmp_interfaces[$item_db['port']]; break; case ITEM_TYPE_IPMI: $item_db['interfaceid'] = $ipmi_interface_id; break; // no interfaces required for these item types // no interfaces required for these item types case ITEM_TYPE_HTTPTEST: case ITEM_TYPE_CALCULATED: case ITEM_TYPE_AGGREGATE: case ITEM_TYPE_INTERNAL: case ITEM_TYPE_ZABBIX_ACTIVE: case ITEM_TYPE_TRAPPER: case ITEM_TYPE_DB_MONITOR: $item_db['interfaceid'] = null; break; } $item_db['key_'] = self::convertOldSimpleKey($item_db['key_']); } $options = array('filter' => array('hostid' => $item_db['hostid'], 'key_' => $item_db['key_']), 'webitems' => 1, 'output' => API_OUTPUT_EXTEND, 'editable' => 1); $current_item = API::Item()->get($options); $current_item = reset($current_item); if (!$current_item && empty($rules['items']['createMissing'])) { info(_s('Item "%1$s" skipped - user rule.', $item_db['key_'])); continue; // break if not update updateExisting } if ($current_item && empty($rules['items']['updateExisting'])) { info(_s('Item "%1$s" skipped - user rule.', $item_db['key_'])); continue; // break if not update updateExisting } // ITEM APPLICATIONS {{{ $applications = $xpath->query('applications/application', $item); $item_applications = array(); $applications_to_add = array(); $applicationsIds = array(); foreach ($applications as $application) { $application_db = array('name' => $application->nodeValue, 'hostid' => $current_hostid); $current_application = API::Application()->get(array('filter' => $application_db, 'output' => API_OUTPUT_EXTEND)); $applicationValue = reset($current_application); if ($current_application) { if (empty($item_applications)) { $item_applications = $current_application; $applicationsIds[] = $applicationValue['applicationid']; } else { if (!in_array($applicationValue['applicationid'], $applicationsIds)) { $item_applications = array_merge($item_applications, $current_application); $applicationsIds[] = $applicationValue['applicationid']; } } } else { $applications_to_add[] = $application_db; } } if (!empty($applications_to_add)) { $result = API::Application()->create($applications_to_add); if (!$result) { throw new Exception(); } $options = array('applicationids' => $result['applicationids'], 'output' => API_OUTPUT_EXTEND); $new_applications = API::Application()->get($options); $item_applications = array_merge($item_applications, $new_applications); } // }}} ITEM APPLICATIONS if ($current_item && !empty($rules['items']['updateExisting'])) { $item_db['itemid'] = $current_item['itemid']; $result = API::Item()->update($item_db); if (!$result) { throw new Exception(); } $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND); $current_item = API::Item()->get($options); } if (!$current_item && !empty($rules['items']['createMissing'])) { $result = API::Item()->create($item_db); if (!$result) { throw new Exception(); } $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND); $current_item = API::Item()->get($options); } if (!empty($item_applications)) { $r = API::Application()->massAdd(array('applications' => $item_applications, 'items' => $current_item)); if ($r === false) { throw new Exception(); } } } } // }}} ITEMS // TRIGGERS {{{ if (!empty($rules['triggers']['updateExisting']) || !empty($rules['triggers']['createMissing'])) { $triggers = $xpath->query('triggers/trigger', $host); $triggers_to_add = array(); $triggers_to_upd = array(); foreach ($triggers as $trigger) { $trigger_db = self::mapXML2arr($trigger, XML_TAG_TRIGGER); if ($old_version_input) { $expressionPart = explode(':', $trigger_db['expression']); $keyName = explode(',', $expressionPart[1], 2); if (count($keyName) == 2) { $keyValue = explode('.', $keyName[1], 2); $key = $keyName[0] . "," . $keyValue[0]; if (in_array($keyName[0], self::$oldKeys) || in_array($keyName[0], self::$oldKeysPref)) { $trigger_db['expression'] = str_replace($key, self::convertOldSimpleKey($key), $trigger_db['expression']); } } } // {HOSTNAME} is here for backward compatibility $trigger_db['expression'] = str_replace('{{HOSTNAME}:', '{' . $host_db['host'] . ':', $trigger_db['expression']); $trigger_db['expression'] = str_replace('{{HOST.HOST}:', '{' . $host_db['host'] . ':', $trigger_db['expression']); $trigger_db['hostid'] = $current_hostid; if ($current_trigger = API::Trigger()->exists($trigger_db)) { $ctriggers = API::Trigger()->get(array('filter' => array('description' => $trigger_db['description']), 'hostids' => $current_hostid, 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); $current_trigger = false; foreach ($ctriggers as $ct) { $tmp_exp = explode_exp($ct['expression']); if (strcmp($trigger_db['expression'], $tmp_exp) == 0) { $current_trigger = $ct; break; } } if (!$current_trigger) { throw new Exception(_s('No permission for trigger "%s".', $trigger_db['description'])); } } unset($trigger_db['hostid']); if (!$current_trigger && empty($rules['triggers']['createMissing'])) { info(_s('Trigger "%1$s" skipped - user rule.', $trigger_db['description'])); continue; // break if not update updateExisting } if ($current_trigger && empty($rules['triggers']['updateExisting'])) { info(_s('Trigger "%1$s" skipped - user rule.', $trigger_db['description'])); continue; // break if not update updateExisting } if ($current_trigger && !empty($rules['triggers']['updateExisting'])) { $trigger_db['triggerid'] = $current_trigger['triggerid']; $triggers_to_upd[] = $trigger_db; } if (!$current_trigger && !empty($rules['triggers']['createMissing'])) { $triggers_to_add[] = $trigger_db; } } if (!empty($triggers_to_upd)) { $result = API::Trigger()->update($triggers_to_upd); if (!$result) { throw new Exception(); } $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND); $r = API::Trigger()->get($options); $triggersForDependencies = array_merge($triggersForDependencies, $r); } if (!empty($triggers_to_add)) { $result = API::Trigger()->create($triggers_to_add); if (!$result) { throw new Exception(); } $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND); $r = API::Trigger()->get($options); $triggersForDependencies = array_merge($triggersForDependencies, $r); } } // }}} TRIGGERS // GRAPHS {{{ if (!empty($rules['graphs']['updateExisting']) || !empty($rules['graphs']['createMissing'])) { $graphs = $xpath->query('graphs/graph', $host); $graphs_to_add = array(); $graphs_to_upd = array(); foreach ($graphs as $graph) { // GRAPH ITEMS {{{ $gitems = $xpath->query('graph_elements/graph_element', $graph); $graph_hostids = array(); $graph_items = array(); foreach ($gitems as $gitem) { $gitem_db = self::mapXML2arr($gitem, XML_TAG_GRAPH_ELEMENT); $data = explode(':', $gitem_db['host_key_']); $gitem_host = array_shift($data); // {HOSTNAME} is here for backward compatibility $gitem_db['host'] = $gitem_host == '{HOSTNAME}' ? $host_db['host'] : $gitem_host; $gitem_db['host'] = $gitem_host == '{HOST.HOST}' ? $host_db['host'] : $gitem_host; if ($old_version_input) { $data[0] = self::convertOldSimpleKey($data[0]); } $gitem_db['key_'] = implode(':', $data); if ($current_item = API::Item()->exists($gitem_db)) { $current_item = API::Item()->get(array('filter' => array('key_' => $gitem_db['key_']), 'webitems' => 1, 'host' => $gitem_db['host'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); if (empty($current_item)) { throw new Exception(_s('No permission for item "%1$s".', $gitem_db['key_'])); } $current_item = reset($current_item); $graph_hostids[] = $current_item['hostid']; $gitem_db['itemid'] = $current_item['itemid']; $graph_items[] = $gitem_db; } else { throw new Exception(_s('Item "%1$s" does not exist.', $gitem_db['host_key_'])); } } // }}} GRAPH ITEMS $graph_db = self::mapXML2arr($graph, XML_TAG_GRAPH); $graph_db['hostids'] = $graph_hostids; // do we need to show the graph legend, after it is imported? // in 1.8, this setting was present only for pie and exploded graphs // for other graph types we are always showing the legend if ($graph_db['graphtype'] != GRAPH_TYPE_PIE && $graph_db['graphtype'] != GRAPH_TYPE_EXPLODED) { $graph_db['show_legend'] = 1; } $current_graph = API::Graph()->exists($graph_db); if ($current_graph) { $current_graph = API::Graph()->get(array('filter' => array('name' => $graph_db['name']), 'hostids' => $graph_db['hostids'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); if (empty($current_graph)) { throw new Exception(_s('No permission for graph "%1$s".', $graph_db['name'])); } $current_graph = reset($current_graph); } if (!$current_graph && empty($rules['graphs']['createMissing'])) { info(_s('Graph "%1$s" skipped - user rule.', $graph_db['name'])); continue; // break if not update updateExisting } if ($current_graph && empty($rules['graphs']['updateExisting'])) { info(_s('Graph "%1$s" skipped - user rule.', $graph_db['name'])); continue; // break if not update updateExisting } if (!isset($graph_db['ymin_type'])) { throw new Exception(_s('No "ymin_type" field for graph "%s".', $graph_db['name'])); } if (!isset($graph_db['ymax_type'])) { throw new Exception(_s('No "ymax_type" field for graph "%s".', $graph_db['name'])); } if ($graph_db['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) { $item_data = explode(':', $graph_db['ymin_item_key'], 2); if (count($item_data) < 2) { throw new Exception(_s('Incorrect y min item for graph "%1$s".', $graph_db['name'])); } if (!($item = get_item_by_key($item_data[1], $item_data[0]))) { throw new Exception(_s('Missing item "%1$s" for host "%2$s".', $graph_db['ymin_item_key'], $host_db['host'])); } $graph_db['ymin_itemid'] = $item['itemid']; } if ($graph_db['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) { $item_data = explode(':', $graph_db['ymax_item_key'], 2); if (count($item_data) < 2) { throw new Exception(_s('Incorrect y max item for graph "%1$s".', $graph_db['name'])); } if (!($item = get_item_by_key($item_data[1], $item_data[0]))) { throw new Exception(_s('Missing item "%1$s" for host "%2$s".', $graph_db['ymax_item_key'], $host_db['host'])); } $graph_db['ymax_itemid'] = $item['itemid']; } $graph_db['gitems'] = $graph_items; if ($current_graph) { $graph_db['graphid'] = $current_graph['graphid']; $graphs_to_upd[] = $graph_db; } else { $graphs_to_add[] = $graph_db; } } if (!empty($graphs_to_add)) { $r = API::Graph()->create($graphs_to_add); if ($r === false) { throw new Exception(); } } if (!empty($graphs_to_upd)) { $r = API::Graph()->update($graphs_to_upd); if ($r === false) { throw new Exception(); } } } // SCREENS if (!empty($rules['screens']['updateExisting']) || !empty($rules['screens']['createMissing'])) { $screens_node = $xpath->query('screens', $host); if ($screens_node->length > 0) { $importScreens = self::XMLtoArray($screens_node->item(0)); foreach ($importScreens as $screen) { $current_screen = API::TemplateScreen()->get(array('filter' => array('name' => $screen['name']), 'templateids' => $current_hostid, 'output' => API_OUTPUT_EXTEND, 'editable' => 1)); $current_screen = reset($current_screen); if (!$current_screen && empty($rules['screens']['createMissing'])) { info(_s('Screen "%1$s" skipped - user rule.', $screen['name'])); continue; } if ($current_screen && empty($rules['screens']['updateExisting'])) { info(_s('Screen "%1$s" skipped - user rule.', $screen['name'])); continue; } if (isset($screen['screenitems'])) { foreach ($screen['screenitems'] as &$screenitem) { $nodeCaption = isset($screenitem['resourceid']['node']) ? $screenitem['resourceid']['node'] . ':' : ''; if (!isset($screenitem['resourceid'])) { $screenitem['resourceid'] = 0; } if (is_array($screenitem['resourceid'])) { switch ($screenitem['resourcetype']) { case SCREEN_RESOURCE_GRAPH: $db_graphs = API::Graph()->getObjects($screenitem['resourceid']); if (empty($db_graphs)) { $error = _s('Cannot find graph "%1$s" used in screen "%2$s".', $nodeCaption . $screenitem['resourceid']['host'] . ':' . $screenitem['resourceid']['name'], $screen['name']); throw new Exception($error); } $tmp = reset($db_graphs); $screenitem['resourceid'] = $tmp['graphid']; break; case SCREEN_RESOURCE_SIMPLE_GRAPH: case SCREEN_RESOURCE_PLAIN_TEXT: $db_items = API::Item()->getObjects($screenitem['resourceid']); if (empty($db_items)) { $error = _s('Cannot find item "%1$s" used in screen "%2$s".', $nodeCaption . $screenitem['resourceid']['host'] . ':' . $screenitem['resourceid']['key_'], $screen['name']); throw new Exception($error); } $tmp = reset($db_items); $screenitem['resourceid'] = $tmp['itemid']; break; default: $screenitem['resourceid'] = 0; break; } } } } $screen['templateid'] = $current_hostid; if ($current_screen) { $screen['screenid'] = $current_screen['screenid']; $result = API::TemplateScreen()->update($screen); if (!$result) { throw new Exception(_('Cannot update screen.')); } info('[' . $current_hostname . '] ' . _s('Screen "%1$s" updated.', $screen['name'])); } else { $result = API::TemplateScreen()->create($screen); if (!$result) { throw new Exception(_('Cannot create screen.')); } info('[' . $current_hostname . '] ' . _s('Screen "%1$s" added.', $screen['name'])); } } } } } // DEPENDENCIES $dependencies = $xpath->query('dependencies/dependency'); if ($dependencies->length > 0) { $triggersForDependencies = zbx_objectValues($triggersForDependencies, 'triggerid'); $triggersForDependencies = array_flip($triggersForDependencies); $newDependencies = array(); foreach ($dependencies as $dependency) { $triggerDescription = $dependency->getAttribute('description'); $currentTrigger = get_trigger_by_description($triggerDescription); if ($currentTrigger && isset($triggersForDependencies[$currentTrigger['triggerid']])) { $dependsOnList = $xpath->query('depends', $dependency); foreach ($dependsOnList as $dependsOn) { $depTrigger = get_trigger_by_description($dependsOn->nodeValue); if ($depTrigger['triggerid']) { $newDependencies[] = array('triggerid' => $currentTrigger['triggerid'], 'dependsOnTriggerid' => $depTrigger['triggerid']); } } } } if ($newDependencies) { API::Trigger()->addDependencies($newDependencies); } } } }
ob_start(); require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'hostid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'graphid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'period' => array(T_ZBX_INT, O_OPT, P_SYS, null, null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'fullscreen' => array(T_ZBX_INT, O_OPT, P_SYS, IN('0,1'), null), 'filterState' => array(T_ZBX_INT, O_OPT, P_ACT, null, null), 'favobj' => array(T_ZBX_STR, O_OPT, P_ACT, null, null), 'favid' => array(T_ZBX_INT, O_OPT, P_ACT, null, null), 'favaction' => array(T_ZBX_STR, O_OPT, P_ACT, IN('"add","remove"'), null)); check_fields($fields); /* * Permissions */ if (getRequest('groupid') && !API::HostGroup()->isReadable(array($_REQUEST['groupid']))) { access_deny(); } if (getRequest('hostid') && !API::Host()->isReadable(array($_REQUEST['hostid']))) { access_deny(); } if (getRequest('graphid')) { $graphs = API::Graph()->get(array('graphids' => array($_REQUEST['graphid']), 'output' => array('graphid'))); if (!$graphs) { access_deny(); } } $pageFilter = new CPageFilter(array('groups' => array('real_hosts' => true, 'with_graphs' => true), 'hosts' => array('with_graphs' => true), 'groupid' => getRequest('groupid'), 'hostid' => getRequest('hostid'), 'graphs' => array('templated' => 0), 'graphid' => getRequest('graphid'))); /* * Ajax */ if (hasRequest('filterState')) { CProfile::update('web.charts.filter.state', getRequest('filterState'), PROFILE_TYPE_INT); } if (isset($_REQUEST['favobj'])) { if (getRequest('favobj') === 'timelinefixedperiod' && hasRequest('favid')) { CProfile::update('web.screens.timelinefixed', getRequest('favid'), PROFILE_TYPE_INT); }
/** * Validates screen items. * * If the $dbScreenItems parameter is given, the screen items will be matched * against the ones given in $dbScreenItems. If a screen item is not present in * $dbScreenItems, a ZBX_API_ERROR_PERMISSIONS exception will be thrown. * * @throws APIException if a validation error occurred. * * @param array $screenItems * @param array $dbScreenItems */ protected function checkInput(array $screenItems, array $dbScreenItems = array()) { $hostGroupsIds = $hostIds = $graphIds = $itemIds = $mapIds = $screenIds = array(); $screenItems = $this->extendFromObjects($screenItems, $dbScreenItems, array('resourcetype', 'resourceid')); foreach ($screenItems as $screenItem) { // check permissions if (isset($screenItem['screenitemid']) && !isset($dbScreenItems[$screenItem['screenitemid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } if (!$this->isValidResourceType($screenItem['resourcetype'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect resource type provided for screen item.')); } if (!isset($screenItem['resourceid'])) { $screenItem['resourceid'] = null; } // check resource id switch ($screenItem['resourcetype']) { case SCREEN_RESOURCE_HOSTS_INFO: case SCREEN_RESOURCE_TRIGGERS_INFO: case SCREEN_RESOURCE_TRIGGERS_OVERVIEW: case SCREEN_RESOURCE_HOSTGROUP_TRIGGERS: case SCREEN_RESOURCE_DATA_OVERVIEW: if (in_array($screenItem['resourcetype'], array(SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW))) { if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No host group ID provided for screen element.')); } } if ($screenItem['resourceid']) { $hostGroupsIds[$screenItem['resourceid']] = $screenItem['resourceid']; } break; case SCREEN_RESOURCE_HOST_TRIGGERS: if ($screenItem['resourceid']) { $hostIds[$screenItem['resourceid']] = $screenItem['resourceid']; } break; case SCREEN_RESOURCE_GRAPH: if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No graph ID provided for screen element.')); } $graphIds[$screenItem['resourceid']] = $screenItem['resourceid']; break; case SCREEN_RESOURCE_SIMPLE_GRAPH: case SCREEN_RESOURCE_PLAIN_TEXT: if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No item ID provided for screen element.')); } $itemIds[$screenItem['resourceid']] = $screenItem['resourceid']; break; case SCREEN_RESOURCE_CLOCK: if (isset($screenItem['style']) && $screenItem['style'] == TIME_TYPE_HOST) { if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No item ID provided for screen element.')); } $itemIds[$screenItem['resourceid']] = $screenItem['resourceid']; } break; case SCREEN_RESOURCE_MAP: if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No map ID provided for screen element.')); } $mapIds[$screenItem['resourceid']] = $screenItem['resourceid']; break; case SCREEN_RESOURCE_SCREEN: if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No screen ID provided for screen element.')); } $screenIds[$screenItem['resourceid']] = $screenItem['resourceid']; break; } // check url if ($screenItem['resourcetype'] == SCREEN_RESOURCE_URL) { if (!isset($screenItem['url']) || zbx_empty($screenItem['url'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No URL provided for screen element.')); } } // check "Show lines" if (isset($screenItem['elements'])) { switch ($screenItem['resourcetype']) { case SCREEN_RESOURCE_ACTIONS: case SCREEN_RESOURCE_EVENTS: case SCREEN_RESOURCE_HOSTGROUP_TRIGGERS: case SCREEN_RESOURCE_HOST_TRIGGERS: case SCREEN_RESOURCE_PLAIN_TEXT: if ($screenItem['elements'] < 1 || $screenItem['elements'] > 100) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" for "%2$s" field: must be between %3$s and %4$s.', $screenItem['elements'], 'elements', 1, 100)); } break; } } } // check host groups if ($hostGroupsIds) { $dbHostGroups = API::HostGroup()->get(array('groupids' => $hostGroupsIds, 'output' => array('groupid'), 'editable' => true, 'preservekeys' => true)); foreach ($hostGroupsIds as $hostGroupsId) { if (!isset($dbHostGroups[$hostGroupsId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect host group ID "%1$s" provided for screen element.', $hostGroupsId)); } } } // check hosts if ($hostIds) { $dbHosts = API::Host()->get(array('hostids' => $hostIds, 'output' => array('hostid'), 'editable' => true, 'preservekeys' => true)); foreach ($hostIds as $hostId) { if (!isset($dbHosts[$hostId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect host ID "%1$s" provided for screen element.', $hostId)); } } } // check graphs if ($graphIds) { $dbGraphs = API::Graph()->get(array('graphids' => $graphIds, 'output' => array('graphid'), 'editable' => true, 'preservekeys' => true)); foreach ($graphIds as $graphId) { if (!isset($dbGraphs[$graphId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect graph ID "%1$s" provided for screen element.', $graphId)); } } } // check items if ($itemIds) { $dbItems = API::Item()->get(array('itemids' => $itemIds, 'output' => array('itemid'), 'editable' => true, 'preservekeys' => true, 'webitems' => true)); foreach ($itemIds as $itemId) { if (!isset($dbItems[$itemId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect item ID "%1$s" provided for screen element.', $itemId)); } } } // check maps if ($mapIds) { $dbMaps = API::Map()->get(array('sysmapids' => $mapIds, 'output' => array('sysmapid'), 'editable' => true, 'preservekeys' => true)); foreach ($mapIds as $mapId) { if (!isset($dbMaps[$mapId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect map ID "%1$s" provided for screen element.', $mapId)); } } } // check screens if ($screenIds) { $dbScreens = API::Screen()->get(array('screenids' => $screenIds, 'output' => array('screenid'), 'editable' => true, 'preservekeys' => true)); if (count($dbScreens) < count($screenIds)) { $dbTemplateScreens = API::TemplateScreen()->get(array('screenids' => $screenIds, 'output' => array('screenid'), 'editable' => true, 'preservekeys' => true)); if ($dbTemplateScreens) { $dbScreens = zbx_array_merge($dbScreens, $dbTemplateScreens); } } foreach ($screenIds as $screenId) { if (!isset($dbScreens[$screenId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect screen ID "%1$s" provided for screen element.', $screenId)); } } } }