/** * Checks if all of the global macros with globalmacroids given in $globalmacroids are present in $globalmacros. * Assumes the "globalmacroids" field is valid. * * @param array $globalmacroids * * @throws APIException if any of the global macros is not present in $globalmacros. */ protected function checkIfGlobalMacrosExist(array $globalmacroids) { if ($globalmacroids) { $db_globamacros = API::getApiService()->select('globalmacro', ['output' => ['globalmacroid'], 'globalmacroids' => $globalmacroids, 'preservekeys' => true]); foreach ($globalmacroids as $globalmacroid) { if (!array_key_exists($globalmacroid, $db_globamacros)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Macro with globalmacroid "%1$s" does not exist.', $globalmacroid)); } } } }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); // selectGroups if ($options['selectGroups'] !== null && $options['selectGroups'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'maintenanceid', 'groupid', 'maintenances_groups'); $groups = API::HostGroup()->get(['output' => $options['selectGroups'], 'hostgroupids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapMany($result, $groups, 'groups'); } // selectHosts if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'maintenanceid', 'hostid', 'maintenances_hosts'); $groups = API::Host()->get(['output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapMany($result, $groups, 'hosts'); } // selectTimeperiods if ($options['selectTimeperiods'] !== null && $options['selectTimeperiods'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'maintenanceid', 'timeperiodid', 'maintenances_windows'); $timeperiods = API::getApiService()->select('timeperiods', ['output' => $options['selectTimeperiods'], 'filter' => ['timeperiodid' => $relationMap->getRelatedIds()], 'preservekeys' => true]); $result = $relationMap->mapMany($result, $timeperiods, 'timeperiods'); } return $result; }
/** * Fetches the fields given in $fields from the database and extends the objects with the loaded data. * * @param string $tableName * @param array $objects * @param array $fields * * @return array */ protected function extendObjects($tableName, array $objects, array $fields) { if ($objects) { $dbObjects = API::getApiService()->select($tableName, ['output' => $fields, $this->pkOption($tableName) => zbx_objectValues($objects, $this->pk($tableName)), 'preservekeys' => true]); foreach ($objects as &$object) { $pk = $object[$this->pk($tableName)]; if (isset($dbObjects[$pk])) { check_db_fields($dbObjects[$pk], $object); } } unset($object); } return $objects; }
/** * Checks if all of the global macros with globalmacroids given in $globalMacroIds are present in $globalMacros. * Assumes the "globalmacroids" field is valid. * * @param array $globalMacroIds * * @throws APIException if any of the global macros is not present in $globalMacros */ protected function checkIfGlobalMacrosExist(array $globalMacroIds) { $globalMacros = API::getApiService()->select('globalmacro', array('output' => array('globalmacroid'), 'globalmacroids' => $globalMacroIds)); $globalMacros = zbx_toHash($globalMacros, 'globalmacroid'); foreach ($globalMacroIds as $globalMacroId) { if (!isset($globalMacros[$globalMacroId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Macro with globalmacroid "%1$s" does not exist.', $globalMacroId)); } } }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $hostids = array_keys($result); // adding inventories if ($options['selectInventory'] !== null) { $relationMap = $this->createRelationMap($result, 'hostid', 'hostid'); $inventory = API::getApiService()->select('host_inventory', ['output' => $options['selectInventory'], 'filter' => ['hostid' => $hostids]]); $result = $relationMap->mapOne($result, zbx_toHash($inventory, 'hostid'), 'inventory'); } // adding hostinterfaces if ($options['selectInterfaces'] !== null) { if ($options['selectInterfaces'] != API_OUTPUT_COUNT) { $interfaces = API::HostInterface()->get(['output' => $this->outputExtend($options['selectInterfaces'], ['hostid', 'interfaceid']), 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true]); // we need to order interfaces for proper linkage and viewing order_result($interfaces, 'interfaceid', ZBX_SORT_UP); $relationMap = $this->createRelationMap($interfaces, 'hostid', 'interfaceid'); $interfaces = $this->unsetExtraFields($interfaces, ['hostid', 'interfaceid'], $options['selectInterfaces']); $result = $relationMap->mapMany($result, $interfaces, 'interfaces', $options['limitSelects']); } else { $interfaces = API::HostInterface()->get(['hostids' => $hostids, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true]); $interfaces = zbx_toHash($interfaces, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['interfaces'] = isset($interfaces[$hostid]) ? $interfaces[$hostid]['rowscount'] : 0; } } } // adding screens if ($options['selectScreens'] !== null) { if ($options['selectScreens'] != API_OUTPUT_COUNT) { $screens = API::TemplateScreen()->get(['output' => $this->outputExtend($options['selectScreens'], ['hostid']), 'hostids' => $hostids, 'nopermissions' => true]); if (!is_null($options['limitSelects'])) { order_result($screens, 'name'); } // inherited screens do not have a unique screenid, so we're building a map using array keys $relationMap = new CRelationMap(); foreach ($screens as $key => $screen) { $relationMap->addRelation($screen['hostid'], $key); } $screens = $this->unsetExtraFields($screens, ['hostid'], $options['selectScreens']); $result = $relationMap->mapMany($result, $screens, 'screens', $options['limitSelects']); } else { $screens = API::TemplateScreen()->get(['hostids' => $hostids, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true]); $screens = zbx_toHash($screens, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['screens'] = isset($screens[$hostid]) ? $screens[$hostid]['rowscount'] : 0; } } } // adding discovery rule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { // discovered items $discoveryRules = DBFetchArray(DBselect('SELECT hd.hostid,hd2.parent_itemid' . ' FROM host_discovery hd,host_discovery hd2' . ' WHERE ' . dbConditionInt('hd.hostid', $hostids) . ' AND hd.parent_hostid=hd2.hostid')); $relationMap = $this->createRelationMap($discoveryRules, 'hostid', 'parent_itemid'); $discoveryRules = API::DiscoveryRule()->get(['output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding host discovery if ($options['selectHostDiscovery'] !== null) { $hostDiscoveries = API::getApiService()->select('host_discovery', ['output' => $this->outputExtend($options['selectHostDiscovery'], ['hostid']), 'filter' => ['hostid' => $hostids], 'preservekeys' => true]); $relationMap = $this->createRelationMap($hostDiscoveries, 'hostid', 'hostid'); $hostDiscoveries = $this->unsetExtraFields($hostDiscoveries, ['hostid'], $options['selectHostDiscovery']); $result = $relationMap->mapOne($result, $hostDiscoveries, 'hostDiscovery'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $iconMapIds = array_keys($result); if ($options['selectMappings'] !== null && $options['selectMappings'] != API_OUTPUT_COUNT) { $mappings = API::getApiService()->select('icon_mapping', ['output' => $this->outputExtend($options['selectMappings'], ['iconmapid', 'iconmappingid']), 'filter' => ['iconmapid' => $iconMapIds], 'preservekeys' => true]); $relationMap = $this->createRelationMap($mappings, 'iconmapid', 'iconmappingid'); $mappings = $this->unsetExtraFields($mappings, ['iconmapid', 'iconmappingid'], $options['selectMappings']); $result = $relationMap->mapMany($result, $mappings, 'mappings'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); // Select mappings for value map. if ($options['selectMappings'] !== null) { if ($options['selectMappings'] == API_OUTPUT_COUNT) { $db_mappings = DBselect('SELECT m.valuemapid,COUNT(*) AS cnt' . ' FROM mappings m' . ' WHERE ' . dbConditionInt('m.valuemapid', array_keys($result)) . ' GROUP BY m.valuemapid'); foreach ($result as &$valuemap) { $valuemap['mappings'] = 0; } unset($valuemap); while ($db_mapping = DBfetch($db_mappings)) { $result[$db_mapping['valuemapid']]['mappings'] = $db_mapping['cnt']; } } else { $db_mappings = API::getApiService()->select('mappings', ['output' => $this->outputExtend($options['selectMappings'], ['valuemapid']), 'filter' => ['valuemapid' => array_keys($result)]]); foreach ($result as &$valuemap) { $valuemap['mappings'] = []; } unset($valuemap); foreach ($db_mappings as $db_mapping) { $valuemapid = $db_mapping['valuemapid']; unset($db_mapping['mappingid'], $db_mapping['valuemapid']); $result[$valuemapid]['mappings'][] = $db_mapping; } } } return $result; }
/** * Get screen data. * * @param array $options * @param bool $options['with_items'] only with items * @param bool $options['editable'] only with read-write permission. Ignored for SuperAdmins * @param int $options['count'] count Hosts, returned column name is rowscount * @param string $options['pattern'] search hosts by pattern in host names * @param int $options['limit'] limit selection * @param string $options['order'] deprecated parameter (for now) * * @return array */ public function get($options = array()) { $result = array(); $userType = self::$userData['type']; $userid = self::$userData['userid']; $sqlParts = array('select' => array('screens' => 's.screenid,s.templateid'), 'from' => array('screens' => 'screens s'), 'where' => array('template' => 's.templateid IS NOT NULL'), 'order' => array(), 'group' => array(), 'limit' => null); $defOptions = array('screenids' => null, 'screenitemids' => null, 'templateids' => null, 'hostids' => null, 'editable' => null, 'noInheritance' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectScreenItems' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($defOptions, $options); if (!is_null($options['editable']) || is_null($options['hostids']) && is_null($options['templateids'])) { $options['noInheritance'] = 1; } // editable + PERMISSION CHECK if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) { // TODO: think how we could combine templateids && hostids options if (!is_null($options['templateids'])) { unset($options['hostids']); $options['templateids'] = API::Template()->get(array('output' => array('templateid'), 'templateids' => $options['templateids'], 'editable' => $options['editable'], 'preservekeys' => true)); $options['templateids'] = array_keys($options['templateids']); } elseif (!is_null($options['hostids'])) { $options['templateids'] = API::Host()->get(array('output' => array('hostid'), 'hostids' => $options['hostids'], 'editable' => $options['editable'], 'preservekeys' => true)); $options['templateids'] = array_keys($options['templateids']); } else { // TODO: get screen $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ; $userGroups = getUserGroupsByUserId($userid); $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE s.templateid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ' AND MAX(r.permission)>=' . zbx_dbstr($permission) . ')'; } } // screenids if (!is_null($options['screenids'])) { zbx_value2array($options['screenids']); $sqlParts['where'][] = dbConditionInt('s.screenid', $options['screenids']); } // screenitemids if (!is_null($options['screenitemids'])) { zbx_value2array($options['screenitemids']); $sqlParts['from']['screens_items'] = 'screens_items si'; $sqlParts['where']['ssi'] = 'si.screenid=s.screenid'; $sqlParts['where'][] = dbConditionInt('si.screenitemid', $options['screenitemids']); } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if (isset($options['hostids']) && !is_null($options['hostids'])) { zbx_value2array($options['hostids']); $options['hostids'] = array_merge($options['hostids'], $options['templateids']); } else { $options['hostids'] = $options['templateids']; } } // hostids $templatesChain = array(); if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); // collecting template chain $linkedTemplateids = $options['hostids']; $childTemplateids = $options['hostids']; while (is_null($options['noInheritance']) && !empty($childTemplateids)) { $sql = 'SELECT ht.*' . ' FROM hosts_templates ht' . ' WHERE ' . dbConditionInt('hostid', $childTemplateids); $dbTemplates = DBselect($sql); $childTemplateids = array(); while ($link = DBfetch($dbTemplates)) { $childTemplateids[$link['templateid']] = $link['templateid']; $linkedTemplateids[$link['templateid']] = $link['templateid']; createParentToChildRelation($templatesChain, $link, 'templateid', 'hostid'); } } if (!is_null($options['groupCount'])) { $sqlParts['group']['templateid'] = 's.templateid'; } $sqlParts['where']['templateid'] = dbConditionInt('s.templateid', $linkedTemplateids); } // filter if (is_array($options['filter'])) { $this->dbFilter('screens s', $options, $sqlParts); } // search if (is_array($options['search'])) { zbx_db_search('screens s', $options, $sqlParts); } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sqlParts['limit'] = $options['limit']; } $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts); $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']); while ($screen = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $screen; } else { $result = $screen['rowscount']; } } else { $result[$screen['screenid']] = $screen; } } if ($options['countOutput'] !== null && $options['groupCount'] === null) { return $result; } $screenIds = array_keys($result); // adding screenitems if ($options['selectScreenItems'] !== null && $options['selectScreenItems'] != API_OUTPUT_COUNT) { $screenItems = API::getApiService()->select('screens_items', array('output' => $this->outputExtend($options['selectScreenItems'], array('screenid', 'screenitemid', 'resourcetype', 'resourceid')), 'filter' => array('screenid' => $screenIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($screenItems, 'screenid', 'screenitemid'); foreach ($screenItems as $screenItem) { switch ($screenItem['resourcetype']) { case SCREEN_RESOURCE_GRAPH: $graphids[$screenItem['resourceid']] = $screenItem['resourceid']; break; case SCREEN_RESOURCE_SIMPLE_GRAPH: case SCREEN_RESOURCE_PLAIN_TEXT: $itemids[$screenItem['resourceid']] = $screenItem['resourceid']; break; } } $screenItems = $this->unsetExtraFields($screenItems, array('screenid', 'screenitemid', 'resourceid', 'resourcetype'), $options['selectScreenItems']); $result = $relationMap->mapMany($result, $screenItems, 'screenitems'); } // creating linkage of template -> real objects if (!is_null($options['selectScreenItems']) && !is_null($options['hostids'])) { // prepare graphs if (!empty($graphids)) { $tplGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true)); $dbGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'selectHosts' => array('hostid'), 'hostids' => $options['hostids'], 'filter' => array('name' => zbx_objectValues($tplGraphs, 'name')), 'nopermissions' => true, 'preservekeys' => true)); $realGraphs = array(); foreach ($dbGraphs as $graph) { $host = reset($graph['hosts']); unset($graph['hosts']); if (!isset($realGraphs[$host['hostid']])) { $realGraphs[$host['hostid']] = array(); } $realGraphs[$host['hostid']][$graph['name']] = $graph; } } // prepare items if (!empty($itemids)) { $tplItems = API::Item()->get(array('output' => array('itemid', 'key_', 'hostid'), 'itemids' => $itemids, 'nopermissions' => true, 'preservekeys' => true)); $dbItems = API::Item()->get(array('output' => array('itemid', 'key_', 'hostid'), 'hostids' => $options['hostids'], 'filter' => array('key_' => zbx_objectValues($tplItems, 'key_')), 'nopermissions' => true, 'preservekeys' => true)); $realItems = array(); foreach ($dbItems as $item) { unset($item['hosts']); if (!isset($realItems[$item['hostid']])) { $realItems[$item['hostid']] = array(); } $realItems[$item['hostid']][$item['key_']] = $item; } } } // hashing $options['hostids'] = zbx_toHash($options['hostids']); if (is_null($options['countOutput']) || !is_null($options['countOutput']) && !is_null($options['groupCount'])) { // creating copies of templated screens (inheritance) // screenNum is needed due to we can't refer to screenid/hostid/templateid as they will repeat $screenNum = 0; $vrtResult = array(); foreach ($result as $screen) { if (is_null($options['hostids']) || isset($options['hostids'][$screen['templateid']])) { $screenNum++; $vrtResult[$screenNum] = $screen; $vrtResult[$screenNum]['hostid'] = $screen['templateid']; } if (!isset($templatesChain[$screen['templateid']])) { continue; } foreach ($templatesChain[$screen['templateid']] as $hostid) { if (!isset($options['hostids'][$hostid])) { continue; } $screenNum++; $vrtResult[$screenNum] = $screen; $vrtResult[$screenNum]['hostid'] = $hostid; if (!isset($vrtResult[$screenNum]['screenitems'])) { continue; } foreach ($vrtResult[$screenNum]['screenitems'] as &$screenitem) { switch ($screenitem['resourcetype']) { case SCREEN_RESOURCE_GRAPH: $graphName = $tplGraphs[$screenitem['resourceid']]['name']; $screenitem['real_resourceid'] = $realGraphs[$hostid][$graphName]['graphid']; break; case SCREEN_RESOURCE_SIMPLE_GRAPH: case SCREEN_RESOURCE_PLAIN_TEXT: $itemKey = $tplItems[$screenitem['resourceid']]['key_']; $screenitem['real_resourceid'] = $realItems[$hostid][$itemKey]['itemid']; break; } } unset($screenitem); } } $result = array_values($vrtResult); } if (!is_null($options['countOutput'])) { return $result; } if ($result) { $result = $this->unsetExtraFields($result, array('templateid'), $options['output']); } // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } elseif (!is_null($options['noInheritance'])) { $result = zbx_toHash($result, 'screenid'); } return $result; }
protected function validateMassRemove(array $data) { // check permissions $this->checkHostPermissions($data['hostids']); // check interfaces foreach ($data['interfaces'] as $interface) { if (!isset($interface['dns']) || !isset($interface['ip']) || !isset($interface['port'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.')); } $this->checkDns($interface); $this->checkIp($interface); $this->checkPort($interface); $this->checkBulk($interface); // check main interfaces $interfacesToRemove = API::getApiService()->select($this->tableName(), ['output' => ['interfaceid'], 'filter' => ['hostid' => $data['hostids'], 'ip' => $interface['ip'], 'dns' => $interface['dns'], 'port' => $interface['port'], 'bulk' => $interface['bulk']]]); if ($interfacesToRemove) { $this->checkMainInterfacesOnDelete(zbx_objectValues($interfacesToRemove, 'interfaceid')); } } }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $actionIds = array_keys($result); // adding formulas if ($options['selectFilter'] !== null) { $formulaRequested = $this->outputIsRequested('formula', $options['selectFilter']); $evalFormulaRequested = $this->outputIsRequested('eval_formula', $options['selectFilter']); $conditionsRequested = $this->outputIsRequested('conditions', $options['selectFilter']); $filters = array(); foreach ($result as $action) { $filters[$action['actionid']] = array('evaltype' => $action['evaltype'], 'formula' => isset($action['formula']) ? $action['formula'] : ''); } if ($formulaRequested || $evalFormulaRequested || $conditionsRequested) { $conditions = API::getApiService()->select('conditions', array('output' => array('actionid', 'conditionid', 'conditiontype', 'operator', 'value'), 'filter' => array('actionid' => $actionIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($conditions, 'actionid', 'conditionid'); $filters = $relationMap->mapMany($filters, $conditions, 'conditions'); foreach ($filters as &$filter) { // in case of a custom expression - use the given formula if ($filter['evaltype'] == CONDITION_EVAL_TYPE_EXPRESSION) { $formula = $filter['formula']; } else { $conditions = $filter['conditions']; // sort conditions $sortFields = array(array('field' => 'conditiontype', 'order' => ZBX_SORT_DOWN), array('field' => 'operator', 'order' => ZBX_SORT_DOWN), array('field' => 'value', 'order' => ZBX_SORT_DOWN)); CArrayHelper::sort($conditions, $sortFields); $conditionsForFormula = array(); foreach ($conditions as $condition) { $conditionsForFormula[$condition['conditionid']] = $condition['conditiontype']; } $formula = CConditionHelper::getFormula($conditionsForFormula, $filter['evaltype']); } // generate formulaids from the effective formula $formulaIds = CConditionHelper::getFormulaIds($formula); foreach ($filter['conditions'] as &$condition) { $condition['formulaid'] = $formulaIds[$condition['conditionid']]; } unset($condition); // generated a letter based formula only for actions with custom expressions if ($formulaRequested && $filter['evaltype'] == CONDITION_EVAL_TYPE_EXPRESSION) { $filter['formula'] = CConditionHelper::replaceNumericIds($formula, $formulaIds); } if ($evalFormulaRequested) { $filter['eval_formula'] = CConditionHelper::replaceNumericIds($formula, $formulaIds); } } unset($filter); } // add filters to the result foreach ($result as &$action) { $action['filter'] = $filters[$action['actionid']]; } unset($action); } // adding operations if ($options['selectOperations'] !== null && $options['selectOperations'] != API_OUTPUT_COUNT) { $operations = API::getApiService()->select('operations', array('output' => $this->outputExtend($options['selectOperations'], array('operationid', 'actionid', 'operationtype')), 'filter' => array('actionid' => $actionIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($operations, 'actionid', 'operationid'); $operationIds = $relationMap->getRelatedIds(); if ($this->outputIsRequested('opconditions', $options['selectOperations'])) { foreach ($operations as &$operation) { $operation['opconditions'] = array(); } unset($operation); $res = DBselect('SELECT op.* FROM opconditions op WHERE ' . dbConditionInt('op.operationid', $operationIds)); while ($opcondition = DBfetch($res)) { $operations[$opcondition['operationid']]['opconditions'][] = $opcondition; } } $opmessage = $opcommand = $opgroup = $optemplate = array(); foreach ($operations as $operationid => $operation) { switch ($operation['operationtype']) { case OPERATION_TYPE_MESSAGE: $opmessage[] = $operationid; break; case OPERATION_TYPE_COMMAND: $opcommand[] = $operationid; break; case OPERATION_TYPE_GROUP_ADD: case OPERATION_TYPE_GROUP_REMOVE: $opgroup[] = $operationid; break; case OPERATION_TYPE_TEMPLATE_ADD: case OPERATION_TYPE_TEMPLATE_REMOVE: $optemplate[] = $operationid; break; case OPERATION_TYPE_HOST_ADD: case OPERATION_TYPE_HOST_REMOVE: case OPERATION_TYPE_HOST_ENABLE: case OPERATION_TYPE_HOST_DISABLE: } } // get OPERATION_TYPE_MESSAGE data if (!empty($opmessage)) { if ($this->outputIsRequested('opmessage', $options['selectOperations'])) { foreach ($opmessage as $operationId) { $operations[$operationId]['opmessage'] = array(); } $dbOpmessages = DBselect('SELECT o.operationid,o.default_msg,o.subject,o.message,o.mediatypeid' . ' FROM opmessage o' . ' WHERE ' . dbConditionInt('operationid', $opmessage)); while ($dbOpmessage = DBfetch($dbOpmessages)) { $operations[$dbOpmessage['operationid']]['opmessage'] = $dbOpmessage; } } if ($this->outputIsRequested('opmessage_grp', $options['selectOperations'])) { foreach ($opmessage as $operationId) { $operations[$operationId]['opmessage_grp'] = array(); } $dbOpmessageGrp = DBselect('SELECT og.operationid,og.usrgrpid' . ' FROM opmessage_grp og' . ' WHERE ' . dbConditionInt('operationid', $opmessage)); while ($opmessageGrp = DBfetch($dbOpmessageGrp)) { $operations[$opmessageGrp['operationid']]['opmessage_grp'][] = $opmessageGrp; } } if ($this->outputIsRequested('opmessage_usr', $options['selectOperations'])) { foreach ($opmessage as $operationId) { $operations[$operationId]['opmessage_usr'] = array(); } $dbOpmessageUsr = DBselect('SELECT ou.operationid,ou.userid' . ' FROM opmessage_usr ou' . ' WHERE ' . dbConditionInt('operationid', $opmessage)); while ($opmessageUsr = DBfetch($dbOpmessageUsr)) { $operations[$opmessageUsr['operationid']]['opmessage_usr'][] = $opmessageUsr; } } } // get OPERATION_TYPE_COMMAND data if (!empty($opcommand)) { if ($this->outputIsRequested('opcommand', $options['selectOperations'])) { foreach ($opcommand as $operationId) { $operations[$operationId]['opcommand'] = array(); } $dbOpcommands = DBselect('SELECT o.*' . ' FROM opcommand o' . ' WHERE ' . dbConditionInt('operationid', $opcommand)); while ($dbOpcommand = DBfetch($dbOpcommands)) { $operations[$dbOpcommand['operationid']]['opcommand'] = $dbOpcommand; } } if ($this->outputIsRequested('opcommand_hst', $options['selectOperations'])) { foreach ($opcommand as $operationId) { $operations[$operationId]['opcommand_hst'] = array(); } $dbOpcommandHst = DBselect('SELECT oh.opcommand_hstid,oh.operationid,oh.hostid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('operationid', $opcommand)); while ($opcommandHst = DBfetch($dbOpcommandHst)) { $operations[$opcommandHst['operationid']]['opcommand_hst'][] = $opcommandHst; } } if ($this->outputIsRequested('opcommand_grp', $options['selectOperations'])) { foreach ($opcommand as $operationId) { $operations[$operationId]['opcommand_grp'] = array(); } $dbOpcommandGrp = DBselect('SELECT og.opcommand_grpid,og.operationid,og.groupid' . ' FROM opcommand_grp og' . ' WHERE ' . dbConditionInt('operationid', $opcommand)); while ($opcommandGrp = DBfetch($dbOpcommandGrp)) { $operations[$opcommandGrp['operationid']]['opcommand_grp'][] = $opcommandGrp; } } } // get OPERATION_TYPE_GROUP_ADD, OPERATION_TYPE_GROUP_REMOVE data if (!empty($opgroup)) { if ($this->outputIsRequested('opgroup', $options['selectOperations'])) { foreach ($opgroup as $operationId) { $operations[$operationId]['opgroup'] = array(); } $dbOpgroup = DBselect('SELECT o.operationid,o.groupid' . ' FROM opgroup o' . ' WHERE ' . dbConditionInt('operationid', $opgroup)); while ($opgroup = DBfetch($dbOpgroup)) { $operations[$opgroup['operationid']]['opgroup'][] = $opgroup; } } } // get OPERATION_TYPE_TEMPLATE_ADD, OPERATION_TYPE_TEMPLATE_REMOVE data if (!empty($optemplate)) { if ($this->outputIsRequested('optemplate', $options['selectOperations'])) { foreach ($optemplate as $operationId) { $operations[$operationId]['optemplate'] = array(); } $dbOptemplate = DBselect('SELECT o.operationid,o.templateid' . ' FROM optemplate o' . ' WHERE ' . dbConditionInt('operationid', $optemplate)); while ($optemplate = DBfetch($dbOptemplate)) { $operations[$optemplate['operationid']]['optemplate'][] = $optemplate; } } } $operations = $this->unsetExtraFields($operations, array('operationid', 'actionid', 'operationtype'), $options['selectOperations']); $result = $relationMap->mapMany($result, $operations, 'operations'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $graphids = array_keys($result); // adding Items if ($options['selectItems'] !== null && $options['selectItems'] !== API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'graphid', 'itemid', 'graphs_items'); $items = API::Item()->get(array('output' => $options['selectItems'], 'itemids' => $relationMap->getRelatedIds(), 'webitems' => true, 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $items, 'items'); } // adding discoveryRule if ($options['selectDiscoveryRule'] !== null) { $dbRules = DBselect('SELECT id.parent_itemid,gd.graphid' . ' FROM graph_discovery gd,item_discovery id,graphs_items gi' . ' WHERE ' . dbConditionInt('gd.graphid', $graphids) . ' AND gd.parent_graphid=gi.graphid' . ' AND gi.itemid=id.itemid'); $relationMap = new CRelationMap(); while ($relation = DBfetch($dbRules)) { $relationMap->addRelation($relation['graphid'], $relation['parent_itemid']); } $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding graph discovery if ($options['selectGraphDiscovery'] !== null) { $graphDiscoveries = API::getApiService()->select('graph_discovery', array('output' => $this->outputExtend($options['selectGraphDiscovery'], array('graphid')), 'filter' => array('graphid' => array_keys($result)), 'preservekeys' => true)); $relationMap = $this->createRelationMap($graphDiscoveries, 'graphid', 'graphid'); $graphDiscoveries = $this->unsetExtraFields($graphDiscoveries, array('graphid'), $options['selectGraphDiscovery']); $result = $relationMap->mapOne($result, $graphDiscoveries, 'graphDiscovery'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $itemIds = array_keys($result); // adding items if (!is_null($options['selectItems'])) { if ($options['selectItems'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'parent_itemid', 'itemid', 'item_discovery'); $items = API::ItemPrototype()->get(array('output' => $options['selectItems'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $items, 'items', $options['limitSelects']); } else { $items = API::ItemPrototype()->get(array('discoveryids' => $itemIds, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true)); $items = zbx_toHash($items, 'parent_itemid'); foreach ($result as $itemid => $item) { $result[$itemid]['items'] = isset($items[$itemid]) ? $items[$itemid]['rowscount'] : 0; } } } // adding triggers if (!is_null($options['selectTriggers'])) { if ($options['selectTriggers'] != API_OUTPUT_COUNT) { $relationMap = new CRelationMap(); $res = DBselect('SELECT id.parent_itemid,f.triggerid' . ' FROM item_discovery id,items i,functions f' . ' WHERE ' . dbConditionInt('id.parent_itemid', $itemIds) . ' AND id.itemid=i.itemid' . ' AND i.itemid=f.itemid'); while ($relation = DBfetch($res)) { $relationMap->addRelation($relation['parent_itemid'], $relation['triggerid']); } $triggers = API::TriggerPrototype()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']); } else { $triggers = API::TriggerPrototype()->get(array('discoveryids' => $itemIds, 'countOutput' => true, 'groupCount' => true)); $triggers = zbx_toHash($triggers, 'parent_itemid'); foreach ($result as $itemid => $item) { $result[$itemid]['triggers'] = isset($triggers[$itemid]) ? $triggers[$itemid]['rowscount'] : 0; } } } // adding graphs if (!is_null($options['selectGraphs'])) { if ($options['selectGraphs'] != API_OUTPUT_COUNT) { $relationMap = new CRelationMap(); $res = DBselect('SELECT id.parent_itemid,gi.graphid' . ' FROM item_discovery id,items i,graphs_items gi' . ' WHERE ' . dbConditionInt('id.parent_itemid', $itemIds) . ' AND id.itemid=i.itemid' . ' AND i.itemid=gi.itemid'); while ($relation = DBfetch($res)) { $relationMap->addRelation($relation['parent_itemid'], $relation['graphid']); } $graphs = API::GraphPrototype()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']); } else { $graphs = API::GraphPrototype()->get(array('discoveryids' => $itemIds, 'countOutput' => true, 'groupCount' => true)); $graphs = zbx_toHash($graphs, 'parent_itemid'); foreach ($result as $itemid => $item) { $result[$itemid]['graphs'] = isset($graphs[$itemid]) ? $graphs[$itemid]['rowscount'] : 0; } } } // adding hosts if ($options['selectHostPrototypes'] !== null) { if ($options['selectHostPrototypes'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'parent_itemid', 'hostid', 'host_discovery'); $hostPrototypes = API::HostPrototype()->get(array('output' => $options['selectHostPrototypes'], 'hostids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $hostPrototypes, 'hostPrototypes', $options['limitSelects']); } else { $hostPrototypes = API::HostPrototype()->get(array('discoveryids' => $itemIds, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true)); $hostPrototypes = zbx_toHash($hostPrototypes, 'parent_itemid'); foreach ($result as $itemid => $item) { $result[$itemid]['hostPrototypes'] = isset($hostPrototypes[$itemid]) ? $hostPrototypes[$itemid]['rowscount'] : 0; } } } if ($options['selectFilter'] !== null) { $formulaRequested = $this->outputIsRequested('formula', $options['selectFilter']); $evalFormulaRequested = $this->outputIsRequested('eval_formula', $options['selectFilter']); $conditionsRequested = $this->outputIsRequested('conditions', $options['selectFilter']); $filters = array(); foreach ($result as $rule) { $filters[$rule['itemid']] = array('evaltype' => $rule['evaltype'], 'formula' => isset($rule['formula']) ? $rule['formula'] : ''); } // adding conditions if ($formulaRequested || $evalFormulaRequested || $conditionsRequested) { $conditions = API::getApiService()->select('item_condition', array('output' => array('item_conditionid', 'macro', 'value', 'itemid', 'operator'), 'filter' => array('itemid' => $itemIds), 'preservekeys' => true, 'sortfield' => 'item_conditionid')); $relationMap = $this->createRelationMap($conditions, 'itemid', 'item_conditionid'); $filters = $relationMap->mapMany($filters, $conditions, 'conditions'); foreach ($filters as &$filter) { // in case of a custom expression - use the given formula if ($filter['evaltype'] == CONDITION_EVAL_TYPE_EXPRESSION) { $formula = $filter['formula']; } else { // sort the conditions by macro before generating the formula $conditions = zbx_toHash($filter['conditions'], 'item_conditionid'); $conditions = order_macros($conditions, 'macro'); $formulaConditions = array(); foreach ($conditions as $condition) { $formulaConditions[$condition['item_conditionid']] = $condition['macro']; } $formula = CConditionHelper::getFormula($formulaConditions, $filter['evaltype']); } // generate formulaids from the effective formula $formulaIds = CConditionHelper::getFormulaIds($formula); foreach ($filter['conditions'] as &$condition) { $condition['formulaid'] = $formulaIds[$condition['item_conditionid']]; } unset($condition); // generated a letter based formula only for rules with custom expressions if ($formulaRequested && $filter['evaltype'] == CONDITION_EVAL_TYPE_EXPRESSION) { $filter['formula'] = CConditionHelper::replaceNumericIds($formula, $formulaIds); } if ($evalFormulaRequested) { $filter['eval_formula'] = CConditionHelper::replaceNumericIds($formula, $formulaIds); } } unset($filter); } // add filters to the result foreach ($result as &$rule) { $rule['filter'] = $filters[$rule['itemid']]; } unset($rule); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $screenIds = array_keys($result); // adding ScreenItems if ($options['selectScreenItems'] !== null && $options['selectScreenItems'] != API_OUTPUT_COUNT) { $screenItems = API::getApiService()->select('screens_items', array('output' => $this->outputExtend($options['selectScreenItems'], array('screenid', 'screenitemid')), 'filter' => array('screenid' => $screenIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($screenItems, 'screenid', 'screenitemid'); $screenItems = $this->unsetExtraFields($screenItems, array('screenid', 'screenitemid'), $options['selectScreenItems']); $result = $relationMap->mapMany($result, $screenItems, 'screenitems'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $alertIds = array_keys($result); // adding hosts if ($options['selectHosts'] !== null && $options['selectHosts'] !== API_OUTPUT_COUNT) { // trigger events if ($options['eventobject'] == EVENT_OBJECT_TRIGGER) { $query = DBselect('SELECT a.alertid,i.hostid' . ' FROM alerts a,events e,functions f,items i' . ' WHERE ' . dbConditionInt('a.alertid', $alertIds) . ' AND a.eventid=e.eventid' . ' AND e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['eventobject']) . ' AND e.source=' . zbx_dbstr($options['eventsource'])); } elseif ($options['eventobject'] == EVENT_OBJECT_ITEM || $options['eventobject'] == EVENT_OBJECT_LLDRULE) { $query = DBselect('SELECT a.alertid,i.hostid' . ' FROM alerts a,events e,items i' . ' WHERE ' . dbConditionInt('a.alertid', $alertIds) . ' AND a.eventid=e.eventid' . ' AND e.objectid=i.itemid' . ' AND e.object=' . zbx_dbstr($options['eventobject']) . ' AND e.source=' . zbx_dbstr($options['eventsource'])); } $relationMap = new CRelationMap(); while ($relation = DBfetch($query)) { $relationMap->addRelation($relation['alertid'], $relation['hostid']); } $hosts = API::Host()->get(['output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapMany($result, $hosts, 'hosts'); } // adding users if ($options['selectUsers'] !== null && $options['selectUsers'] !== API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'alertid', 'userid'); $users = API::User()->get(['output' => $options['selectUsers'], 'userids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapMany($result, $users, 'users'); } // adding media types if ($options['selectMediatypes'] !== null && $options['selectMediatypes'] !== API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'alertid', 'mediatypeid'); $mediatypes = API::getApiService()->select('media_type', ['output' => $options['selectMediatypes'], 'filter' => ['mediatypeid' => $relationMap->getRelatedIds()], 'preservekeys' => true]); $result = $relationMap->mapMany($result, $mediatypes, 'mediatypes'); } return $result; }
/** * Update existing drules. * * @param array( * druleid => int, * name => string, * proxy_hostid => int, * iprange => string, * delay => string, * status => int, * dchecks => array( * array( * dcheckid => int, * type => int, * ports => string, * key_ => string, * snmp_community => string, * snmpv3_securityname => string, * snmpv3_securitylevel => int, * snmpv3_authpassphrase => string, * snmpv3_privpassphrase => string, * uniq => int, * ), ... * ) * ) $dRules * * @return array */ public function update(array $dRules) { $this->checkInput($dRules); $this->validateRequiredFields($dRules, __FUNCTION__); $dRuleIds = zbx_objectValues($dRules, 'druleid'); $dRulesDb = API::DRule()->get(array('druleids' => $dRuleIds, 'output' => API_OUTPUT_EXTEND, 'selectDChecks' => API_OUTPUT_EXTEND, 'editable' => true, 'preservekeys' => true)); $defaultValues = DB::getDefaults('dchecks'); $dRulesUpdate = array(); $dCheckIdsDelete = array(); $dChecksCreate = array(); $dRuleNamesChanged = array(); // validate drule duplicate names foreach ($dRules as $dRule) { if (!isset($dRulesDb[$dRule['druleid']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } if ($dRulesDb[$dRule['druleid']]['name'] !== $dRule['name']) { if (isset($dRuleNamesChanged[$dRule['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Discovery rule "%1$s" already exists.', $dRule['name'])); } else { $dRuleNamesChanged[$dRule['name']] = $dRule['name']; } } } if ($dRuleNamesChanged) { $dbDRules = API::getApiService()->select($this->tableName(), array('output' => array('name'), 'filter' => array('name' => $dRuleNamesChanged), 'limit' => 1)); if ($dbDRules) { $dbDRule = reset($dbDRules); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Discovery rule "%1$s" already exists.', $dbDRule['name'])); } } foreach ($dRules as $dRule) { $dRulesUpdate[] = array('values' => $dRule, 'where' => array('druleid' => $dRule['druleid'])); // update dchecks $dbChecks = $dRulesDb[$dRule['druleid']]['dchecks']; $newChecks = array(); $oldChecks = array(); foreach ($dRule['dchecks'] as $check) { $check['druleid'] = $dRule['druleid']; if (!isset($check['dcheckid'])) { $newChecks[] = array_merge($defaultValues, $check); } else { $oldChecks[] = $check; } } $delDCheckIds = array_diff(zbx_objectValues($dbChecks, 'dcheckid'), zbx_objectValues($oldChecks, 'dcheckid')); if ($delDCheckIds) { $this->deleteActionConditions($delDCheckIds); } DB::replace('dchecks', $dbChecks, array_merge($oldChecks, $newChecks)); } DB::update('drules', $dRulesUpdate); return array('druleids' => $dRuleIds); }
protected function checkLinkInput($links, $method) { $update = $method == 'updateLink'; $delete = $method == 'deleteLink'; // permissions if ($update || $delete) { $linkDbFields = ['linkid' => null]; $dbLinks = API::getApiService()->select('sysmap_element_url', ['filter' => ['selementid' => zbx_objectValues($links, 'linkid')], 'output' => ['linkid'], 'preservekeys' => true]); } else { $linkDbFields = ['sysmapid' => null, 'selementid1' => null, 'selementid2' => null]; } $colorValidator = new CColorValidator(); foreach ($links as $link) { if (!check_db_fields($linkDbFields, $link)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Wrong fields for map link.')); } if (isset($link['color']) && !$colorValidator->validate($link['color'])) { self::exception(ZBX_API_ERROR_PARAMETERS, $colorValidator->getError()); } if ($update || $delete) { if (!isset($dbLinks[$link['linkid']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } } } return true; }
/** * Retrieves and adds additional requested data (options 'selectHosts', 'selectGroups', etc.) to result set. * * @param array $options * @param array $result * * @return array */ protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $triggerPrototypeIds = array_keys($result); if ($options['selectDependencies'] !== null && $options['selectDependencies'] != API_OUTPUT_COUNT) { // Add trigger prototype dependencies. $res = DBselect('SELECT td.triggerid_up,td.triggerid_down' . ' FROM trigger_depends td' . ' WHERE ' . dbConditionInt('td.triggerid_down', $triggerPrototypeIds)); $relationMap = new CRelationMap(); while ($relation = DBfetch($res)) { $relationMap->addRelation($relation['triggerid_down'], $relation['triggerid_up']); } $dependencies = API::getApiService()->select($this->tableName(), ['output' => $options['selectDependencies'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapMany($result, $dependencies, 'dependencies'); } // adding items if ($options['selectItems'] !== null && $options['selectItems'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'triggerid', 'itemid', 'functions'); $items = API::Item()->get(['output' => $options['selectItems'], 'itemids' => $relationMap->getRelatedIds(), 'webitems' => true, 'nopermissions' => true, 'preservekeys' => true, 'filter' => ['flags' => null]]); $result = $relationMap->mapMany($result, $items, 'items'); } // adding discovery rule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { $dbRules = DBselect('SELECT id.parent_itemid,f.triggerid' . ' FROM item_discovery id,functions f' . ' WHERE ' . dbConditionInt('f.triggerid', $triggerPrototypeIds) . ' AND f.itemid=id.itemid'); $relationMap = new CRelationMap(); while ($rule = DBfetch($dbRules)) { $relationMap->addRelation($rule['triggerid'], $rule['parent_itemid']); } $discoveryRules = API::DiscoveryRule()->get(['output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true]); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } return $result; }
/** * Validates the input parameters for the update() method. * * @param array $mediatypes * * @throws APIException if the input is invalid. */ protected function validateUpdate(array $mediatypes) { if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('Only Super Admins can edit media types.')); } if (!$mediatypes) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } // Validate given IDs. $this->checkObjectIds($mediatypes, 'mediatypeid', _('No "%1$s" given for media type.'), _('Empty media type ID.'), _('Incorrect media type ID.')); $mediatypeids = zbx_objectValues($mediatypes, 'mediatypeid'); // Check value map names. $db_mediatypes = API::getApiService()->select('media_type', ['output' => ['mediatypeid', 'type', 'description', 'exec_path', 'status', 'smtp_port', 'smtp_verify_peer', 'smtp_verify_host', 'smtp_authentication'], 'mediatypeids' => $mediatypeids, 'preservekeys' => true]); $check_names = []; foreach ($mediatypes as $mediatype) { // Check if this media type exists. if (!array_key_exists($mediatype['mediatypeid'], $db_mediatypes)) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } // Validate "description" field. if (array_key_exists('description', $mediatype)) { if (is_array($mediatype['description'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.')); } elseif ($mediatype['description'] === '' || $mediatype['description'] === null || $mediatype['description'] === false) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value for field "%1$s": %2$s.', 'description', _('cannot be empty'))); } $check_names[$mediatype['description']] = true; } } if ($check_names) { $db_mediatype_names = API::getApiService()->select('media_type', ['output' => ['mediatypeid', 'description'], 'filter' => ['name' => array_keys($check_names)]]); $db_mediatype_names = zbx_toHash($db_mediatype_names, 'description'); foreach ($mediatypes as $mediatype) { if (array_key_exists('description', $mediatype) && array_key_exists($mediatype['description'], $db_mediatype_names) && !idcmp($db_mediatype_names[$mediatype['description']]['mediatypeid'], $mediatype['mediatypeid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Media type "%1$s" already exists.', $mediatype['description'])); } } } // Populate "description" field, if not set. Type field should not be populated at this point. $mediatypes = $this->extendFromObjects(zbx_toHash($mediatypes, 'mediatypeid'), $db_mediatypes, ['description']); $duplicate_name = CArrayHelper::findDuplicate($mediatypes, 'description'); if ($duplicate_name) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate "description" value "%1$s" for media type.', $duplicate_name['description'])); } foreach ($mediatypes as $mediatype) { $db_mediatype = $db_mediatypes[$mediatype['mediatypeid']]; // Recheck mandatory fields if type changed. if (array_key_exists('type', $mediatype) && $db_mediatype['type'] != $mediatype['type']) { $this->checkRequiredFieldsByType($mediatype); } else { $optional_fields_by_type = [MEDIA_TYPE_EMAIL => ['smtp_server', 'smtp_helo', 'smtp_email'], MEDIA_TYPE_EXEC => ['exec_path'], MEDIA_TYPE_SMS => ['gsm_modem'], MEDIA_TYPE_JABBER => ['username'], MEDIA_TYPE_EZ_TEXTING => ['exec_path', 'username']]; foreach ($optional_fields_by_type[$db_mediatype['type']] as $field) { if (array_key_exists($field, $mediatype) && ($mediatype[$field] === '' || $mediatype[$field] === null)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Field "%1$s" is missing a value for media type "%2$s".', $field, $mediatype['description'])); } } // Populate "type" field from DB, since it is not set and is required for further validation. $mediatype['type'] = $db_mediatype['type']; } switch ($mediatype['type']) { case MEDIA_TYPE_EZ_TEXTING: if (array_key_exists('exec_path', $mediatype)) { $message_text_limit_validator = new CLimitedSetValidator(['values' => [EZ_TEXTING_LIMIT_USA, EZ_TEXTING_LIMIT_CANADA]]); if ($db_mediatype['exec_path'] !== $mediatype['exec_path'] && !$message_text_limit_validator->validate($mediatype['exec_path'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" in field "%2$s" for media type "%3$s".', $mediatype['exec_path'], 'exec_path', $mediatype['description'])); } } break; case MEDIA_TYPE_EMAIL: if (array_key_exists('smtp_authentication', $mediatype)) { $smtp_authentication_validator = new CLimitedSetValidator(['values' => [SMTP_AUTHENTICATION_NONE, SMTP_AUTHENTICATION_NORMAL]]); if (!$smtp_authentication_validator->validate($mediatype['smtp_authentication'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" in field "%2$s" for media type "%3$s".', $mediatype['smtp_authentication'], 'smtp_authentication', $mediatype['description'])); } if ($mediatype['smtp_authentication'] == SMTP_AUTHENTICATION_NORMAL) { // Check 'passwd' field when auth is set to 'normal' manually. if ($db_mediatype['smtp_authentication'] == $mediatype['smtp_authentication'] && array_key_exists('passwd', $mediatype) && ($mediatype['passwd'] === '' || $mediatype['passwd'] === null)) { /* * When auth is set to 'normal', check if password field is set manually. * Otherwise the password is not changed. */ self::exception(ZBX_API_ERROR_PARAMETERS, _s('Password required for media type "%1$s".', $mediatype['description'])); } elseif ($db_mediatype['smtp_authentication'] != $mediatype['smtp_authentication'] && (!array_key_exists('passwd', $mediatype) || $mediatype['passwd'] === '' || $mediatype['passwd'] === null)) { /* * First check if 'passwd' field exists when authentication is changed from * 'none' to 'normal' and then validate it. */ self::exception(ZBX_API_ERROR_PARAMETERS, _s('Password required for media type "%1$s".', $mediatype['description'])); } } } elseif ($db_mediatype['smtp_authentication'] == SMTP_AUTHENTICATION_NORMAL && array_key_exists('passwd', $mediatype) && ($mediatype['passwd'] === '' || $mediatype['passwd'] === null)) { // Check 'passwd' field depeding on authentication set from DB and when it is set to 'normal'. self::exception(ZBX_API_ERROR_PARAMETERS, _s('Password required for media type "%1$s".', $mediatype['description'])); } // Validate optional 'smtp_port' field. if (array_key_exists('smtp_port', $mediatype) && $db_mediatype['smtp_port'] != $mediatype['smtp_port'] && !validatePortNumber($mediatype['smtp_port'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" in field "%2$s" for media type "%3$s".', $mediatype['smtp_port'], 'smtp_port', $mediatype['description'])); } // Validate optional field 'smtp_security'. if (array_key_exists('smtp_security', $mediatype)) { $smtp_security_validator = new CLimitedSetValidator(['values' => [SMTP_CONNECTION_SECURITY_NONE, SMTP_CONNECTION_SECURITY_STARTTLS, SMTP_CONNECTION_SECURITY_SSL_TLS]]); if (!$smtp_security_validator->validate($mediatype['smtp_security'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" in field "%2$s" for media type "%3$s".', $mediatype['smtp_security'], 'smtp_security', $mediatype['description'])); } } // Validate optional field 'smtp_verify_peer'. if (array_key_exists('smtp_verify_peer', $mediatype) && $db_mediatype['smtp_verify_peer'] != $mediatype['smtp_verify_peer']) { $smtp_verify_peer_validator = new CLimitedSetValidator(['values' => [0, 1]]); if (!$smtp_verify_peer_validator->validate($mediatype['smtp_verify_peer'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" in field "%2$s" for media type "%3$s".', $mediatype['smtp_verify_peer'], 'smtp_verify_peer', $mediatype['description'])); } } // Validate optional field 'smtp_verify_host'. if (array_key_exists('smtp_verify_host', $mediatype) && $db_mediatype['smtp_verify_host'] != $mediatype['smtp_verify_host']) { $smtp_verify_host_validator = new CLimitedSetValidator(['values' => [0, 1]]); if (!$smtp_verify_host_validator->validate($mediatype['smtp_verify_host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" in field "%2$s" for media type "%3$s".', $mediatype['smtp_verify_host'], 'smtp_verify_host', $mediatype['description'])); } } break; case MEDIA_TYPE_EXEC: if (array_key_exists('exec_params', $mediatype) && $mediatype['exec_params'] !== '') { $pos = strrpos($mediatype['exec_params'], "\n"); if ($pos === false || strlen($mediatype['exec_params']) != $pos + 1) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Script parameters "%1$s" are missing the last new line feed for media type "%2$s".', $mediatype['exec_params'], $mediatype['description'])); } } break; } // Validate optional 'status' field and only when status is changed. if (array_key_exists('status', $mediatype) && $db_mediatype['status'] != $mediatype['status']) { $status_validator = new CLimitedSetValidator(['values' => [MEDIA_TYPE_STATUS_ACTIVE, MEDIA_TYPE_STATUS_DISABLED]]); if (!$status_validator->validate($mediatype['status'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" in field "%2$s" for media type "%3$s".', $mediatype['status'], 'status', $mediatype['description'])); } } } }
/** * Deletes all trigger dependencies from the given triggers and their children. * * @param array $triggers an array of triggers with the 'triggerid' field defined * * @return array */ public function deleteDependencies(array $triggers) { $triggers = zbx_toArray($triggers); $this->validateDeleteDependencies($triggers); $triggerids = zbx_objectValues($triggers, 'triggerid'); try { // delete the dependencies from the child triggers $childTriggers = API::getApiService()->select($this->tableName(), ['output' => ['triggerid'], 'filter' => ['templateid' => $triggerids]]); if ($childTriggers) { $this->deleteDependencies($childTriggers); } DB::delete('trigger_depends', ['triggerid_down' => $triggerids]); } catch (APIException $e) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete dependency')); } return ['triggerids' => $triggerids]; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $groupIds = array_keys($result); sort($groupIds); // adding hosts if ($options['selectHosts'] !== null) { if ($options['selectHosts'] !== API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'groupid', 'hostid', 'hosts_groups'); $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($hosts, 'host'); } $result = $relationMap->mapMany($result, $hosts, 'hosts', $options['limitSelects']); } else { $hosts = API::Host()->get(array('groupids' => $groupIds, 'countOutput' => true, 'groupCount' => true)); $hosts = zbx_toHash($hosts, 'groupid'); foreach ($result as $groupid => $group) { if (isset($hosts[$groupid])) { $result[$groupid]['hosts'] = $hosts[$groupid]['rowscount']; } else { $result[$groupid]['hosts'] = 0; } } } } // adding templates if ($options['selectTemplates'] !== null) { if ($options['selectTemplates'] !== API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'groupid', 'hostid', 'hosts_groups'); $hosts = API::Template()->get(array('output' => $options['selectTemplates'], 'templateids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($hosts, 'host'); } $result = $relationMap->mapMany($result, $hosts, 'templates', $options['limitSelects']); } else { $hosts = API::Template()->get(array('groupids' => $groupIds, 'countOutput' => true, 'groupCount' => true)); $hosts = zbx_toHash($hosts, 'groupid'); foreach ($result as $groupid => $group) { if (isset($hosts[$groupid])) { $result[$groupid]['templates'] = $hosts[$groupid]['rowscount']; } else { $result[$groupid]['templates'] = 0; } } } } // adding discovery rule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { // discovered items $discoveryRules = DBFetchArray(DBselect('SELECT gd.groupid,hd.parent_itemid' . ' FROM group_discovery gd,group_prototype gp,host_discovery hd' . ' WHERE ' . dbConditionInt('gd.groupid', $groupIds) . ' AND gd.parent_group_prototypeid=gp.group_prototypeid' . ' AND gp.hostid=hd.hostid')); $relationMap = $this->createRelationMap($discoveryRules, 'groupid', 'parent_itemid'); $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding group discovery if ($options['selectGroupDiscovery'] !== null) { $groupDiscoveries = API::getApiService()->select('group_discovery', array('output' => $this->outputExtend($options['selectGroupDiscovery'], array('groupid')), 'filter' => array('groupid' => $groupIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($groupDiscoveries, 'groupid', 'groupid'); $groupDiscoveries = $this->unsetExtraFields($groupDiscoveries, array('groupid'), $options['selectGroupDiscovery']); $result = $relationMap->mapOne($result, $groupDiscoveries, 'groupDiscovery'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $triggerids = array_keys($result); // adding groups if ($options['selectGroups'] !== null && $options['selectGroups'] != API_OUTPUT_COUNT) { $res = DBselect('SELECT f.triggerid,hg.groupid' . ' FROM functions f,items i,hosts_groups hg' . ' WHERE ' . dbConditionInt('f.triggerid', $triggerids) . ' AND f.itemid=i.itemid' . ' AND i.hostid=hg.hostid'); $relationMap = new CRelationMap(); while ($relation = DBfetch($res)) { $relationMap->addRelation($relation['triggerid'], $relation['groupid']); } $groups = API::HostGroup()->get(array('output' => $options['selectGroups'], 'groupids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapMany($result, $groups, 'groups'); } // adding hosts if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) { $res = DBselect('SELECT f.triggerid,i.hostid' . ' FROM functions f,items i' . ' WHERE ' . dbConditionInt('f.triggerid', $triggerids) . ' AND f.itemid=i.itemid'); $relationMap = new CRelationMap(); while ($relation = DBfetch($res)) { $relationMap->addRelation($relation['triggerid'], $relation['hostid']); } $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'templated_hosts' => true, 'nopermissions' => true, 'preservekeys' => true)); if (!is_null($options['limitSelects'])) { order_result($hosts, 'host'); } $result = $relationMap->mapMany($result, $hosts, 'hosts', $options['limitSelects']); } // adding functions if ($options['selectFunctions'] !== null && $options['selectFunctions'] != API_OUTPUT_COUNT) { $functions = API::getApiService()->select('functions', array('output' => $this->outputExtend($options['selectFunctions'], array('triggerid', 'functionid')), 'filter' => array('triggerid' => $triggerids), 'preservekeys' => true)); $relationMap = $this->createRelationMap($functions, 'triggerid', 'functionid'); $functions = $this->unsetExtraFields($functions, array('triggerid', 'functionid'), $options['selectFunctions']); $result = $relationMap->mapMany($result, $functions, 'functions'); } return $result; }
/** * Check if trigger prototype has at least one item prototype and belongs to one discovery rule. * * @throws APIException if trigger prototype has no item prototype or items belong to multiple discovery rules. * * @param array $triggerPrototype array of trigger data, uses 'description' element * @param array $items array of trigger items * * @return void */ protected function checkDiscoveryRuleCount(array $triggerPrototype, array $items) { if ($items) { $itemDiscoveries = API::getApiService()->select('item_discovery', array('output' => array('parent_itemid'), 'filter' => array('itemid' => zbx_objectValues($items, 'itemid')))); $itemDiscoveryIds = array_flip(zbx_objectValues($itemDiscoveries, 'parent_itemid')); if (count($itemDiscoveryIds) > 1) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger prototype "%1$s" contains item prototypes from multiple discovery rules.', $triggerPrototype['description'])); } elseif (!$itemDiscoveryIds) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger prototype "%1$s" must contain at least one item prototype.', $triggerPrototype['description'])); } } }
/** * Checks if the given events exist, are accessible and can be acknowledged. * * @throws APIException if an event does not exist, is not accessible or is not a trigger event * * @param array $eventIds * * @return void */ protected function checkCanBeAcknowledged(array $eventIds) { $allowedEvents = $this->get(array('eventids' => $eventIds, 'output' => array('eventid'), 'preservekeys' => true)); foreach ($eventIds as $eventId) { if (!isset($allowedEvents[$eventId])) { // check if an event actually exists but maybe belongs to a different source or object $event = API::getApiService()->select($this->tableName(), array('output' => array('eventid', 'source', 'object'), 'eventids' => $eventId, 'limit' => 1)); $event = reset($event); // if the event exists, check if we have permissions to access it if ($event) { $event = $this->get(array('output' => array('eventid'), 'eventids' => $event['eventid'], 'source' => $event['source'], 'object' => $event['object'], 'limit' => 1)); } // the event exists, is accessible but belongs to a different object or source if ($event) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('Only trigger events can be acknowledged.')); } else { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } } }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $serviceIds = array_keys($result); // selectDependencies if ($options['selectDependencies'] !== null && $options['selectDependencies'] != API_OUTPUT_COUNT) { $dependencies = $this->fetchChildDependencies($serviceIds, $this->outputExtend($options['selectDependencies'], array('serviceupid', 'linkid'))); $dependencies = zbx_toHash($dependencies, 'linkid'); $relationMap = $this->createRelationMap($dependencies, 'serviceupid', 'linkid'); $dependencies = $this->unsetExtraFields($dependencies, array('serviceupid', 'linkid'), $options['selectDependencies']); $result = $relationMap->mapMany($result, $dependencies, 'dependencies'); } // selectParentDependencies if ($options['selectParentDependencies'] !== null && $options['selectParentDependencies'] != API_OUTPUT_COUNT) { $dependencies = $this->fetchParentDependencies($serviceIds, $this->outputExtend($options['selectParentDependencies'], array('servicedownid', 'linkid'))); $dependencies = zbx_toHash($dependencies, 'linkid'); $relationMap = $this->createRelationMap($dependencies, 'servicedownid', 'linkid'); $dependencies = $this->unsetExtraFields($dependencies, array('servicedownid', 'linkid'), $options['selectParentDependencies']); $result = $relationMap->mapMany($result, $dependencies, 'parentDependencies'); } // selectParent if ($options['selectParent'] !== null && $options['selectParent'] != API_OUTPUT_COUNT) { $dependencies = $this->fetchParentDependencies($serviceIds, array('servicedownid', 'serviceupid'), false); $relationMap = $this->createRelationMap($dependencies, 'servicedownid', 'serviceupid'); $parents = $this->get(array('output' => $options['selectParent'], 'serviceids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapOne($result, $parents, 'parent'); } // selectTimes if ($options['selectTimes'] !== null && $options['selectTimes'] != API_OUTPUT_COUNT) { $serviceTimes = API::getApiService()->select('services_times', array('output' => $this->outputExtend($options['selectTimes'], array('serviceid', 'timeid')), 'filter' => array('serviceid' => $serviceIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($serviceTimes, 'serviceid', 'timeid'); $serviceTimes = $this->unsetExtraFields($serviceTimes, array('serviceid', 'timeid'), $options['selectTimes']); $result = $relationMap->mapMany($result, $serviceTimes, 'times'); } // selectAlarms if ($options['selectAlarms'] !== null && $options['selectAlarms'] != API_OUTPUT_COUNT) { $serviceAlarms = API::getApiService()->select('service_alarms', array('output' => $this->outputExtend($options['selectAlarms'], array('serviceid', 'servicealarmid')), 'filter' => array('serviceid' => $serviceIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($serviceAlarms, 'serviceid', 'servicealarmid'); $serviceAlarms = $this->unsetExtraFields($serviceAlarms, array('serviceid', 'servicealarmid'), $options['selectAlarms']); $result = $relationMap->mapMany($result, $serviceAlarms, 'alarms'); } // selectTrigger if ($options['selectTrigger'] !== null && $options['selectTrigger'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'serviceid', 'triggerid'); $triggers = API::getApiService()->select('triggers', array('output' => $options['selectTrigger'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true)); $result = $relationMap->mapOne($result, $triggers, 'trigger'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $httpTestIds = array_keys($result); // adding hosts if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'httptestid', 'hostid'); $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostid' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'templated_hosts' => true, 'preservekeys' => true)); $result = $relationMap->mapMany($result, $hosts, 'hosts'); } // adding steps if ($options['selectSteps'] !== null) { if ($options['selectSteps'] != API_OUTPUT_COUNT) { $httpSteps = API::getApiService()->select('httpstep', array('output' => $this->outputExtend($options['selectSteps'], array('httptestid', 'httpstepid')), 'filters' => array('httptestid' => $httpTestIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($httpSteps, 'httptestid', 'httpstepid'); $httpSteps = $this->unsetExtraFields($httpSteps, array('httptestid', 'httpstepid'), $options['selectSteps']); $result = $relationMap->mapMany($result, $httpSteps, 'steps'); } else { $dbHttpSteps = DBselect('SELECT hs.httptestid,COUNT(hs.httpstepid) AS stepscnt' . ' FROM httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', $httpTestIds) . ' GROUP BY hs.httptestid'); while ($dbHttpStep = DBfetch($dbHttpSteps)) { $result[$dbHttpStep['httptestid']]['steps'] = $dbHttpStep['stepscnt']; } } } return $result; }
/** * Validate update. * * @param array $images * * @throws APIException if user has no permissions. * @throws APIException if wrong fields are passed. * @throws APIException if image with same name already exists. */ protected function validateUpdate(array $images) { if (self::$userData['type'] < USER_TYPE_ZABBIX_ADMIN) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } foreach ($images as $image) { if (!check_db_fields(array('imageid'), $image)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect input parameters.')); } } $dbImages = API::getApiService()->select($this->tableName(), array('filter' => array('imageid' => zbx_objectValues($images, 'imageid')), 'output' => array('imageid', 'name'), 'preservekeys' => true)); $changedImageNames = array(); foreach ($images as $image) { if (!isset($dbImages[$image['imageid']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } if (array_key_exists('imagetype', $image)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot update "imagetype" for image "%1$s".', $dbImages[$image['imageid']]['name'])); } if (isset($image['name']) && !zbx_empty($image['name']) && $dbImages[$image['imageid']]['name'] !== $image['name']) { if (isset($changedImageNames[$image['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Image "%1$s" already exists.', $image['name'])); } else { $changedImageNames[$image['name']] = $image['name']; } } } // check for existing image names if ($changedImageNames) { $dbImages = API::getApiService()->select($this->tableName(), array('output' => array('name'), 'filter' => array('name' => $changedImageNames), 'limit' => 1)); if ($dbImages) { $dbImage = reset($dbImages); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Image "%1$s" already exists.', $dbImage['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; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $hostPrototypeIds = array_keys($result); // adding discovery rule if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'hostid', 'parent_itemid', 'host_discovery'); $discoveryRules = API::DiscoveryRule()->get(['output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true]); $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule'); } // adding group links if ($options['selectGroupLinks'] !== null && $options['selectGroupLinks'] != API_OUTPUT_COUNT) { $groupPrototypes = DBFetchArray(DBselect('SELECT hg.group_prototypeid,hg.hostid' . ' FROM group_prototype hg' . ' WHERE ' . dbConditionInt('hg.hostid', $hostPrototypeIds) . ' AND hg.groupid IS NOT NULL')); $relationMap = $this->createRelationMap($groupPrototypes, 'hostid', 'group_prototypeid'); $groupPrototypes = API::getApiService()->select('group_prototype', ['output' => $options['selectGroupLinks'], 'group_prototypeids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); foreach ($groupPrototypes as &$groupPrototype) { unset($groupPrototype['name']); } unset($groupPrototype); $result = $relationMap->mapMany($result, $groupPrototypes, 'groupLinks'); } // adding group prototypes if ($options['selectGroupPrototypes'] !== null && $options['selectGroupPrototypes'] != API_OUTPUT_COUNT) { $groupPrototypes = DBFetchArray(DBselect('SELECT hg.group_prototypeid,hg.hostid' . ' FROM group_prototype hg' . ' WHERE ' . dbConditionInt('hg.hostid', $hostPrototypeIds) . ' AND hg.groupid IS NULL')); $relationMap = $this->createRelationMap($groupPrototypes, 'hostid', 'group_prototypeid'); $groupPrototypes = API::getApiService()->select('group_prototype', ['output' => $options['selectGroupPrototypes'], 'group_prototypeids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); foreach ($groupPrototypes as &$groupPrototype) { unset($groupPrototype['groupid']); } unset($groupPrototype); $result = $relationMap->mapMany($result, $groupPrototypes, 'groupPrototypes'); } // adding host if ($options['selectParentHost'] !== null && $options['selectParentHost'] != API_OUTPUT_COUNT) { $relationMap = new CRelationMap(); $dbRules = DBselect('SELECT hd.hostid,i.hostid AS parent_hostid' . ' FROM host_discovery hd,items i' . ' WHERE ' . dbConditionInt('hd.hostid', $hostPrototypeIds) . ' AND hd.parent_itemid=i.itemid'); while ($relation = DBfetch($dbRules)) { $relationMap->addRelation($relation['hostid'], $relation['parent_hostid']); } $hosts = API::Host()->get(['output' => $options['selectParentHost'], 'hostids' => $relationMap->getRelatedIds(), 'templated_hosts' => true, 'nopermissions' => true, 'preservekeys' => true]); $result = $relationMap->mapOne($result, $hosts, 'parentHost'); } // adding templates if ($options['selectTemplates'] !== null) { if ($options['selectTemplates'] != API_OUTPUT_COUNT) { $relationMap = $this->createRelationMap($result, 'hostid', 'templateid', 'hosts_templates'); $templates = API::Template()->get(['output' => $options['selectTemplates'], 'templateids' => $relationMap->getRelatedIds(), 'preservekeys' => true]); $result = $relationMap->mapMany($result, $templates, 'templates'); } else { $templates = API::Template()->get(['hostids' => $hostPrototypeIds, 'countOutput' => true, 'groupCount' => true]); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $hostid => $host) { $result[$hostid]['templates'] = isset($templates[$hostid]) ? $templates[$hostid]['rowscount'] : 0; } } } // adding inventory if ($options['selectInventory'] !== null) { $relationMap = $this->createRelationMap($result, 'hostid', 'hostid'); // only allow to retrieve the hostid and inventory_mode fields $output = []; if ($this->outputIsRequested('hostid', $options['selectInventory'])) { $output[] = 'hostid'; } if ($this->outputIsRequested('inventory_mode', $options['selectInventory'])) { $output[] = 'inventory_mode'; } $inventory = API::getApiService()->select('host_inventory', ['output' => $output, 'filter' => ['hostid' => $hostPrototypeIds]]); $result = $relationMap->mapOne($result, zbx_toHash($inventory, 'hostid'), 'inventory'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $sysmapIds = array_keys($result); // adding elements if ($options['selectSelements'] !== null && $options['selectSelements'] != API_OUTPUT_COUNT) { $selements = API::getApiService()->select('sysmaps_elements', array('output' => $this->outputExtend($options['selectSelements'], array('selementid', 'sysmapid')), 'filter' => array('sysmapid' => $sysmapIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($selements, 'sysmapid', 'selementid'); // add selement URLs if ($this->outputIsRequested('urls', $options['selectSelements'])) { foreach ($selements as &$selement) { $selement['urls'] = array(); } unset($selement); if (!is_null($options['expandUrls'])) { $dbMapUrls = DBselect('SELECT su.sysmapurlid,su.sysmapid,su.name,su.url,su.elementtype' . ' FROM sysmap_url su' . ' WHERE ' . dbConditionInt('su.sysmapid', $sysmapIds)); while ($mapUrl = DBfetch($dbMapUrls)) { foreach ($selements as $snum => $selement) { if (bccomp($selement['sysmapid'], $mapUrl['sysmapid']) == 0 && ($selement['elementtype'] == $mapUrl['elementtype'] && $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP || $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS && $mapUrl['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST)) { $selements[$snum]['urls'][] = $this->expandUrlMacro($mapUrl, $selement); } } } } $dbSelementUrls = DBselect('SELECT seu.sysmapelementurlid,seu.selementid,seu.name,seu.url' . ' FROM sysmap_element_url seu' . ' WHERE ' . dbConditionInt('seu.selementid', array_keys($selements))); while ($selementUrl = DBfetch($dbSelementUrls)) { $selements[$selementUrl['selementid']]['urls'][] = is_null($options['expandUrls']) ? $selementUrl : $this->expandUrlMacro($selementUrl, $selements[$selementUrl['selementid']]); } } $selements = $this->unsetExtraFields($selements, array('sysmapid', 'selementid'), $options['selectSelements']); $result = $relationMap->mapMany($result, $selements, 'selements'); } // adding icon maps if ($options['selectIconMap'] !== null && $options['selectIconMap'] != API_OUTPUT_COUNT) { $iconMaps = API::IconMap()->get(array('output' => $this->outputExtend($options['selectIconMap'], array('sysmapid', 'iconmapid')), 'sysmapids' => $sysmapIds, 'preservekeys' => true, 'nopermissions' => true)); $relationMap = $this->createRelationMap($iconMaps, 'sysmapid', 'iconmapid'); $iconMaps = $this->unsetExtraFields($iconMaps, array('sysmapid', 'iconmapid'), $options['selectIconMap']); $result = $relationMap->mapOne($result, $iconMaps, 'iconmap'); } // adding links if ($options['selectLinks'] !== null && $options['selectLinks'] != API_OUTPUT_COUNT) { $links = API::getApiService()->select('sysmaps_links', array('output' => $this->outputExtend($options['selectLinks'], array('sysmapid', 'linkid')), 'filter' => array('sysmapid' => $sysmapIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($links, 'sysmapid', 'linkid'); // add link triggers if ($this->outputIsRequested('linktriggers', $options['selectLinks'])) { $linkTriggers = DBFetchArrayAssoc(DBselect('SELECT DISTINCT slt.*' . ' FROM sysmaps_link_triggers slt' . ' WHERE ' . dbConditionInt('slt.linkid', $relationMap->getRelatedIds())), 'linktriggerid'); $linkTriggerRelationMap = $this->createRelationMap($linkTriggers, 'linkid', 'linktriggerid'); $links = $linkTriggerRelationMap->mapMany($links, $linkTriggers, 'linktriggers'); } $links = $this->unsetExtraFields($links, array('sysmapid', 'linkid'), $options['selectLinks']); $result = $relationMap->mapMany($result, $links, 'links'); } // adding urls if ($options['selectUrls'] !== null && $options['selectUrls'] != API_OUTPUT_COUNT) { $links = API::getApiService()->select('sysmap_url', array('output' => $this->outputExtend($options['selectUrls'], array('sysmapid', 'sysmapurlid')), 'filter' => array('sysmapid' => $sysmapIds), 'preservekeys' => true)); $relationMap = $this->createRelationMap($links, 'sysmapid', 'sysmapurlid'); $links = $this->unsetExtraFields($links, array('sysmapid', 'sysmapurlid'), $options['selectUrls']); $result = $relationMap->mapMany($result, $links, 'urls'); } return $result; }
protected function addRelatedObjects(array $options, array $result) { $result = parent::addRelatedObjects($options, $result); $screenIds = array_keys($result); // adding ScreenItems if ($options['selectScreenItems'] !== null && $options['selectScreenItems'] != API_OUTPUT_COUNT) { $screenItems = API::getApiService()->select('screens_items', ['output' => $this->outputExtend($options['selectScreenItems'], ['screenid', 'screenitemid']), 'filter' => ['screenid' => $screenIds], 'preservekeys' => true]); $relation_map = $this->createRelationMap($screenItems, 'screenid', 'screenitemid'); $screenItems = $this->unsetExtraFields($screenItems, ['screenid', 'screenitemid'], $options['selectScreenItems']); $result = $relation_map->mapMany($result, $screenItems, 'screenitems'); } // Adding user shares. if ($options['selectUsers'] !== null && $options['selectUsers'] != API_OUTPUT_COUNT) { $relation_map = $this->createRelationMap($result, 'screenid', 'userid', 'screen_user'); // Get all allowed users. $related_users = API::User()->get(['output' => ['userid'], 'userids' => $relation_map->getRelatedIds(), 'preservekeys' => true]); $related_userids = zbx_objectValues($related_users, 'userid'); if ($related_userids) { $users = API::getApiService()->select('screen_user', ['output' => $this->outputExtend($options['selectUsers'], ['screenid', 'userid']), 'filter' => ['screenid' => $screenIds, 'userid' => $related_userids], 'preservekeys' => true]); $relation_map = $this->createRelationMap($users, 'screenid', 'screenuserid'); $users = $this->unsetExtraFields($users, ['screenuserid', 'userid', 'permission'], $options['selectUsers']); foreach ($users as &$user) { unset($user['screenid']); } unset($user); $result = $relation_map->mapMany($result, $users, 'users'); } else { foreach ($result as &$row) { $row['users'] = []; } unset($row); } } // Adding user group shares. if ($options['selectUserGroups'] !== null && $options['selectUserGroups'] != API_OUTPUT_COUNT) { $relation_map = $this->createRelationMap($result, 'screenid', 'usrgrpid', 'screen_usrgrp'); // Get all allowed groups. $related_groups = API::UserGroup()->get(['output' => ['usrgrpid'], 'usrgrpids' => $relation_map->getRelatedIds(), 'preservekeys' => true]); $related_groupids = zbx_objectValues($related_groups, 'usrgrpid'); if ($related_groupids) { $user_groups = API::getApiService()->select('screen_usrgrp', ['output' => $this->outputExtend($options['selectUserGroups'], ['screenid', 'usrgrpid']), 'filter' => ['screenid' => $screenIds, 'usrgrpid' => $related_groupids], 'preservekeys' => true]); $relation_map = $this->createRelationMap($user_groups, 'screenid', 'screenusrgrpid'); $user_groups = $this->unsetExtraFields($user_groups, ['screenusrgrpid', 'usrgrpid', 'permission'], $options['selectUserGroups']); foreach ($user_groups as &$user_group) { unset($user_group['screenid']); } unset($user_group); $result = $relation_map->mapMany($result, $user_groups, 'userGroups'); } else { foreach ($result as &$row) { $row['userGroups'] = []; } unset($row); } } return $result; }