protected function doAction() { $sortField = $this->getInput('sort', CProfile::get('web.proxies.php.sort', 'host')); $sortOrder = $this->getInput('sortorder', CProfile::get('web.proxies.php.sortorder', ZBX_SORT_UP)); CProfile::update('web.proxies.php.sort', $sortField, PROFILE_TYPE_STR); CProfile::update('web.proxies.php.sortorder', $sortOrder, PROFILE_TYPE_STR); $config = select_config(); $data = ['uncheck' => $this->hasInput('uncheck'), 'sort' => $sortField, 'sortorder' => $sortOrder, 'config' => ['max_in_table' => $config['max_in_table']]]; $data['proxies'] = API::Proxy()->get(['output' => ['proxyid', 'host', 'status', 'lastaccess', 'tls_connect', 'tls_accept'], 'selectHosts' => ['hostid', 'name', 'status'], 'sortfield' => $sortField, 'limit' => $config['search_limit'] + 1, 'editable' => true, 'preservekeys' => true]); // sorting & paging order_result($data['proxies'], $sortField, $sortOrder); $url = (new CUrl('zabbix.php'))->setArgument('action', 'proxy.list'); $data['paging'] = getPagingLine($data['proxies'], $sortOrder, $url); foreach ($data['proxies'] as &$proxy) { order_result($proxy['hosts'], 'name'); } unset($proxy); // get proxy IDs for a *selected* page $proxyIds = array_keys($data['proxies']); if ($proxyIds) { // calculate performance $dbPerformance = DBselect('SELECT h.proxy_hostid,SUM(1.0/i.delay) AS qps' . ' FROM hosts h,items i' . ' WHERE h.hostid=i.hostid' . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.delay<>0' . ' AND i.flags<>' . ZBX_FLAG_DISCOVERY_PROTOTYPE . ' AND ' . dbConditionInt('h.proxy_hostid', $proxyIds) . ' GROUP BY h.proxy_hostid'); while ($performance = DBfetch($dbPerformance)) { $data['proxies'][$performance['proxy_hostid']]['perf'] = round($performance['qps'], 2); } // get items $items = API::Item()->get(['proxyids' => $proxyIds, 'groupCount' => true, 'countOutput' => true, 'webitems' => true, 'monitored' => true]); foreach ($items as $item) { $data['proxies'][$item['proxy_hostid']]['item_count'] = $item['rowscount']; } } $response = new CControllerResponseData($data); $response->setTitle(_('Configuration of proxies')); $this->setResponse($response); }
/** * Process screen. * * @return CDiv (screen inside container) */ public function get() { $error = null; $timeOffset = null; $timeZone = null; switch ($this->screenitem['style']) { case TIME_TYPE_HOST: $items = API::Item()->get(array('itemids' => $this->screenitem['resourceid'], 'selectHosts' => array('host'), 'output' => array('itemid', 'value_type'))); $item = reset($items); $host = reset($item['hosts']); $lastValue = Manager::History()->getLast(array($item)); if ($lastValue) { $lastValue = reset($lastValue[$item['itemid']]); $item['lastvalue'] = $lastValue['value']; $item['lastclock'] = $lastValue['clock']; } else { $item['lastvalue'] = '0'; $item['lastclock'] = '0'; } $timeType = $host['host']; preg_match('/([+-]{1})([\\d]{1,2}):([\\d]{1,2})/', $item['lastvalue'], $arr); if (!empty($arr)) { $timeZone = $arr[2] * SEC_PER_HOUR + $arr[3] * SEC_PER_MIN; if ($arr[1] == '-') { $timeZone = 0 - $timeZone; } } if ($lastvalue = strtotime($item['lastvalue'])) { $diff = time() - $item['lastclock']; $timeOffset = $lastvalue + $diff; } else { $error = _('NO DATA'); } break; case TIME_TYPE_SERVER: $error = null; $timeType = _('SERVER'); $timeOffset = time(); $timeZone = date('Z'); break; default: $error = null; $timeType = _('LOCAL'); $timeOffset = null; $timeZone = null; break; } if ($this->screenitem['width'] > $this->screenitem['height']) { $this->screenitem['width'] = $this->screenitem['height']; } $item = new CFlashClock($this->screenitem['width'], $this->screenitem['height'], $this->action); $item->setTimeError($error); $item->setTimeType($timeType); $item->setTimeZone($timeZone); $item->setTimeOffset($timeOffset); $flashclockOverDiv = new CDiv(null, 'flashclock'); $flashclockOverDiv->setAttribute('style', 'width: ' . $this->screenitem['width'] . 'px; height: ' . $this->screenitem['height'] . 'px;'); return $this->getOutput(array($item, $flashclockOverDiv)); }
function is_script_success($hostid, $script_itemkey) { $items = API::Item()->get(array("hostids" => $hostid, "filter" => array("type" => ITEM_TYPE_EXTERNAL, "status" => HOST_STATUS_MONITORED), "search" => array("key_" => $script_itemkey), "output" => "extend")); if (!empty($items)) { $result = true; foreach ($items as $item) { $result = $result && empty($item["error"]) && $item["lastvalue"] == 0; } } else { $result = false; } return $result; }
/** * Prepare data for favourite graphs menu popup. * * @return array */ public static function getFavouriteGraphs() { $graphs = []; $simple_graphs = []; $favourites = CFavorite::get('web.favorite.graphids'); if ($favourites) { $graphids = []; $itemids = []; $db_graphs = []; $db_items = []; foreach ($favourites as $favourite) { if ($favourite['source'] === 'itemid') { $itemids[$favourite['value']] = true; } else { $graphids[$favourite['value']] = true; } } if ($graphids) { $db_graphs = API::Graph()->get(['output' => ['graphid', 'name'], 'selectHosts' => ['hostid', 'name'], 'expandName' => true, 'graphids' => array_keys($graphids), 'preservekeys' => true]); } if ($itemids) { $db_items = API::Item()->get(['output' => ['itemid', 'hostid', 'name', 'key_'], 'selectHosts' => ['hostid', 'name'], 'itemids' => array_keys($itemids), 'webitems' => true, 'preservekeys' => true]); $db_items = CMacrosResolverHelper::resolveItemNames($db_items); } foreach ($favourites as $favourite) { $sourceid = $favourite['value']; if ($favourite['source'] === 'itemid') { if (array_key_exists($sourceid, $db_items)) { $db_item = $db_items[$sourceid]; $simple_graphs[] = ['id' => $sourceid, 'label' => $db_item['hosts'][0]['name'] . NAME_DELIMITER . $db_item['name_expanded']]; } } else { if (array_key_exists($sourceid, $db_graphs)) { $db_graph = $db_graphs[$sourceid]; $graphs[] = ['id' => $sourceid, 'label' => $db_graph['hosts'][0]['name'] . NAME_DELIMITER . $db_graph['name']]; } } } } return ['type' => 'favouriteGraphs', 'graphs' => $graphs, 'simpleGraphs' => $simple_graphs]; }
/** * Prepare data for favourite graphs menu popup. * * @return array */ public static function getFavouriteGraphs() { $graphs = $simpeGraphs = array(); $favourites = CFavorite::get('web.favorite.graphids'); if ($favourites) { $graphIds = $itemIds = $dbGraphs = $dbItems = array(); foreach ($favourites as $favourite) { if ($favourite['source'] === 'itemid') { $itemIds[$favourite['value']] = $favourite['value']; } else { $graphIds[$favourite['value']] = $favourite['value']; } } if ($graphIds) { $dbGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'selectHosts' => array('hostid', 'host'), 'expandName' => true, 'graphids' => $graphIds, 'preservekeys' => true)); } if ($itemIds) { $dbItems = API::Item()->get(array('output' => array('itemid', 'hostid', 'name', 'key_'), 'selectHosts' => array('hostid', 'host'), 'itemids' => $itemIds, 'webitems' => true, 'preservekeys' => true)); $dbItems = CMacrosResolverHelper::resolveItemNames($dbItems); } foreach ($favourites as $favourite) { $sourceId = $favourite['value']; if ($favourite['source'] === 'itemid') { if (isset($dbItems[$sourceId])) { $dbItem = $dbItems[$sourceId]; $dbHost = reset($dbItem['hosts']); $simpeGraphs[] = array('id' => $sourceId, 'label' => $dbHost['host'] . NAME_DELIMITER . $dbItem['name_expanded']); } } else { if (isset($dbGraphs[$sourceId])) { $dbGraph = $dbGraphs[$sourceId]; $dbHost = reset($dbGraph['hosts']); $graphs[] = array('id' => $sourceId, 'label' => $dbHost['host'] . NAME_DELIMITER . $dbGraph['name']); } } } } return array('type' => 'favouriteGraphs', 'graphs' => $graphs, 'simpleGraphs' => $simpeGraphs); }
/** * Retrieves items created for item prototype given as resource for this screen item * and returns array of the item IDs, ordered by item name. * * @return array */ protected function getCreatedItemIds() { if (!$this->createdItemIds) { $itemPrototype = $this->getItemPrototype(); if ($itemPrototype) { // get all created (discovered) items for current host $allCreatedItems = API::Item()->get(array('output' => array('itemid', 'name', 'key_', 'hostid'), 'hostids' => array($itemPrototype['discoveryRule']['hostid']), 'selectItemDiscovery' => array('itemid', 'parent_itemid'), 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_CREATED))); // collect those items where parent item is item prototype selected for this screen item as resource $createdItems = array(); foreach ($allCreatedItems as $item) { if ($item['itemDiscovery']['parent_itemid'] == $itemPrototype['itemid']) { $createdItems[] = $item; } } $createdItems = CMacrosResolverHelper::resolveItemNames($createdItems); foreach ($createdItems as $item) { $this->createdItemIds[$item['itemid']] = $item['name_expanded']; } natsort($this->createdItemIds); $this->createdItemIds = array_keys($this->createdItemIds); } } return $this->createdItemIds; }
function make_graph_submenu() { $graphids = array(); $itemids = array(); $favGraphs = array(); $fav_graphs = CFavorite::get('web.favorite.graphids'); if (!$fav_graphs) { return $favGraphs; } foreach ($fav_graphs as $favorite) { if ('itemid' == $favorite['source']) { $itemids[$favorite['value']] = $favorite['value']; } else { $graphids[$favorite['value']] = $favorite['value']; } } if ($graphids) { $options = array('graphids' => $graphids, 'selectHosts' => array('hostid', 'host'), 'output' => array('graphid', 'name'), 'expandName' => true); $graphs = API::Graph()->get($options); $graphs = zbx_toHash($graphs, 'graphid'); } if ($itemids) { $options = array('itemids' => $itemids, 'selectHosts' => array('hostid', 'host'), 'output' => array('itemid', 'name', 'key_'), 'webitems' => 1); $items = API::Item()->get($options); $items = zbx_toHash($items, 'itemid'); } foreach ($fav_graphs as $favorite) { $source = $favorite['source']; $sourceid = $favorite['value']; if ('itemid' == $source) { if (!isset($items[$sourceid])) { continue; } $item_added = true; $item = $items[$sourceid]; $host = reset($item['hosts']); $item['name'] = itemName($item); $favGraphs[] = array('name' => $host['host'] . NAME_DELIMITER . $item['name'], 'favobj' => 'itemid', 'favid' => $sourceid, 'favaction' => 'remove'); } else { if (!isset($graphs[$sourceid])) { continue; } $graph_added = true; $graph = $graphs[$sourceid]; $ghost = reset($graph['hosts']); $favGraphs[] = array('name' => $ghost['host'] . NAME_DELIMITER . $graph['name'], 'favobj' => 'graphid', 'favid' => $sourceid, 'favaction' => 'remove'); } } if (isset($graph_added)) { $favGraphs[] = array('name' => _('Remove') . ' ' . _('All') . ' ' . _('Graphs'), 'favobj' => 'graphid', 'favid' => 0, 'favaction' => 'remove'); } if (isset($item_added)) { $favGraphs[] = array('name' => _('Remove') . ' ' . _('All') . ' ' . _('Simple graphs'), 'favobj' => 'itemid', 'favid' => 0, 'favaction' => 'remove'); } return $favGraphs; }
$fields = array('period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'stime' => array(T_ZBX_INT, O_OPT, P_NZERO, null, null), 'httptestid' => array(T_ZBX_INT, O_OPT, P_NZERO, null, null), 'http_item_type' => array(T_ZBX_INT, O_OPT, null, null, null), 'name' => array(T_ZBX_STR, O_OPT, null, null, null), 'width' => array(T_ZBX_INT, O_OPT, null, BETWEEN(0, 65535), null), 'height' => array(T_ZBX_INT, O_OPT, null, BETWEEN(0, 65535), null), 'ymin_type' => array(T_ZBX_INT, O_OPT, null, IN('0,1,2'), null), 'ymax_type' => array(T_ZBX_INT, O_OPT, null, IN('0,1,2'), null), 'ymin_itemid' => array(T_ZBX_INT, O_OPT, null, DB_ID, null), 'ymax_itemid' => array(T_ZBX_INT, O_OPT, null, DB_ID, null), 'legend' => array(T_ZBX_INT, O_OPT, null, IN('0,1'), null), 'showworkperiod' => array(T_ZBX_INT, O_OPT, null, IN('0,1'), null), 'showtriggers' => array(T_ZBX_INT, O_OPT, null, IN('0,1'), null), 'graphtype' => array(T_ZBX_INT, O_OPT, null, IN('0,1'), null), 'yaxismin' => array(T_ZBX_DBL, O_OPT, null, null, null), 'yaxismax' => array(T_ZBX_DBL, O_OPT, null, null, null), 'percent_left' => array(T_ZBX_DBL, O_OPT, null, BETWEEN(0, 100), null), 'percent_right' => array(T_ZBX_DBL, O_OPT, null, BETWEEN(0, 100), null), 'items' => array(T_ZBX_STR, O_OPT, null, null, null)); $isDataValid = check_fields($fields); if ($httptestid = get_request('httptestid', false)) { $color = array('current' => 0, 0 => array('next' => '1'), 1 => array('color' => 'Red', 'next' => '2'), 2 => array('color' => 'Dark Green', 'next' => '3'), 3 => array('color' => 'Blue', 'next' => '4'), 4 => array('color' => 'Dark Yellow', 'next' => '5'), 5 => array('color' => 'Cyan', 'next' => '6'), 6 => array('color' => 'Gray', 'next' => '7'), 7 => array('color' => 'Dark Red', 'next' => '8'), 8 => array('color' => 'Green', 'next' => '9'), 9 => array('color' => 'Dark Blue', 'next' => '10'), 10 => array('color' => 'Yellow', 'next' => '11'), 11 => array('color' => 'Black', 'next' => '1')); $items = array(); $dbItems = DBselect('SELECT i.itemid' . ' FROM httpstepitem hi,items i,httpstep hs' . ' WHERE i.itemid=hi.itemid' . ' AND hs.httptestid=' . $httptestid . ' AND hs.httpstepid=hi.httpstepid' . ' AND hi.type=' . get_request('http_item_type', HTTPSTEP_ITEM_TYPE_TIME) . ' ORDER BY hs.no DESC'); while ($item = DBfetch($dbItems)) { $itemColor = $color[$color['current'] = $color[$color['current']]['next']]['color']; $items[] = array('itemid' => $item['itemid'], 'color' => $itemColor); } $httptest = get_httptest_by_httptestid($httptestid); $name = $httptest['name']; } else { $items = get_request('items', array()); asort_by_key($items, 'sortorder'); $dbItems = API::Item()->get(array('webitems' => true, 'itemids' => zbx_objectValues($items, 'itemid'), 'nodeids' => get_current_nodeid(true), 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true, 'filter' => array('flags' => null))); $dbItems = zbx_toHash($dbItems, 'itemid'); foreach ($items as $item) { if (!isset($dbItems[$item['itemid']])) { access_deny(); } } $name = get_request('name', ''); } /* * Display */ if ($isDataValid) { $graph = new CChart(get_request('graphtype', GRAPH_TYPE_NORMAL)); $graph->setHeader($name); navigation_bar_calc();
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__) . '/include/config.inc.php'; $page['file'] = 'chart.php'; $page['type'] = PAGE_TYPE_IMAGE; require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('itemid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, null), 'screenid' => array(T_ZBX_STR, O_OPT, null, null, null), 'period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'profileIdx' => array(T_ZBX_STR, O_OPT, null, null, null), 'profileIdx2' => array(T_ZBX_STR, O_OPT, null, null, null), 'updateProfile' => array(T_ZBX_STR, O_OPT, null, null, null), 'from' => array(T_ZBX_INT, O_OPT, null, '{}>=0', null), 'width' => array(T_ZBX_INT, O_OPT, null, '{}>0', null), 'height' => array(T_ZBX_INT, O_OPT, null, '{}>0', null), 'border' => array(T_ZBX_INT, O_OPT, null, IN('0,1'), null)); check_fields($fields); /* * Permissions */ if (!DBfetch(DBselect('SELECT i.itemid FROM items i WHERE i.itemid=' . $_REQUEST['itemid']))) { show_error_message(_('No items defined.')); } $dbItems = API::Item()->get(array('itemids' => $_REQUEST['itemid'], 'webitems' => true, 'nodeids' => get_current_nodeid(true), 'filter' => array('flags' => null))); if (empty($dbItems)) { access_deny(); } /* * Display */ $timeline = CScreenBase::calculateTime(array('profileIdx' => get_request('profileIdx', 'web.screens'), 'profileIdx2' => get_request('profileIdx2'), 'updateProfile' => get_request('updateProfile', true), 'period' => get_request('period'), 'stime' => get_request('stime'))); $graph = new CChart(); $graph->setPeriod($timeline['period']); $graph->setSTime($timeline['stime']); if (isset($_REQUEST['from'])) { $graph->setFrom($_REQUEST['from']); } if (isset($_REQUEST['width'])) { $graph->setWidth($_REQUEST['width']);
/** * Check, if items that are about to be inserted or updated violate the rule: * only one item can be linked to a inventory filed. * If everything is ok, function return true or throws Exception otherwise * * @static * * @param array $items * @param bool $update whether this is update operation * * @return bool */ public static function validateInventoryLinks(array $items, $update = false) { // inventory link field is not being updated, or being updated to 0, no need to validate anything then foreach ($items as $i => $item) { if (!isset($item['inventory_link']) || $item['inventory_link'] == 0) { unset($items[$i]); } } if (zbx_empty($items)) { return true; } $possibleHostInventories = getHostInventories(); if ($update) { // for successful validation we need three fields for each item: inventory_link, hostid and key_ // problem is, that when we are updating an item, we might not have them, because they are not changed // so, we need to find out what is missing and use API to get the lacking info $itemsWithNoHostId = array(); $itemsWithNoInventoryLink = array(); $itemsWithNoKeys = array(); foreach ($items as $item) { if (!isset($item['inventory_link'])) { $itemsWithNoInventoryLink[$item['itemid']] = $item['itemid']; } if (!isset($item['hostid'])) { $itemsWithNoHostId[$item['itemid']] = $item['itemid']; } if (!isset($item['key_'])) { $itemsWithNoKeys[$item['itemid']] = $item['itemid']; } } $itemsToFind = array_merge($itemsWithNoHostId, $itemsWithNoInventoryLink, $itemsWithNoKeys); // are there any items with lacking info? if (!zbx_empty($itemsToFind)) { $missingInfo = API::Item()->get(array('output' => array('hostid', 'inventory_link', 'key_'), 'filter' => array('itemid' => $itemsToFind), 'nopermissions' => true)); $missingInfo = zbx_toHash($missingInfo, 'itemid'); // appending host ids, inventory_links and keys where they are needed foreach ($items as $i => $item) { if (isset($missingInfo[$item['itemid']])) { if (!isset($items[$i]['hostid'])) { $items[$i]['hostid'] = $missingInfo[$item['itemid']]['hostid']; } if (!isset($items[$i]['inventory_link'])) { $items[$i]['inventory_link'] = $missingInfo[$item['itemid']]['inventory_link']; } if (!isset($items[$i]['key_'])) { $items[$i]['key_'] = $missingInfo[$item['itemid']]['key_']; } } } } } $hostids = zbx_objectValues($items, 'hostid'); // getting all inventory links on every affected host $itemsOnHostsInfo = API::Item()->get(array('output' => array('key_', 'inventory_link', 'hostid'), 'filter' => array('hostid' => $hostids), 'nopermissions' => true)); // now, changing array to: 'hostid' => array('key_'=>'inventory_link') $linksOnHostsCurr = array(); foreach ($itemsOnHostsInfo as $info) { // 0 means no link - we are not interested in those ones if ($info['inventory_link'] != 0) { if (!isset($linksOnHostsCurr[$info['hostid']])) { $linksOnHostsCurr[$info['hostid']] = array($info['key_'] => $info['inventory_link']); } else { $linksOnHostsCurr[$info['hostid']][$info['key_']] = $info['inventory_link']; } } } $linksOnHostsFuture = array(); foreach ($items as $item) { // checking if inventory_link value is a valid number if ($update || $item['value_type'] != ITEM_VALUE_TYPE_LOG) { // does inventory field with provided number exists? if (!isset($possibleHostInventories[$item['inventory_link']])) { $maxVar = max(array_keys($possibleHostInventories)); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item "%1$s" cannot populate a missing host inventory field number "%2$d". Choices are: from 0 (do not populate) to %3$d.', $item['name'], $item['inventory_link'], $maxVar)); } } if (!isset($linksOnHostsFuture[$item['hostid']])) { $linksOnHostsFuture[$item['hostid']] = array($item['key_'] => $item['inventory_link']); } else { $linksOnHostsFuture[$item['hostid']][$item['key_']] = $item['inventory_link']; } } foreach ($linksOnHostsFuture as $hostId => $linkFuture) { if (isset($linksOnHostsCurr[$hostId])) { $futureSituation = array_merge($linksOnHostsCurr[$hostId], $linksOnHostsFuture[$hostId]); } else { $futureSituation = $linksOnHostsFuture[$hostId]; } $valuesCount = array_count_values($futureSituation); // if we have a duplicate inventory links after merging - we are in trouble if (max($valuesCount) > 1) { // what inventory field caused this conflict? $conflictedLink = array_keys($valuesCount, 2); $conflictedLink = reset($conflictedLink); // which of updated items populates this link? $beingSavedItemName = ''; foreach ($items as $item) { if ($item['inventory_link'] == $conflictedLink) { if (isset($item['name'])) { $beingSavedItemName = $item['name']; } else { $thisItem = API::Item()->get(array('output' => array('name'), 'filter' => array('itemid' => $item['itemid']), 'nopermissions' => true)); $beingSavedItemName = $thisItem[0]['name']; } break; } } // name of the original item that already populates the field $originalItem = API::Item()->get(array('output' => array('name'), 'filter' => array('hostid' => $hostId, 'inventory_link' => $conflictedLink), 'nopermissions' => true)); $originalItemName = $originalItem[0]['name']; self::exception(ZBX_API_ERROR_PARAMETERS, _s('Two items ("%1$s" and "%2$s") cannot populate one host inventory field "%3$s", this would lead to a conflict.', $beingSavedItemName, $originalItemName, $possibleHostInventories[$conflictedLink]['title'])); } } return true; }
/** * Add Items to applications * * @param array $data * @param array $data['applications'] * @param array $data['items'] * @return boolean */ public function massAdd($data) { if (empty($data['applications'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $applications = zbx_toArray($data['applications']); $items = zbx_toArray($data['items']); $applicationids = zbx_objectValues($applications, 'applicationid'); $itemids = zbx_objectValues($items, 'itemid'); // validate permissions $appOptions = array('applicationids' => $applicationids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1); $allowedApplications = $this->get($appOptions); foreach ($applications as $application) { if (!isset($allowedApplications[$application['applicationid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $allowedItems = API::Item()->get(array('itemids' => $itemids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CHILD, ZBX_FLAG_DISCOVERY_CREATED)))); foreach ($items as $num => $item) { if (!isset($allowedItems[$item['itemid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $linkedDb = DBselect('SELECT ia.itemid,ia.applicationid' . ' FROM items_applications ia' . ' WHERE ' . dbConditionInt('ia.itemid', $itemids) . ' AND ' . dbConditionInt('ia.applicationid', $applicationids)); while ($pair = DBfetch($linkedDb)) { $linked[$pair['applicationid']] = array($pair['itemid'] => $pair['itemid']); } $appsInsert = array(); foreach ($applicationids as $applicationid) { foreach ($itemids as $inum => $itemid) { if (isset($linked[$applicationid]) && isset($linked[$applicationid][$itemid])) { continue; } $appsInsert[] = array('itemid' => $itemid, 'applicationid' => $applicationid); } } DB::insert('items_applications', $appsInsert); foreach ($itemids as $inum => $itemid) { $dbChilds = DBselect('SELECT i.itemid,i.hostid FROM items i WHERE i.templateid=' . zbx_dbstr($itemid)); while ($child = DBfetch($dbChilds)) { $dbApps = DBselect('SELECT a1.applicationid' . ' FROM applications a1,applications a2' . ' WHERE a1.name=a2.name' . ' AND a1.hostid=' . $child['hostid'] . ' AND ' . dbConditionInt('a2.applicationid', $applicationids)); $childApplications = array(); while ($app = DBfetch($dbApps)) { $childApplications[] = $app; } $result = $this->massAdd(array('items' => $child, 'applications' => $childApplications)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot add items.'); } } } return array('applicationids' => $applicationids); }
$proxies = API::proxy()->get(['output' => ['hostid', 'host'], 'preservekeys' => true]); order_result($proxies, 'host'); $proxies[0] = ['host' => _('Server')]; $table->setHeader([_('Proxy'), _('5 seconds'), _('10 seconds'), _('30 seconds'), _('1 minute'), _('5 minutes'), _('More than 10 minutes')]); $queueData = zbx_toHash($queueData, 'proxyid'); foreach ($proxies as $proxyId => $proxy) { if (isset($queueData[$proxyId])) { $proxyData = $queueData[$proxyId]; } else { $proxyData = ['delay5' => 0, 'delay10' => 0, 'delay30' => 0, 'delay60' => 0, 'delay300' => 0, 'delay600' => 0]; } $table->addRow([$proxy['host'], getSeverityCell(TRIGGER_SEVERITY_NOT_CLASSIFIED, $severityConfig, $proxyData['delay5'], !$proxyData['delay5']), getSeverityCell(TRIGGER_SEVERITY_INFORMATION, $severityConfig, $proxyData['delay10'], !$proxyData['delay10']), getSeverityCell(TRIGGER_SEVERITY_WARNING, $severityConfig, $proxyData['delay30'], !$proxyData['delay30']), getSeverityCell(TRIGGER_SEVERITY_AVERAGE, $severityConfig, $proxyData['delay60'], !$proxyData['delay60']), getSeverityCell(TRIGGER_SEVERITY_HIGH, $severityConfig, $proxyData['delay300'], !$proxyData['delay300']), getSeverityCell(TRIGGER_SEVERITY_DISASTER, $severityConfig, $proxyData['delay600'], !$proxyData['delay600'])]); } } elseif ($config == QUEUE_DETAILS) { $queueData = zbx_toHash($queueData, 'itemid'); $items = API::Item()->get(['output' => ['itemid', 'hostid', 'name', 'key_'], 'selectHosts' => ['name'], 'itemids' => array_keys($queueData), 'webitems' => true, 'preservekeys' => true]); $items = CMacrosResolverHelper::resolveItemNames($items); // get hosts for queue items $hostIds = zbx_objectValues($items, 'hostid'); $hostIds = array_keys(array_flip($hostIds)); $hosts = API::Host()->get(['output' => ['hostid', 'proxy_hostid'], 'hostids' => $hostIds, 'preservekeys' => true]); // get proxies for those hosts $proxyHostIds = []; foreach ($hosts as $host) { if ($host['proxy_hostid']) { $proxyHostIds[$host['proxy_hostid']] = $host['proxy_hostid']; } } if ($proxyHostIds) { $proxies = API::Proxy()->get(['proxyids' => $proxyHostIds, 'output' => ['proxyid', 'host'], 'preservekeys' => true]); }
if ($_REQUEST['form'] == 'full_clone') { // host applications $hostApps = API::Application()->get(array('hostids' => $_REQUEST['hostid'], 'inherited' => false, 'output' => array('name'), 'preservekeys' => true)); if (!empty($hostApps)) { $applicationsList = array(); foreach ($hostApps as $hostAppId => $hostApp) { $applicationsList[$hostAppId] = $hostApp['name']; } order_result($applicationsList); $listBox = new CListBox('applications', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($applicationsList); $hostList->addRow(_('Applications'), $listBox); } // host items $hostItems = API::Item()->get(array('hostids' => $_REQUEST['hostid'], 'inherited' => false, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL), 'output' => array('itemid', 'key_', 'name'))); if (!empty($hostItems)) { $itemsList = array(); foreach ($hostItems as $hostItem) { $itemsList[$hostItem['itemid']] = itemName($hostItem); } order_result($itemsList); $listBox = new CListBox('items', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($itemsList); $hostList->addRow(_('Items'), $listBox); } // host triggers $hostTriggers = API::Trigger()->get(array('inherited' => false, 'hostids' => $_REQUEST['hostid'], 'output' => array('triggerid', 'description'), 'selectItems' => array('type'), 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL)))); if (!empty($hostTriggers)) { $triggersList = array();
/** * Deletes items from DB that are missing in XML. * * @return null */ protected function deleteMissingItems() { if (!$this->options['items']['deleteMissing']) { return; } $processedHostIds = $this->importedObjectContainer->getHostIds(); $processedTemplateIds = $this->importedObjectContainer->getTemplateIds(); $processedHostIds = array_merge($processedHostIds, $processedTemplateIds); // no hosts or templates have been processed if (!$processedHostIds) { return; } $itemIdsXML = array(); $allItems = $this->getFormattedItems(); if ($allItems) { foreach ($allItems as $host => $items) { $hostId = $this->referencer->resolveHostOrTemplate($host); foreach ($items as $item) { $itemId = $this->referencer->resolveItem($hostId, $item['key_']); if ($itemId) { $itemIdsXML[$itemId] = $itemId; } } } } $dbItemIds = API::Item()->get(array('output' => array('itemid'), 'hostids' => $processedHostIds, 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); $itemsToDelete = array_diff_key($dbItemIds, $itemIdsXML); if ($itemsToDelete) { API::Item()->delete(array_keys($itemsToDelete)); } $this->referencer->refreshItems(); }
/** * Copies all of the graphs from the source discovery to the target discovery rule. * * @throws APIException if graph saving fails * * @param array $srcDiscovery The source discovery rule to copy from * @param array $dstDiscovery The target discovery rule to copy to * * @return array */ protected function copyGraphPrototypes(array $srcDiscovery, array $dstDiscovery) { // fetch source graphs $srcGraphs = API::GraphPrototype()->get(array('discoveryids' => $srcDiscovery['itemid'], 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'selectHosts' => API_OUTPUT_REFER, 'preservekeys' => true)); if (!$srcGraphs) { return array(); } $srcItemIds = array(); foreach ($srcGraphs as $key => $graph) { // skip graphs with items from multiple hosts if (count($graph['hosts']) > 1) { unset($srcGraphs[$key]); continue; } // skip graphs with http items if (httpItemExists($graph['gitems'])) { unset($srcGraphs[$key]); continue; } // save all used item ids to map them to the new items foreach ($graph['gitems'] as $item) { $srcItemIds[$item['itemid']] = $item['itemid']; } if ($graph['ymin_itemid']) { $srcItemIds[$graph['ymin_itemid']] = $graph['ymin_itemid']; } if ($graph['ymax_itemid']) { $srcItemIds[$graph['ymax_itemid']] = $graph['ymax_itemid']; } } // fetch source items $items = API::Item()->get(array('itemids' => $srcItemIds, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'filter' => array('flags' => null))); $srcItems = array(); $itemKeys = array(); foreach ($items as $item) { $srcItems[$item['itemid']] = $item; $itemKeys[$item['key_']] = $item['key_']; } // fetch newly cloned items $newItems = API::Item()->get(array('hostids' => $dstDiscovery['hostid'], 'filter' => array('key_' => $itemKeys, 'flags' => null), 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); $items = array_merge($dstDiscovery['items'], $newItems); $dstItems = array(); foreach ($items as $item) { $dstItems[$item['key_']] = $item; } $dstGraphs = $srcGraphs; foreach ($dstGraphs as &$graph) { unset($graph['graphid']); unset($graph['templateid']); foreach ($graph['gitems'] as &$gitem) { // replace the old item with the new one with the same key $item = $srcItems[$gitem['itemid']]; $gitem['itemid'] = $dstItems[$item['key_']]['itemid']; unset($gitem['gitemid'], $gitem['graphid']); } // replace the old axis items with the new one with the same key if ($graph['ymin_itemid']) { $yMinSrcItem = $srcItems[$graph['ymin_itemid']]; $graph['ymin_itemid'] = $dstItems[$yMinSrcItem['key_']]['itemid']; } if ($graph['ymax_itemid']) { $yMaxSrcItem = $srcItems[$graph['ymax_itemid']]; $graph['ymax_itemid'] = $dstItems[$yMaxSrcItem['key_']]['itemid']; } } // save graphs $rs = API::Graph()->create($dstGraphs); if (!$rs) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot clone graph prototypes.')); } return $rs; }
/** * Get history data * * @param array $options * @param array $options['itemids'] * @param boolean $options['editable'] * @param string $options['pattern'] * @param int $options['limit'] * @param string $options['order'] * @return array|int item data as array or false if error */ public function get($options = array()) { $result = array(); $nodeCheck = false; // allowed columns for sorting $sortColumns = array('itemid', 'clock'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND); $sqlParts = array('select' => array('history' => 'h.itemid'), 'from' => array(), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('history' => ITEM_VALUE_TYPE_UINT64, 'nodeids' => null, 'hostids' => null, 'itemids' => null, 'triggerids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'time_from' => null, 'time_till' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'groupCount' => null, 'groupOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); switch ($options['history']) { case ITEM_VALUE_TYPE_LOG: $sqlParts['from']['history'] = 'history_log h'; $sortColumns[] = 'id'; break; case ITEM_VALUE_TYPE_TEXT: $sqlParts['from']['history'] = 'history_text h'; $sortColumns[] = 'id'; break; case ITEM_VALUE_TYPE_STR: $sqlParts['from']['history'] = 'history_str h'; break; case ITEM_VALUE_TYPE_UINT64: $sqlParts['from']['history'] = 'history_uint h'; break; case ITEM_VALUE_TYPE_FLOAT: default: $sqlParts['from']['history'] = 'history h'; } // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == self::$userData['type'] || $options['nopermissions']) { } else { $itemOptions = array('editable' => $options['editable'], 'preservekeys' => true, 'webitems' => true); if (!is_null($options['itemids'])) { $itemOptions['itemids'] = $options['itemids']; } $items = API::Item()->get($itemOptions); $options['itemids'] = array_keys($items); } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); $sqlParts['where']['itemid'] = dbConditionInt('h.itemid', $options['itemids']); if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('h.itemid', $nodeids); } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['hostid'] = 'i.hostid'; } $sqlParts['from']['items'] = 'items i'; $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']); $sqlParts['where']['hi'] = 'h.itemid=i.itemid'; if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('i.hostid', $nodeids); } } // should be last, after all ****IDS checks if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('h.itemid', $nodeids); } // time_from if (!is_null($options['time_from'])) { $sqlParts['select']['clock'] = 'h.clock'; $sqlParts['where']['clock_from'] = 'h.clock>=' . zbx_dbstr($options['time_from']); } // time_till if (!is_null($options['time_till'])) { $sqlParts['select']['clock'] = 'h.clock'; $sqlParts['where']['clock_till'] = 'h.clock<=' . zbx_dbstr($options['time_till']); } // filter if (is_array($options['filter'])) { $this->dbFilter($sqlParts['from']['history'], $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search($sqlParts['from']['history'], $options, $sqlParts); } // output if ($options['output'] == API_OUTPUT_EXTEND) { unset($sqlParts['select']['clock']); $sqlParts['select']['history'] = '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; } } } // groupOutput $groupOutput = false; if (!is_null($options['groupOutput'])) { if (str_in_array('h.' . $options['groupOutput'], $sqlParts['select']) || str_in_array('h.*', $sqlParts['select'])) { $groupOutput = true; } } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'h'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $itemids = array(); $sqlParts['select'] = array_unique($sqlParts['select']); $sqlParts['from'] = array_unique($sqlParts['from']); $sqlParts['where'] = array_unique($sqlParts['where']); $sqlParts['order'] = array_unique($sqlParts['order']); $sqlSelect = ''; $sqlFrom = ''; $sqlWhere = ''; $sqlOrder = ''; if (!empty($sqlParts['select'])) { $sqlSelect .= implode(',', $sqlParts['select']); } if (!empty($sqlParts['from'])) { $sqlFrom .= implode(',', $sqlParts['from']); } if (!empty($sqlParts['where'])) { $sqlWhere .= implode(' AND ', $sqlParts['where']); } if (!empty($sqlParts['order'])) { $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']); } $sqlLimit = $sqlParts['limit']; $sql = 'SELECT ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlOrder; $dbRes = DBselect($sql, $sqlLimit); $count = 0; $group = array(); while ($data = DBfetch($dbRes)) { if ($options['countOutput']) { $result = $data; } else { $itemids[$data['itemid']] = $data['itemid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$count] = array('itemid' => $data['itemid']); } else { $result[$count] = array(); // hostids if (isset($data['hostid'])) { if (!isset($result[$count]['hosts'])) { $result[$count]['hosts'] = array(); } $result[$count]['hosts'][] = array('hostid' => $data['hostid']); unset($data['hostid']); } // triggerids if (isset($data['triggerid'])) { if (!isset($result[$count]['triggers'])) { $result[$count]['triggers'] = array(); } $result[$count]['triggers'][] = array('triggerid' => $data['triggerid']); unset($data['triggerid']); } $result[$count] += $data; // grouping if ($groupOutput) { $dataid = $data[$options['groupOutput']]; if (!isset($group[$dataid])) { $group[$dataid] = array(); } $group[$dataid][] = $result[$count]; } $count++; } } } if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
if ($httptestid = getRequest('httptestid', false)) { if (!API::HttpTest()->isReadable(array($_REQUEST['httptestid']))) { access_deny(); } $color = array('current' => 0, 0 => array('next' => '1'), 1 => array('color' => 'Red', 'next' => '2'), 2 => array('color' => 'Dark Green', 'next' => '3'), 3 => array('color' => 'Blue', 'next' => '4'), 4 => array('color' => 'Dark Yellow', 'next' => '5'), 5 => array('color' => 'Cyan', 'next' => '6'), 6 => array('color' => 'Gray', 'next' => '7'), 7 => array('color' => 'Dark Red', 'next' => '8'), 8 => array('color' => 'Green', 'next' => '9'), 9 => array('color' => 'Dark Blue', 'next' => '10'), 10 => array('color' => 'Yellow', 'next' => '11'), 11 => array('color' => 'Black', 'next' => '1')); $items = array(); $dbItems = DBselect('SELECT i.itemid' . ' FROM httpstepitem hi,items i,httpstep hs' . ' WHERE i.itemid=hi.itemid' . ' AND hs.httptestid=' . zbx_dbstr($httptestid) . ' AND hs.httpstepid=hi.httpstepid' . ' AND hi.type=' . zbx_dbstr(getRequest('http_item_type', HTTPSTEP_ITEM_TYPE_TIME)) . ' ORDER BY hs.no DESC'); while ($item = DBfetch($dbItems)) { $itemColor = $color[$color['current'] = $color[$color['current']]['next']]['color']; $items[] = array('itemid' => $item['itemid'], 'color' => $itemColor); } $httpTest = get_httptest_by_httptestid($httptestid); $name = CMacrosResolverHelper::resolveHttpTestName($httpTest['hostid'], $httpTest['name']); } elseif ($items = getRequest('items', array())) { asort_by_key($items, 'sortorder'); $dbItems = API::Item()->get(array('itemids' => zbx_objectValues($items, 'itemid'), 'output' => array('itemid'), 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_PROTOTYPE, ZBX_FLAG_DISCOVERY_CREATED)), 'webitems' => true, 'preservekeys' => true)); foreach ($items as $item) { if (!isset($dbItems[$item['itemid']])) { access_deny(); } } $name = getRequest('name', ''); } else { show_error_message(_('No items defined.')); exit; } /* * Display */ $profileIdx = getRequest('profileIdx', 'web.httptest'); $profileIdx2 = getRequest('httptestid', getRequest('profileIdx2'));
/** * Prepares and returns an array of child items, inherited from items $itemsToInherit on the given hosts. * * @param array $itemsToInherit * @param array|null $hostIds * * @return array an array of unsaved child items */ protected function prepareInheritedItems(array $itemsToInherit, array $hostIds = null) { // fetch all child hosts $chdHosts = API::Host()->get(array('output' => array('hostid', 'host', 'status'), 'selectParentTemplates' => array('templateid'), 'selectInterfaces' => API_OUTPUT_EXTEND, 'templateids' => zbx_objectValues($itemsToInherit, 'hostid'), 'hostids' => $hostIds, 'preservekeys' => true, 'nopermissions' => true, 'templated_hosts' => true)); if (empty($chdHosts)) { return array(); } $newItems = array(); foreach ($chdHosts as $hostId => $host) { $templateids = zbx_toHash($host['parentTemplates'], 'templateid'); // skip items not from parent templates of current host $parentItems = array(); foreach ($itemsToInherit as $inum => $parentItem) { if (isset($templateids[$parentItem['hostid']])) { $parentItems[$inum] = $parentItem; } } // check existing items to decide insert or update $exItems = API::Item()->get(array('output' => array('itemid', 'type', 'key_', 'flags', 'templateid'), 'hostids' => $hostId, 'preservekeys' => true, 'nopermissions' => true, 'filter' => array('flags' => null))); $exItemsKeys = zbx_toHash($exItems, 'key_'); $exItemsTpl = zbx_toHash($exItems, 'templateid'); foreach ($parentItems as $parentItem) { $exItem = null; // check if an item of a different type with the same key exists if (isset($exItemsKeys[$parentItem['key_']])) { $exItem = $exItemsKeys[$parentItem['key_']]; if ($exItem['flags'] != $parentItem['flags']) { $this->errorInheritFlags($exItem['flags'], $exItem['key_'], $host['host']); } } // update by templateid if (isset($exItemsTpl[$parentItem['itemid']])) { $exItem = $exItemsTpl[$parentItem['itemid']]; if (isset($exItemsKeys[$parentItem['key_']]) && !idcmp($exItemsKeys[$parentItem['key_']]['templateid'], $parentItem['itemid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _params($this->getErrorMsg(self::ERROR_EXISTS), array($parentItem['key_'], $host['host']))); } } // update by key if (isset($exItemsKeys[$parentItem['key_']])) { $exItem = $exItemsKeys[$parentItem['key_']]; if ($exItem['templateid'] > 0 && !idcmp($exItem['templateid'], $parentItem['itemid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _params($this->getErrorMsg(self::ERROR_EXISTS_TEMPLATE), array($parentItem['key_'], $host['host']))); } } if ($host['status'] == HOST_STATUS_TEMPLATE || !isset($parentItem['type'])) { unset($parentItem['interfaceid']); } elseif (isset($parentItem['type']) && isset($exItem) && $parentItem['type'] != $exItem['type'] || !isset($exItem)) { $interface = self::findInterfaceForItem($parentItem, $host['interfaces']); if (!empty($interface)) { $parentItem['interfaceid'] = $interface['interfaceid']; } elseif ($interface !== false) { self::exception(ZBX_API_ERROR_PARAMETERS, _params($this->getErrorMsg(self::ERROR_NO_INTERFACE), array($host['host'], $parentItem['key_']))); } } else { unset($parentItem['interfaceid']); } // copying item $newItem = $parentItem; $newItem['hostid'] = $host['hostid']; $newItem['templateid'] = $parentItem['itemid']; // setting item application if (isset($parentItem['applications'])) { $newItem['applications'] = get_same_applications_for_host($parentItem['applications'], $host['hostid']); } if ($exItem) { $newItem['itemid'] = $exItem['itemid']; } else { unset($newItem['itemid']); } $newItems[] = $newItem; } } return $newItems; }
function get_item_function_info($expr) { $value_type = array(ITEM_VALUE_TYPE_UINT64 => _('Numeric (integer 64bit)'), ITEM_VALUE_TYPE_FLOAT => _('Numeric (float)'), ITEM_VALUE_TYPE_STR => _('Character'), ITEM_VALUE_TYPE_LOG => _('Log'), ITEM_VALUE_TYPE_TEXT => _('Text')); $type_of_value_type = array(ITEM_VALUE_TYPE_UINT64 => T_ZBX_INT, ITEM_VALUE_TYPE_FLOAT => T_ZBX_DBL, ITEM_VALUE_TYPE_STR => T_ZBX_STR, ITEM_VALUE_TYPE_LOG => T_ZBX_STR, ITEM_VALUE_TYPE_TEXT => T_ZBX_STR); $function_info = array('band' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'abschange' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'avg' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'change' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'count' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'date' => array('value_type' => 'YYYYMMDD', 'type' => T_ZBX_INT, 'validation' => '{}>=19700101&&{}<=99991231'), 'dayofmonth' => array('value_type' => '1-31', 'type' => T_ZBX_INT, 'validation' => '{}>=1&&{}<=31'), 'dayofweek' => array('value_type' => '1-7', 'type' => T_ZBX_INT, 'validation' => IN('1,2,3,4,5,6,7')), 'delta' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'diff' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'fuzzytime' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'iregexp' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'last' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'logeventid' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'logseverity' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'logsource' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'max' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'min' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'nodata' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'now' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'prev' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'regexp' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'str' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'strlen' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'sum' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'time' => array('value_type' => 'HHMMSS', 'type' => T_ZBX_INT, 'validation' => 'zbx_strlen({})==6')); $expressionData = new CTriggerExpression(); if ($expressionData->parse($expr)) { if (isset($expressionData->macros[0])) { $result = array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')); } elseif (isset($expressionData->usermacros[0]) || isset($expressionData->lldmacros[0])) { $result = array('value_type' => $value_type[ITEM_VALUE_TYPE_FLOAT], 'type' => T_ZBX_STR, 'validation' => 'preg_match("/^' . ZBX_PREG_NUMBER . '$/u", {})'); } elseif (isset($expressionData->expressions[0])) { $exprPart = reset($expressionData->expressions); if (!isset($function_info[$exprPart['functionName']])) { return EXPRESSION_FUNCTION_UNKNOWN; } $hostFound = API::Host()->get(array('filter' => array('host' => array($exprPart['host'])), 'templated_hosts' => true)); if (!$hostFound) { return EXPRESSION_HOST_UNKNOWN; } $itemFound = API::Item()->get(array('output' => array('value_type'), 'hostids' => zbx_objectValues($hostFound, 'hostid'), 'filter' => array('key_' => array($exprPart['item'])), 'webitems' => true)); if (!$itemFound) { $itemFound = API::ItemPrototype()->get(array('output' => array('value_type'), 'hostids' => zbx_objectValues($hostFound, 'hostid'), 'filter' => array('key_' => array($exprPart['item'])))); if (!$itemFound) { return EXPRESSION_HOST_ITEM_UNKNOWN; } } $itemFound = reset($itemFound); $result = $function_info[$exprPart['functionName']]; if (is_array($result['value_type'])) { $result['value_type'] = $result['value_type'][$itemFound['value_type']]; $result['type'] = $result['type'][$itemFound['value_type']]; if ($result['type'] == T_ZBX_INT || $result['type'] == T_ZBX_DBL) { $result['type'] = T_ZBX_STR; $result['validation'] = 'preg_match("/^' . ZBX_PREG_NUMBER . '$/u",{})'; } } } else { return EXPRESSION_NOT_A_MACRO_ERROR; } } return $result; }
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__) . '/include/config.inc.php'; require_once dirname(__FILE__) . '/include/graphs.inc.php'; $page['file'] = 'chart7.php'; $page['type'] = PAGE_TYPE_IMAGE; require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'from' => array(T_ZBX_INT, O_OPT, P_NZERO, null, null), 'stime' => array(T_ZBX_INT, O_OPT, P_NZERO, null, null), 'border' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'name' => array(T_ZBX_STR, O_OPT, null, null, null), 'width' => array(T_ZBX_INT, O_OPT, null, BETWEEN(0, 65535), null), 'height' => array(T_ZBX_INT, O_OPT, null, BETWEEN(0, 65535), null), 'graphtype' => array(T_ZBX_INT, O_OPT, null, IN('2,3'), null), 'graph3d' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'legend' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'items' => array(T_ZBX_STR, O_OPT, null, null, null)); $isDataValid = check_fields($fields); $items = getRequest('items', array()); asort_by_key($items, 'sortorder'); /* * Permissions */ $dbItems = API::Item()->get(array('webitems' => true, 'itemids' => zbx_objectValues($items, 'itemid'))); $dbItems = zbx_toHash($dbItems, 'itemid'); foreach ($items as $item) { if (!isset($dbItems[$item['itemid']])) { access_deny(); } } /* * Validation */ $types = array(); foreach ($items as $item) { if ($item['type'] == GRAPH_ITEM_SUM) { if (!in_array($item['type'], $types)) { array_push($types, $item['type']); } else {
/** * Check graph data * * @param array $graphs * @param boolean $update * * @return void */ protected function checkInput($graphs, $update = false) { $itemids = array(); foreach ($graphs as $graph) { // no items if (!isset($graph['gitems']) || !is_array($graph['gitems']) || empty($graph['gitems'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Missing items for graph "%1$s".', $graph['name'])); } $fields = array('itemid' => null); foreach ($graph['gitems'] as $gitem) { if (!check_db_fields($fields, $gitem)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Missing "itemid" field for item.')); } // assigning with key preserves unique itemids $itemids[$gitem['itemid']] = $gitem['itemid']; } } $allowedItems = API::Item()->get(array('nodeids' => get_current_nodeid(true), 'itemids' => $itemids, 'webitems' => true, 'editable' => true, 'output' => array('flags'), 'selectItemDiscovery' => array('parent_itemid'), 'preservekeys' => true, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CHILD, ZBX_FLAG_DISCOVERY_CREATED)))); foreach ($itemids as $itemid) { if (!isset($allowedItems[$itemid])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } } parent::checkInput($graphs, $update); $this->checkDiscoveryRuleCount($graphs, $allowedItems); }
/** * Import items. */ protected function processItems() { $allItems = $this->getFormattedItems(); if (empty($allItems)) { return; } $itemsToCreate = array(); $itemsToUpdate = array(); foreach ($allItems as $host => $items) { if (!$this->referencer->isProcessedHost($host)) { continue; } $hostid = $this->referencer->resolveHostOrTemplate($host); foreach ($items as $item) { $item['hostid'] = $hostid; if (isset($item['applications']) && $item['applications']) { $applicationsIds = array(); foreach ($item['applications'] as $application) { if ($applicationId = $this->referencer->resolveApplication($hostid, $application['name'])) { $applicationsIds[] = $applicationId; } else { throw new Exception(_s('Item "%1$s" on "%2$s": application "%3$s" does not exist.', $item['name'], $host, $application['name'])); } } $item['applications'] = $applicationsIds; } if (isset($item['interface_ref']) && $item['interface_ref']) { $item['interfaceid'] = $this->referencer->interfacesCache[$hostid][$item['interface_ref']]; } if (isset($item['valuemap']) && $item['valuemap']) { $valueMapId = $this->referencer->resolveValueMap($item['valuemap']['name']); if (!$valueMapId) { throw new Exception(_s('Cannot find value map "%1$s" used for item "%2$s" on "%3$s".', $item['valuemap']['name'], $item['name'], $host)); } $item['valuemapid'] = $valueMapId; } $itemsId = $this->referencer->resolveItem($hostid, $item['key_']); if ($itemsId) { $item['itemid'] = $itemsId; $itemsToUpdate[] = $item; } else { $itemsToCreate[] = $item; } } } // create/update the items and create a hash hostid->key_->itemid if ($this->options['items']['createMissing'] && $itemsToCreate) { $newItemsIds = API::Item()->create($itemsToCreate); foreach ($newItemsIds['itemids'] as $inum => $itemid) { $item = $itemsToCreate[$inum]; $this->referencer->addItemRef($item['hostid'], $item['key_'], $itemid); } } if ($this->options['items']['updateExisting'] && $itemsToUpdate) { API::Item()->update($itemsToUpdate); } // refresh items because templated ones can be inherited to host and used in triggers, grahs, etc. $this->referencer->refreshItems(); }
/** * Validate graph prototype specific data on Update method. * Get allowed item ID's, check permissions, check if items have at least one prototype, do all general validation, * and check for numeric item types. * * @param array $graphs * @param array $dbGraphs */ protected function validateUpdate(array $graphs, array $dbGraphs) { // check for "itemid" when updating graph prototype with only "gitemid" passed foreach ($graphs as &$graph) { if (isset($graph['gitems'])) { foreach ($graph['gitems'] as &$gitem) { if (isset($gitem['gitemid']) && !isset($gitem['itemid'])) { $dbGitems = zbx_toHash($dbGraphs[$graph['graphid']]['gitems'], 'gitemid'); $gitem['itemid'] = $dbGitems[$gitem['gitemid']]['itemid']; } } unset($gitem); } } unset($graph); $itemIds = $this->validateItemsUpdate($graphs); $allowedItems = API::Item()->get(array('itemids' => $itemIds, 'webitems' => true, 'editable' => true, 'output' => array('itemid', 'name', 'value_type', 'flags'), 'selectItemDiscovery' => array('parent_itemid'), 'preservekeys' => true, 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_PROTOTYPE, ZBX_FLAG_DISCOVERY_CREATED)))); foreach ($itemIds as $itemId) { if (!isset($allowedItems[$itemId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } } $this->checkDiscoveryRuleCount($graphs, $allowedItems); parent::validateUpdate($graphs, $dbGraphs); $allowedValueTypes = array(ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64); foreach ($allowedItems as $item) { if (!in_array($item['value_type'], $allowedValueTypes)) { foreach ($dbGraphs as $dbGraph) { $itemIdsInGraphItems = zbx_objectValues($dbGraph['gitems'], 'itemid'); if (in_array($item['itemid'], $itemIdsInGraphItems)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot add a non-numeric item "%1$s" to graph prototype "%2$s".', $item['name'], $dbGraph['name'])); } } } } }
/** * Get data for item edit page. * * @param array $item item, item prototype or LLD rule to take the data from * @param bool $options['is_discovery_rule'] * * @return array */ function getItemFormData(array $item = array(), array $options = array()) { $data = array('form' => getRequest('form'), 'form_refresh' => getRequest('form_refresh'), 'is_discovery_rule' => !empty($options['is_discovery_rule']), 'parent_discoveryid' => getRequest('parent_discoveryid', !empty($options['is_discovery_rule']) ? getRequest('itemid') : null), 'itemid' => getRequest('itemid'), 'limited' => false, 'interfaceid' => getRequest('interfaceid', 0), 'name' => getRequest('name', ''), 'description' => getRequest('description', ''), 'key' => getRequest('key', ''), 'hostname' => getRequest('hostname'), 'delay' => getRequest('delay', ZBX_ITEM_DELAY_DEFAULT), 'history' => getRequest('history', 90), 'status' => getRequest('status', isset($_REQUEST['form_refresh']) ? 1 : 0), 'type' => getRequest('type', 0), 'snmp_community' => getRequest('snmp_community', 'public'), 'snmp_oid' => getRequest('snmp_oid', 'interfaces.ifTable.ifEntry.ifInOctets.1'), 'port' => getRequest('port', ''), 'value_type' => getRequest('value_type', ITEM_VALUE_TYPE_UINT64), 'data_type' => getRequest('data_type', ITEM_DATA_TYPE_DECIMAL), 'trapper_hosts' => getRequest('trapper_hosts', ''), 'units' => getRequest('units', ''), 'valuemapid' => getRequest('valuemapid', 0), 'params' => getRequest('params', ''), 'multiplier' => getRequest('multiplier', 0), 'delta' => getRequest('delta', 0), 'trends' => getRequest('trends', DAY_IN_YEAR), 'new_application' => getRequest('new_application', ''), 'applications' => getRequest('applications', array()), 'delay_flex' => getRequest('delay_flex', array()), 'new_delay_flex' => getRequest('new_delay_flex', array('delay' => 50, 'period' => ZBX_DEFAULT_INTERVAL)), 'snmpv3_contextname' => getRequest('snmpv3_contextname', ''), 'snmpv3_securityname' => getRequest('snmpv3_securityname', ''), 'snmpv3_securitylevel' => getRequest('snmpv3_securitylevel', 0), 'snmpv3_authprotocol' => getRequest('snmpv3_authprotocol', ITEM_AUTHPROTOCOL_MD5), 'snmpv3_authpassphrase' => getRequest('snmpv3_authpassphrase', ''), 'snmpv3_privprotocol' => getRequest('snmpv3_privprotocol', ITEM_PRIVPROTOCOL_DES), 'snmpv3_privpassphrase' => getRequest('snmpv3_privpassphrase', ''), 'ipmi_sensor' => getRequest('ipmi_sensor', ''), 'authtype' => getRequest('authtype', 0), 'username' => getRequest('username', ''), 'password' => getRequest('password', ''), 'publickey' => getRequest('publickey', ''), 'privatekey' => getRequest('privatekey', ''), 'formula' => getRequest('formula', 1), 'logtimefmt' => getRequest('logtimefmt', ''), 'add_groupid' => getRequest('add_groupid', getRequest('groupid', 0)), 'valuemaps' => null, 'possibleHostInventories' => null, 'alreadyPopulated' => null, 'initial_item_type' => null, 'templates' => array()); // hostid if (!empty($data['parent_discoveryid'])) { $discoveryRule = API::DiscoveryRule()->get(array('itemids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true)); $discoveryRule = reset($discoveryRule); $data['hostid'] = $discoveryRule['hostid']; } else { $data['hostid'] = getRequest('hostid', 0); } // types, http items only for internal processes $data['types'] = item_type2str(); unset($data['types'][ITEM_TYPE_HTTPTEST]); if (!empty($options['is_discovery_rule'])) { unset($data['types'][ITEM_TYPE_AGGREGATE], $data['types'][ITEM_TYPE_CALCULATED], $data['types'][ITEM_TYPE_SNMPTRAP]); } // item if ($item) { $data['item'] = $item; $data['hostid'] = !empty($data['hostid']) ? $data['hostid'] : $data['item']['hostid']; $data['limited'] = $data['item']['templateid'] != 0; // get templates $itemid = $item['itemid']; do { $params = array('itemids' => $itemid, 'output' => array('itemid', 'templateid'), 'selectHosts' => array('name')); if ($data['is_discovery_rule']) { $item = API::DiscoveryRule()->get($params); } else { $params['selectDiscoveryRule'] = array('itemid'); $params['filter'] = array('flags' => null); $item = API::Item()->get($params); } $item = reset($item); if (!empty($item)) { $host = reset($item['hosts']); if (!empty($item['hosts'])) { $host['name'] = CHtml::encode($host['name']); if (bccomp($data['itemid'], $itemid) == 0) { } elseif ($data['is_discovery_rule']) { $data['templates'][] = new CLink($host['name'], 'host_discovery.php?form=update&itemid=' . $item['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } elseif ($item['discoveryRule']) { $data['templates'][] = new CLink($host['name'], 'disc_prototypes.php?form=update&itemid=' . $item['itemid'] . '&parent_discoveryid=' . $item['discoveryRule']['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } else { $data['templates'][] = new CLink($host['name'], 'items.php?form=update&itemid=' . $item['itemid'], 'highlight underline weight_normal'); $data['templates'][] = SPACE . '⇒' . SPACE; } } $itemid = $item['templateid']; } else { break; } } while ($itemid != 0); $data['templates'] = array_reverse($data['templates']); array_shift($data['templates']); } // caption if (!empty($data['is_discovery_rule'])) { $data['caption'] = _('Discovery rule'); } else { $data['caption'] = !empty($data['parent_discoveryid']) ? _('Item prototype') : _('Item'); } // hostname if (empty($data['is_discovery_rule']) && empty($data['hostname'])) { if (!empty($data['hostid'])) { $hostInfo = API::Host()->get(array('hostids' => $data['hostid'], 'output' => array('name'), 'templated_hosts' => true)); $hostInfo = reset($hostInfo); $data['hostname'] = $hostInfo['name']; } else { $data['hostname'] = _('not selected'); } } // fill data from item if (!hasRequest('form_refresh') && ($item || $data['limited'])) { $data['name'] = $data['item']['name']; $data['description'] = $data['item']['description']; $data['key'] = $data['item']['key_']; $data['interfaceid'] = $data['item']['interfaceid']; $data['type'] = $data['item']['type']; $data['snmp_community'] = $data['item']['snmp_community']; $data['snmp_oid'] = $data['item']['snmp_oid']; $data['port'] = $data['item']['port']; $data['value_type'] = $data['item']['value_type']; $data['data_type'] = $data['item']['data_type']; $data['trapper_hosts'] = $data['item']['trapper_hosts']; $data['units'] = $data['item']['units']; $data['valuemapid'] = $data['item']['valuemapid']; $data['multiplier'] = $data['item']['multiplier']; $data['hostid'] = $data['item']['hostid']; $data['params'] = $data['item']['params']; $data['snmpv3_contextname'] = $data['item']['snmpv3_contextname']; $data['snmpv3_securityname'] = $data['item']['snmpv3_securityname']; $data['snmpv3_securitylevel'] = $data['item']['snmpv3_securitylevel']; $data['snmpv3_authprotocol'] = $data['item']['snmpv3_authprotocol']; $data['snmpv3_authpassphrase'] = $data['item']['snmpv3_authpassphrase']; $data['snmpv3_privprotocol'] = $data['item']['snmpv3_privprotocol']; $data['snmpv3_privpassphrase'] = $data['item']['snmpv3_privpassphrase']; $data['ipmi_sensor'] = $data['item']['ipmi_sensor']; $data['authtype'] = $data['item']['authtype']; $data['username'] = $data['item']['username']; $data['password'] = $data['item']['password']; $data['publickey'] = $data['item']['publickey']; $data['privatekey'] = $data['item']['privatekey']; $data['logtimefmt'] = $data['item']['logtimefmt']; $data['new_application'] = getRequest('new_application', ''); if (!$data['is_discovery_rule']) { $data['formula'] = $data['item']['formula']; } if (!$data['limited'] || !isset($_REQUEST['form_refresh'])) { $data['delay'] = $data['item']['delay']; if (($data['type'] == ITEM_TYPE_TRAPPER || $data['type'] == ITEM_TYPE_SNMPTRAP) && $data['delay'] == 0) { $data['delay'] = ZBX_ITEM_DELAY_DEFAULT; } $data['history'] = $data['item']['history']; $data['status'] = $data['item']['status']; $data['delta'] = $data['item']['delta']; $data['trends'] = $data['item']['trends']; $db_delay_flex = $data['item']['delay_flex']; if (isset($db_delay_flex)) { $arr_of_dellays = explode(';', $db_delay_flex); foreach ($arr_of_dellays as $one_db_delay) { $arr_of_delay = explode('/', $one_db_delay); if (!isset($arr_of_delay[0]) || !isset($arr_of_delay[1])) { continue; } array_push($data['delay_flex'], array('delay' => $arr_of_delay[0], 'period' => $arr_of_delay[1])); } } $data['applications'] = array_unique(zbx_array_merge($data['applications'], get_applications_by_itemid($data['itemid']))); } } // applications if (count($data['applications']) == 0) { array_push($data['applications'], 0); } $data['db_applications'] = DBfetchArray(DBselect('SELECT DISTINCT a.applicationid,a.name' . ' FROM applications a' . ' WHERE a.hostid=' . zbx_dbstr($data['hostid']))); order_result($data['db_applications'], 'name'); // interfaces $data['interfaces'] = API::HostInterface()->get(array('hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND)); // valuemapid if ($data['limited']) { if (!empty($data['valuemapid'])) { if ($map_data = DBfetch(DBselect('SELECT v.name FROM valuemaps v WHERE v.valuemapid=' . zbx_dbstr($data['valuemapid'])))) { $data['valuemaps'] = $map_data['name']; } } } else { $data['valuemaps'] = DBfetchArray(DBselect('SELECT v.* FROM valuemaps v')); order_result($data['valuemaps'], 'name'); } // possible host inventories if (empty($data['parent_discoveryid'])) { $data['possibleHostInventories'] = getHostInventories(); // get already populated fields by other items $data['alreadyPopulated'] = API::item()->get(array('output' => array('inventory_link'), 'filter' => array('hostid' => $data['hostid']), 'nopermissions' => true)); $data['alreadyPopulated'] = zbx_toHash($data['alreadyPopulated'], 'inventory_link'); } // template $data['is_template'] = isTemplate($data['hostid']); // unset snmpv3 fields if ($data['type'] != ITEM_TYPE_SNMPV3) { $data['snmpv3_contextname'] = ''; $data['snmpv3_securityname'] = ''; $data['snmpv3_securitylevel'] = ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV; $data['snmpv3_authprotocol'] = ITEM_AUTHPROTOCOL_MD5; $data['snmpv3_authpassphrase'] = ''; $data['snmpv3_privprotocol'] = ITEM_PRIVPROTOCOL_DES; $data['snmpv3_privpassphrase'] = ''; } // unset ssh auth fields if ($data['type'] != ITEM_TYPE_SSH) { $data['authtype'] = ITEM_AUTHTYPE_PASSWORD; $data['publickey'] = ''; $data['privatekey'] = ''; } return $data; }
$itemId = $item['itemid']; } else { error(_('Unknown host item, no such item in selected host')); } } } } else { if (preg_match('/^([a-z]+)\\[([=><]{1,2})\\]$/i', $exprType, $matches)) { $function = $matches[1]; $operator = $matches[2]; if (!isset($functions[$exprType])) { unset($function); } } // fetch item $item = API::Item()->get(['output' => ['itemid', 'hostid', 'name', 'key_', 'value_type'], 'selectHosts' => ['host', 'name'], 'itemids' => $itemId, 'webitems' => true, 'filter' => ['flags' => null]]); $item = reset($item); } if ($itemId) { $items = CMacrosResolverHelper::resolveItemNames([$item]); $item = $items[0]; $itemValueType = $item['value_type']; $itemKey = $item['key_']; $itemHostData = reset($item['hosts']); $description = $itemHostData['name'] . NAME_DELIMITER . $item['name_expanded']; } else { $itemKey = ''; $description = ''; $itemValueType = null; } if (is_null($paramType) && isset($functions[$exprType]['params']['M'])) {
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $eventIds = array_keys($result); // adding hosts if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) { // trigger events if ($options['object'] == EVENT_OBJECT_TRIGGER) { $query = DBselect('SELECT e.eventid,i.hostid' . ' FROM events e,functions f,items i' . ' WHERE ' . dbConditionInt('e.eventid', $eventIds) . ' AND e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['object']) . ' AND e.source=' . zbx_dbstr($options['source'])); } elseif ($options['object'] == EVENT_OBJECT_ITEM || $options['object'] == EVENT_OBJECT_LLDRULE) { $query = DBselect('SELECT e.eventid,i.hostid' . ' FROM events e,items i' . ' WHERE ' . dbConditionInt('e.eventid', $eventIds) . ' AND e.objectid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['object']) . ' AND e.source=' . zbx_dbstr($options['source'])); } $relationMap = new CRelationMap(); while ($relation = DBfetch($query)) { $relationMap->addRelation($relation['eventid'], $relation['hostid']); } $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $hosts, 'hosts'); } // adding the related object if ($options['selectRelatedObject'] !== null && $options['selectRelatedObject'] != API_OUTPUT_COUNT && $options['object'] != EVENT_OBJECT_AUTOREGHOST) { $relationMap = new CRelationMap(); foreach ($result as $event) { $relationMap->addRelation($event['eventid'], $event['objectid']); } switch ($options['object']) { case EVENT_OBJECT_TRIGGER: $api = API::Trigger(); break; case EVENT_OBJECT_DHOST: $api = API::DHost(); break; case EVENT_OBJECT_DSERVICE: $api = API::DService(); break; case EVENT_OBJECT_ITEM: $api = API::Item(); break; case EVENT_OBJECT_LLDRULE: $api = API::DiscoveryRule(); break; } $objects = $api->get(array('output' => $options['selectRelatedObject'], $api->pkOption() => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $objects, 'relatedObject'); } // adding alerts if ($options['select_alerts'] !== null && $options['select_alerts'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'eventid', 'alertid', 'alerts'); $alerts = API::Alert()->get(array('output' => $options['select_alerts'], 'selectMediatypes' => API_OUTPUT_EXTEND, 'alertids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true, 'sortfield' => 'clock', 'sortorder' => ZBX_SORT_DOWN)); $result = $relationMap->mapMany($result, $alerts, 'alerts'); } // adding acknowledges if ($options['select_acknowledges'] !== null) { if ($options['select_acknowledges'] != API_OUTPUT_COUNT) { // create the base query $sqlParts = API::getApiService()->createSelectQueryParts('acknowledges', 'a', array('output' => $this->outputExtend($options['select_acknowledges'], array('acknowledgeid', 'eventid', 'clock')), 'filter' => array('eventid' => $eventIds))); $sqlParts['order'][] = 'a.clock DESC'; // if the user data is requested via extended output or specified fields, join the users table $userFields = array('alias', 'name', 'surname'); $requestUserData = array(); foreach ($userFields as $userField) { if ($this->outputIsRequested($userField, $options['select_acknowledges'])) { $requestUserData[] = $userField; } } if ($requestUserData) { foreach ($requestUserData as $userField) { $sqlParts = $this->addQuerySelect('u.' . $userField, $sqlParts); } $sqlParts['from'][] = 'users u'; $sqlParts['where'][] = 'a.userid=u.userid'; } $acknowledges = DBFetchArrayAssoc(DBselect($this->createSelectQueryFromParts($sqlParts)), 'acknowledgeid'); $relationMap = $this->createRelationMap($acknowledges, 'eventid', 'acknowledgeid'); $acknowledges = $this->unsetExtraFields($acknowledges, array('eventid', 'acknowledgeid', 'clock'), $options['select_acknowledges']); $result = $relationMap->mapMany($result, $acknowledges, 'acknowledges'); } else { $acknowledges = DBFetchArrayAssoc(DBselect('SELECT COUNT(a.acknowledgeid) AS rowscount,a.eventid' . ' FROM acknowledges a' . ' WHERE ' . dbConditionInt('a.eventid', $eventIds) . ' GROUP BY a.eventid'), 'eventid'); foreach ($result as &$event) { if (isset($acknowledges[$event['eventid']])) { $event['acknowledges'] = $acknowledges[$event['eventid']]['rowscount']; } else { $event['acknowledges'] = 0; } } unset($event); } } return $result; }
/** * Takes sysmap selements array, applies filtering by application to triggers and returns sysmap selements array. * * @param array $selements selements of current sysmap * @param array $selementHostApplicationFilters a list of application filters applied to each host under each element * @see getSelementHostApplicationFilters() * @param array $triggersFromMonitoredHosts triggers that are relevant to filtering * @param array $subSysmapTriggerIdToSelementIds a map of triggers in sysmaps to selement IDs * * @return array */ function filterSysmapTriggers(array $selements, array $selementHostApplicationFilters, array $triggersFromMonitoredHosts, array $subSysmapTriggerIdToSelementIds) { // pick only host, host group or map selements $filterableSelements = array(); foreach ($selements as $selementId => $selement) { if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST || $selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP || $selement['elementtype'] == SYSMAP_ELEMENT_TYPE_MAP) { $filterableSelements[$selementId] = $selement; } } // calculate list of triggers that might get removed from $selement['triggers'] $triggersToFilter = array(); foreach ($filterableSelements as $selementId => $selement) { foreach ($selement['triggers'] as $triggerId) { if (!isset($triggersFromMonitoredHosts[$triggerId])) { continue; } $trigger = $triggersFromMonitoredHosts[$triggerId]; foreach ($trigger['hosts'] as $host) { $hostId = $host['hostid']; if (isset($selementHostApplicationFilters[$selementId][$hostId])) { $triggersToFilter[$triggerId] = $trigger; } } } } // if there are no triggers to filter if (!$triggersToFilter) { return $selements; } // produce mapping of trigger to application names it is related to and produce mapping of host to triggers $itemIds = array(); foreach ($triggersToFilter as $trigger) { foreach ($trigger['items'] as $item) { $itemIds[$item['itemid']] = $item['itemid']; } } $items = API::Item()->get(array('output' => array('itemid'), 'selectApplications' => array('name'), 'itemids' => $itemIds, 'webitems' => true, 'preservekeys' => true)); $triggerApplications = array(); $hostIdToTriggers = array(); foreach ($triggersToFilter as $trigger) { $triggerId = $trigger['triggerid']; foreach ($trigger['items'] as $item) { foreach ($items[$item['itemid']]['applications'] as $application) { $triggerApplications[$triggerId][$application['name']] = true; } } foreach ($trigger['hosts'] as $host) { $hostIdToTriggers[$host['hostid']][$triggerId] = $trigger; } } foreach ($filterableSelements as $selementId => &$selement) { // walk through each host of a submap and apply its filters to all its triggers foreach ($selement['hosts'] as $hostId) { // skip hosts that don't have any filters or triggers to filter if (!isset($hostIdToTriggers[$hostId]) || !isset($selementHostApplicationFilters[$selementId][$hostId])) { continue; } // remove the triggers that don't have applications or don't match the filter $filteredApplicationNames = $selementHostApplicationFilters[$selementId][$hostId]; foreach ($hostIdToTriggers[$hostId] as $trigger) { $triggerId = $trigger['triggerid']; // skip if this trigger is standalone trigger and those are not filtered if (isset($subSysmapTriggerIdToSelementIds[$triggerId]) && isset($subSysmapTriggerIdToSelementIds[$triggerId][$selementId])) { continue; } $applicationNamesForTrigger = isset($triggerApplications[$triggerId]) ? array_keys($triggerApplications[$triggerId]) : array(); if (!array_intersect($applicationNamesForTrigger, $filteredApplicationNames)) { unset($selement['triggers'][$triggerId]); } } } } unset($selement); // put back updated selements foreach ($filterableSelements as $selementId => $selement) { $selements[$selementId] = $selement; } return $selements; }
/** * Delete Host. * * @param array $hostIds * @param bool $nopermissions * * @return array */ public function delete(array $hostIds, $nopermissions = false) { $this->validateDelete($hostIds, $nopermissions); // delete the discovery rules first $delRules = API::DiscoveryRule()->get(['output' => ['itemid'], 'hostids' => $hostIds, 'nopermissions' => true, 'preservekeys' => true]); if ($delRules) { API::DiscoveryRule()->delete(array_keys($delRules), true); } // delete the items $delItems = API::Item()->get(['templateids' => $hostIds, 'output' => ['itemid'], 'nopermissions' => true, 'preservekeys' => true]); if ($delItems) { API::Item()->delete(array_keys($delItems), true); } // delete web tests $delHttptests = []; $dbHttptests = get_httptests_by_hostid($hostIds); while ($dbHttptest = DBfetch($dbHttptests)) { $delHttptests[$dbHttptest['httptestid']] = $dbHttptest['httptestid']; } if (!empty($delHttptests)) { API::HttpTest()->delete($delHttptests, true); } // delete screen items DB::delete('screens_items', ['resourceid' => $hostIds, 'resourcetype' => SCREEN_RESOURCE_HOST_TRIGGERS]); // delete host from maps if (!empty($hostIds)) { DB::delete('sysmaps_elements', ['elementtype' => SYSMAP_ELEMENT_TYPE_HOST, 'elementid' => $hostIds]); } // disable actions // actions from conditions $actionids = []; $sql = 'SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_HOST . ' AND ' . dbConditionString('value', $hostIds); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } // actions from operations $sql = 'SELECT DISTINCT o.actionid' . ' FROM operations o, opcommand_hst oh' . ' WHERE o.operationid=oh.operationid' . ' AND ' . dbConditionInt('oh.hostid', $hostIds); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } if (!empty($actionids)) { $update = []; $update[] = ['values' => ['status' => ACTION_STATUS_DISABLED], 'where' => ['actionid' => $actionids]]; DB::update('actions', $update); } // delete action conditions DB::delete('conditions', ['conditiontype' => CONDITION_TYPE_HOST, 'value' => $hostIds]); // delete action operation commands $operationids = []; $sql = 'SELECT DISTINCT oh.operationid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('oh.hostid', $hostIds); $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $operationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('opcommand_hst', ['hostid' => $hostIds]); // delete empty operations $delOperationids = []; $sql = 'SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS(SELECT oh.opcommand_hstid FROM opcommand_hst oh WHERE oh.operationid=o.operationid)'; $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('operations', ['operationid' => $delOperationids]); $hosts = API::Host()->get(['output' => ['hostid', 'name'], 'hostids' => $hostIds, 'nopermissions' => true]); // delete host inventory DB::delete('host_inventory', ['hostid' => $hostIds]); // delete host applications DB::delete('applications', ['hostid' => $hostIds]); // delete host DB::delete('hosts', ['hostid' => $hostIds]); // TODO: remove info from API foreach ($hosts as $host) { info(_s('Deleted: Host "%1$s".', $host['name'])); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['name'], 'hosts', NULL, NULL); } // remove Monitoring > Latest data toggle profile values related to given hosts DB::delete('profiles', ['idx' => 'web.latest.toggle_other', 'idx2' => $hostIds]); return ['hostids' => $hostIds]; }
/** * Delete Item prototypes. * * @param array $prototypeids * @param bool $nopermissions * * @return array */ public function delete(array $prototypeids, $nopermissions = false) { if (empty($prototypeids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $prototypeids = array_keys(array_flip($prototypeids)); $options = array('itemids' => $prototypeids, 'editable' => true, 'preservekeys' => true, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => array('name')); $delItemPrototypes = $this->get($options); // TODO: remove $nopermissions hack if (!$nopermissions) { foreach ($prototypeids as $prototypeid) { if (!isset($delItemPrototypes[$prototypeid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } if ($delItemPrototypes[$prototypeid]['templateid'] != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete templated items')); } } } // first delete child items $parentItemids = $prototypeids; $childPrototypeids = array(); do { $dbItems = DBselect('SELECT itemid FROM items WHERE ' . dbConditionInt('templateid', $parentItemids)); $parentItemids = array(); while ($dbItem = DBfetch($dbItems)) { $parentItemids[$dbItem['itemid']] = $dbItem['itemid']; $childPrototypeids[$dbItem['itemid']] = $dbItem['itemid']; } } while ($parentItemids); $options = array('output' => API_OUTPUT_EXTEND, 'itemids' => $childPrototypeids, 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => array('name')); $delItemPrototypesChilds = $this->get($options); $delItemPrototypes = array_merge($delItemPrototypes, $delItemPrototypesChilds); $prototypeids = array_merge($prototypeids, $childPrototypeids); // delete graphs with this item prototype $delGraphPrototypes = API::GraphPrototype()->get(array('output' => array(), 'itemids' => $prototypeids, 'nopermissions' => true, 'preservekeys' => true)); if ($delGraphPrototypes) { API::GraphPrototype()->delete(array_keys($delGraphPrototypes), true); } // check if any graphs are referencing this item $this->checkGraphReference($prototypeids); // CREATED ITEMS $createdItems = array(); $sql = 'SELECT itemid FROM item_discovery WHERE ' . dbConditionInt('parent_itemid', $prototypeids); $dbItems = DBselect($sql); while ($item = DBfetch($dbItems)) { $createdItems[$item['itemid']] = $item['itemid']; } if ($createdItems) { API::Item()->delete($createdItems, true); } // TRIGGER PROTOTYPES $delTriggerPrototypes = API::TriggerPrototype()->get(array('output' => array(), 'itemids' => $prototypeids, 'nopermissions' => true, 'preservekeys' => true)); if ($delTriggerPrototypes) { API::TriggerPrototype()->delete(array_keys($delTriggerPrototypes), true); } // screen items DB::delete('screens_items', array('resourceid' => $prototypeids, 'resourcetype' => array(SCREEN_RESOURCE_LLD_SIMPLE_GRAPH))); // ITEM PROTOTYPES DB::delete('items', array('itemid' => $prototypeids)); // TODO: remove info from API foreach ($delItemPrototypes as $item) { $host = reset($item['hosts']); info(_s('Deleted: Item prototype "%1$s" on "%2$s".', $item['name'], $host['name'])); } return array('prototypeids' => $prototypeids); }
/** * Delete web scenario. * * @param array $httpTestIds * @param bool $nopermissions * * @return array */ public function delete(array $httpTestIds, $nopermissions = false) { if (empty($httpTestIds)) { return true; } $delHttpTests = $this->get(array('httptestids' => $httpTestIds, 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'selectHosts' => API_OUTPUT_EXTEND, 'preservekeys' => true)); if (!$nopermissions) { foreach ($httpTestIds as $httpTestId) { if (!empty($delHttpTests[$httpTestId]['templateid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot delete templated web scenario "%1$s".', $delHttpTests[$httpTestId]['name'])); } if (!isset($delHttpTests[$httpTestId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } } } $parentHttpTestIds = $httpTestIds; $childHttpTestIds = array(); do { $dbTests = DBselect('SELECT ht.httptestid FROM httptest ht WHERE ' . dbConditionInt('ht.templateid', $parentHttpTestIds)); $parentHttpTestIds = array(); while ($dbTest = DBfetch($dbTests)) { $parentHttpTestIds[] = $dbTest['httptestid']; $childHttpTestIds[$dbTest['httptestid']] = $dbTest['httptestid']; } } while (!empty($parentHttpTestIds)); $options = array('httptestids' => $childHttpTestIds, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => API_OUTPUT_EXTEND); $delHttpTestChilds = $this->get($options); $delHttpTests = zbx_array_merge($delHttpTests, $delHttpTestChilds); $httpTestIds = array_merge($httpTestIds, $childHttpTestIds); $itemidsDel = array(); $dbTestItems = DBselect('SELECT hsi.itemid' . ' FROM httptestitem hsi' . ' WHERE ' . dbConditionInt('hsi.httptestid', $httpTestIds)); while ($testitem = DBfetch($dbTestItems)) { $itemidsDel[] = $testitem['itemid']; } $dbStepItems = DBselect('SELECT DISTINCT hsi.itemid' . ' FROM httpstepitem hsi,httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', $httpTestIds) . ' AND hs.httpstepid=hsi.httpstepid'); while ($stepitem = DBfetch($dbStepItems)) { $itemidsDel[] = $stepitem['itemid']; } if (!empty($itemidsDel)) { API::Item()->delete($itemidsDel, true); } DB::delete('httptest', array('httptestid' => $httpTestIds)); // TODO: REMOVE foreach ($delHttpTests as $httpTest) { $host = reset($httpTest['hosts']); info(_s('Deleted: Web scenario "%1$s" on "%2$s".', $httpTest['name'], $host['host'])); add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_SCENARIO, 'Web scenario [' . $httpTest['name'] . '] [' . $httpTest['httptestid'] . '] Host [' . $host['name'] . ']'); } return array('httptestids' => $httpTestIds); }