/** * Import maps. * * @param array $maps * * @return void */ public function import(array $maps) { $maps = zbx_toHash($maps, 'name'); $this->checkCircularMapReferences($maps); do { $im = $this->getIndependentMaps($maps); $mapsToCreate = array(); $mapsToUpdate = array(); foreach ($im as $name) { $map = $maps[$name]; unset($maps[$name]); $map = $this->resolveMapReferences($map); if ($mapId = $this->referencer->resolveMap($map['name'])) { $map['sysmapid'] = $mapId; $mapsToUpdate[] = $map; } else { $mapsToCreate[] = $map; } } if ($this->options['maps']['createMissing'] && $mapsToCreate) { $newMapIds = API::Map()->create($mapsToCreate); foreach ($mapsToCreate as $num => $map) { $mapId = $newMapIds['sysmapids'][$num]; $this->referencer->addMapRef($map['name'], $mapId); } } if ($this->options['maps']['updateExisting'] && $mapsToUpdate) { API::Map()->update($mapsToUpdate); } } while (!empty($im)); }
/** * Validates the given condition formula and checks if the given conditions match the formula. * * @param array $object * * @return bool */ public function validate($object) { // validate only custom expressions if ($object['evaltype'] != CONDITION_EVAL_TYPE_EXPRESSION) { return true; } // check if the formula is valid $parser = new CConditionFormula(); if (!$parser->parse($object['formula'])) { $this->error($this->messageInvalidFormula, $object['formula'], $parser->error); return false; } // check that all conditions used in the formula are defined in the "conditions" array $conditions = zbx_toHash($object['conditions'], 'formulaid'); $constants = array_unique(zbx_objectValues($parser->constants, 'value')); foreach ($constants as $constant) { if (!array_key_exists($constant, $conditions)) { $this->error($this->messageMissingCondition, $constant, $object['formula']); return false; } unset($conditions[$constant]); } // check that the "conditions" array has no unused conditions if ($conditions) { $condition = reset($conditions); $this->error($this->messageUnusedCondition, $condition['formulaid'], $object['formula']); return false; } return true; }
function check_permission_for_action_conditions($conditions) { global $USER_DETAILS; if (USER_TYPE_SUPER_ADMIN == $USER_DETAILS['type']) { return true; } $groupids = array(); $hostids = array(); $triggerids = array(); foreach ($conditions as $ac_data) { if ($ac_data['operator'] != 0) { continue; } switch ($ac_data['type']) { case CONDITION_TYPE_HOST_GROUP: $groupids[$ac_data['value']] = $ac_data['value']; break; case CONDITION_TYPE_HOST: case CONDITION_TYPE_HOST_TEMPLATE: $hostids[$ac_data['value']] = $ac_data['value']; break; case CONDITION_TYPE_TRIGGER: $triggerids[$ac_data['value']] = $ac_data['value']; break; } } $options = array('groupids' => $groupids, 'editable' => 1); try { $groups = CHostgroup::get($options); $groups = zbx_toHash($groups, 'groupid'); foreach ($groupids as $hgnum => $groupid) { if (!isset($groups[$groupid])) { throw new Exception(S_INCORRECT_GROUP); } } $options = array('hostids' => $hostids, 'editable' => 1); $hosts = CHost::get($options); $hosts = zbx_toHash($hosts, 'hostid'); foreach ($hostids as $hnum => $hostid) { if (!isset($hosts[$hostid])) { throw new Exception(S_INCORRECT_HOST); } } $options = array('triggerids' => $triggerids, 'editable' => 1); $triggers = CTrigger::get($options); $triggers = zbx_toHash($triggers, 'triggerid'); foreach ($triggerids as $hnum => $triggerid) { if (!isset($triggers[$triggerid])) { throw new Exception(S_INCORRECT_TRIGGER); } } } catch (Exception $e) { // throw new Exception($e->getMessage()); // error($e->getMessage()); return false; } return true; }
public function __construct(&$form, $name, $value = null, $size = 10) { $this->form =& $form; $this->name = $name . '_tweenbox'; $this->varname = $name; $this->value = zbx_toHash($value); $this->id_l = $this->varname . '_left'; $this->id_r = $this->varname . '_right'; $this->lbox = new CListBox($this->id_l, null, $size); $this->rbox = new CListBox($this->id_r, null, $size); $this->lbox->setAttribute('style', 'width: 280px;'); $this->rbox->setAttribute('style', 'width: 280px;'); }
/** * Import maps. * * @param array $maps * * @return void */ public function import(array $maps) { $maps = zbx_toHash($maps, 'name'); $this->checkCircularMapReferences($maps); $maps = $this->resolveMapElementReferences($maps); /* * Get all importable maps with removed elements and links. First import maps and then update maps with * elements and links from import file. This way we make sure we are able to resolve any references * between maps and links that are imported. */ $mapsWithoutElements = $this->getMapsWithoutElements($maps); $mapsToProcess = array('createMissing' => array(), 'updateExisting' => array()); foreach ($mapsWithoutElements as $mapName => $mapWithoutElements) { $mapId = $this->referencer->resolveMap($mapWithoutElements['name']); if ($mapId) { // Update sysmapid in source map too. $mapWithoutElements['sysmapid'] = $mapId; $maps[$mapName]['sysmapid'] = $mapId; $mapsToProcess['updateExisting'][] = $mapWithoutElements; } else { $mapsToProcess['createMissing'][] = $mapWithoutElements; } } if ($this->options['maps']['createMissing'] && $mapsToProcess['createMissing']) { $newMapIds = API::Map()->create($mapsToProcess['createMissing']); foreach ($mapsToProcess['createMissing'] as $num => $map) { $mapId = $newMapIds['sysmapids'][$num]; $this->referencer->addMapRef($map['name'], $mapId); $maps[$map['name']]['sysmapid'] = $mapId; } } if ($this->options['maps']['updateExisting'] && $mapsToProcess['updateExisting']) { API::Map()->update($mapsToProcess['updateExisting']); } // Form an array of maps that need to be updated with elements and links, respecting the create/update options. $mapsToUpdate = array(); foreach ($mapsToProcess as $mapActionKey => $mapArray) { if ($this->options['maps'][$mapActionKey] && $mapsToProcess[$mapActionKey]) { foreach ($mapArray as $mapItem) { $map = array('sysmapid' => $maps[$mapItem['name']]['sysmapid'], 'name' => $mapItem['name'], 'selements' => $maps[$mapItem['name']]['selements'], 'links' => $maps[$mapItem['name']]['links']); $map = $this->resolveMapReferences($map); // Remove the map name so API does not make an update query to the database. unset($map['name']); $mapsToUpdate[] = $map; } } } if ($mapsToUpdate) { API::Map()->update($mapsToUpdate); } }
public function __construct(&$form, $name, $value = null, $size = 10) { zbx_add_post_js('if (IE7) $$("select option[disabled]").each(function(e) { e.setStyle({color: "gray"}); });'); $this->form =& $form; $this->name = $name . '_tweenbox'; $this->varname = $name; $this->value = zbx_toHash($value); $this->id_l = $this->varname . '_left'; $this->id_r = $this->varname . '_right'; $this->lbox = new CListBox($this->id_l, null, $size); $this->rbox = new CListBox($this->id_r, null, $size); $this->lbox->setAttribute('style', 'width: 280px;'); $this->rbox->setAttribute('style', 'width: 280px;'); }
protected function doAction() { $filter = ['groupids' => null, 'maintenance' => null, 'severity' => null, 'trigger_name' => '', 'extAck' => 0]; if (CProfile::get('web.dashconf.filter.enable', 0) == 1) { // groups if (CProfile::get('web.dashconf.groups.grpswitch', 0) == 0) { // null mean all groups $filter['groupids'] = null; } else { $filter['groupids'] = zbx_objectValues(CFavorite::get('web.dashconf.groups.groupids'), 'value'); $hideHostGroupIds = zbx_objectValues(CFavorite::get('web.dashconf.groups.hide.groupids'), 'value'); if ($hideHostGroupIds) { // get all groups if no selected groups defined if (!$filter['groupids']) { $dbHostGroups = API::HostGroup()->get(['output' => ['groupid']]); $filter['groupids'] = zbx_objectValues($dbHostGroups, 'groupid'); } $filter['groupids'] = array_diff($filter['groupids'], $hideHostGroupIds); // get available hosts $dbAvailableHosts = API::Host()->get(['groupids' => $filter['groupids'], 'output' => ['hostid']]); $availableHostIds = zbx_objectValues($dbAvailableHosts, 'hostid'); $dbDisabledHosts = API::Host()->get(['groupids' => $hideHostGroupIds, 'output' => ['hostid']]); $disabledHostIds = zbx_objectValues($dbDisabledHosts, 'hostid'); $filter['hostids'] = array_diff($availableHostIds, $disabledHostIds); } else { if (!$filter['groupids']) { // null mean all groups $filter['groupids'] = null; } } } // hosts $maintenance = CProfile::get('web.dashconf.hosts.maintenance', 1); $filter['maintenance'] = $maintenance == 0 ? 0 : null; // triggers $severity = CProfile::get('web.dashconf.triggers.severity', null); $filter['severity'] = zbx_empty($severity) ? null : explode(';', $severity); $filter['severity'] = zbx_toHash($filter['severity']); $filter['trigger_name'] = CProfile::get('web.dashconf.triggers.name', ''); $config = select_config(); $filter['extAck'] = $config['event_ack_enable'] ? CProfile::get('web.dashconf.events.extAck', 0) : 0; } $this->setResponse(new CControllerResponseData(['filter' => $filter, 'user' => ['debug_mode' => $this->getDebugMode()]])); }
/** * Validates the given condition formula and checks if the given conditions match the formula. * * @param array $object * * @return bool */ public function validate($object) { if ($object['evaltype'] == CONDITION_EVAL_TYPE_AND) { // get triggers count in formula $trigger_count = 0; foreach ($object['conditions'] as $condition) { if (array_key_exists('conditiontype', $condition) && array_key_exists('operator', $condition) && $condition['conditiontype'] == CONDITION_TYPE_TRIGGER && $condition['operator'] == CONDITION_OPERATOR_EQUAL) { $trigger_count++; } } // check if multiple triggers are compared with AND if ($trigger_count > 1) { $this->error($this->messageAndWithSeveralTriggers); return false; } } // validate only custom expressions if ($object['evaltype'] != CONDITION_EVAL_TYPE_EXPRESSION) { return true; } // check if the formula is valid $parser = new CConditionFormula(); if (!$parser->parse($object['formula'])) { $this->error($this->messageInvalidFormula, $object['formula'], $parser->error); return false; } // check that all conditions used in the formula are defined in the "conditions" array $conditions = zbx_toHash($object['conditions'], 'formulaid'); $constants = array_unique(zbx_objectValues($parser->constants, 'value')); foreach ($constants as $constant) { if (!array_key_exists($constant, $conditions)) { $this->error($this->messageMissingCondition, $constant, $object['formula']); return false; } unset($conditions[$constant]); } // check that the "conditions" array has no unused conditions if ($conditions) { $condition = reset($conditions); $this->error($this->messageUnusedCondition, $condition['formulaid'], $object['formula']); return false; } return true; }
/** * Import screens. * * @param array $screens * * @return mixed */ public function import(array $screens) { $screens = zbx_toHash($screens, 'name'); $this->checkCircularScreenReferences($screens); do { $independentScreens = $this->getIndependentScreens($screens); $screensToCreate = array(); $screensToUpdate = array(); foreach ($independentScreens as $name) { $screen = $screens[$name]; unset($screens[$name]); $screen = $this->resolveScreenReferences($screen); if ($screenId = $this->referencer->resolveScreen($screen['name'])) { $screen['screenid'] = $screenId; $screensToUpdate[] = $screen; } else { $screensToCreate[] = $screen; } } if ($this->options['screens']['createMissing'] && $screensToCreate) { $newScreenIds = API::Screen()->create($screensToCreate); foreach ($screensToCreate as $num => $newScreen) { $screenidId = $newScreenIds['screenids'][$num]; $this->referencer->addScreenRef($newScreen['name'], $screenidId); } } if ($this->options['screens']['updateExisting'] && $screensToUpdate) { API::Screen()->update($screensToUpdate); } } while (!empty($independentScreens)); // if there are screens left in $screens, then they have unresolved references foreach ($screens as $screen) { $unresolvedReferences = array(); foreach ($screen['screenitems'] as $screenItem) { if ($screenItem['resourcetype'] == SCREEN_RESOURCE_SCREEN && !$this->referencer->resolveScreen($screenItem['resource']['name'])) { $unresolvedReferences[] = $screenItem['resource']['name']; } } $unresolvedReferences = array_unique($unresolvedReferences); throw new Exception(_n('Cannot import screen "%1$s": subscreen "%2$s" does not exist.', 'Cannot import screen "%1$s": subscreens "%2$s" do not exist.', $screen['name'], implode(', ', $unresolvedReferences), count($unresolvedReferences))); } }
} $mapInfo = array(); foreach ($map['selements'] as $selement) { // if element use icon map and icon map is set for map, and is host like element, we use default icon map icon if ($map['iconmapid'] && $selement['use_iconmap'] && ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST || $selement['elementtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP && $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS)) { $iconid = $defaultAutoIconId; } else { $iconid = $selement['iconid_off']; } $mapInfo[$selement['selementid']] = array('iconid' => $iconid, 'icon_type' => SYSMAP_ELEMENT_ICON_OFF); $mapInfo[$selement['selementid']]['name'] = $selement['elementtype'] == SYSMAP_ELEMENT_TYPE_IMAGE ? _('Image') : $selement['elementName']; } $allLinks = true; } else { // we need selements to be a hash for further processing $map['selements'] = zbx_toHash($map['selements'], 'selementid'); add_triggerExpressions($map['selements']); $areas = populateFromMapAreas($map); $mapInfo = getSelementsInfo($map, array('severity_min' => get_request('severity_min'))); processAreasCoordinates($map, $areas, $mapInfo); $allLinks = false; } /* * Draw map */ drawMapConnectors($im, $map, $mapInfo, $allLinks); if (!isset($_REQUEST['noselements'])) { drawMapHighligts($im, $map, $mapInfo); drawMapSelements($im, $map, $mapInfo); } $expandMacros = get_request('expand_macros', true);
/** * Get Service data * * @param _array $options * @param array $options['nodeids'] Node IDs * @param array $options['groupids'] ServiceGroup IDs * @param array $options['hostids'] Service IDs * @param boolean $options['monitored_hosts'] only monitored Services * @param boolean $options['templated_hosts'] include templates in result * @param boolean $options['with_items'] only with items * @param boolean $options['with_historical_items'] only with historical items * @param boolean $options['with_triggers'] only with triggers * @param boolean $options['with_httptests'] only with http tests * @param boolean $options['with_graphs'] only with graphs * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins * @param boolean $options['selectGroups'] select ServiceGroups * @param boolean $options['selectTemplates'] select Templates * @param boolean $options['selectItems'] select Items * @param boolean $options['selectTriggers'] select Triggers * @param boolean $options['selectGraphs'] select Graphs * @param boolean $options['selectApplications'] select Applications * @param boolean $options['selectMacros'] select Macros * @param int $options['count'] count Services, returned column name is rowscount * @param string $options['pattern'] search hosts by pattern in Service name * @param string $options['extendPattern'] search hosts by pattern in Service name, ip and DNS * @param int $options['limit'] limit selection * @param string $options['sortfield'] field to sort by * @param string $options['sortorder'] sort order * @return array|boolean Service data as array or false if error */ public function get($options = array()) { $result = array(); $nodeCheck = false; $userType = self::$userData['type']; // allowed columns for sorting $sortColumns = array('dserviceid', 'dhostid', 'ip'); // allowed output options for [ select_* ] params $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM); $sqlParts = array('select' => array('dservices' => 'ds.dserviceid'), 'from' => array('dservices' => 'dservices ds'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $defOptions = array('nodeids' => null, 'dserviceids' => null, 'dhostids' => null, 'dcheckids' => null, 'druleids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectDRules' => null, 'selectDHosts' => null, 'selectDChecks' => null, 'selectHosts' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($defOptions, $options); if (is_array($options['output'])) { unset($sqlParts['select']['dservices']); $dbTable = DB::getSchema('dservices'); foreach ($options['output'] as $field) { if (isset($dbTable['fields'][$field])) { $sqlParts['select'][$field] = 's.' . $field; } } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == $userType) { } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) { } elseif (!is_null($options['editable']) && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { return array(); } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // dserviceids if (!is_null($options['dserviceids'])) { zbx_value2array($options['dserviceids']); $sqlParts['where']['dserviceid'] = dbConditionInt('ds.dserviceid', $options['dserviceids']); if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids); } } // dhostids if (!is_null($options['dhostids'])) { zbx_value2array($options['dhostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dhostid'] = 'ds.dhostid'; } $sqlParts['where'][] = dbConditionInt('ds.dhostid', $options['dhostids']); if (!is_null($options['groupCount'])) { $sqlParts['group']['dhostid'] = 'ds.dhostid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ds.dhostid', $nodeids); } } // dcheckids if (!is_null($options['dcheckids'])) { zbx_value2array($options['dcheckids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['dcheckid'] = 'dc.dcheckid'; } $sqlParts['from']['dhosts'] = 'dhosts dh'; $sqlParts['from']['dchecks'] = 'dchecks dc'; $sqlParts['where'][] = dbConditionInt('dc.dcheckid', $options['dcheckids']); $sqlParts['where']['dhds'] = 'dh.hostid=ds.hostid'; $sqlParts['where']['dcdh'] = 'dc.druleid=dh.druleid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['dcheckid'] = 'dc.dcheckid'; } } // druleids if (!is_null($options['druleids'])) { zbx_value2array($options['druleids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sqlParts['select']['druleid'] = 'dh.druleid'; } $sqlParts['from']['dhosts'] = 'dhosts dh'; $sqlParts['where']['druleid'] = dbConditionInt('dh.druleid', $options['druleids']); $sqlParts['where']['dhds'] = 'dh.dhostid=ds.dhostid'; if (!is_null($options['groupCount'])) { $sqlParts['group']['druleid'] = 'dh.druleid'; } if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('dh.druleid', $nodeids); } } // node check !!!!! // should last, after all ****IDS checks if (!$nodeCheck) { $nodeCheck = true; $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids); } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sqlParts['select']['dservices'] = 'ds.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sqlParts['select'] = array('count(DISTINCT ds.dserviceid) as rowscount'); //groupCount if (!is_null($options['groupCount'])) { foreach ($sqlParts['group'] as $key => $fields) { $sqlParts['select'][$key] = $fields; } } } // filter if (is_array($options['filter'])) { $this->dbFilter('dservices ds', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('dservices ds', $options, $sqlParts); } // sorting zbx_db_sorting($sqlParts, $options, $sortColumns, 'ds'); // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } //------- $dserviceids = array(); $sqlParts['select'] = array_unique($sqlParts['select']); $sqlParts['from'] = array_unique($sqlParts['from']); $sqlParts['where'] = array_unique($sqlParts['where']); $sqlParts['group'] = array_unique($sqlParts['group']); $sqlParts['order'] = array_unique($sqlParts['order']); $sqlSelect = ''; $sqlFrom = ''; $sqlWhere = ''; $sqlGroup = ''; $sqlOrder = ''; if (!empty($sqlParts['select'])) { $sqlSelect .= implode(',', $sqlParts['select']); } if (!empty($sqlParts['from'])) { $sqlFrom .= implode(',', $sqlParts['from']); } if (!empty($sqlParts['where'])) { $sqlWhere .= implode(' AND ', $sqlParts['where']); } if (!empty($sqlParts['group'])) { $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']); } if (!empty($sqlParts['order'])) { $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']); } $sqlLimit = $sqlParts['limit']; $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder; //SDI($sql); $res = DBselect($sql, $sqlLimit); while ($dservice = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $dservice; } else { $result = $dservice['rowscount']; } } else { $dserviceids[$dservice['dserviceid']] = $dservice['dserviceid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$dservice['dserviceid']] = array('dserviceid' => $dservice['dserviceid']); } else { if (!isset($result[$dservice['dserviceid']])) { $result[$dservice['dserviceid']] = array(); } if (!is_null($options['selectDRules']) && !isset($result[$dservice['dserviceid']]['drules'])) { $result[$dservice['dserviceid']]['drules'] = array(); } if (!is_null($options['selectDHosts']) && !isset($result[$dservice['dserviceid']]['dhosts'])) { $result[$dservice['dserviceid']]['dhosts'] = array(); } if (!is_null($options['selectDChecks']) && !isset($result[$dservice['dserviceid']]['dchecks'])) { $result[$dservice['dserviceid']]['dchecks'] = array(); } if (!is_null($options['selectHosts']) && !isset($result[$dservice['dserviceid']]['hosts'])) { $result[$dservice['dserviceid']]['hosts'] = array(); } // druleids if (isset($dservice['druleid']) && is_null($options['selectDRules'])) { if (!isset($result[$dservice['dserviceid']]['drules'])) { $result[$dservice['dserviceid']]['drules'] = array(); } $result[$dservice['dserviceid']]['drules'][] = array('druleid' => $dservice['druleid']); } // dhostids if (isset($dservice['dhostid']) && is_null($options['selectDHosts'])) { if (!isset($result[$dservice['dserviceid']]['dhosts'])) { $result[$dservice['dserviceid']]['dhosts'] = array(); } $result[$dservice['dserviceid']]['dhosts'][] = array('dhostid' => $dservice['dhostid']); } // dcheckids if (isset($dservice['dcheckid']) && is_null($options['selectDChecks'])) { if (!isset($result[$dservice['dserviceid']]['dchecks'])) { $result[$dservice['dserviceid']]['dchecks'] = array(); } $result[$dservice['dserviceid']]['dchecks'][] = array('dcheckid' => $dservice['dcheckid']); } $result[$dservice['dserviceid']] += $dservice; } } } if (!is_null($options['countOutput'])) { return $result; } // Adding Objects // select_drules if (!is_null($options['selectDRules'])) { $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1); if (is_array($options['selectDRules']) || str_in_array($options['selectDRules'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDRules']; $drules = API::DRule()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($drules, 'name'); } foreach ($drules as $druleid => $drule) { unset($drules[$druleid]['dservices']); $count = array(); foreach ($drule['dservices'] as $dnum => $dservice) { if (!is_null($options['limitSelects'])) { if (!isset($count[$dservice['dserviceid']])) { $count[$dservice['dserviceid']] = 0; } $count[$dservice['dserviceid']]++; if ($count[$dservice['dserviceid']] > $options['limitSelects']) { continue; } } $result[$dservice['dserviceid']]['drules'][] =& $drules[$druleid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDRules']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $drules = API::DRule()->get($objParams); $drules = zbx_toHash($drules, 'dserviceid'); foreach ($result as $dserviceid => $dservice) { if (isset($drules[$dserviceid])) { $result[$dserviceid]['drules'] = $drules[$dserviceid]['rowscount']; } else { $result[$dserviceid]['drules'] = 0; } } } } // selectDHosts if (!is_null($options['selectDHosts'])) { $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1); if (is_array($options['selectDHosts']) || str_in_array($options['selectDHosts'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectDHosts']; $dhosts = API::DHost()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($dhosts, 'dhostid'); } foreach ($dhosts as $dhostid => $dhost) { unset($dhosts[$dhostid]['dservices']); foreach ($dhost['dservices'] as $snum => $dservice) { if (!is_null($options['limitSelects'])) { if (!isset($count[$dservice['dserviceid']])) { $count[$dservice['dserviceid']] = 0; } $count[$dservice['dserviceid']]++; if ($count[$dservice['dserviceid']] > $options['limitSelects']) { continue; } } $result[$dservice['dserviceid']]['dhosts'][] =& $dhosts[$dhostid]; } } } elseif (API_OUTPUT_COUNT == $options['selectDHosts']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $dhosts = API::DHost()->get($objParams); $dhosts = zbx_toHash($dhosts, 'dhostid'); foreach ($result as $dserviceid => $dservice) { if (isset($dhosts[$dserviceid])) { $result[$dserviceid]['dhosts'] = $dhosts[$dserviceid]['rowscount']; } else { $result[$dserviceid]['dhosts'] = 0; } } } } // selectHosts if (!is_null($options['selectHosts'])) { $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1, 'sortfield' => 'status'); if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) { $objParams['output'] = $options['selectHosts']; $hosts = API::Host()->get($objParams); if (!is_null($options['limitSelects'])) { order_result($hosts, 'hostid'); } foreach ($hosts as $hostid => $host) { unset($hosts[$hostid]['dservices']); foreach ($host['dservices'] as $dnum => $dservice) { if (!is_null($options['limitSelects'])) { if (!isset($count[$dservice['dserviceid']])) { $count[$dservice['dserviceid']] = 0; } $count[$dservice['dserviceid']]++; if ($count[$dservice['dserviceid']] > $options['limitSelects']) { continue; } } $result[$dservice['dserviceid']]['hosts'][] =& $hosts[$hostid]; } } } elseif (API_OUTPUT_COUNT == $options['selectHosts']) { $objParams['countOutput'] = 1; $objParams['groupCount'] = 1; $hosts = API::Host()->get($objParams); $hosts = zbx_toHash($hosts, 'hostid'); foreach ($result as $dserviceid => $dservice) { if (isset($hosts[$dserviceid])) { $result[$dserviceid]['hosts'] = $hosts[$dserviceid]['rowscount']; } else { $result[$dserviceid]['hosts'] = 0; } } } } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
} if (getRequest('favobj') === 'timeline' && hasRequest('elementid') && hasRequest('period')) { navigation_bar_calc('web.hostscreen', getRequest('elementid'), true); } if ($page['type'] == PAGE_TYPE_JS || $page['type'] == PAGE_TYPE_HTML_BLOCK) { 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']); }
/** * Mass update hosts * * @param _array $hosts multidimensional array with Hosts data * @param array $hosts['hosts'] Array of Host objects to update * @param string $hosts['fields']['host'] Host name. * @param array $hosts['fields']['groupids'] HostGroup IDs add Host to. * @param int $hosts['fields']['port'] Port. OPTIONAL * @param int $hosts['fields']['status'] Host Status. OPTIONAL * @param int $hosts['fields']['useip'] Use IP. OPTIONAL * @param string $hosts['fields']['dns'] DNS. OPTIONAL * @param string $hosts['fields']['ip'] IP. OPTIONAL * @param int $hosts['fields']['proxy_hostid'] Proxy Host ID. OPTIONAL * @param int $hosts['fields']['useipmi'] Use IPMI. OPTIONAL * @param string $hosts['fields']['ipmi_ip'] IPMAI IP. OPTIONAL * @param int $hosts['fields']['ipmi_port'] IPMI port. OPTIONAL * @param int $hosts['fields']['ipmi_authtype'] IPMI authentication type. OPTIONAL * @param int $hosts['fields']['ipmi_privilege'] IPMI privilege. OPTIONAL * @param string $hosts['fields']['ipmi_username'] IPMI username. OPTIONAL * @param string $hosts['fields']['ipmi_password'] IPMI password. OPTIONAL * @return boolean */ public static function massUpdate($data) { $hosts = zbx_toArray($data['hosts']); $hostids = zbx_objectValues($hosts, 'hostid'); try { self::BeginTransaction(__METHOD__); $options = array('hostids' => $hostids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1); $upd_hosts = self::get($options); foreach ($hosts as $hnum => $host) { if (!isset($upd_hosts[$host['hostid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION); } } // CHECK IF HOSTS HAVE AT LEAST 1 GROUP {{{ if (isset($data['groups']) && empty($data['groups'])) { self::exception(ZBX_API_ERROR_PARAMETERS, 'No groups for hosts'); } // }}} CHECK IF HOSTS HAVE AT LEAST 1 GROUP // UPDATE HOSTS PROPERTIES {{{ if (isset($data['host'])) { if (count($hosts) > 1) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot mass update host name'); } $cur_host = reset($hosts); $options = array('filter' => array('host' => $cur_host['host']), 'output' => API_OUTPUT_SHORTEN, 'editable' => 1, 'nopermissions' => 1); $host_exists = self::get($options); $host_exist = reset($host_exists); if ($host_exist && $host_exist['hostid'] != $cur_host['hostid']) { self::exception(ZBX_API_ERROR_PARAMETERS, S_HOST . ' [ ' . $data['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL); } //can't add host with the same name as existing template if (CTemplate::exists(array('host' => $cur_host['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, S_TEMPLATE . ' [ ' . $cur_host['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL); } } if (isset($data['host']) && !preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/i', $data['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for Hostname [ ' . $data['host'] . ' ]'); } if (isset($data['dns']) && !empty($data['dns']) && !preg_match('/^' . ZBX_PREG_DNS_FORMAT . '$/i', $data['dns'])) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for DNS [ ' . $data['dns'] . ' ]'); } $sql_set = array(); if (isset($data['proxy_hostid'])) { $sql_set[] = 'proxy_hostid=' . $data['proxy_hostid']; } if (isset($data['host'])) { $sql_set[] = 'host=' . zbx_dbstr($data['host']); } if (isset($data['port'])) { $sql_set[] = 'port=' . $data['port']; } if (isset($data['status'])) { $sql_set[] = 'status=' . $data['status']; } if (isset($data['useip'])) { $sql_set[] = 'useip=' . $data['useip']; } if (isset($data['dns'])) { $sql_set[] = 'dns=' . zbx_dbstr($data['dns']); } if (isset($data['ip'])) { $sql_set[] = 'ip=' . zbx_dbstr($data['ip']); } if (isset($data['useipmi'])) { $sql_set[] = 'useipmi=' . $data['useipmi']; } if (isset($data['ipmi_port'])) { $sql_set[] = 'ipmi_port=' . $data['ipmi_port']; } if (isset($data['ipmi_authtype'])) { $sql_set[] = 'ipmi_authtype=' . $data['ipmi_authtype']; } if (isset($data['ipmi_privilege'])) { $sql_set[] = 'ipmi_privilege=' . $data['ipmi_privilege']; } if (isset($data['ipmi_username'])) { $sql_set[] = 'ipmi_username='******'ipmi_username']); } if (isset($data['ipmi_password'])) { $sql_set[] = 'ipmi_password='******'ipmi_password']); } if (isset($data['ipmi_ip'])) { $sql_set[] = 'ipmi_ip=' . zbx_dbstr($data['ipmi_ip']); } if (!empty($sql_set)) { $sql = 'UPDATE hosts SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $hostids); $result = DBexecute($sql); if (isset($data['status'])) { update_host_status($hostids, $data['status']); } } // }}} UPDATE HOSTS PROPERTIES // UPDATE HOSTGROUPS LINKAGE {{{ if (isset($data['groups']) && !is_null($data['groups'])) { $data['groups'] = zbx_toArray($data['groups']); $host_groups = CHostGroup::get(array('hostids' => $hostids)); $host_groupids = zbx_objectValues($host_groups, 'groupid'); $new_groupids = zbx_objectValues($data['groups'], 'groupid'); $groups_to_add = array_diff($new_groupids, $host_groupids); if (!empty($groups_to_add)) { $result = self::massAdd(array('hosts' => $hosts, 'groups' => zbx_toObject($groups_to_add, 'groupid'))); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t add group'); } } $groupids_to_del = array_diff($host_groupids, $new_groupids); if (!empty($groupids_to_del)) { $result = self::massRemove(array('hostids' => $hostids, 'groupids' => $groupids_to_del)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove group'); } } } // }}} UPDATE HOSTGROUPS LINKAGE $data['templates_clear'] = isset($data['templates_clear']) ? zbx_toArray($data['templates_clear']) : array(); $cleared_templateids = array(); foreach ($hostids as $hostid) { foreach ($data['templates_clear'] as $tpl) { $result = unlink_template($hostid, $tpl['templateid'], false); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot unlink template [ ' . $tpl['templateid'] . ' ]'); } $cleared_templateids[] = $tpl['templateid']; } } // UPDATE TEMPLATE LINKAGE {{{ if (isset($data['templates']) && !is_null($data['templates'])) { $opt = array('hostids' => $hostids, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true); $host_templates = CTemplate::get($opt); $host_templateids = array_keys($host_templates); $new_templateids = zbx_objectValues($data['templates'], 'templateid'); $templates_to_del = array_diff($host_templateids, $new_templateids); $templates_to_del = array_diff($templates_to_del, $cleared_templateids); if (!empty($templates_to_del)) { $result = self::massRemove(array('hostids' => $hostids, 'templateids' => $templates_to_del)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, S_CANNOT_UNLINK_TEMPLATE); } } $result = self::massAdd(array('hosts' => $hosts, 'templates' => $data['templates'])); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, S_CANNOT_LINK_TEMPLATE); } } // }}} UPDATE TEMPLATE LINKAGE // UPDATE MACROS {{{ if (isset($data['macros']) && !is_null($data['macros'])) { $macrosToAdd = zbx_toHash($data['macros'], 'macro'); $hostMacros = CUserMacro::get(array('hostids' => $hostids, 'output' => API_OUTPUT_EXTEND)); $hostMacros = zbx_toHash($hostMacros, 'macro'); // Delete $macrosToDelete = array(); foreach ($hostMacros as $hmnum => $hmacro) { if (!isset($macrosToAdd[$hmacro['macro']])) { $macrosToDelete[] = $hmacro['macro']; } } // Update $macrosToUpdate = array(); foreach ($macrosToAdd as $nhmnum => $nhmacro) { if (isset($hostMacros[$nhmacro['macro']])) { $macrosToUpdate[] = $nhmacro; unset($macrosToAdd[$nhmnum]); } } //---- if (!empty($macrosToDelete)) { $result = self::massRemove(array('hostids' => $hostids, 'macros' => $macrosToDelete)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove macro'); } } if (!empty($macrosToUpdate)) { $result = CUsermacro::massUpdate(array('hosts' => $hosts, 'macros' => $macrosToUpdate)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update macro'); } } if (!empty($macrosToAdd)) { $result = self::massAdd(array('hosts' => $hosts, 'macros' => $macrosToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot add macro'); } } } // }}} UPDATE MACROS // PROFILE {{{ if (isset($data['profile']) && !is_null($data['profile'])) { if (empty($data['profile'])) { $sql = 'DELETE FROM hosts_profiles WHERE ' . DBcondition('hostid', $hostids); if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot delete profile'); } } else { $existing_profiles = array(); $existing_profiles_db = DBselect('SELECT hostid FROM hosts_profiles WHERE ' . DBcondition('hostid', $hostids)); while ($existing_profile = DBfetch($existing_profiles_db)) { $existing_profiles[] = $existing_profile['hostid']; } $hostids_without_profile = array_diff($hostids, $existing_profiles); $fields = array_keys($data['profile']); $fields = implode(', ', $fields); $values = array_map('zbx_dbstr', $data['profile']); $values = implode(', ', $values); foreach ($hostids_without_profile as $hostid) { $sql = 'INSERT INTO hosts_profiles (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')'; if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot create profile'); } } if (!empty($existing_profiles)) { $host_profile_fields = array('devicetype', 'name', 'os', 'serialno', 'tag', 'macaddress', 'hardware', 'software', 'contact', 'location', 'notes'); $sql_set = array(); foreach ($host_profile_fields as $field) { if (isset($data['profile'][$field])) { $sql_set[] = $field . '=' . zbx_dbstr($data['profile'][$field]); } } $sql = 'UPDATE hosts_profiles SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $existing_profiles); if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update profile'); } } } } // }}} PROFILE // EXTENDED PROFILE {{{ if (isset($data['extendedProfile']) && !is_null($data['extendedProfile'])) { if (empty($data['extendedProfile'])) { $sql = 'DELETE FROM hosts_profiles_ext WHERE ' . DBcondition('hostid', $hostids); if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot delete extended profile'); } } else { $existing_profiles = array(); $existing_profiles_db = DBselect('SELECT hostid FROM hosts_profiles_ext WHERE ' . DBcondition('hostid', $hostids)); while ($existing_profile = DBfetch($existing_profiles_db)) { $existing_profiles[] = $existing_profile['hostid']; } $hostids_without_profile = array_diff($hostids, $existing_profiles); $fields = array_keys($data['extendedProfile']); $fields = implode(', ', $fields); $values = array_map('zbx_dbstr', $data['extendedProfile']); $values = implode(', ', $values); foreach ($hostids_without_profile as $hostid) { $sql = 'INSERT INTO hosts_profiles_ext (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')'; if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot create extended profile'); } } if (!empty($existing_profiles)) { $host_profile_ext_fields = array('device_alias', 'device_type', 'device_chassis', 'device_os', 'device_os_short', 'device_hw_arch', 'device_serial', 'device_model', 'device_tag', 'device_vendor', 'device_contract', 'device_who', 'device_status', 'device_app_01', 'device_app_02', 'device_app_03', 'device_app_04', 'device_app_05', 'device_url_1', 'device_url_2', 'device_url_3', 'device_networks', 'device_notes', 'device_hardware', 'device_software', 'ip_subnet_mask', 'ip_router', 'ip_macaddress', 'oob_ip', 'oob_subnet_mask', 'oob_router', 'date_hw_buy', 'date_hw_install', 'date_hw_expiry', 'date_hw_decomm', 'site_street_1', 'site_street_2', 'site_street_3', 'site_city', 'site_state', 'site_country', 'site_zip', 'site_rack', 'site_notes', 'poc_1_name', 'poc_1_email', 'poc_1_phone_1', 'poc_1_phone_2', 'poc_1_cell', 'poc_1_screen', 'poc_1_notes', 'poc_2_name', 'poc_2_email', 'poc_2_phone_1', 'poc_2_phone_2', 'poc_2_cell', 'poc_2_screen', 'poc_2_notes'); $sql_set = array(); foreach ($host_profile_ext_fields as $field) { if (isset($data['extendedProfile'][$field])) { $sql_set[] = $field . '=' . zbx_dbstr($data['extendedProfile'][$field]); } } $sql = 'UPDATE hosts_profiles_ext SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $existing_profiles); if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update extended profile'); } } } } // }}} EXTENDED PROFILE self::EndTransaction(true, __METHOD__); return array('hostids' => $hostids); } catch (APIException $e) { self::EndTransaction(false, __METHOD__); $error = $e->getErrors(); $error = reset($error); self::setError(__METHOD__, $e->getCode(), $error); return false; } }
/** * Validates the input parameters for the update() method. * * @throws APIException if the input is invalid * * @param array $scripts */ protected function validateUpdate(array $scripts) { if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } foreach ($scripts as $script) { if (empty($script['scriptid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Invalid method parameters.')); } } $scripts = zbx_toHash($scripts, 'scriptid'); $scriptIds = array_keys($scripts); $names = array(); $dbScripts = $this->get(array('scriptids' => $scriptIds, 'output' => array('scriptid'), 'preservekeys' => true)); foreach ($scripts as $script) { if (!isset($dbScripts[$script['scriptid']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Script with scriptid "%1$s" does not exist.', $script['scriptid'])); } if (isset($script['name'])) { if (zbx_empty($script['name'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty name for script.')); } if (isset($names[$script['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate script name "%1$s".', $script['name'])); } $names[$script['name']] = $script['name']; } } if ($names) { $dbScripts = $this->get(array('output' => array('scriptid', 'name'), 'filter' => array('name' => $names), 'nopermissions' => true, 'preservekeys' => true)); foreach ($dbScripts as $dbScript) { if (!isset($scripts[$dbScript['scriptid']]) || bccomp($scripts[$dbScript['scriptid']]['scriptid'], $dbScript['scriptid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Script "%1$s" already exists.', $dbScript['name'])); } } } }
public function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $itemids = array_keys($result); // adding applications if ($options['selectApplications'] !== null && $options['selectApplications'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'applicationid', 'items_applications'); $applications = API::Application()->get(array('output' => $options['selectApplications'], 'applicationids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $applications, 'applications'); } // adding interfaces if ($options['selectInterfaces'] !== null && $options['selectInterfaces'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'interfaceid'); $interfaces = API::HostInterface()->get(array('output' => $options['selectInterfaces'], 'interfaceids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $interfaces, 'interfaces'); } // adding triggers if (!is_null($options['selectTriggers'])) { if ($options['selectTriggers'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'triggerid', 'functions'); $triggers = API::Trigger()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']); } else { $triggers = API::Trigger()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $triggers = zbx_toHash($triggers, 'itemid'); foreach ($result as $itemid => $item) { if (isset($triggers[$itemid])) { $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount']; } else { $result[$itemid]['triggers'] = 0; } } } } // adding graphs if (!is_null($options['selectGraphs'])) { if ($options['selectGraphs'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'graphid', 'graphs_items'); $graphs = API::Graph()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']); } else { $graphs = API::Graph()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $graphs = zbx_toHash($graphs, 'itemid'); foreach ($result as $itemid => $item) { if (isset($graphs[$itemid])) { $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount']; } else { $result[$itemid]['graphs'] = 0; } } } } // adding discoveryrule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { $relationMap = new CRelationMap(); // discovered items $dbRules = DBselect('SELECT id1.itemid,id2.parent_itemid' . ' FROM item_discovery id1,item_discovery id2,items i' . ' WHERE ' . dbConditionInt('id1.itemid', $itemids) . ' AND id1.parent_itemid=id2.itemid' . ' AND i.itemid=id1.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_CREATED); while ($rule = DBfetch($dbRules)) { $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']); } // item prototypes // TODO: this should not be in the item API $dbRules = DBselect('SELECT id.parent_itemid,id.itemid' . ' FROM item_discovery id,items i' . ' WHERE ' . dbConditionInt('id.itemid', $itemids) . ' AND i.itemid=id.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_PROTOTYPE); while ($rule = DBfetch($dbRules)) { $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']); } $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding item discovery if ($options['selectItemDiscovery'] !== null) { $itemDiscoveries = API::getApiService()->select('item_discovery', array('output' => $this->outputExtend($options['selectItemDiscovery'], array('itemdiscoveryid', 'itemid')), 'filter' => array('itemid' => array_keys($result)), 'preservekeys' => true)); $relationMap = $this->createRelationMap($itemDiscoveries, 'itemid', 'itemdiscoveryid'); $itemDiscoveries = $this->unsetExtraFields($itemDiscoveries, array('itemid', 'itemdiscoveryid'), $options['selectItemDiscovery']); $result = $relationMap->mapOne($result, $itemDiscoveries, 'itemDiscovery'); } // adding history data $requestedOutput = array(); if ($this->outputIsRequested('lastclock', $options['output'])) { $requestedOutput['lastclock'] = true; } if ($this->outputIsRequested('lastns', $options['output'])) { $requestedOutput['lastns'] = true; } if ($this->outputIsRequested('lastvalue', $options['output'])) { $requestedOutput['lastvalue'] = true; } if ($this->outputIsRequested('prevvalue', $options['output'])) { $requestedOutput['prevvalue'] = true; } if ($requestedOutput) { $history = Manager::History()->getLast($result, 2, ZBX_HISTORY_PERIOD); foreach ($result as &$item) { $lastHistory = isset($history[$item['itemid']][0]) ? $history[$item['itemid']][0] : null; $prevHistory = isset($history[$item['itemid']][1]) ? $history[$item['itemid']][1] : null; if (isset($requestedOutput['lastclock'])) { $item['lastclock'] = $lastHistory ? $lastHistory['clock'] : '0'; } if (isset($requestedOutput['lastns'])) { $item['lastns'] = $lastHistory ? $lastHistory['ns'] : '0'; } if (isset($requestedOutput['lastvalue'])) { $item['lastvalue'] = $lastHistory ? $lastHistory['value'] : '0'; } if (isset($requestedOutput['prevvalue'])) { $item['prevvalue'] = $prevHistory ? $prevHistory['value'] : '0'; } } unset($item); } return $result; }
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. **/ require_once 'include/config.inc.php'; require_once 'include/graphs.inc.php'; $page['file'] = 'chart7.php'; // $page['title'] = "S_CHART"; $page['type'] = PAGE_TYPE_IMAGE; include_once '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)); check_fields($fields); $items = get_request('items', array()); asort_by_key($items, 'sortorder'); $options = array('webitems' => 1, 'itemids' => zbx_objectValues($items, 'itemid'), 'nodeids' => get_current_nodeid(true)); $db_data = CItem::get($options); $db_data = zbx_toHash($db_data, 'itemid'); foreach ($items as $id => $gitem) { if (!isset($db_data[$gitem['itemid']])) { access_deny(); } } $effectiveperiod = navigation_bar_calc(); $graph = new CPie(get_request('graphtype', GRAPH_TYPE_NORMAL)); $graph->setHeader(get_request('name', '')); $graph3d = get_request('graph3d', 0); $legend = get_request('legend', 0); if ($graph3d == 1) { $graph->switchPie3D(); } $graph->showLegend($legend); unset($host);
function make_screen_submenu() { $favScreens = array(); $fav_screens = CFavorite::get('web.favorite.screenids'); if (!$fav_screens) { return $favScreens; } $screenids = array(); foreach ($fav_screens as $favorite) { if ('screenid' == $favorite['source']) { $screenids[$favorite['value']] = $favorite['value']; } } $options = array('screenids' => $screenids, 'output' => array('screenid', 'name')); $screens = API::Screen()->get($options); $screens = zbx_toHash($screens, 'screenid'); foreach ($fav_screens as $favorite) { $source = $favorite['source']; $sourceid = $favorite['value']; if ('slideshowid' == $source) { if (!slideshow_accessible($sourceid, PERM_READ)) { continue; } if (!($slide = get_slideshow_by_slideshowid($sourceid))) { continue; } $slide_added = true; $favScreens[] = array('name' => $slide['name'], 'favobj' => 'slideshowid', 'favid' => $slide['slideshowid'], 'favaction' => 'remove'); } else { if (!isset($screens[$sourceid])) { continue; } $screen = $screens[$sourceid]; $screen_added = true; $favScreens[] = array('name' => $screen['name'], 'favobj' => 'screenid', 'favid' => $screen['screenid'], 'favaction' => 'remove'); } } if (isset($screen_added)) { $favScreens[] = array('name' => _('Remove') . ' ' . _('All') . ' ' . _('Screens'), 'favobj' => 'screenid', 'favid' => 0, 'favaction' => 'remove'); } if (isset($slide_added)) { $favScreens[] = array('name' => _('Remove') . ' ' . _('All') . ' ' . _('Slides'), 'favobj' => 'slideshowid', 'favid' => 0, 'favaction' => 'remove'); } return $favScreens; }
/** * Resolve user macros in trigger expression. * * @static * * @param array $trigger * @param array $trigger['triggerid'] * @param array $trigger['expression'] * * @return string */ public static function resolveTriggerExpressionUserMacro(array $trigger) { if (zbx_empty($trigger['expression'])) { return $trigger['expression']; } self::init(); $triggers = self::$macrosResolver->resolve(array('config' => 'triggerExpressionUser', 'data' => zbx_toHash(array($trigger), 'triggerid'))); $trigger = reset($triggers); return $trigger['expression']; }
/** * Updates maintenance time periods. * * @param array $maintenance * @param array $oldMaintenance */ protected function replaceTimePeriods(array $oldMaintenance, array $maintenance) { // replace time periods $timePeriods = DB::replace('timeperiods', $oldMaintenance['timeperiods'], $maintenance['timeperiods']); // link new time periods to maintenance $oldTimePeriods = zbx_toHash($oldMaintenance['timeperiods'], 'timeperiodid'); $newMaintenanceWindows = []; foreach ($timePeriods as $tp) { if (!isset($oldTimePeriods[$tp['timeperiodid']])) { $newMaintenanceWindows[] = ['maintenanceid' => $maintenance['maintenanceid'], 'timeperiodid' => $tp['timeperiodid']]; } } DB::insert('maintenances_windows', $newMaintenanceWindows); }
if ($ack_status == ZBX_ACK_STS_WITH_LAST_UNACK) { $options['withLastEventUnacknowledged'] = 1; } if ($show_severity > -1) { $options['min_severity'] = $show_severity; } if ($_REQUEST['status_change']) { $options['lastChangeSince'] = time() - $_REQUEST['status_change_days'] * 86400; } $triggers = CTrigger::get($options); // sorting && paging order_result($triggers, $sortfield, $sortorder); $paging = getPagingLine($triggers); $options = array('nodeids' => get_current_nodeid(), 'triggerids' => zbx_objectValues($triggers, 'triggerid'), 'output' => API_OUTPUT_EXTEND, 'select_hosts' => array('hostid', 'host', 'maintenance_status', 'maintenance_type', 'maintenanceid'), 'select_items' => API_OUTPUT_EXTEND, 'select_dependencies' => API_OUTPUT_EXTEND); $triggers = CTrigger::get($options); $triggers = zbx_toHash($triggers, 'triggerid'); order_result($triggers, $sortfield, $sortorder); //--------- if ($config['event_ack_enable']) { foreach ($triggers as $tnum => $trigger) { $options = array('countOutput' => 1, 'triggerids' => $trigger['triggerid'], 'object' => EVENT_OBJECT_TRIGGER, 'acknowledged' => 0, 'value' => TRIGGER_VALUE_TRUE, 'nopermissions' => 1); $triggers[$tnum]['event_count'] = CEvent::get($options); } } $tr_hostids = array(); foreach ($triggers as $tnum => $trigger) { $triggers[$tnum]['events'] = array(); //getting all host ids and names foreach ($trigger['hosts'] as $tr_hosts) { $tr_hostids[$tr_hosts['hostid']] = $tr_hosts['hostid']; }
function delete_application($applicationids) { $applicationids = zbx_toHash($applicationids); $apps = array(); $sql = 'SELECT a.applicationid, h.host, a.name, a.templateid ' . ' FROM applications a, hosts h ' . ' WHERE ' . DBcondition('a.applicationid', $applicationids) . ' AND h.hostid=a.hostid'; $res = DBselect($sql); while ($db_app = DBfetch($res)) { $apps[$db_app['applicationid']] = $db_app; } // first delete child applications $tmp_appids = array(); $sql = 'SELECT a.applicationid ' . ' FROM applications a ' . ' WHERE ' . DBcondition('a.templateid', $applicationids); $db_applications = DBselect($sql); while ($db_app = DBfetch($db_applications)) { $tmp_appids[$db_app['applicationid']] = $db_app['applicationid']; } if (!empty($tmp_appids)) { // recursion!!! if (!delete_application($tmp_appids)) { return false; } } $unlink_apps = array(); //check if app is used by web scenario $sql = 'SELECT ht.name, ht.applicationid ' . ' FROM httptest ht ' . ' WHERE ' . DBcondition('ht.applicationid', $applicationids); $res = DBselect($sql); while ($info = DBfetch($res)) { if ($apps[$info['applicationid']]['templateid'] > 0) { $unlink_apps[$info['applicationid']] = $info['applicationid']; unset($applicationids[$info['applicationid']]); } else { error(S_APPLICATION . ' [' . $apps[$info['applicationid']]['host'] . ':' . $apps[$info['applicationid']]['name'] . '] ' . S_USED_IN_WEB_SCENARIO); return false; } } $sql = 'SELECT i.itemid, i.key_, i.description, ia.applicationid ' . ' FROM items_applications ia, items i ' . ' WHERE i.type=' . ITEM_TYPE_HTTPTEST . ' AND i.itemid=ia.itemid ' . ' AND ' . DBcondition('ia.applicationid', $applicationids); $res = DBselect($sql); if ($info = DBfetch($res)) { error(S_APPLICATION . ' [' . $apps[$info['applicationid']]['host'] . ':' . $apps[$info['applicationid']]['name'] . '] ' . S_USED_BY_ITEM_SMALL . ' [' . item_description($info) . ']'); return false; } $result = DBexecute('UPDATE applications SET templateid=0 WHERE ' . DBcondition('applicationid', $unlink_apps)); $result &= DBexecute('DELETE FROM items_applications WHERE ' . DBcondition('applicationid', $applicationids)); $result &= DBexecute('DELETE FROM applications WHERE ' . DBcondition('applicationid', $applicationids)); if ($result) { foreach ($apps as $appid => $app) { if (isset($unlink_apps[$appid])) { info(S_APPLICATION . ' [' . $app['host'] . ':' . $app['name'] . '] ' . S_USED_IN_WEB_SCENARIO . ' (' . S_UNLINKED_SMALL . ')'); } else { info(S_APPLICATION . ' [' . $app['host'] . ':' . $app['name'] . '] ' . S_DELETED_SMALL); } } } return $result; }
/** * 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'])); } } } } }
$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(); $graph->setPeriod($_REQUEST['period']);
/** * Process screen. * * @return CDiv (screen inside container) */ public function get() { $this->dataId = 'discovery'; $sort_field = $this->data['sort']; $sort_order = $this->data['sortorder']; $druleid = $this->data['druleid']; // discovery rules $options = ['output' => ['druleid', 'name'], 'selectDHosts' => ['dhostid', 'status', 'lastup', 'lastdown'], 'filter' => ['status' => DRULE_STATUS_ACTIVE]]; if ($druleid > 0) { $options['druleids'] = $druleid; // set selected discovery rule id } $drules = API::DRule()->get($options); if ($drules) { order_result($drules, 'name'); } // discovery services $options = ['selectHosts' => ['hostid', 'name', 'status'], 'output' => ['dserviceid', 'type', 'key_', 'port', 'status', 'lastup', 'lastdown', 'ip', 'dns'], 'sortfield' => $sort_field, 'sortorder' => $sort_order, 'limitSelects' => 1]; if ($druleid > 0) { $options['druleids'] = $druleid; } else { $options['druleids'] = zbx_objectValues($drules, 'druleid'); } $dservices = API::DService()->get($options); // user macros $macros = API::UserMacro()->get(['output' => ['macro', 'value'], 'globalmacro' => true]); $macros = zbx_toHash($macros, 'macro'); // services $services = []; foreach ($dservices as $dservice) { $key_ = $dservice['key_']; if ($key_ !== '') { if (array_key_exists($key_, $macros)) { $key_ = $macros[$key_]['value']; } $key_ = ': ' . $key_; } $service_name = discovery_check_type2str($dservice['type']) . discovery_port2str($dservice['type'], $dservice['port']) . $key_; $services[$service_name] = 1; } ksort($services); // discovery services to hash $dservices = zbx_toHash($dservices, 'dserviceid'); // discovery hosts $dhosts = API::DHost()->get(['druleids' => zbx_objectValues($drules, 'druleid'), 'selectDServices' => ['dserviceid', 'ip', 'dns', 'type', 'status', 'key_'], 'output' => ['dhostid', 'lastdown', 'lastup', 'druleid']]); $dhosts = zbx_toHash($dhosts, 'dhostid'); $header = [make_sorting_header(_('Discovered device'), 'ip', $sort_field, $sort_order, 'zabbix.php?action=discovery.view'), _('Monitored host'), _('Uptime') . '/' . _('Downtime')]; foreach ($services as $name => $foo) { $header[] = (new CColHeader($name))->addClass('vertical_rotation'); } // create table $table = (new CTableInfo())->makeVerticalRotation()->setHeader($header); foreach ($drules as $drule) { $discovery_info = []; foreach ($drule['dhosts'] as $dhost) { if ($dhost['status'] == DHOST_STATUS_DISABLED) { $hclass = 'disabled'; $htime = $dhost['lastdown']; } else { $hclass = 'enabled'; $htime = $dhost['lastup']; } // $primary_ip stores the primary host ip of the dhost $primary_ip = ''; foreach ($dhosts[$dhost['dhostid']]['dservices'] as $dservice) { $dservice = $dservices[$dservice['dserviceid']]; $hostName = ''; $host = reset($dservices[$dservice['dserviceid']]['hosts']); if (!is_null($host)) { $hostName = $host['name']; } if ($primary_ip !== '') { if ($primary_ip === $dservice['ip']) { $htype = 'primary'; } else { $htype = 'slave'; } } else { $primary_ip = $dservice['ip']; $htype = 'primary'; } if (!array_key_exists($dservice['ip'], $discovery_info)) { $discovery_info[$dservice['ip']] = ['ip' => $dservice['ip'], 'dns' => $dservice['dns'], 'type' => $htype, 'class' => $hclass, 'host' => $hostName, 'time' => $htime]; } if ($dservice['status'] == DSVC_STATUS_DISABLED) { $class = ZBX_STYLE_INACTIVE_BG; $time = 'lastdown'; } else { $class = ZBX_STYLE_ACTIVE_BG; $time = 'lastup'; } $key_ = $dservice['key_']; if ($key_ !== '') { if (array_key_exists($key_, $macros)) { $key_ = $macros[$key_]['value']; } $key_ = NAME_DELIMITER . $key_; } $service_name = discovery_check_type2str($dservice['type']) . discovery_port2str($dservice['type'], $dservice['port']) . $key_; $discovery_info[$dservice['ip']]['services'][$service_name] = ['class' => $class, 'time' => $dservice[$time]]; } } if ($druleid == 0 && $discovery_info) { $col = new CCol([bold($drule['name']), SPACE . '(' . _n('%d device', '%d devices', count($discovery_info)) . ')']); $col->setColSpan(count($services) + 3); $table->addRow($col); } order_result($discovery_info, $sort_field, $sort_order); foreach ($discovery_info as $ip => $h_data) { $dns = $h_data['dns'] == '' ? '' : ' (' . $h_data['dns'] . ')'; $row = [$h_data['type'] == 'primary' ? (new CSpan($ip . $dns))->addClass($h_data['class']) : new CSpan(SPACE . SPACE . $ip . $dns), new CSpan(array_key_exists('host', $h_data) ? $h_data['host'] : ''), (new CSpan($h_data['time'] == 0 || $h_data['type'] === 'slave' ? '' : convert_units(['value' => time() - $h_data['time'], 'units' => 'uptime'])))->addClass($h_data['class'])]; foreach ($services as $name => $foo) { $class = null; $time = SPACE; $hint = (new CDiv(SPACE))->addClass($class); $hint_table = null; if (array_key_exists($name, $h_data['services'])) { $class = $h_data['services'][$name]['class']; $time = $h_data['services'][$name]['time']; $hint_table = (new CTableInfo())->setAttribute('style', 'width: auto;'); if ($class == ZBX_STYLE_ACTIVE_BG) { $hint_table->setHeader(_('Uptime')); } else { $hint_table->setHeader(_('Downtime')); } $hint_table->addRow((new CCol(zbx_date2age($h_data['services'][$name]['time'])))->addClass($class)); } $column = (new CCol($hint))->addClass($class); if (!is_null($hint_table)) { $column->setHint($hint_table); } $row[] = $column; } $table->addRow($row); } } return $this->getOutput($table, true, $this->data); }
function drawMapLabels(&$im, $map, $mapInfo, $resolveMacros = true) { global $colors; if ($map['label_type'] == MAP_LABEL_TYPE_NOTHING && $map['label_format'] == SYSMAP_LABEL_ADVANCED_OFF) { return; } $selements = $map['selements']; $allStrings = ''; $labelLines = array(); $statusLines = array(); foreach ($selements as $sid => $selement) { if (isset($selement['elementsubtype']) && $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS) { unset($selements[$sid]); } } // set label type and custom label text for all selements foreach ($selements as $selementId => $selement) { $selements[$selementId]['label_type'] = $map['label_type']; if ($map['label_format'] == SYSMAP_LABEL_ADVANCED_OFF) { continue; } switch ($selement['elementtype']) { case SYSMAP_ELEMENT_TYPE_HOST_GROUP: $selements[$selementId]['label_type'] = $map['label_type_hostgroup']; if ($map['label_type_hostgroup'] == MAP_LABEL_TYPE_CUSTOM) { $selements[$selementId]['label'] = $map['label_string_hostgroup']; } break; case SYSMAP_ELEMENT_TYPE_HOST: $selements[$selementId]['label_type'] = $map['label_type_host']; if ($map['label_type_host'] == MAP_LABEL_TYPE_CUSTOM) { $selements[$selementId]['label'] = $map['label_string_host']; } break; case SYSMAP_ELEMENT_TYPE_TRIGGER: $selements[$selementId]['label_type'] = $map['label_type_trigger']; if ($map['label_type_trigger'] == MAP_LABEL_TYPE_CUSTOM) { $selements[$selementId]['label'] = $map['label_string_trigger']; } break; case SYSMAP_ELEMENT_TYPE_MAP: $selements[$selementId]['label_type'] = $map['label_type_map']; if ($map['label_type_map'] == MAP_LABEL_TYPE_CUSTOM) { $selements[$selementId]['label'] = $map['label_string_map']; } break; case SYSMAP_ELEMENT_TYPE_IMAGE: $selements[$selementId]['label_type'] = $map['label_type_image']; if ($map['label_type_image'] == MAP_LABEL_TYPE_CUSTOM) { $selements[$selementId]['label'] = $map['label_string_image']; } break; } } foreach ($selements as $selementId => $selement) { if (!isset($labelLines[$selementId])) { $labelLines[$selementId] = array(); } if (!isset($statusLines[$selementId])) { $statusLines[$selementId] = array(); } $msg = $resolveMacros ? CMacrosResolverHelper::resolveMapLabelMacrosAll($selement) : $selement['label']; $allStrings .= $msg; $msgs = explode("\n", $msg); foreach ($msgs as $msg) { $labelLines[$selementId][] = array('msg' => $msg); } $elementInfo = $mapInfo[$selementId]; foreach (array('problem', 'unack', 'maintenance', 'ok', 'status') as $caption) { if (!isset($elementInfo['info'][$caption]) || zbx_empty($elementInfo['info'][$caption]['msg'])) { continue; } $statusLines[$selementId][] = array('msg' => $elementInfo['info'][$caption]['msg'], 'color' => $elementInfo['info'][$caption]['color']); $allStrings .= $elementInfo['info'][$caption]['msg']; } } $allLabelsSize = imageTextSize(8, 0, str_replace("\r", '', str_replace("\n", '', $allStrings))); $labelFontHeight = $allLabelsSize['height']; $labelFontBaseline = $allLabelsSize['baseline']; $elementsHostIds = array(); foreach ($selements as $selement) { if ($selement['label_type'] != MAP_LABEL_TYPE_IP) { continue; } if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST) { $elementsHostIds[] = $selement['elementid']; } } if (!empty($elementsHostIds)) { $mapHosts = API::Host()->get(array('hostids' => $elementsHostIds, 'output' => array('hostid'), 'selectInterfaces' => API_OUTPUT_EXTEND)); $mapHosts = zbx_toHash($mapHosts, 'hostid'); } // draw foreach ($selements as $selementId => $selement) { if (empty($selement) || $selement['label_type'] == MAP_LABEL_TYPE_NOTHING) { continue; } $elementInfo = $mapInfo[$selementId]; $hl_color = null; $st_color = null; if (!isset($_REQUEST['noselements']) && $map['highlight'] % 2 == SYSMAP_HIGHLIGHT_ON) { if ($elementInfo['icon_type'] == SYSMAP_ELEMENT_ICON_ON) { $hl_color = true; } if ($elementInfo['icon_type'] == SYSMAP_ELEMENT_ICON_MAINTENANCE) { $st_color = true; } if ($elementInfo['icon_type'] == SYSMAP_ELEMENT_ICON_DISABLED) { $st_color = true; } } if (in_array($selement['elementtype'], array(SYSMAP_ELEMENT_TYPE_HOST_GROUP, SYSMAP_ELEMENT_TYPE_MAP)) && !is_null($hl_color)) { $st_color = null; } elseif (!is_null($st_color)) { $hl_color = null; } $labelLocation = is_null($selement['label_location']) || $selement['label_location'] < 0 ? $map['label_location'] : $selement['label_location']; $label = array(); if ($selement['label_type'] == MAP_LABEL_TYPE_IP && $selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST) { $interface = reset($mapHosts[$selement['elementid']]['interfaces']); $label[] = array('msg' => $interface['ip']); $label = array_merge($label, $statusLines[$selementId]); } elseif ($selement['label_type'] == MAP_LABEL_TYPE_STATUS) { $label = $statusLines[$selementId]; } elseif ($selement['label_type'] == MAP_LABEL_TYPE_NAME) { $label[] = array('msg' => $elementInfo['name']); $label = array_merge($label, $statusLines[$selementId]); } else { $label = array_merge($labelLines[$selementId], $statusLines[$selementId]); } if (empty($label)) { continue; } $w = 0; foreach ($label as $str) { $dims = imageTextSize(8, 0, $str['msg']); $w = max($w, $dims['width']); } $h = count($label) * $labelFontHeight; $x = $selement['x']; $y = $selement['y']; $image = get_png_by_selement($elementInfo); $iconX = imagesx($image); $iconY = imagesy($image); if (!is_null($hl_color)) { $icon_hl = 14; } elseif (!is_null($st_color)) { $icon_hl = 6; } else { $icon_hl = 2; } switch ($labelLocation) { case MAP_LABEL_LOC_TOP: $y_rec = $y - $icon_hl - $h - 6; $x_rec = $x + $iconX / 2 - $w / 2; break; case MAP_LABEL_LOC_LEFT: $y_rec = $y - $h / 2 + $iconY / 2; $x_rec = $x - $icon_hl - $w; break; case MAP_LABEL_LOC_RIGHT: $y_rec = $y - $h / 2 + $iconY / 2; $x_rec = $x + $iconX + $icon_hl; break; case MAP_LABEL_LOC_BOTTOM: default: $y_rec = $y + $iconY + $icon_hl; $x_rec = $x + $iconX / 2 - $w / 2; } $increasey = 12; foreach ($label as $line) { if (zbx_empty($line['msg'])) { continue; } $str = str_replace("\r", '', $line['msg']); $color = isset($line['color']) ? $line['color'] : $colors['Black']; $dims = imageTextSize(8, 0, $str); if ($labelLocation == MAP_LABEL_LOC_TOP || $labelLocation == MAP_LABEL_LOC_BOTTOM) { $x_label = $x + ceil($iconX / 2) - ceil($dims['width'] / 2); } elseif ($labelLocation == MAP_LABEL_LOC_LEFT) { $x_label = $x_rec + $w - $dims['width']; } else { $x_label = $x_rec; } imagefilledrectangle($im, $x_label - 1, $y_rec + $increasey - $labelFontHeight + $labelFontBaseline, $x_label + $dims['width'] + 1, $y_rec + $increasey + $labelFontBaseline, $colors['White']); imagetext($im, 8, 0, $x_label, $y_rec + $increasey, $color, $str); $increasey += $labelFontHeight + 1; } } }
} $delButton = new CButton('delete', S_DELETE_SELECTED); if (!$filterEnable) { $delButton->setAttribute('disabled', 'disabled'); } $dashForm->addRow(S_GROUPS, array($lstGroups, BR(), $addButton, $delButton)); } //HOSTS // SPACE added to extend CB width in Chrome $cbMain = new CCheckBox('maintenance', $maintenance, null, '1'); if (!$filterEnable) { $cbMain->setAttribute('disabled', 'disabled'); } $dashForm->addRow(S_HOSTS, array($cbMain, S_SHOW_HOSTS_IN_MAINTENANCE)); // Trigger $severity = zbx_toHash($severity); $trgSeverities = array(); $severities = array(TRIGGER_SEVERITY_NOT_CLASSIFIED, TRIGGER_SEVERITY_INFORMATION, TRIGGER_SEVERITY_WARNING, TRIGGER_SEVERITY_AVERAGE, TRIGGER_SEVERITY_HIGH, TRIGGER_SEVERITY_DISASTER); foreach ($severities as $snum => $sever) { $cb = new CCheckBox('trgSeverity[' . $sever . ']', isset($severity[$sever]), '', 1); $cb->setEnabled($filterEnable); $trgSeverities[] = array($cb, getSeverityCaption($sever)); $trgSeverities[] = BR(); } array_pop($trgSeverities); $dashForm->addRow(S_TRIGGERS_WITH_SEVERITY, $trgSeverities); $config = select_config(); $cb = new CComboBox('extAck', $extAck); $cb->addItems(array(EXTACK_OPTION_ALL => S_O_ALL, EXTACK_OPTION_BOTH => S_O_SEPARATED, EXTACK_OPTION_UNACK => S_O_UNACKNOWLEDGED_ONLY)); $cb->setEnabled($filterEnable && $config['event_ack_enable']); if (!$config['event_ack_enable']) {
public function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $itemids = array_keys($result); // adding applications if ($options['selectApplications'] !== null && $options['selectApplications'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'applicationid', 'items_applications'); $applications = API::Application()->get(array('output' => $options['selectApplications'], 'applicationids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $applications, 'applications'); } // adding triggers if (!is_null($options['selectTriggers'])) { if ($options['selectTriggers'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'triggerid', 'functions'); $triggers = API::TriggerPrototype()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']); } else { $triggers = API::TriggerPrototype()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $triggers = zbx_toHash($triggers, 'itemid'); foreach ($result as $itemid => $item) { if (isset($triggers[$itemid])) { $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount']; } else { $result[$itemid]['triggers'] = 0; } } } } // adding graphs if (!is_null($options['selectGraphs'])) { if ($options['selectGraphs'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'graphid', 'graphs_items'); $graphs = API::GraphPrototype()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']); } else { $graphs = API::GraphPrototype()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids)); $graphs = zbx_toHash($graphs, 'itemid'); foreach ($result as $itemid => $item) { if (isset($graphs[$itemid])) { $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount']; } else { $result[$itemid]['graphs'] = 0; } } } } // adding discoveryrule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'itemid', 'parent_itemid', 'item_discovery'); $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } return $result; }
/** * Import templates. * * @throws Exception * * @param array $templates * * @return void */ public function import(array $templates) { $templates = zbx_toHash($templates, 'host'); $this->checkCircularTemplateReferences($templates); foreach ($templates as &$template) { if (!$this->options['templateLinkage']['createMissing']) { unset($template['templates']); } } unset($template); do { $independentTemplates = $this->getIndependentTemplates($templates); $templatesToCreate = []; $templatesToUpdate = []; $templateLinkage = []; foreach ($independentTemplates as $name) { $template = $templates[$name]; unset($templates[$name]); $template = $this->resolveTemplateReferences($template); // if we need to add linkages, save linked templates to massAdd later if ($this->options['templateLinkage']['createMissing'] && !empty($template['templates'])) { $templateLinkage[$template['host']] = $template['templates']; unset($template['templates']); } if (!empty($template['templateid'])) { $templatesToUpdate[] = $template; } else { $templatesToCreate[] = $template; } } if ($this->options['templates']['createMissing'] && $templatesToCreate) { $newTemplateIds = API::Template()->create($templatesToCreate); foreach ($templatesToCreate as $num => $createdTemplate) { $templateId = $newTemplateIds['templateids'][$num]; $this->referencer->addTemplateRef($createdTemplate['host'], $templateId); $this->processedTemplateIds[$templateId] = $templateId; if (!empty($templateLinkage[$createdTemplate['host']])) { API::Template()->massAdd(['templates' => ['templateid' => $templateId], 'templates_link' => $templateLinkage[$createdTemplate['host']]]); } } } if ($this->options['templates']['updateExisting'] && $templatesToUpdate) { API::Template()->update($templatesToUpdate); foreach ($templatesToUpdate as $updatedTemplate) { $this->processedTemplateIds[$updatedTemplate['templateid']] = $updatedTemplate['templateid']; if (!empty($templateLinkage[$updatedTemplate['host']])) { API::Template()->massAdd(['templates' => $updatedTemplate, 'templates_link' => $templateLinkage[$updatedTemplate['host']]]); } } } } while (!empty($independentTemplates)); // if there are templates left in $templates, then they have unresolved references foreach ($templates as $template) { $unresolvedReferences = []; foreach ($template['templates'] as $linkedTemplate) { if (!$this->referencer->resolveTemplate($linkedTemplate['name'])) { $unresolvedReferences[] = $linkedTemplate['name']; } } throw new Exception(_n('Cannot import template "%1$s", linked template "%2$s" does not exist.', 'Cannot import template "%1$s", linked templates "%2$s" do not exist.', $template['host'], implode(', ', $unresolvedReferences), count($unresolvedReferences))); } }
public function checkInput(&$maps, $method) { $create = $method == 'create'; $update = $method == 'update'; $delete = $method == 'delete'; // permissions if ($update || $delete) { $mapDbFields = array('sysmapid' => null); $dbMaps = $this->get(array('sysmapids' => zbx_objectValues($maps, 'sysmapid'), 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'preservekeys' => true, 'selectLinks' => API_OUTPUT_EXTEND, 'selectSelements' => API_OUTPUT_EXTEND, 'selectUrls' => API_OUTPUT_EXTEND)); } else { $mapDbFields = array('name' => null, 'width' => null, 'height' => null, 'urls' => array(), 'selements' => array(), 'links' => array()); } $mapNames = array(); foreach ($maps as &$map) { if (!check_db_fields($mapDbFields, $map)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect fields for sysmap.')); } if ($update || $delete) { if (!isset($dbMaps[$map['sysmapid']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } $dbMap = array_merge($dbMaps[$map['sysmapid']], $map); } else { $dbMap = $map; } if (isset($map['name'])) { if (isset($mapNames[$map['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate map name for map "%s".', $dbMap['name'])); } else { $mapNames[$map['name']] = $update ? $map['sysmapid'] : 1; } } if (isset($map['width']) && ($map['width'] > 65535 || $map['width'] < 1)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect map width value for map "%s".', $dbMap['name'])); } if (isset($map['height']) && ($map['height'] > 65535 || $map['height'] < 1)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect map height value for map "%s".', $dbMap['name'])); } // labels $mapLabels = array('label_type' => array('typeName' => _('icon'))); if ($dbMap['label_format'] == SYSMAP_LABEL_ADVANCED_ON) { $mapLabels['label_type_hostgroup'] = array('string' => 'label_string_hostgroup', 'typeName' => _('host group')); $mapLabels['label_type_host'] = array('string' => 'label_string_host', 'typeName' => _('host')); $mapLabels['label_type_trigger'] = array('string' => 'label_string_trigger', 'typeName' => _('trigger')); $mapLabels['label_type_map'] = array('string' => 'label_string_map', 'typeName' => _('map')); $mapLabels['label_type_image'] = array('string' => 'label_string_image', 'typeName' => _('image')); } foreach ($mapLabels as $labelName => $labelData) { if (!isset($map[$labelName])) { continue; } if (sysmapElementLabel($map[$labelName]) === false) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } if ($map[$labelName] == MAP_LABEL_TYPE_CUSTOM) { if (!isset($labelData['string'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } if (!isset($map[$labelData['string']]) || zbx_empty($map[$labelData['string']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Custom label for map "%2$s" elements of type "%1$s" may not be empty.', $labelData['typeName'], $dbMap['name'])); } } if ($labelName == 'label_type_image' && $map[$labelName] == MAP_LABEL_TYPE_STATUS) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } if ($labelName == 'label_type' || $labelName == 'label_type_host') { continue; } if ($map[$labelName] == MAP_LABEL_TYPE_IP) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } } // validating grid options $possibleGridSizes = array(20, 40, 50, 75, 100); if ($update || $create) { // grid size if (isset($map['grid_size']) && !in_array($map['grid_size'], $possibleGridSizes)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Value "%1$s" is invalid for parameter "grid_show". Choices are: "%2$s".', $map['grid_size'], implode('", "', $possibleGridSizes))); } // grid auto align if (isset($map['grid_align']) && $map['grid_align'] != SYSMAP_GRID_ALIGN_ON && $map['grid_align'] != SYSMAP_GRID_ALIGN_OFF) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Value "%1$s" is invalid for parameter "grid_align". Choices are: "%2$s" and "%3$s"', $map['grid_align'], SYSMAP_GRID_ALIGN_ON, SYSMAP_GRID_ALIGN_OFF)); } // grid show if (isset($map['grid_show']) && $map['grid_show'] != SYSMAP_GRID_SHOW_ON && $map['grid_show'] != SYSMAP_GRID_SHOW_OFF) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Value "%1$s" is invalid for parameter "grid_show". Choices are: "%2$s" and "%3$s".', $map['grid_show'], SYSMAP_GRID_SHOW_ON, SYSMAP_GRID_SHOW_OFF)); } } // urls if (isset($map['urls']) && !empty($map['urls'])) { $urlNames = zbx_toHash($map['urls'], 'name'); foreach ($map['urls'] as $url) { if ($url['name'] === '' || $url['url'] === '') { self::exception(ZBX_API_ERROR_PARAMETERS, _s('URL should have both "name" and "url" fields for map "%s".', $dbMap['name'])); } if (!isset($urlNames[$url['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('URL name should be unique for map "%s".', $dbMap['name'])); } unset($urlNames[$url['name']]); } } // map selement links if (!empty($map['links'])) { $selementIds = zbx_objectValues($dbMap['selements'], 'selementid'); foreach ($map['links'] as $link) { if (!in_array($link['selementid1'], $selementIds)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Link selementid1 field is pointing to a nonexistent map selement ID "%1$s" for map "%2$s".', $link['selementid1'], $dbMap['name'])); } if (!in_array($link['selementid2'], $selementIds)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Link selementid2 field is pointing to a nonexistent map selement ID "%1$s" for map "%2$s".', $link['selementid2'], $dbMap['name'])); } } } } unset($map); // exists if (($create || $update) && $mapNames) { $existDbMaps = $this->get(array('filter' => array('name' => array_keys($mapNames)), 'output' => array('sysmapid', 'name'), 'nopermissions' => true)); foreach ($existDbMaps as $dbMap) { if ($create || bccomp($mapNames[$dbMap['name']], $dbMap['sysmapid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Map with name "%s" already exists.', $dbMap['name'])); } } } return $update || $delete ? $dbMaps : true; }
protected function inherit($applications, $hostids = null) { if (empty($applications)) { return $applications; } $applications = zbx_toHash($applications, 'applicationid'); $chdHosts = API::Host()->get(array('output' => array('hostid', 'host'), 'templateids' => zbx_objectValues($applications, 'hostid'), 'hostids' => $hostids, 'preservekeys' => 1, 'nopermissions' => 1, 'templated_hosts' => 1)); if (empty($chdHosts)) { return true; } $insertApplications = array(); $updateApplications = array(); foreach ($chdHosts as $hostid => $host) { $templateids = zbx_toHash($host['templates'], 'templateid'); // skip applications not from parent templates of current host $parentApplications = array(); foreach ($applications as $parentApplicationId => $parentApplication) { if (isset($templateids[$parentApplication['hostid']])) { $parentApplications[$parentApplicationId] = $parentApplication; } } // check existing items to decide insert or update $exApplications = $this->get(array('output' => API_OUTPUT_EXTEND, 'hostids' => $hostid, 'preservekeys' => true, 'nopermissions' => true)); $exApplicationsNames = zbx_toHash($exApplications, 'name'); $exApplicationsTpl = zbx_toHash($exApplications, 'templateid'); foreach ($parentApplications as $parentApplicationId => $parentApplication) { $exApplication = null; // update by templateid if (isset($exApplicationsTpl[$parentApplicationId])) { $exApplication = $exApplicationsTpl[$parentApplicationId]; } // update by name if (isset($parentApplication['name']) && isset($exApplicationsNames[$parentApplication['name']])) { $exApplication = $exApplicationsNames[$parentApplication['name']]; if ($exApplication['templateid'] > 0 && !idcmp($exApplication['templateid'], $parentApplication['applicationid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Application "%1$s" already exists for host "%2$s".', $exApplication['name'], $host['name'])); } } $newApplication = $parentApplication; $newApplication['hostid'] = $host['hostid']; $newApplication['templateid'] = $parentApplication['applicationid']; if ($exApplication) { $newApplication['applicationid'] = $exApplication['applicationid']; $updateApplications[] = $newApplication; } else { $insertApplications[] = $newApplication; } } } $this->createReal($insertApplications); $this->updateReal($updateApplications); $inheritedApplications = array_merge($insertApplications, $updateApplications); $this->inherit($inheritedApplications); return true; }