/** * Tries to login a user and populates self::$data on success. * * @param string $login user login * @param string $password user password * * @throws Exception if user cannot be logged in * * @return bool */ public static function login($login, $password) { try { self::setDefault(); self::$data = API::User()->login(array('user' => $login, 'password' => $password, 'userData' => true)); if (!self::$data) { throw new Exception(); } if (self::$data['gui_access'] == GROUP_GUI_ACCESS_DISABLED) { error(_('GUI access disabled.')); throw new Exception(); } if (empty(self::$data['url'])) { self::$data['url'] = CProfile::get('web.menu.view.last', 'index.php'); } $result = (bool) self::$data; if (isset(self::$data['attempt_failed']) && self::$data['attempt_failed']) { CProfile::init(); CProfile::update('web.login.attempt.failed', self::$data['attempt_failed'], PROFILE_TYPE_INT); CProfile::update('web.login.attempt.ip', self::$data['attempt_ip'], PROFILE_TYPE_STR); CProfile::update('web.login.attempt.clock', self::$data['attempt_clock'], PROFILE_TYPE_INT); $result &= CProfile::flush(); } // remove guest session after successful login $result &= DBexecute('DELETE FROM sessions WHERE sessionid=' . zbx_dbstr(get_cookie('zbx_sessionid'))); if ($result) { self::setSessionCookie(self::$data['sessionid']); add_audit_ext(AUDIT_ACTION_LOGIN, AUDIT_RESOURCE_USER, self::$data['userid'], '', null, null, null); } return $result; } catch (Exception $e) { self::setDefault(); return false; } }
function add_mediatype($type, $description, $smtp_server, $smtp_helo, $smtp_email, $exec_path, $gsm_modem, $username, $password) { $ret = 0; if ($description == "") { error(S_INCORRECT_DESCRIPTION); return 0; } $sql = "select * from media_type where description=" . zbx_dbstr($description); $result = DBexecute($sql); if (DBfetch($result)) { error("An action type with description '{$description}' already exists."); } else { $mediatypeid = get_dbid("media_type", "mediatypeid"); $sql = "insert into media_type (mediatypeid,type,description,smtp_server,smtp_helo,smtp_email,exec_path,gsm_modem,username,passwd) values ({$mediatypeid},{$type}," . zbx_dbstr($description) . "," . zbx_dbstr($smtp_server) . "," . zbx_dbstr($smtp_helo) . "," . zbx_dbstr($smtp_email) . "," . zbx_dbstr($exec_path) . "," . zbx_dbstr($gsm_modem) . "," . zbx_dbstr($username) . "," . zbx_dbstr($password) . ")"; $ret = DBexecute($sql); if ($ret) { $ret = $mediatypeid; add_audit_ext(AUDIT_ACTION_ADD, AUDIT_RESOURCE_MEDIA_TYPE, $mediatypeid, $description, NULL, NULL, NULL); } } return $ret; }
add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_MACRO, $macro['globalmacroid'], $macro['macro'] . SPACE . RARR . SPACE . $macro['value'], null, null, null); } } // create if (!empty($newMacros)) { // mark marcos as new foreach ($newMacros as $number => $macro) { $_REQUEST['macros'][$number]['type'] = 'new'; } $newMacrosIds = API::UserMacro()->createGlobal(array_values($newMacros)); if (!$newMacrosIds) { throw new Exception(_('Cannot add macro.')); } $newMacrosCreated = API::UserMacro()->get(array('globalmacroids' => $newMacrosIds['globalmacroids'], 'globalmacro' => 1, 'output' => API_OUTPUT_EXTEND)); foreach ($newMacrosCreated as $macro) { add_audit_ext(AUDIT_ACTION_ADD, AUDIT_RESOURCE_MACRO, $macro['globalmacroid'], $macro['macro'] . SPACE . RARR . SPACE . $macro['value'], null, null, null); } } // reload macros after updating to properly display them in the form $_REQUEST['macros'] = API::UserMacro()->get(array('globalmacro' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); $result = true; DBend(true); show_message(_('Macros updated')); } catch (Exception $e) { $result = false; DBend(false); error($e->getMessage()); show_error_message(_('Cannot update macros')); } } /*
/** * Update maintenances. * * @param array $maintenances * * @return boolean */ public function update(array $maintenances) { $maintenances = zbx_toArray($maintenances); $maintenanceids = zbx_objectValues($maintenances, 'maintenanceid'); // validate maintenance permissions if (self::$userData['type'] == USER_TYPE_ZABBIX_USER) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } $updMaintenances = $this->get(['maintenanceids' => zbx_objectValues($maintenances, 'maintenanceid'), 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'selectGroups' => ['groupid'], 'selectHosts' => ['hostid'], 'selectTimeperiods' => API_OUTPUT_EXTEND, 'preservekeys' => true]); $maintenanceNamesChanged = []; foreach ($maintenances as $maintenance) { if (!isset($updMaintenances[$maintenance['maintenanceid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } if (isset($maintenance['name']) && !zbx_empty($maintenance['name']) && $updMaintenances[$maintenance['maintenanceid']]['name'] !== $maintenance['name']) { if (isset($maintenanceNamesChanged[$maintenance['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Maintenance "%1$s" already exists.', $maintenance['name'])); } else { $maintenanceNamesChanged[$maintenance['name']] = $maintenance['name']; } } } // check if maintenance already exists if ($maintenanceNamesChanged) { $dbMaintenances = $this->get(['output' => ['name'], 'filter' => ['name' => $maintenanceNamesChanged], 'nopermissions' => true, 'limit' => 1]); if ($dbMaintenances) { $dbMaintenance = reset($dbMaintenances); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Maintenance "%1$s" already exists.', $dbMaintenance['name'])); } } $hostids = []; $groupids = []; foreach ($maintenances as $maintenance) { // validate maintenance active since if (!validateUnixTime($maintenance['active_since'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active since'))); } // validate maintenance active till if (!validateUnixTime($maintenance['active_till'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active till'))); } // validate maintenance active interval if ($maintenance['active_since'] > $maintenance['active_till']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Maintenance "Active since" value cannot be bigger than "Active till".')); } // validate timeperiods if (!array_key_exists('timeperiods', $maintenance) || !is_array($maintenance['timeperiods']) || !$maintenance['timeperiods']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one maintenance period must be created.')); } foreach ($maintenance['timeperiods'] as $timeperiod) { if (!is_array($timeperiod)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one maintenance period must be created.')); } } $hostids = array_merge($hostids, $maintenance['hostids']); $groupids = array_merge($groupids, $maintenance['groupids']); } // validate hosts & groups if (empty($hostids) && empty($groupids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one host or group should be selected.')); } // validate hosts permissions $options = ['hostids' => $hostids, 'editable' => true, 'output' => ['hostid'], 'preservekeys' => true]; $updHosts = API::Host()->get($options); foreach ($hostids as $hostid) { if (!isset($updHosts[$hostid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // validate groups permissions $options = ['groupids' => $groupids, 'editable' => true, 'output' => ['groupid'], 'preservekeys' => true]; $updGroups = API::HostGroup()->get($options); foreach ($groupids as $groupid) { if (!isset($updGroups[$groupid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $this->removeSecondsFromTimes($maintenances); $update = []; foreach ($maintenances as $mnum => $maintenance) { $dbFields = ['maintenanceid' => null]; // validate fields if (!check_db_fields($dbFields, $maintenance)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect parameters for maintenance.')); } $update[$mnum] = ['values' => $maintenance, 'where' => ['maintenanceid' => $maintenance['maintenanceid']]]; // update time periods $this->replaceTimePeriods($updMaintenances[$maintenance['maintenanceid']], $maintenance); } DB::update('maintenances', $update); // some of the hosts and groups bound to maintenance must be deleted, other inserted and others left alone $insertHosts = []; $insertGroups = []; foreach ($maintenances as $maintenance) { // putting apart those host<->maintenance connections that should be inserted, deleted and not changed // $hostDiff['first'] - new hosts, that should be inserted // $hostDiff['second'] - hosts, that should be deleted // $hostDiff['both'] - hosts, that should not be touched $hostDiff = zbx_array_diff(zbx_toObject($maintenance['hostids'], 'hostid'), $updMaintenances[$maintenance['maintenanceid']]['hosts'], 'hostid'); foreach ($hostDiff['first'] as $host) { $insertHosts[] = ['hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']]; } foreach ($hostDiff['second'] as $host) { $deleteHosts = ['hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']]; DB::delete('maintenances_hosts', $deleteHosts); } // now the same with the groups $groupDiff = zbx_array_diff(zbx_toObject($maintenance['groupids'], 'groupid'), $updMaintenances[$maintenance['maintenanceid']]['groups'], 'groupid'); foreach ($groupDiff['first'] as $group) { $insertGroups[] = ['groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']]; } foreach ($groupDiff['second'] as $group) { $deleteGroups = ['groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']]; DB::delete('maintenances_groups', $deleteGroups); } add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_MAINTENANCE, $maintenance['maintenanceid'], array_key_exists('name', $maintenance) ? $maintenance['name'] : $updMaintenances[$maintenance['maintenanceid']]['name'], 'maintenances', $updMaintenances[$maintenance['maintenanceid']], $maintenance); } DB::insert('maintenances_hosts', $insertHosts); DB::insert('maintenances_groups', $insertGroups); return ['maintenanceids' => $maintenanceids]; }
function updateHostStatus($hostids, $status) { zbx_value2array($hostids); $hostIds = array(); $oldStatus = $status == HOST_STATUS_MONITORED ? HOST_STATUS_NOT_MONITORED : HOST_STATUS_MONITORED; $db_hosts = DBselect('SELECT h.hostid,h.host,h.status' . ' FROM hosts h' . ' WHERE ' . dbConditionInt('h.hostid', $hostids) . ' AND h.status=' . zbx_dbstr($oldStatus)); while ($host = DBfetch($db_hosts)) { $hostIds[] = $host['hostid']; $host_new = $host; $host_new['status'] = $status; add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['host'], 'hosts', $host, $host_new); info(_('Updated status of host') . ' "' . $host['host'] . '"'); } return DB::update('hosts', array('values' => array('status' => $status), 'where' => array('hostid' => $hostIds))); }
unset($_REQUEST['screenid']); $_REQUEST['form'] = 'clone'; } elseif (isset($_REQUEST['save'])) { if (isset($_REQUEST['screenid'])) { $screen = array('screenid' => $_REQUEST['screenid'], 'name' => $_REQUEST['name'], 'hsize' => $_REQUEST['hsize'], 'vsize' => $_REQUEST['vsize']); if (isset($_REQUEST['templateid'])) { $screenOld = API::TemplateScreen()->get(array('screenids' => $_REQUEST['screenid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true)); $screenOld = reset($screenOld); $screenids = API::TemplateScreen()->update($screen); } else { $screenOld = API::Screen()->get(array('screenids' => $_REQUEST['screenid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true)); $screenOld = reset($screenOld); $screenids = API::Screen()->update($screen); } if (!empty($screenids)) { add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_SCREEN, $screen['screenid'], $screen['name'], 'screens', $screenOld, $screen); } show_messages(!empty($screenids), _('Screen updated'), _('Cannot update screen')); } else { $screen = array('name' => $_REQUEST['name'], 'hsize' => $_REQUEST['hsize'], 'vsize' => $_REQUEST['vsize']); if (isset($_REQUEST['templateid'])) { $screen['templateid'] = get_request('templateid'); $screenids = API::TemplateScreen()->create($screen); } else { $screenids = API::Screen()->create($screen); } if (!empty($screenids)) { $screenid = reset($screenids); $screenid = reset($screenid); add_audit_details(AUDIT_ACTION_ADD, AUDIT_RESOURCE_SCREEN, $screenid, $screen['name']); }
/** * Updates trigger records in database. * * @param array $triggers */ protected function updateReal(array $triggers) { $triggers = zbx_toArray($triggers); $infos = []; $triggerIds = zbx_objectValues($triggers, 'triggerid'); $dbTriggers = $this->get(['output' => API_OUTPUT_EXTEND, 'triggerids' => $triggerIds, 'selectHosts' => ['name'], 'selectDependencies' => ['triggerid'], 'preservekeys' => true, 'nopermissions' => true]); $dbTriggers = CMacrosResolverHelper::resolveTriggerExpressions($dbTriggers); $changedPriorityTriggerIds = []; foreach ($triggers as &$trigger) { $descriptionChanged = false; $expressionChanged = false; $dbTrigger = $dbTriggers[$trigger['triggerid']]; $hosts = zbx_objectValues($dbTrigger['hosts'], 'name'); if (isset($trigger['description']) && strcmp($dbTrigger['description'], $trigger['description']) != 0) { $descriptionChanged = true; } else { $trigger['description'] = $dbTrigger['description']; } if (isset($trigger['expression']) && $dbTrigger['expression'] !== $trigger['expression']) { $this->validateItems($trigger); $expressionChanged = true; $expressionFull = $trigger['expression']; } if ($expressionChanged) { // check the expression $expressionData = new CTriggerExpression(); if (!$expressionData->parse($expressionFull)) { self::exception(ZBX_API_ERROR_PARAMETERS, $expressionData->error); } // remove triggers if expression is changed in a way that trigger will not appear in current host $oldExpressionData = new CTriggerExpression(); $oldExpressionData->parse($dbTrigger['expression']); // check if at least one template has stayed in expression, this means that child trigger will stay in host $oldTemplates = $oldExpressionData->getHosts(); $newTemplates = zbx_toHash($expressionData->getHosts()); $proceed = true; foreach ($oldTemplates as $oldTemplate) { if (isset($newTemplates[$oldTemplate])) { $proceed = false; break; } } // proceed if there is possibility that child triggers should be deleted if ($proceed) { $sql = 'SELECT t.triggerid' . ' FROM triggers t' . ' WHERE t.templateid=' . zbx_dbstr($trigger['triggerid']); $cTrigCursor = DBselect($sql); $cTrigIds = []; while ($cTrig = DBfetch($cTrigCursor)) { // get templates linked to templated trigger host $templateNames = DBfetchArrayAssoc(DBselect('SELECT h.name' . ' FROM hosts h, hosts_templates ht, items i, functions f' . ' WHERE h.hostid = ht.templateid AND ht.hostid = i.hostid AND i.itemid = f.itemid AND' . ' f.triggerid=' . zbx_dbstr($cTrig['triggerid'])), 'name'); // if we have at least one template linked to trigger host inside trigger expression, // then we don't delete this trigger $expressionHosts = $expressionData->getHosts(); foreach ($expressionHosts as $templateName) { if (isset($templateNames[$templateName])) { continue 2; } } $cTrigIds[] = $cTrig['triggerid']; } $this->deleteByIds($cTrigIds); } DB::delete('functions', ['triggerid' => $trigger['triggerid']]); try { $trigger['expression'] = implode_exp($expressionFull, $trigger['triggerid'], $hosts); } catch (Exception $e) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot implode expression "%s".', $expressionFull) . ' ' . $e->getMessage()); } // if the expression has changed, we must revalidate the existing dependencies if (!isset($trigger['dependencies'])) { $trigger['dependencies'] = zbx_objectValues($dbTrigger['dependencies'], 'triggerid'); } } $triggerUpdate = $trigger; if (!$descriptionChanged) { unset($triggerUpdate['description']); } if (!$expressionChanged) { unset($triggerUpdate['expression']); } // skip updating read only values unset($triggerUpdate['state'], $triggerUpdate['value'], $triggerUpdate['lastchange'], $triggerUpdate['error']); DB::update('triggers', ['values' => $triggerUpdate, 'where' => ['triggerid' => $trigger['triggerid']]]); // update service status if (isset($trigger['priority']) && $trigger['priority'] != $dbTrigger['priority']) { $changedPriorityTriggerIds[] = $trigger['triggerid']; } // restore the full expression to properly validate dependencies $trigger['expression'] = $expressionChanged ? $expressionFull : $dbTrigger['expression']; $infos[] = _s('Updated: Trigger "%1$s" on "%2$s".', $trigger['description'], implode(', ', $hosts)); add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER, $dbTrigger['triggerid'], $dbTrigger['description'], null, $dbTrigger, $triggerUpdate); } unset($trigger); if ($changedPriorityTriggerIds && $this->usedInItServices($changedPriorityTriggerIds)) { updateItServices(); } foreach ($infos as $info) { info($info); } }
/** * Delete triggers. * * @param int|string|array $triggerIds array with trigger ids * @param bool $nopermissions * * @return array */ public function delete($triggerIds, $nopermissions = false) { if (empty($triggerIds)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $triggerIds = zbx_toArray($triggerIds); $triggerPrototypeIds = $triggerIds; $delTriggers = $this->get(array('triggerids' => $triggerIds, 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'preservekeys' => true)); // TODO: remove $nopermissions hack if (!$nopermissions) { foreach ($triggerIds as $triggerId) { if (!isset($delTriggers[$triggerId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } if ($delTriggers[$triggerId]['templateid'] != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot delete templated trigger "%1$s:%2$s".', $delTriggers[$triggerId]['description'], explode_exp($delTriggers[$triggerId]['expression']))); } } } // get child triggers $parentTriggerids = $triggerIds; do { $dbItems = DBselect('SELECT triggerid FROM triggers WHERE ' . dbConditionInt('templateid', $parentTriggerids)); $parentTriggerids = array(); while ($dbTrigger = DBfetch($dbItems)) { $parentTriggerids[] = $dbTrigger['triggerid']; $triggerIds[$dbTrigger['triggerid']] = $dbTrigger['triggerid']; } } while (!empty($parentTriggerids)); // select all triggers which are deleted (include childs) $delTriggers = $this->get(array('triggerids' => $triggerIds, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => array('name'))); // created triggers $createdTriggers = array(); $sql = 'SELECT triggerid FROM trigger_discovery WHERE ' . dbConditionInt('parent_triggerid', $triggerIds); $dbTriggers = DBselect($sql); while ($trigger = DBfetch($dbTriggers)) { $createdTriggers[$trigger['triggerid']] = $trigger['triggerid']; } if (!empty($createdTriggers)) { $result = API::Trigger()->delete($createdTriggers, true); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete triggers created by low level discovery.')); } } // TODO: REMOVE info foreach ($delTriggers as $trigger) { info(_s('Deleted: Trigger prototype "%1$s" on "%2$s".', $trigger['description'], implode(', ', zbx_objectValues($trigger['hosts'], 'name')))); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_TRIGGER_PROTOTYPE, $trigger['triggerid'], $trigger['description'] . ':' . $trigger['expression'], null, null, null); } DB::delete('triggers', array('triggerid' => $triggerIds)); return array('triggerids' => $triggerPrototypeIds); }
} } // clone screens $screens = API::TemplateScreen()->get(array('templateids' => $cloneTemplateId, 'output' => array('screenid'), 'preservekeys' => true, 'inherited' => false)); if ($screens) { $screensCopied = API::TemplateScreen()->copy(array('screenIds' => zbx_objectValues($screens, 'screenid'), 'templateIds' => $templateId)); if (!$screensCopied) { throw new Exception(); } } } DBend(true); show_messages(true, $msgOk, $msgFail); clearCookies(true); if ($created) { add_audit_ext(AUDIT_ACTION_ADD, AUDIT_RESOURCE_TEMPLATE, $templateId, $templateName, 'hosts', null, null); } unset($_REQUEST['form'], $_REQUEST['templateid']); } catch (Exception $e) { DBend(false); show_messages(false, $msgOk, $msgFail); } unset($_REQUEST['save']); } elseif (isset($_REQUEST['delete']) && isset($_REQUEST['templateid'])) { DBstart(); $goResult = true; $result = API::Template()->massUpdate(array('templates' => zbx_toObject($_REQUEST['templateid'], 'templateid'), 'hosts' => array())); if ($result) { $result = API::Template()->delete($_REQUEST['templateid']); } $result = DBend($result);
$groups = get_request('groups', array()); $go_result = API::HostGroup()->delete($groups); show_messages($go_result, _('Group deleted'), _('Cannot delete group')); } elseif (str_in_array($_REQUEST['go'], array('activate', 'disable'))) { $status = $_REQUEST['go'] == 'activate' ? HOST_STATUS_MONITORED : HOST_STATUS_NOT_MONITORED; $groups = get_request('groups', array()); if (!empty($groups)) { DBstart(); $hosts = API::Host()->get(array('groupids' => $groups, 'editable' => 1, 'output' => API_OUTPUT_EXTEND)); if (empty($hosts)) { $go_result = true; } else { $go_result = API::Host()->massUpdate(array('hosts' => $hosts, 'status' => $status)); if ($go_result) { foreach ($hosts as $host) { add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['host'], 'hosts', array('status' => $host['status']), array('status' => $status)); } } } $go_result = DBend($go_result); show_messages($go_result, _('Host status updated'), _('Cannot update host')); } } if ($_REQUEST['go'] != 'none' && isset($go_result) && $go_result) { $url = new CUrl(); $path = $url->getPath(); insert_js('cookie.eraseArray("' . $path . '")'); } /* * Display */
/** * Delete host groups. * * @param array $groupids * * @return boolean */ public function delete($groupids) { if (empty($groupids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $groupids = zbx_toArray($groupids); $options = array('groupids' => $groupids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true); $delGroups = $this->get($options); foreach ($groupids as $groupid) { if (!isset($delGroups[$groupid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } if ($delGroups[$groupid]['internal'] == ZBX_INTERNAL_GROUP) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Group "%1$s" is internal and can not be deleted.', $delGroups[$groupid]['name'])); } } $dltGroupids = getDeletableHostGroups($groupids); if (count($groupids) != count($dltGroupids)) { foreach ($groupids as $groupid) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Group "%s" cannot be deleted, because some hosts depend on it.', $delGroups[$groupid]['name'])); } } $dbScripts = API::Script()->get(array('groupids' => $groupids, 'output' => array('scriptid', 'groupid'), 'nopermissions' => true)); if (!empty($dbScripts)) { foreach ($dbScripts as $script) { if ($script['groupid'] == 0) { continue; } self::exception(ZBX_API_ERROR_PARAMETERS, _s('Group "%s" cannot be deleted, because it is used in a global script.', $delGroups[$script['groupid']]['name'])); } } // delete screens items $resources = array(SCREEN_RESOURCE_HOSTGROUP_TRIGGERS, SCREEN_RESOURCE_HOSTS_INFO, SCREEN_RESOURCE_TRIGGERS_INFO, SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW); DB::delete('screens_items', array('resourceid' => $groupids, 'resourcetype' => $resources)); // delete sysmap element if (!empty($groupids)) { DB::delete('sysmaps_elements', array('elementtype' => SYSMAP_ELEMENT_TYPE_HOST_GROUP, 'elementid' => $groupids)); } // disable actions // actions from conditions $actionids = array(); $dbActions = DBselect('SELECT DISTINCT c.actionid' . ' FROM conditions c' . ' WHERE c.conditiontype=' . CONDITION_TYPE_HOST_GROUP . ' AND ' . dbConditionString('c.value', $groupids)); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } // actions from operations $dbActions = DBselect('SELECT DISTINCT o.actionid' . ' FROM operations o,opgroup og' . ' WHERE o.operationid=og.operationid' . ' AND ' . dbConditionInt('og.groupid', $groupids)); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } if (!empty($actionids)) { $update = array(); $update[] = array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionids)); DB::update('actions', $update); } // delete action conditions DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_HOST_GROUP, 'value' => $groupids)); // delete action operation commands $operationids = array(); $dbOperations = DBselect('SELECT DISTINCT og.operationid' . ' FROM opgroup og' . ' WHERE ' . dbConditionInt('og.groupid', $groupids)); while ($dbOperation = DBfetch($dbOperations)) { $operationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('opgroup', array('groupid' => $groupids)); // delete empty operations $delOperationids = array(); $dbOperations = DBselect('SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS (SELECT NULL FROM opgroup og WHERE o.operationid=og.operationid)'); while ($dbOperation = DBfetch($dbOperations)) { $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('operations', array('operationid' => $delOperationids)); // host groups DB::delete('groups', array('groupid' => $groupids)); // TODO: remove audit foreach ($groupids as $groupid) { add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST_GROUP, $groupid, $delGroups[$groupid]['name'], 'groups', null, null); } return array('groupids' => $groupids); }
show_messages($go_result, S_TRIGGER_ADDED, S_CANNOT_ADD_TRIGGER); } else { if ($_REQUEST['go'] == 'delete' && isset($_REQUEST['g_triggerid'])) { DBstart(); $triggerids = array(); $options = array('triggerids' => $_REQUEST['g_triggerid'], 'editable' => 1, 'select_hosts' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND, 'expandDescription' => 1); $triggers = CTrigger::get($options); foreach ($triggers as $tnum => $trigger) { if ($trigger['templateid'] != 0) { unset($triggers[$tnum]); error(S_CANNOT_DELETE_TRIGGER . ' [ ' . $trigger['description'] . ' ] (' . S_TEMPLATED_TRIGGER . ')'); continue; } $triggerids[] = $trigger['triggerid']; $host = reset($trigger['hosts']); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_TRIGGER, $trigger['triggerid'], $host['host'] . ':' . $trigger['description'], NULL, NULL, NULL); } $go_result = !empty($triggerids); if ($go_result) { $go_result = CTrigger::delete($triggerids); } $go_result = DBend($go_result); show_messages($go_result, S_TRIGGERS_DELETED, S_CANNOT_DELETE_TRIGGERS); } } } } } } } }
} else { error('No target selection.'); } show_messages($result, S_TRIGGER_ADDED, S_CANNOT_ADD_TRIGGER); } else { if ($_REQUEST['go'] == 'delete' && isset($_REQUEST['g_triggerid'])) { $_REQUEST['g_triggerid'] = array_intersect($_REQUEST['g_triggerid'], $available_triggers); DBstart(); foreach ($_REQUEST['g_triggerid'] as $id => $triggerid) { $row = DBfetch(DBselect('SELECT triggerid,templateid FROM triggers t WHERE t.triggerid=' . $triggerid)); if ($row['templateid'] != 0) { unset($_REQUEST['g_triggerid'][$id]); continue; } $description = expand_trigger_description($triggerid); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_TRIGGER, $triggerid, $description, NULL, NULL, NULL); } $result = delete_trigger($_REQUEST['g_triggerid']); $result = DBend($result); show_messages($result, S_TRIGGERS_DELETED, S_CANNOT_DELETE_TRIGGERS); } } } } } } } } } if (isset($_REQUEST['hostid']) && !isset($_REQUEST['groupid']) && !isset($_REQUEST['triggerid'])) { $sql = 'SELECT DISTINCT hg.groupid ' . ' FROM hosts_groups hg ' . ' WHERE hg.hostid=' . $_REQUEST['hostid'];
$goResult = API::HostGroup()->delete(get_request('groups', array())); show_messages($goResult, _('Group deleted'), _('Cannot delete group')); clearCookies($goResult); } elseif (str_in_array(getRequest('go'), array('activate', 'disable'))) { $enable = getRequest('go') == 'activate'; $status = $enable ? HOST_STATUS_MONITORED : HOST_STATUS_NOT_MONITORED; $auditAction = $enable ? AUDIT_ACTION_ENABLE : AUDIT_ACTION_DISABLE; $groups = getRequest('groups', array()); if ($groups) { DBstart(); $hosts = API::Host()->get(array('groupids' => $groups, 'editable' => true, 'output' => API_OUTPUT_EXTEND)); if ($hosts) { $result = API::Host()->massUpdate(array('hosts' => $hosts, 'status' => $status)); if ($result) { foreach ($hosts as $host) { add_audit_ext($auditAction, AUDIT_RESOURCE_HOST, $host['hostid'], $host['host'], 'hosts', array('status' => $host['status']), array('status' => $status)); } } } else { $result = true; } $result = DBend($result); $updated = count($hosts); $messageSuccess = $enable ? _n('Host enabled', 'Hosts enabled', $updated) : _n('Host disabled', 'Hosts disabled', $updated); $messageFailed = $enable ? _n('Cannot enable host', 'Cannot enable hosts', $updated) : _n('Cannot disable host', 'Cannot disable hosts', $updated); show_messages($result, $messageSuccess, $messageFailed); clearCookies($result); } } /* * Display
function delete_item($itemids) { zbx_value2array($itemids); if (empty($itemids)) { return true; } // Get items INFO before delete them! $items = array(); $item_res = DBselect('SELECT itemid, description, key_ FROM items WHERE ' . DBcondition('itemid', $itemids)); while ($item_rows = DBfetch($item_res)) { $items[$item_rows['itemid']] = $item_rows; } // -- $hosts = array(); $hosts = get_host_by_itemid($itemids); // first delete child items $del_cld_items = array(); $db_items = DBselect('SELECT itemid FROM items WHERE ' . DBcondition('templateid', $itemids)); while ($db_item = DBfetch($db_items)) { // recursion !!!! $del_cld_items[$db_item['itemid']] = $db_item['itemid']; } if (!empty($del_cld_items)) { $result = delete_item($del_cld_items); if (!$result) { return $result; } } //-- // triggers $result = delete_triggers_by_itemid($itemids); if (!$result) { return $result; } //-- // delete graphs $del_graphs = array(); $db_gitems = DBselect('SELECT DISTINCT graphid FROM graphs_items WHERE ' . DBcondition('itemid', $itemids)); while ($db_gitem = DBfetch($db_gitems)) { $del_graphs[$db_gitem['graphid']] = $db_gitem['graphid']; } if (!empty($del_graphs)) { $result = delete_graph($del_graphs); if (!$result) { return $result; } } //-- $result = delete_history_by_itemid($itemids, 1); if (!$result) { return $result; } $temp_arr = array(SCREEN_RESOURCE_SIMPLE_GRAPH, SCREEN_RESOURCE_PLAIN_TEXT); DBexecute('DELETE FROM screens_items WHERE ' . DBcondition('resourceid', $itemids) . ' AND ' . DBcondition('resourcetype', $temp_arr)); DBexecute('DELETE FROM items_applications WHERE ' . DBcondition('itemid', $itemids)); DBexecute("DELETE FROM profiles WHERE idx='web.favorite.graphids' AND source='itemid' AND " . DBcondition('value_id', $itemids)); foreach ($itemids as $id) { /* The section should be improved */ $item_old = get_item_by_itemid($id); $result = DBexecute('DELETE FROM items WHERE itemid=' . $id); if ($result) { add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_ITEM, $id, $item_old['description'], 'items', NULL, NULL); } else { break; } } /* $result = DBexecute('DELETE FROM items WHERE '.DBcondition('itemid',$itemids));*/ if ($result) { foreach ($items as $itemid => $item) { info("Item '" . $hosts[$itemid]['host'] . ':' . $item['key_'] . "' deleted"); } } return $result; }
/** * Delete Host * * @param array $hosts * @param array $hosts[0, ...]['hostid'] Host ID to delete * * @return array|boolean */ public function delete($hosts) { if (empty($hosts)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $hosts = zbx_toArray($hosts); $hostids = zbx_objectValues($hosts, 'hostid'); $this->checkInput($hosts, __FUNCTION__); // delete the discovery rules first $delRules = API::DiscoveryRule()->get(array('hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true)); if ($delRules) { API::DiscoveryRule()->delete(array_keys($delRules), true); } // delete the items $delItems = API::Item()->get(array('templateids' => $hostids, 'output' => API_OUTPUT_SHORTEN, 'nopermissions' => true, 'preservekeys' => true)); if ($delItems) { API::Item()->delete(array_keys($delItems), true); } // delete web tests $delHttptests = array(); $dbHttptests = get_httptests_by_hostid($hostids); while ($dbHttptest = DBfetch($dbHttptests)) { $delHttptests[$dbHttptest['httptestid']] = $dbHttptest['httptestid']; } if (!empty($delHttptests)) { API::WebCheck()->delete($delHttptests); } // delete screen items DB::delete('screens_items', array('resourceid' => $hostids, 'resourcetype' => SCREEN_RESOURCE_HOST_TRIGGERS)); // delete host from maps if (!empty($hostids)) { DB::delete('sysmaps_elements', array('elementtype' => SYSMAP_ELEMENT_TYPE_HOST, 'elementid' => $hostids)); } // disable actions // actions from conditions $actionids = array(); $sql = 'SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_HOST . ' AND ' . dbConditionString('value', $hostids); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } // actions from operations $sql = 'SELECT DISTINCT o.actionid' . ' FROM operations o, opcommand_hst oh' . ' WHERE o.operationid=oh.operationid' . ' AND ' . dbConditionInt('oh.hostid', $hostids); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } if (!empty($actionids)) { $update = array(); $update[] = array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionids)); DB::update('actions', $update); } // delete action conditions DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_HOST, 'value' => $hostids)); // delete action operation commands $operationids = array(); $sql = 'SELECT DISTINCT oh.operationid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('oh.hostid', $hostids); $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $operationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('opcommand_hst', array('hostid' => $hostids)); // delete empty operations $delOperationids = array(); $sql = 'SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS(SELECT oh.opcommand_hstid FROM opcommand_hst oh WHERE oh.operationid=o.operationid)'; $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('operations', array('operationid' => $delOperationids)); $hosts = API::Host()->get(array('output' => array('hostid', 'name'), 'hostids' => $hostids, 'nopermissions' => true)); // delete host inventory DB::delete('host_inventory', array('hostid' => $hostids)); // delete host applications DB::delete('applications', array('hostid' => $hostids)); // delete host DB::delete('hosts', array('hostid' => $hostids)); // TODO: remove info from API foreach ($hosts as $host) { info(_s('Deleted: Host "%1$s".', $host['name'])); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['name'], 'hosts', NULL, NULL); } return array('hostids' => $hostids); }
/** * Delete Host * * @param string|array $hostIds * @param bool $nopermissions * * @return array|boolean */ public function delete($hostIds, $nopermissions = false) { $hostIds = zbx_toArray($hostIds); // deprecated input support if ($hostIds && is_array($hostIds[0])) { $this->deprecated('Passing objects is deprecated, use an array of IDs instead.'); foreach ($hostIds as $host) { if (!check_db_fields(array('hostid' => null), $host)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No host ID given.')); } } $hostIds = zbx_objectValues($hostIds, 'hostid'); } $this->validateDelete($hostIds, $nopermissions); // delete the discovery rules first $delRules = API::DiscoveryRule()->get(array('hostids' => $hostIds, 'nopermissions' => true, 'preservekeys' => true)); if ($delRules) { API::DiscoveryRule()->delete(array_keys($delRules), true); } // delete the items $delItems = API::Item()->get(array('templateids' => $hostIds, 'output' => array('itemid'), 'nopermissions' => true, 'preservekeys' => true)); if ($delItems) { API::Item()->delete(array_keys($delItems), true); } // delete web tests $delHttptests = array(); $dbHttptests = get_httptests_by_hostid($hostIds); while ($dbHttptest = DBfetch($dbHttptests)) { $delHttptests[$dbHttptest['httptestid']] = $dbHttptest['httptestid']; } if (!empty($delHttptests)) { API::HttpTest()->delete($delHttptests, true); } // delete screen items DB::delete('screens_items', array('resourceid' => $hostIds, 'resourcetype' => SCREEN_RESOURCE_HOST_TRIGGERS)); // delete host from maps if (!empty($hostIds)) { DB::delete('sysmaps_elements', array('elementtype' => SYSMAP_ELEMENT_TYPE_HOST, 'elementid' => $hostIds)); } // disable actions // actions from conditions $actionids = array(); $sql = 'SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_HOST . ' AND ' . dbConditionString('value', $hostIds); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } // actions from operations $sql = 'SELECT DISTINCT o.actionid' . ' FROM operations o, opcommand_hst oh' . ' WHERE o.operationid=oh.operationid' . ' AND ' . dbConditionInt('oh.hostid', $hostIds); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } if (!empty($actionids)) { $update = array(); $update[] = array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionids)); DB::update('actions', $update); } // delete action conditions DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_HOST, 'value' => $hostIds)); // delete action operation commands $operationids = array(); $sql = 'SELECT DISTINCT oh.operationid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('oh.hostid', $hostIds); $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $operationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('opcommand_hst', array('hostid' => $hostIds)); // delete empty operations $delOperationids = array(); $sql = 'SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS(SELECT oh.opcommand_hstid FROM opcommand_hst oh WHERE oh.operationid=o.operationid)'; $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('operations', array('operationid' => $delOperationids)); $hosts = API::Host()->get(array('output' => array('hostid', 'name'), 'hostids' => $hostIds, 'nopermissions' => true)); // delete host inventory DB::delete('host_inventory', array('hostid' => $hostIds)); // delete host applications DB::delete('applications', array('hostid' => $hostIds)); // delete host DB::delete('hosts', array('hostid' => $hostIds)); // TODO: remove info from API foreach ($hosts as $host) { info(_s('Deleted: Host "%1$s".', $host['name'])); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['name'], 'hosts', NULL, NULL); } // remove Monitoring > Latest data toggle profile values related to given hosts CProfile::delete('web.latest.toggle_other', $hostIds); return array('hostids' => $hostIds); }
if ($result) { unset($_REQUEST['form']); } } else { if (isset($_REQUEST['delete']) && isset($_REQUEST['sysmapid']) || $_REQUEST['go'] == 'delete') { $sysmapids = get_request('maps', array()); if (isset($_REQUEST['sysmapid'])) { $sysmapids[] = $_REQUEST['sysmapid']; } $maps = CMap::get(array('sysmapids' => $sysmapids, 'output' => API_OUTPUT_EXTEND, 'editable => 1')); $go_result = CMap::delete($sysmapids); show_messages($go_result, S_MAP_DELETED, S_CANNOT_DELETE_MAP); if ($go_result) { unset($_REQUEST['form']); foreach ($maps as $map) { add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_MAP, $map['sysmapid'], $map['name'], null, null, null); } } } } if ($_REQUEST['go'] != 'none' && isset($go_result) && $go_result) { $url = new CUrl(); $path = $url->getPath(); insert_js('cookie.eraseArray("' . $path . '")'); } $form = new CForm(null, 'get'); $form->addItem(new CButton('form', S_CREATE_MAP)); $form->addItem(new CButton('form', S_IMPORT_MAP)); $map_wdgt = new CWidget(); $map_wdgt->addPageHeader(S_CONFIGURATION_OF_NETWORK_MAPS, $form); if (isset($_REQUEST['form'])) {
if ($createNew) { $hostIds = API::Host()->create($host); if ($hostIds) { $hostId = reset($hostIds['hostids']); } else { throw new Exception(); } add_audit_ext(AUDIT_ACTION_ADD, AUDIT_RESOURCE_HOST, $hostId, $host['host'], null, null, null); } else { $hostId = $host['hostid'] = $_REQUEST['hostid']; if (!API::Host()->update($host)) { throw new Exception(); } $hostNew = API::Host()->get(array('hostids' => $hostId, 'editable' => true, 'output' => API_OUTPUT_EXTEND)); $hostNew = reset($hostNew); add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_HOST, $hostNew['hostid'], $hostNew['host'], 'hosts', $hostOld, $hostNew); } if ($_REQUEST['form'] == 'full_clone') { $srcHostId = get_request('hostid'); if (!copyApplications($srcHostId, $hostId)) { throw new Exception(); } if (!copyItems($srcHostId, $hostId)) { throw new Exception(); } // clone triggers $triggers = API::Trigger()->get(array('output' => array('triggerid'), 'hostids' => $srcHostId, 'inherited' => false)); if ($triggers) { if (!copyTriggersToHosts(zbx_objectValues($triggers, 'triggerid'), $hostId, $srcHostId)) { throw new Exception(); }
throw new Exception(); } } // clone screens $screens = API::TemplateScreen()->get(array('templateids' => $clone_templateid, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true, 'inherited' => false)); if ($screens) { $screensCopied = API::TemplateScreen()->copy(array('screenIds' => zbx_objectValues($screens, 'screenid'), 'templateIds' => $templateid)); if (!$screensCopied) { throw new Exception(); } } } DBend(true); show_messages(true, $msg_ok, $msg_fail); if ($created) { add_audit_ext(AUDIT_ACTION_ADD, AUDIT_RESOURCE_TEMPLATE, $templateid, $template_name, 'hosts', NULL, NULL); } unset($_REQUEST['form']); unset($_REQUEST['templateid']); } catch (Exception $e) { DBend(false); show_messages(false, $msg_ok, $msg_fail); } unset($_REQUEST['save']); } elseif (isset($_REQUEST['delete']) && isset($_REQUEST['templateid'])) { DBstart(); $go_result = true; $result = API::Template()->massUpdate(array('templates' => zbx_toObject($_REQUEST['templateid'], 'templateid'), 'hosts' => array())); if ($result) { $result = API::Template()->delete($_REQUEST['templateid']); }
/** * Delete value maps. * * @param array $valuemapids * * @return array */ public function delete(array $valuemapids) { // Check permissions. if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('Only super admins can delete value maps.')); } if (!$valuemapids) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } // Check if value map exists. $db_valuemaps = API::getApiService()->select('valuemaps', ['output' => ['valuemapid', 'name'], 'valuemapids' => $valuemapids, 'preservekeys' => true]); foreach ($valuemapids as $valuemapid) { if (!is_int($valuemapid) && !is_string($valuemapid)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.')); } elseif (!array_key_exists($valuemapid, $db_valuemaps)) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } // Mappings are handled with cascade delete, but items.valuemapid reference should be removed first. $result = DB::update('items', [['values' => ['valuemapid' => 0], 'where' => ['valuemapid' => $valuemapids]]]); if ($result) { $this->deleteByIds($valuemapids); } foreach ($db_valuemaps as $db_valuemap) { add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_VALUE_MAP, $db_valuemap['valuemapid'], $db_valuemap['name'], null, null, null); } return ['valuemapids' => $valuemapids]; }
$result &= API::DiscoveryRule()->copy(array('discoveryids' => zbx_objectValues($dbDiscoveryRules, 'itemid'), 'hostids' => array($templateId))); if (!$result) { throw new Exception(); } } // copy template screens $dbTemplateScreens = API::TemplateScreen()->get(array('output' => array('screenid'), 'templateids' => $cloneTemplateId, 'preservekeys' => true, 'inherited' => false)); if ($dbTemplateScreens) { $result &= API::TemplateScreen()->copy(array('screenIds' => zbx_objectValues($dbTemplateScreens, 'screenid'), 'templateIds' => $templateId)); if (!$result) { throw new Exception(); } } } if ($result) { add_audit_ext($auditAction, AUDIT_RESOURCE_TEMPLATE, $templateId, $templateName, 'hosts', null, null); } unset($_REQUEST['form'], $_REQUEST['templateid']); $result = DBend($result); if ($result) { uncheckTableRows(); } show_messages($result, $messageSuccess, $messageFailed); } catch (Exception $e) { DBend(false); show_error_message($messageFailed); } } elseif (isset($_REQUEST['delete']) && isset($_REQUEST['templateid'])) { DBstart(); $result = API::Template()->massUpdate(array('templates' => zbx_toObject($_REQUEST['templateid'], 'templateid'), 'hosts' => array())); if ($result) {
/** * Delete Host. * * @param array $hostIds * @param bool $nopermissions * * @return array */ public function delete(array $hostIds, $nopermissions = false) { $this->validateDelete($hostIds, $nopermissions); // delete the discovery rules first $delRules = API::DiscoveryRule()->get(['output' => ['itemid'], 'hostids' => $hostIds, 'nopermissions' => true, 'preservekeys' => true]); if ($delRules) { API::DiscoveryRule()->delete(array_keys($delRules), true); } // delete the items $delItems = API::Item()->get(['templateids' => $hostIds, 'output' => ['itemid'], 'nopermissions' => true, 'preservekeys' => true]); if ($delItems) { API::Item()->delete(array_keys($delItems), true); } // delete web tests $delHttptests = []; $dbHttptests = get_httptests_by_hostid($hostIds); while ($dbHttptest = DBfetch($dbHttptests)) { $delHttptests[$dbHttptest['httptestid']] = $dbHttptest['httptestid']; } if (!empty($delHttptests)) { API::HttpTest()->delete($delHttptests, true); } // delete screen items DB::delete('screens_items', ['resourceid' => $hostIds, 'resourcetype' => SCREEN_RESOURCE_HOST_TRIGGERS]); // delete host from maps if (!empty($hostIds)) { DB::delete('sysmaps_elements', ['elementtype' => SYSMAP_ELEMENT_TYPE_HOST, 'elementid' => $hostIds]); } // disable actions // actions from conditions $actionids = []; $sql = 'SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_HOST . ' AND ' . dbConditionString('value', $hostIds); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } // actions from operations $sql = 'SELECT DISTINCT o.actionid' . ' FROM operations o, opcommand_hst oh' . ' WHERE o.operationid=oh.operationid' . ' AND ' . dbConditionInt('oh.hostid', $hostIds); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } if (!empty($actionids)) { $update = []; $update[] = ['values' => ['status' => ACTION_STATUS_DISABLED], 'where' => ['actionid' => $actionids]]; DB::update('actions', $update); } // delete action conditions DB::delete('conditions', ['conditiontype' => CONDITION_TYPE_HOST, 'value' => $hostIds]); // delete action operation commands $operationids = []; $sql = 'SELECT DISTINCT oh.operationid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('oh.hostid', $hostIds); $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $operationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('opcommand_hst', ['hostid' => $hostIds]); // delete empty operations $delOperationids = []; $sql = 'SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS(SELECT oh.opcommand_hstid FROM opcommand_hst oh WHERE oh.operationid=o.operationid)'; $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('operations', ['operationid' => $delOperationids]); $hosts = API::Host()->get(['output' => ['hostid', 'name'], 'hostids' => $hostIds, 'nopermissions' => true]); // delete host inventory DB::delete('host_inventory', ['hostid' => $hostIds]); // delete host applications DB::delete('applications', ['hostid' => $hostIds]); // delete host DB::delete('hosts', ['hostid' => $hostIds]); // TODO: remove info from API foreach ($hosts as $host) { info(_s('Deleted: Host "%1$s".', $host['name'])); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['name'], 'hosts', NULL, NULL); } // remove Monitoring > Latest data toggle profile values related to given hosts DB::delete('profiles', ['idx' => 'web.latest.toggle_other', 'idx2' => $hostIds]); return ['hostids' => $hostIds]; }
function update_item_status($itemids, $status) { zbx_value2array($itemids); $result = true; $db_items = DBselect('SELECT i.* FROM items i WHERE ' . dbConditionInt('i.itemid', $itemids)); while ($item = DBfetch($db_items)) { $old_status = $item['status']; if ($status != $old_status) { $result &= DBexecute('UPDATE items SET status=' . zbx_dbstr($status) . ' WHERE itemid=' . zbx_dbstr($item['itemid'])); if ($result) { $host = get_host_by_hostid($item['hostid']); $item_new = get_item_by_itemid($item['itemid']); add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_ITEM, $item['itemid'], $host['host'] . NAME_DELIMITER . $item['name'], 'items', $item, $item_new); } } } return $result; }
function update_trigger($triggerid, $expression = NULL, $description = NULL, $type = NULL, $priority = NULL, $status = NULL, $comments = NULL, $url = NULL, $deps = array(), $templateid = 0) { $trigger = get_trigger_by_triggerid($triggerid); $trig_hosts = get_hosts_by_triggerid($triggerid); $trig_host = DBfetch($trig_hosts); $event_to_unknown = false; if (is_null($expression)) { /* Restore expression */ $expression = explode_exp($trigger["expression"], 0); } else { if ($expression != explode_exp($trigger["expression"], 0)) { $event_to_unknown = true; } } if (!validate_expression($expression)) { return false; } $exp_hosts = get_hosts_by_expression($expression); if ($exp_hosts) { $chd_hosts = get_hosts_by_templateid($trig_host["hostid"]); if (DBfetch($chd_hosts)) { $exp_host = DBfetch($exp_hosts); $db_chd_triggers = get_triggers_by_templateid($triggerid); while ($db_chd_trigger = DBfetch($db_chd_triggers)) { $chd_trig_hosts = get_hosts_by_triggerid($db_chd_trigger["triggerid"]); $chd_trig_host = DBfetch($chd_trig_hosts); $newexpression = str_replace("{" . $exp_host["host"] . ":", "{" . $chd_trig_host["host"] . ":", $expression); // recursion update_trigger($db_chd_trigger["triggerid"], $newexpression, $description, $type, $priority, NULL, $comments, $url, replace_template_dependencies($deps, $chd_trig_host['hostid']), $triggerid); } } } $result = delete_function_by_triggerid($triggerid); if (!$result) { return $result; } $expression = implode_exp($expression, $triggerid); /* errors can be ignored cose function must return NULL */ if ($event_to_unknown) { add_event($triggerid, TRIGGER_VALUE_UNKNOWN); } reset_items_nextcheck($triggerid); $sql = "UPDATE triggers SET"; if (!is_null($expression)) { $sql .= ' expression=' . zbx_dbstr($expression) . ','; } if (!is_null($description)) { $sql .= ' description=' . zbx_dbstr($description) . ','; } if (!is_null($type)) { $sql .= ' type=' . $type . ','; } if (!is_null($priority)) { $sql .= ' priority=' . $priority . ','; } if (!is_null($status)) { $sql .= ' status=' . $status . ','; } if (!is_null($comments)) { $sql .= ' comments=' . zbx_dbstr($comments) . ','; } if (!is_null($url)) { $sql .= ' url=' . zbx_dbstr($url) . ','; } if (!is_null($templateid)) { $sql .= ' templateid=' . $templateid . ','; } $sql .= ' value=2 WHERE triggerid=' . $triggerid; $result = DBexecute($sql); delete_dependencies_by_triggerid($triggerid); foreach ($deps as $id => $triggerid_up) { if (!($result2 = add_trigger_dependency($triggerid, $triggerid_up))) { error(S_INCORRECT_DEPENDENCY . ' [' . expand_trigger_description($triggerid_up) . ']'); } $result &= $result2; } if ($result) { $trig_hosts = get_hosts_by_triggerid($triggerid); $msg = "Trigger '" . $trigger["description"] . "' updated"; $trig_host = DBfetch($trig_hosts); if ($trig_host) { $msg .= " for host '" . $trig_host["host"] . "'"; } info($msg); } if ($result) { $trigger_new = get_trigger_by_triggerid($triggerid); add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER, $triggerid, $trigger["description"], 'triggers', $trigger, $trigger_new); } return $result; }
$_REQUEST['enter'] = _('Sign in'); $_REQUEST['name'] = $_SERVER['PHP_AUTH_USER']; } else { access_deny(); } } // login via form if (isset($_REQUEST['enter']) && $_REQUEST['enter'] == _('Sign in')) { // try to login if (CWebUser::login(get_request('name', ''), get_request('password', ''))) { // save remember login preference $user = array('autologin' => get_request('autologin', 0)); if (CWebUser::$data['autologin'] != $user['autologin']) { $result = API::User()->updateProfile($user); } add_audit_ext(AUDIT_ACTION_LOGIN, AUDIT_RESOURCE_USER, CWebUser::$data['userid'], '', null, null, null); $request = get_request('request'); $url = zbx_empty($request) ? CWebUser::$data['url'] : $request; if (zbx_empty($url) || $url == $page['file']) { $url = 'dashboard.php'; } redirect($url); exit; } else { CWebUser::checkAuthentication(null); } } else { // login the user from the session, if the session id is empty - login as a guest CWebUser::checkAuthentication(get_cookie('zbx_sessionid')); } // the user is not logged in, display the login form
function update_host_status($hostids, $status) { $res = true; zbx_value2array($hostids); // $hosts = array(); $sql = 'SELECT * ' . ' FROM hosts ' . ' WHERE ' . DBcondition('hostid', $hostids) . ' AND status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')'; $result = DBselect($sql); while ($host = DBfetch($result)) { if ($status != $host['status']) { // $hosts[$host['hostid']] = $host['hostid']; update_trigger_value_to_unknown_by_hostid($host['hostid']); $res = DBexecute('UPDATE hosts SET status=' . $status . ' WHERE hostid=' . $host['hostid']); if ($res) { $host_new = $host; //get_host_by_hostid($host['hostid']); $host_new['status'] = $status; add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['host'], 'hosts', $host, $host_new); } info(S_UPDATED_STATUS_OF_HOST . ' "' . $host['host'] . '"'); } } /* if(!empty($hosts)){ update_trigger_value_to_unknown_by_hostid($hosts); return DBexecute('UPDATE hosts SET status='.$status. ' WHERE '.DBcondition('hostid',$hosts). ' AND status IN ('.HOST_STATUS_MONITORED.','.HOST_STATUS_NOT_MONITORED.')' ); } else{z return 1; } //*/ return $res; }
/** * Delete existing trigger prototypes. * * @see https://www.zabbix.com/documentation/3.0/manual/api/reference/triggerprototype/delete * * @param array $triggerPrototypeIds * @param bool $nopermissions * * @throws APIException * * @return array */ public function delete(array $triggerPrototypeIds, $nopermissions = false) { if (!$triggerPrototypeIds) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } // TODO: remove $nopermissions hack if (!$nopermissions) { $dbTriggerPrototypes = $this->get(['triggerids' => $triggerPrototypeIds, 'output' => ['description', 'expression', 'templateid'], 'editable' => true, 'preservekeys' => true]); foreach ($triggerPrototypeIds as $triggerPrototypeId) { if (!isset($dbTriggerPrototypes[$triggerPrototypeId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } $dbTriggerPrototype = $dbTriggerPrototypes[$triggerPrototypeId]; if ($dbTriggerPrototype['templateid'] != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot delete templated trigger "%1$s:%2$s".', $dbTriggerPrototype['description'], CMacrosResolverHelper::resolveTriggerExpression($dbTriggerPrototype['expression']))); } } } // get child trigger prototypes $parentTriggerPrototypeIds = $triggerPrototypeIds; do { $dbTriggerPrototypes = DBselect('SELECT triggerid' . ' FROM triggers' . ' WHERE ' . dbConditionInt('templateid', $parentTriggerPrototypeIds)); $parentTriggerPrototypeIds = []; while ($dbTriggerPrototype = DBfetch($dbTriggerPrototypes)) { $parentTriggerPrototypeIds[] = $dbTriggerPrototype['triggerid']; $triggerPrototypeIds[$dbTriggerPrototype['triggerid']] = $dbTriggerPrototype['triggerid']; } } while ($parentTriggerPrototypeIds); // delete triggers created from this prototype $createdTriggerIds = DBfetchColumn(DBselect('SELECT triggerid' . ' FROM trigger_discovery' . ' WHERE ' . dbConditionInt('parent_triggerid', $triggerPrototypeIds)), 'triggerid'); if ($createdTriggerIds) { API::Trigger()->delete($createdTriggerIds, true); } // select all trigger prototypes which are deleted (include children) $dbTriggerPrototypes = $this->get(['triggerids' => $triggerPrototypeIds, 'output' => ['triggerid', 'description', 'expression'], 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => ['name']]); // TODO: REMOVE info foreach ($dbTriggerPrototypes as $dbTriggerPrototype) { info(_s('Deleted: Trigger prototype "%1$s" on "%2$s".', $dbTriggerPrototype['description'], implode(', ', zbx_objectValues($dbTriggerPrototype['hosts'], 'name')))); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_TRIGGER_PROTOTYPE, $dbTriggerPrototype['triggerid'], $dbTriggerPrototype['description'] . ':' . $dbTriggerPrototype['expression'], null, null, null); } DB::delete('triggers', ['triggerid' => $triggerPrototypeIds]); return ['triggerids' => $triggerPrototypeIds]; }
/** * Delete Template * * @param array $templateids * @param array $templateids['templateids'] * @return boolean */ public function delete($templateids) { if (empty($templateids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } $templateids = zbx_toArray($templateids); $options = array('templateids' => $templateids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true); $delTemplates = $this->get($options); foreach ($templateids as $templateid) { if (!isset($delTemplates[$templateid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } API::Template()->unlink($templateids, null, true); // delete the discovery rules first $delRules = API::DiscoveryRule()->get(array('hostids' => $templateids, 'nopermissions' => true, 'preservekeys' => true)); if ($delRules) { API::DiscoveryRule()->delete(array_keys($delRules), true); } // delete the items $delItems = API::Item()->get(array('templateids' => $templateids, 'output' => API_OUTPUT_SHORTEN, 'nopermissions' => true, 'preservekeys' => true)); if ($delItems) { API::Item()->delete(array_keys($delItems), true); } // delete screen items DBexecute('DELETE FROM screens_items WHERE ' . dbConditionInt('resourceid', $templateids) . ' AND resourcetype=' . SCREEN_RESOURCE_HOST_TRIGGERS); // delete host from maps if (!empty($templateids)) { DB::delete('sysmaps_elements', array('elementtype' => SYSMAP_ELEMENT_TYPE_HOST, 'elementid' => $templateids)); } // disable actions // actions from conditions $actionids = array(); $sql = 'SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_HOST_TEMPLATE . ' AND ' . dbConditionString('value', $templateids); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } // actions from operations $sql = 'SELECT DISTINCT o.actionid' . ' FROM operations o,optemplate ot' . ' WHERE o.operationid=ot.operationid' . ' AND ' . dbConditionInt('ot.templateid', $templateids); $dbActions = DBselect($sql); while ($dbAction = DBfetch($dbActions)) { $actionids[$dbAction['actionid']] = $dbAction['actionid']; } if (!empty($actionids)) { DB::update('actions', array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionids))); } // delete action conditions DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_HOST_TEMPLATE, 'value' => $templateids)); // delete action operation commands $operationids = array(); $sql = 'SELECT DISTINCT ot.operationid' . ' FROM optemplate ot' . ' WHERE ' . dbConditionInt('ot.templateid', $templateids); $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $operationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('optemplate', array('templateid' => $templateids)); // delete empty operations $delOperationids = array(); $sql = 'SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS(SELECT NULL FROM optemplate ot WHERE ot.operationid=o.operationid)'; $dbOperations = DBselect($sql); while ($dbOperation = DBfetch($dbOperations)) { $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid']; } DB::delete('operations', array('operationid' => $delOperationids)); // Applications $delApplications = API::Application()->get(array('templateids' => $templateids, 'output' => API_OUTPUT_SHORTEN, 'nopermissions' => 1, 'preservekeys' => 1)); if (!empty($delApplications)) { API::Application()->delete(array_keys($delApplications), true); } DB::delete('hosts', array('hostid' => $templateids)); // TODO: remove info from API foreach ($delTemplates as $template) { info(_s('Deleted: Template "%1$s".', $template['name'])); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $template['hostid'], $template['host'], 'hosts', NULL, NULL); } return array('templateids' => $templateids); }
$options = array('filter' => array('templateid' => $childTriggerIds), 'output' => array('triggerid', 'status'), 'preservekeys' => true, 'nopermissions' => true); $triggers = API::TriggerPrototype()->get($options); $childTriggerIds = array_keys($triggers); foreach ($triggers as $triggerid => $trigger) { if ($trigger['status'] != $status) { $triggerIdsToUpdate[] = $triggerid; } } } while (!empty($childTriggerIds)); DB::update('triggers', array('values' => array('status' => $status), 'where' => array('triggerid' => $triggerIdsToUpdate))); // get updated triggers with additional data $options = array('triggerids' => $triggerIdsToUpdate, 'output' => array('triggerid', 'description'), 'preservekeys' => true, 'selectHosts' => API_OUTPUT_EXTEND, 'nopermissions' => true); $triggers = API::TriggerPrototype()->get($options); foreach ($triggers as $triggerid => $trigger) { $host = reset($trigger['hosts']); add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER_PROTOTYPE, $triggerid, $host['host'] . ': ' . $trigger['description'], 'triggers', $statusOld, $statusNew); } } $go_result = DBend($go_result); show_messages($go_result, _('Status updated'), _('Cannot update status')); } elseif ($_REQUEST['go'] == 'delete' && isset($_REQUEST['g_triggerid'])) { $go_result = API::TriggerPrototype()->delete($_REQUEST['g_triggerid']); show_messages($go_result, _('Triggers deleted'), _('Cannot delete triggers')); } if ($_REQUEST['go'] != 'none' && !empty($go_result)) { $url = new CUrl(); $path = $url->getPath(); insert_js('cookie.eraseArray(\'' . $path . '\')'); $_REQUEST['go'] = 'none'; } /*