/** * Import template screens. * * @param array $allScreens * * @return void */ public function import(array $allScreens) { $screensToCreate = array(); $screensToUpdate = array(); foreach ($allScreens as $template => $screens) { // TODO: select all at once out of loop $dbScreens = DBselect('SELECT s.screenid,s.name FROM screens s WHERE' . ' s.templateid=' . zbx_dbstr($this->referencer->resolveTemplate($template)) . ' AND ' . dbConditionString('s.name', array_keys($screens))); while ($dbScreen = DBfetch($dbScreens)) { $screens[$dbScreen['name']]['screenid'] = $dbScreen['screenid']; } foreach ($screens as $screen) { $screen = $this->resolveScreenReferences($screen); if (isset($screen['screenid'])) { $screensToUpdate[] = $screen; } else { $screen['templateid'] = $this->referencer->resolveTemplate($template); $screensToCreate[] = $screen; } } } if ($this->options['templateScreens']['createMissing'] && $screensToCreate) { API::TemplateScreen()->create($screensToCreate); } if ($this->options['templateScreens']['updateExisting'] && $screensToUpdate) { API::TemplateScreen()->update($screensToUpdate); } }
/** * Get screen item data. * * @param array $options * @param array $options['hostid'] Use hostid to get real resource id * @param array $options['screenitemids'] Search by screen item IDs * @param array $options['screenids'] Search by screen IDs * @param array $options['filter'] Result filter * @param array $options['limit'] The size of the result set * * @return array */ public function get(array $options = []) { $options = zbx_array_merge($this->getOptions, $options); // build and execute query $sql = $this->createSelectQuery($this->tableName(), $options); $res = DBselect($sql, $options['limit']); // fetch results $result = []; while ($row = DBfetch($res)) { // count query, return a single result if ($options['countOutput'] !== null) { $result = $row['rowscount']; } else { if ($options['preservekeys'] !== null) { $result[$row['screenitemid']] = $row; } else { $result[] = $row; } } } // fill result with real resourceid if ($options['hostids'] && $result) { if (empty($options['screenitemid'])) { $options['screenitemid'] = zbx_objectValues($result, 'screenitemid'); } $dbTemplateScreens = API::TemplateScreen()->get(['output' => ['screenitemid'], 'screenitemids' => $options['screenitemid'], 'hostids' => $options['hostids'], 'selectScreenItems' => API_OUTPUT_EXTEND]); if ($dbTemplateScreens) { foreach ($result as &$screenItem) { foreach ($dbTemplateScreens as $dbTemplateScreen) { foreach ($dbTemplateScreen['screenitems'] as $dbScreenItem) { if ($screenItem['screenitemid'] == $dbScreenItem['screenitemid'] && isset($dbScreenItem['real_resourceid']) && $dbScreenItem['real_resourceid']) { $screenItem['real_resourceid'] = $dbScreenItem['real_resourceid']; } } } } unset($screenItem); } } return $result; }
/** * Get 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; }
/** * Get templates for export from database. * * @param array $templateIds */ protected function gatherTemplates(array $templateIds) { $templates = API::Template()->get(array('templateids' => $templateIds, 'output' => array('host', 'name'), 'selectMacros' => API_OUTPUT_EXTEND, 'selectGroups' => API_OUTPUT_EXTEND, 'selectParentTemplates' => API_OUTPUT_EXTEND, 'preservekeys' => true)); // merge host groups with all groups $templateGroups = array(); foreach ($templates as &$template) { $templateGroups += zbx_toHash($template['groups'], 'groupid'); $template['screens'] = array(); $template['applications'] = array(); $template['discoveryRules'] = array(); $template['items'] = array(); } unset($template); $this->data['groups'] += $templateGroups; // applications $applications = API::Application()->get(array('hostids' => $templateIds, 'output' => API_OUTPUT_EXTEND, 'inherited' => false, 'preservekeys' => true)); foreach ($applications as $application) { if (!isset($templates[$application['hostid']]['applications'])) { $templates[$application['hostid']]['applications'] = array(); } $templates[$application['hostid']]['applications'][] = $application; } // screens $screens = API::TemplateScreen()->get(array('templateids' => $templateIds, 'selectScreenItems' => API_OUTPUT_EXTEND, 'noInheritance' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); $this->prepareScreenExport($screens); foreach ($screens as $screen) { if (!isset($templates[$screen['templateid']]['screens'])) { $templates[$screen['templateid']]['screens'] = array(); } $templates[$screen['templateid']]['screens'][] = $screen; } $this->data['templates'] = $templates; $this->gatherTemplateItems($templateIds); $this->gatherTemplateDiscoveryRules($templateIds); }
$templateList->addRow(_('Trigger prototypes'), $listBox); } // Graph prototypes $hostGraphPrototypes = API::GraphPrototype()->get(['hostids' => $data['templateId'], 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND]); if (!empty($hostGraphPrototypes)) { $prototypeList = []; foreach ($hostGraphPrototypes as $graphPrototype) { $prototypeList[$graphPrototype['graphid']] = $graphPrototype['name']; } order_result($prototypeList); $listBox = (new CListBox('graphPrototypes', null, 8))->setAttribute('disabled', 'disabled')->addItems($prototypeList); $templateList->addRow(_('Graph prototypes'), $listBox); } } // screens $screens = API::TemplateScreen()->get(['inherited' => false, 'templateids' => $data['templateId'], 'output' => ['screenid', 'name']]); if (!empty($screens)) { $screensList = []; foreach ($screens as $screen) { $screensList[$screen['screenid']] = $screen['name']; } order_result($screensList); $listBox = (new CListBox('screens', null, 8))->setAttribute('disabled', 'disabled')->addItems($screensList); $templateList->addRow(_('Screens'), $listBox); } // web scenarios $httpTests = API::HttpTest()->get(['output' => ['httptestid', 'name'], 'hostids' => $data['templateId'], 'inherited' => false]); if ($httpTests) { $httpTestList = []; foreach ($httpTests as $httpTest) { $httpTestList[$httpTest['httptestid']] = $httpTest['name'];
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $hostids = array_keys($result); // adding inventories if ($options['selectInventory'] !== null) { $relationMap = $this->createRelationMap($result, 'hostid', 'hostid'); $inventory = API::getApiService()->select('host_inventory', ['output' => $options['selectInventory'], 'filter' => ['hostid' => $hostids]]); $result = $relationMap->mapOne($result, zbx_toHash($inventory, 'hostid'), 'inventory'); } // adding hostinterfaces if ($options['selectInterfaces'] !== null) { if ($options['selectInterfaces'] != API_OUTPUT_COUNT) { $interfaces = API::HostInterface()->get(['output' => $this->outputExtend($options['selectInterfaces'], ['hostid', 'interfaceid']), 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true]); // we need to order interfaces for proper linkage and viewing order_result($interfaces, 'interfaceid', ZBX_SORT_UP); $relationMap = $this->createRelationMap($interfaces, 'hostid', 'interfaceid'); $interfaces = $this->unsetExtraFields($interfaces, ['hostid', 'interfaceid'], $options['selectInterfaces']); $result = $relationMap->mapMany($result, $interfaces, 'interfaces', $options['limitSelects']); } else { $interfaces = API::HostInterface()->get(['hostids' => $hostids, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true]); $interfaces = zbx_toHash($interfaces, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['interfaces'] = isset($interfaces[$hostid]) ? $interfaces[$hostid]['rowscount'] : 0; } } } // adding screens if ($options['selectScreens'] !== null) { if ($options['selectScreens'] != API_OUTPUT_COUNT) { $screens = API::TemplateScreen()->get(['output' => $this->outputExtend($options['selectScreens'], ['hostid']), 'hostids' => $hostids, 'nopermissions' => true]); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } // inherited screens do not have a unique screenid, so we're building a map using array keys $relationMap = new CRelationMap(); foreach ($screens as $key => $screen) { $relationMap->addRelation($screen['hostid'], $key); } $screens = $this->unsetExtraFields($screens, ['hostid'], $options['selectScreens']); $result = $relationMap->mapMany($result, $screens, 'screens', $options['limitSelects']); } else { $screens = API::TemplateScreen()->get(['hostids' => $hostids, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true]); $screens = zbx_toHash($screens, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['screens'] = isset($screens[$hostid]) ? $screens[$hostid]['rowscount'] : 0; } } } // adding discovery rule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { // discovered items $discoveryRules = DBFetchArray(DBselect('SELECT hd.hostid,hd2.parent_itemid' . ' FROM host_discovery hd,host_discovery hd2' . ' WHERE ' . dbConditionInt('hd.hostid', $hostids) . ' AND hd.parent_hostid=hd2.hostid')); $relationMap = $this->createRelationMap($discoveryRules, 'hostid', 'parent_itemid'); $discoveryRules = API::DiscoveryRule()->get(['output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding host discovery if ($options['selectHostDiscovery'] !== null) { $hostDiscoveries = API::getApiService()->select('host_discovery', ['output' => $this->outputExtend($options['selectHostDiscovery'], ['hostid']), 'filter' => ['hostid' => $hostids], 'preservekeys' => true]); $relationMap = $this->createRelationMap($hostDiscoveries, 'hostid', 'hostid'); $hostDiscoveries = $this->unsetExtraFields($hostDiscoveries, ['hostid'], $options['selectHostDiscovery']); $result = $relationMap->mapOne($result, $hostDiscoveries, 'hostDiscovery'); } return $result; }
/** * Deletes missing template screens. * * @param array $allScreens * * @return null */ public function delete(array $allScreens) { if (!$this->options['templateScreens']['deleteMissing']) { return; } $templateIdsXML = $this->importedObjectContainer->getTemplateIds(); // no templates have been processed if (!$templateIdsXML) { return; } $templateScreenIdsXML = array(); if ($allScreens) { foreach ($allScreens as $template => $screens) { $templateId = $this->referencer->resolveTemplate($template); if ($templateId) { foreach ($screens as $screenName => $screen) { $templateScreenId = $this->referencer->resolveTemplateScreen($templateId, $screenName); if ($templateScreenId) { $templateScreenIdsXML[$templateScreenId] = $templateScreenId; } } } } } $dbTemplateScreenIds = API::TemplateScreen()->get(array('output' => array('screenid'), 'hostids' => $templateIdsXML, 'nopermissions' => true, 'preservekeys' => true)); $templateScreensToDelete = array_diff_key($dbTemplateScreenIds, $templateScreenIdsXML); if ($templateScreensToDelete) { API::TemplateScreen()->delete(array_keys($templateScreensToDelete)); } }
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); } } } }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $templateids = array_keys($result); // Adding Templates if ($options['selectTemplates'] !== null) { if ($options['selectTemplates'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'templateid', 'hostid', 'hosts_templates'); $templates = API::Template()->get(array('output' => $options['selectTemplates'], 'templateids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } $result = $relationMap->mapMany($result, $templates, 'templates', $options['limitSelects']); } else { $templates = API::Template()->get(array('parentTemplateids' => $templateids, 'countOutput' => true, 'groupCount' => true)); $templates = zbx_toHash($templates, 'templateid'); foreach ($result as $templateid => $template) { if (isset($templates[$templateid])) { $result[$templateid]['templates'] = $templates[$templateid]['rowscount']; } else { $result[$templateid]['templates'] = 0; } } } } // Adding Hosts if ($options['selectHosts'] !== null) { if ($options['selectHosts'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'templateid', 'hostid', 'hosts_templates'); $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($hosts, 'host'); } $result = $relationMap->mapMany($result, $hosts, 'hosts', $options['limitSelects']); } else { $hosts = API::Host()->get(array('templateids' => $templateids, 'countOutput' => true, 'groupCount' => true)); $hosts = zbx_toHash($hosts, 'templateid'); foreach ($result as $templateid => $template) { if (isset($hosts[$templateid])) { $result[$templateid]['hosts'] = $hosts[$templateid]['rowscount']; } else { $result[$templateid]['hosts'] = 0; } } } } // Adding screens if ($options['selectScreens'] !== null) { if ($options['selectScreens'] != API_OUTPUT_COUNT) { $screens = API::TemplateScreen()->get(array('output' => $this->outputExtend($options['selectScreens'], array('templateid')), 'templateids' => $templateids, 'nopermissions' => true)); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } // preservekeys is not supported by templatescreen.get, so we're building a map using array keys $relationMap = new CRelationMap(); foreach ($screens as $key => $screen) { $relationMap->addRelation($screen['templateid'], $key); } $screens = $this->unsetExtraFields($screens, array('templateid'), $options['selectScreens']); $result = $relationMap->mapMany($result, $screens, 'screens', $options['limitSelects']); } else { $screens = API::TemplateScreen()->get(array('templateids' => $templateids, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true)); $screens = zbx_toHash($screens, 'templateid'); foreach ($result as $templateid => $template) { if (isset($screens[$templateid])) { $result[$templateid]['screens'] = $screens[$templateid]['rowscount']; } else { $result[$templateid]['screens'] = 0; } } } } return $result; }
/** * Appends boolean option 'isTemplatedScreen' to ouput options. * * @param array $options * * @return array */ protected static function appendTemplatedScreenOption(array $options) { if (array_key_exists('screen', $options)) { $options['isTemplatedScreen'] = (bool) $options['screen']['templateid']; } elseif (array_key_exists('screenid', $options) && $options['screenid'] > 0) { $options['isTemplatedScreen'] = (bool) API::TemplateScreen()->get(['screenids' => [$options['screenid']], 'output' => []]); } return $options; }
/** * 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 = array(); $hostIds = array(); $graphIds = array(); $itemIds = array(); $mapIds = array(); $screenIds = array(); $itemPrototypeIds = array(); $graphPrototypeIds = array(); $screenItems = $this->extendFromObjects($screenItems, $dbScreenItems, array('resourcetype')); $validStyles = array(SCREEN_RESOURCE_CLOCK => array(TIME_TYPE_LOCAL, TIME_TYPE_SERVER, TIME_TYPE_HOST), SCREEN_RESOURCE_DATA_OVERVIEW => array(STYLE_TOP, STYLE_LEFT), SCREEN_RESOURCE_TRIGGERS_OVERVIEW => array(STYLE_TOP, STYLE_LEFT), SCREEN_RESOURCE_HOSTS_INFO => array(STYLE_VERTICAL, STYLE_HORIZONTAL), SCREEN_RESOURCE_TRIGGERS_INFO => array(STYLE_VERTICAL, STYLE_HORIZONTAL)); 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: $overviewResources = array(SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW); if (in_array($screenItem['resourcetype'], $overviewResources)) { 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_LLD_GRAPH: if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No graph prototype ID provided for screen element.')); } $graphPrototypeIds[$screenItem['resourceid']] = $screenItem['resourceid']; break; case SCREEN_RESOURCE_LLD_SIMPLE_GRAPH: if (!$screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No item prototype ID provided for screen element.')); } $itemPrototypeIds[$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'])) { if ($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']; } elseif ($screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set resource ID for screen element.')); } } 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; case SCREEN_RESOURCE_ACTIONS: case SCREEN_RESOURCE_SERVER_INFO: case SCREEN_RESOURCE_SYSTEM_STATUS: case SCREEN_RESOURCE_URL: if ($screenItem['resourceid']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set resource ID for screen element.')); } 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 'max_columns' parameter for LLD screen resources: // is set and valid for create method, and is valid for update method, if set $dbScreenItem = isset($screenItem['screenitemid']) ? $dbScreenItems[$screenItem['screenitemid']] : null; $lldResources = array(SCREEN_RESOURCE_LLD_GRAPH, SCREEN_RESOURCE_LLD_SIMPLE_GRAPH); if (in_array($screenItem['resourcetype'], $lldResources)) { $set = isset($screenItem['max_columns']); $valid = $set && $this->isValidMaxColumns($screenItem['max_columns']); $error = $dbScreenItem ? $set && !$valid : !$set || !$valid; if ($error) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect max columns provided for screen element.')); } } if (isset($validStyles[$screenItem['resourcetype']]) && !in_array($screenItem['style'], $validStyles[$screenItem['resourcetype']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect style provided for screen element.')); } } // check host groups if ($hostGroupsIds) { $dbHostGroups = API::HostGroup()->get(array('output' => array('groupid'), 'groupids' => $hostGroupsIds, '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('output' => array('hostid'), 'hostids' => $hostIds, '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('output' => array('graphid'), 'graphids' => $graphIds, '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 graph prototypes if ($graphPrototypeIds) { $dbGraphPrototypes = API::GraphPrototype()->get(array('output' => array('graphid'), 'graphids' => $graphPrototypeIds, 'editable' => true, 'preservekeys' => true)); foreach ($graphPrototypeIds as $graphPrototypeId) { if (!isset($dbGraphPrototypes[$graphPrototypeId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect graph prototype ID "%1$s" provided for screen element.', $graphPrototypeId)); } } } // check items if ($itemIds) { $dbItems = API::Item()->get(array('output' => array('itemid'), 'itemids' => $itemIds, '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 item prototypes if ($itemPrototypeIds) { $dbItemPrototypes = API::ItemPrototype()->get(array('output' => array('itemid'), 'itemids' => $itemPrototypeIds, 'editable' => true, 'preservekeys' => true)); foreach ($itemPrototypeIds as $itemPrototypeId) { if (!isset($dbItemPrototypes[$itemPrototypeId])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect item prototype ID "%1$s" provided for screen element.', $itemPrototypeId)); } } } // check maps if ($mapIds) { $dbMaps = API::Map()->get(array('output' => array('sysmapid'), 'sysmapids' => $mapIds, '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('output' => array('screenid'), 'screenids' => $screenIds, 'editable' => true, 'preservekeys' => true)); if (count($dbScreens) < count($screenIds)) { $dbTemplateScreens = API::TemplateScreen()->get(array('output' => array('screenid'), 'screenids' => $screenIds, '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)); } } } }
/** * Appends boolean option 'isTemplatedScreen' to ouput options. * * @param array $options * * @return array */ protected static function appendTemplatedScreenOption(array $options) { if (isset($options['screen'])) { $options['isTemplatedScreen'] = (bool) $options['screen']['templateid']; } elseif (isset($options['screenid'])) { $options['isTemplatedScreen'] = (bool) API::TemplateScreen()->get(array('screenids' => array($options['screenid']), 'output' => array())); } return $options; }
/** * Select template screen IDs for previously added screen names and template IDs. */ protected function selectTemplateScreens() { if ($this->templateScreens) { $this->templateScreensRefs = []; $db_template_screens = API::TemplateScreen()->get(['filter' => ['name' => $this->templateScreens], 'output' => ['screenid', 'name', 'templateid']]); foreach ($db_template_screens as $screen) { $this->templateScreensRefs[$screen['templateid']][$screen['name']] = $screen['screenid']; } $this->templateScreens = []; } }
// Graph prototypes $hostGraphPrototypes = API::GraphPrototype()->get(array('hostids' => $templateid, 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND)); if (!empty($hostGraphPrototypes)) { $prototypeList = array(); foreach ($hostGraphPrototypes as $graphPrototype) { $prototypeList[$graphPrototype['graphid']] = $graphPrototype['name']; } order_result($prototypeList); $listBox = new CListBox('graphPrototypes', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($prototypeList); $templateList->addRow(_('Graph prototypes'), $listBox); } } // screens $screens = API::TemplateScreen()->get(array('inherited' => false, 'templateids' => $templateid, 'output' => array('screenid', 'name'))); if (!empty($screens)) { $screensList = array(); foreach ($screens as $screen) { $screensList[$screen['screenid']] = $screen['name']; } order_result($screensList); $listBox = new CListBox('screens', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($screensList); $templateList->addRow(_('Screens'), $listBox); } // web scenarios $httpTests = API::HttpTest()->get(array('output' => array('httptestid', 'name'), 'hostids' => $templateid, 'inherited' => false)); if ($httpTests) { $httpTestList = array();
/** * Create CDiv with host/template information and references to it's elements * * @param string $currentElement * @param int $hostid * @param int $discoveryid * * @return object */ function get_header_host_table($currentElement, $hostid, $discoveryid = null) { // LLD rule header if ($discoveryid) { $elements = array('items' => 'items', 'triggers' => 'triggers', 'graphs' => 'graphs', 'hosts' => 'hosts'); } else { $elements = array('items' => 'items', 'triggers' => 'triggers', 'graphs' => 'graphs', 'applications' => 'applications', 'screens' => 'screens', 'discoveries' => 'discoveries', 'web' => 'web'); } $options = array('hostids' => $hostid, 'output' => API_OUTPUT_EXTEND, 'templated_hosts' => true, 'selectHostDiscovery' => array('ts_delete')); if (isset($elements['items'])) { $options['selectItems'] = API_OUTPUT_COUNT; } if (isset($elements['triggers'])) { $options['selectTriggers'] = API_OUTPUT_COUNT; } if (isset($elements['graphs'])) { $options['selectGraphs'] = API_OUTPUT_COUNT; } if (isset($elements['applications'])) { $options['selectApplications'] = API_OUTPUT_COUNT; } if (isset($elements['discoveries'])) { $options['selectDiscoveries'] = API_OUTPUT_COUNT; } if (isset($elements['web'])) { $options['selectHttpTests'] = API_OUTPUT_COUNT; } if (isset($elements['hosts'])) { $options['selectHostPrototypes'] = API_OUTPUT_COUNT; } // get hosts $dbHost = API::Host()->get($options); $dbHost = reset($dbHost); if (!$dbHost) { return null; } // get discoveries if (!empty($discoveryid)) { $options['itemids'] = $discoveryid; $options['output'] = array('name'); unset($options['hostids'], $options['templated_hosts']); $dbDiscovery = API::DiscoveryRule()->get($options); $dbDiscovery = reset($dbDiscovery); } /* * Back */ $list = new CList(null, 'objectlist'); if ($dbHost['status'] == HOST_STATUS_TEMPLATE) { $list->addItem(array('« ', new CLink(_('Template list'), 'templates.php?templateid=' . $dbHost['hostid'] . url_param('groupid')))); $dbHost['screens'] = API::TemplateScreen()->get(array('editable' => true, 'countOutput' => true, 'groupCount' => true, 'templateids' => $dbHost['hostid'])); $dbHost['screens'] = isset($dbHost['screens'][0]['rowscount']) ? $dbHost['screens'][0]['rowscount'] : 0; } else { $list->addItem(array('« ', new CLink(_('Host list'), 'hosts.php?hostid=' . $dbHost['hostid'] . url_param('groupid')))); } /* * Name */ $proxyName = ''; if ($dbHost['proxy_hostid']) { $proxy = get_host_by_hostid($dbHost['proxy_hostid']); $proxyName = CHtml::encode($proxy['host']) . NAME_DELIMITER; } $name = get_node_name_by_elid($dbHost['hostid'], true, NAME_DELIMITER) . $proxyName . CHtml::encode($dbHost['name']); if ($dbHost['status'] == HOST_STATUS_TEMPLATE) { $list->addItem(array(bold(_('Template') . NAME_DELIMITER), new CLink($name, 'templates.php?form=update&templateid=' . $dbHost['hostid']))); } else { switch ($dbHost['status']) { case HOST_STATUS_MONITORED: if ($dbHost['maintenance_status'] == HOST_MAINTENANCE_STATUS_ON) { $status = new CSpan(_('In maintenance'), 'orange'); } else { $status = new CSpan(_('Monitored'), 'enabled'); } break; case HOST_STATUS_NOT_MONITORED: $status = new CSpan(_('Not monitored'), 'on'); break; default: $status = _('Unknown'); break; } $list->addItem(array(bold(_('Host') . NAME_DELIMITER), new CLink($name, 'hosts.php?form=update&hostid=' . $dbHost['hostid']))); $list->addItem($status); $list->addItem(getAvailabilityTable($dbHost)); } if (!empty($dbDiscovery)) { $list->addItem(array('« ', new CLink(_('Discovery list'), 'host_discovery.php?hostid=' . $dbHost['hostid'] . url_param('groupid')))); $list->addItem(array(bold(_('Discovery') . NAME_DELIMITER), new CLink(CHtml::encode($dbDiscovery['name']), 'host_discovery.php?form=update&itemid=' . $dbDiscovery['itemid']))); } /* * Rowcount */ if (isset($elements['applications'])) { if ($currentElement == 'applications') { $list->addItem(_('Applications') . ' (' . $dbHost['applications'] . ')'); } else { $list->addItem(array(new CLink(_('Applications'), 'applications.php?hostid=' . $dbHost['hostid']), ' (' . $dbHost['applications'] . ')')); } } if (isset($elements['items'])) { if (!empty($dbDiscovery)) { if ($currentElement == 'items') { $list->addItem(_('Item prototypes') . ' (' . $dbDiscovery['items'] . ')'); } else { $list->addItem(array(new CLink(_('Item prototypes'), 'disc_prototypes.php?hostid=' . $dbHost['hostid'] . '&parent_discoveryid=' . $dbDiscovery['itemid']), ' (' . $dbDiscovery['items'] . ')')); } } else { if ($currentElement == 'items') { $list->addItem(_('Items') . ' (' . $dbHost['items'] . ')'); } else { $list->addItem(array(new CLink(_('Items'), 'items.php?filter_set=1&hostid=' . $dbHost['hostid']), ' (' . $dbHost['items'] . ')')); } } } if (isset($elements['triggers'])) { if (!empty($dbDiscovery)) { if ($currentElement == 'triggers') { $list->addItem(_('Trigger prototypes') . ' (' . $dbDiscovery['triggers'] . ')'); } else { $list->addItem(array(new CLink(_('Trigger prototypes'), 'trigger_prototypes.php?hostid=' . $dbHost['hostid'] . '&parent_discoveryid=' . $dbDiscovery['itemid']), ' (' . $dbDiscovery['triggers'] . ')')); } } else { if ($currentElement == 'triggers') { $list->addItem(_('Triggers') . ' (' . $dbHost['triggers'] . ')'); } else { $list->addItem(array(new CLink(_('Triggers'), 'triggers.php?hostid=' . $dbHost['hostid']), ' (' . $dbHost['triggers'] . ')')); } } } if (isset($elements['graphs'])) { if (!empty($dbDiscovery)) { if ($currentElement == 'graphs') { $list->addItem(_('Graph prototypes') . ' (' . $dbDiscovery['graphs'] . ')'); } else { $list->addItem(array(new CLink(_('Graph prototypes'), 'graphs.php?hostid=' . $dbHost['hostid'] . '&parent_discoveryid=' . $dbDiscovery['itemid']), ' (' . $dbDiscovery['graphs'] . ')')); } } else { if ($currentElement == 'graphs') { $list->addItem(_('Graphs') . ' (' . $dbHost['graphs'] . ')'); } else { $list->addItem(array(new CLink(_('Graphs'), 'graphs.php?hostid=' . $dbHost['hostid']), ' (' . $dbHost['graphs'] . ')')); } } } if (isset($elements['hosts']) && $dbHost['flags'] == ZBX_FLAG_DISCOVERY_NORMAL) { if ($currentElement == 'hosts') { $list->addItem(_('Host prototypes') . ' (' . $dbDiscovery['hostPrototypes'] . ')'); } else { $list->addItem(array(new CLink(_('Host prototypes'), 'host_prototypes.php?parent_discoveryid=' . $dbDiscovery['itemid']), ' (' . $dbDiscovery['hostPrototypes'] . ')')); } } if (isset($elements['screens']) && $dbHost['status'] == HOST_STATUS_TEMPLATE) { if ($currentElement == 'screens') { $list->addItem(_('Screens') . ' (' . $dbHost['screens'] . ')'); } else { $list->addItem(array(new CLink(_('Screens'), 'screenconf.php?templateid=' . $dbHost['hostid']), ' (' . $dbHost['screens'] . ')')); } } if (isset($elements['discoveries'])) { if ($currentElement == 'discoveries') { $list->addItem(_('Discovery rules') . ' (' . $dbHost['discoveries'] . ')'); } else { $list->addItem(array(new CLink(_('Discovery rules'), 'host_discovery.php?hostid=' . $dbHost['hostid']), ' (' . $dbHost['discoveries'] . ')')); } } if (isset($elements['web'])) { if ($currentElement == 'web') { $list->addItem(_('Web scenarios') . ' (' . $dbHost['httpTests'] . ')'); } else { $list->addItem(array(new CLink(_('Web scenarios'), 'httpconf.php?hostid=' . $dbHost['hostid']), ' (' . $dbHost['httpTests'] . ')')); } } return new CDiv($list, 'objectgroup top ui-widget-content ui-corner-all'); }
/** * 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; }
} if (!$result) { throw new Exception(); } // clone discovery rules $discoveryRules = API::DiscoveryRule()->get(array('hostids' => $clone_templateid, 'inherited' => false)); if ($discoveryRules) { $copyDiscoveryRules = API::DiscoveryRule()->copy(array('discoveryids' => zbx_objectValues($discoveryRules, 'itemid'), 'hostids' => array($templateid))); if (!$copyDiscoveryRules) { throw new Exception(); } } // clone screens $screens = API::TemplateScreen()->get(array('templateids' => $clone_templateid, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true, 'inherited' => false)); if ($screens) { $screensCopied = API::TemplateScreen()->copy(array('screenIds' => zbx_objectValues($screens, 'screenid'), 'templateIds' => $templateid)); if (!$screensCopied) { throw new Exception(); } } } DBend(true); show_messages(true, $msg_ok, $msg_fail); if ($created) { add_audit_ext(AUDIT_ACTION_ADD, AUDIT_RESOURCE_TEMPLATE, $templateid, $template_name, 'hosts', NULL, NULL); } unset($_REQUEST['form']); unset($_REQUEST['templateid']); } catch (Exception $e) { DBend(false); show_messages(false, $msg_ok, $msg_fail);
/** * 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)); } } } }
if ($applications) { foreach ($applications as &$application) { $application['hostname'] = $hosts[$application['hostid']]['name']; $application['item_cnt'] = 0; } unset($application); // by default order by application name and application id $sortFields = $sortField === 'host' ? array(array('field' => 'hostname', 'order' => $sortOrder)) : array(); array_push($sortFields, 'name', 'applicationid'); CArrayHelper::sort($applications, $sortFields); } if (!$singleHostSelected) { // get host scripts $hostScripts = API::Script()->getScriptsByHosts($hostIds); // get templates screen count $screens = API::TemplateScreen()->get(array('hostids' => $hostIds, 'countOutput' => true, 'groupCount' => true)); $screens = zbx_toHash($screens, 'hostid'); foreach ($hosts as &$host) { $host['screens'] = isset($screens[$host['hostid']]); } unset($host); } } } if ($filter['showDetails']) { $config = select_config(); } // multiselect hosts $multiSelectHostData = array(); if ($filter['hostids']) { $filterHosts = API::Host()->get(array('output' => array('hostid', 'name'), 'hostids' => $filter['hostids']));
} } else { $data['name'] = get_request('name', ''); $data['hsize'] = get_request('hsize', 1); $data['vsize'] = get_request('vsize', 1); } // render view $screenView = new CView('configuration.screen.edit', $data); $screenView->render(); $screenView->show(); } else { $data = array('templateid' => get_request('templateid', null)); $sortfield = getPageSortField('name'); $options = array('editable' => true, 'output' => API_OUTPUT_EXTEND, 'templateids' => $data['templateid'], 'sortfield' => $sortfield, 'limit' => $config['search_limit']); if (!empty($data['templateid'])) { $data['screens'] = API::TemplateScreen()->get($options); } else { $data['screens'] = API::Screen()->get($options); } order_result($data['screens'], $sortfield, getPageSortOrder()); // paging $data['paging'] = getPagingLine($data['screens'], array('screenid'), array('templateid' => get_request('templateid'))); // nodes if ($data['displayNodes'] = is_array(get_current_nodeid())) { foreach ($data['screens'] as &$screen) { $screen['nodename'] = get_node_name_by_elid($screen['screenid'], true); } unset($screen); } // render view $screenView = new CView('configuration.screen.list', $data);
$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)); if (!$result) { throw new Exception(); } } } if ($result) { add_audit_ext($auditAction, AUDIT_RESOURCE_TEMPLATE, $templateId, $templateName, 'hosts', null, null); } unset($_REQUEST['form'], $_REQUEST['templateid']); $result = DBend($result); if ($result) { uncheckTableRows(); } show_messages($result, $messageSuccess, $messageFailed); } catch (Exception $e) {
require_once dirname(__FILE__) . '/include/page_footer.php'; exit; } /* * Display */ $data = array('hostid' => getRequest('hostid', 0), 'fullscreen' => $_REQUEST['fullscreen'], 'screenid' => getRequest('screenid', CProfile::get('web.hostscreen.screenid', null)), 'period' => getRequest('period'), 'stime' => getRequest('stime')); CProfile::update('web.hostscreen.screenid', $data['screenid'], PROFILE_TYPE_ID); // get screen list $data['screens'] = API::TemplateScreen()->get(array('hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND)); $data['screens'] = zbx_toHash($data['screens'], 'screenid'); order_result($data['screens'], 'name'); // get screen $screenid = null; if (!empty($data['screens'])) { $screen = !isset($data['screens'][$data['screenid']]) ? reset($data['screens']) : $data['screens'][$data['screenid']]; if (!empty($screen['screenid'])) { $screenid = $screen['screenid']; } } $data['screen'] = API::TemplateScreen()->get(array('screenids' => $screenid, 'hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND, 'selectScreenItems' => API_OUTPUT_EXTEND)); $data['screen'] = reset($data['screen']); // get host if (!empty($data['screen']['hostid'])) { $data['host'] = get_host_by_hostid($data['screen']['hostid']); } // render view $screenView = new CView('monitoring.hostscreen', $data); $screenView->render(); $screenView->show(); require_once dirname(__FILE__) . '/include/page_footer.php';
$data['current_user_userid'] = $current_userid; $data['form_refresh'] = getRequest('form_refresh'); // render view $screenView = new CView('monitoring.screen.edit', $data); $screenView->render(); $screenView->show(); } else { CProfile::delete('web.screens.elementid'); $sortField = getRequest('sort', CProfile::get('web.' . $page['file'] . '.sort', 'name')); $sortOrder = getRequest('sortorder', CProfile::get('web.' . $page['file'] . '.sortorder', ZBX_SORT_UP)); CProfile::update('web.' . $page['file'] . '.sort', $sortField, PROFILE_TYPE_STR); CProfile::update('web.' . $page['file'] . '.sortorder', $sortOrder, PROFILE_TYPE_STR); $config = select_config(); $data = ['templateid' => getRequest('templateid'), 'sort' => $sortField, 'sortorder' => $sortOrder]; if ($data['templateid']) { $data['screens'] = API::TemplateScreen()->get(['output' => ['screenid', 'name', 'hsize', 'vsize'], 'templateids' => $data['templateid'], 'sortfield' => $sortField, 'limit' => $config['search_limit'], 'editable' => true, 'preservekeys' => true]); } else { if (hasRequest('filter_set')) { CProfile::update('web.screenconf.filter_name', getRequest('filter_name', ''), PROFILE_TYPE_STR); } elseif (hasRequest('filter_rst')) { DBStart(); CProfile::delete('web.screenconf.filter_name'); DBend(); } $data['filter'] = ['name' => CProfile::get('web.screenconf.filter_name', '')]; $data['screens'] = API::Screen()->get(['output' => ['screenid', 'name', 'hsize', 'vsize'], 'sortfield' => $sortField, 'limit' => $config['search_limit'], 'search' => ['name' => $data['filter']['name'] === '' ? null : $data['filter']['name']], 'preservekeys' => true]); $user_type = CWebUser::getType(); if ($user_type != USER_TYPE_SUPER_ADMIN && $user_type != USER_TYPE_ZABBIX_ADMIN) { $editable_screens = API::Screen()->get(['output' => [], 'screenids' => array_keys($data['screens']), 'editable' => true, 'preservekeys' => true]); foreach ($data['screens'] as &$screen) { $screen['editable'] = array_key_exists($screen['screenid'], $editable_screens);