/** * Checks if the given array of objects is valid. * * @param array $value * * @return bool */ public function validate($value) { if (!is_array($value)) { $this->error($this->messageInvalid); return false; } // check if it's empty if (!$this->empty && !$value) { $this->error($this->messageEmpty); return false; } // check for objects with duplicate values if ($this->uniqueField) { if ($duplicate = CArrayHelper::findDuplicate($value, $this->uniqueField, $this->uniqueField2)) { $this->error($this->messageDuplicate, $duplicate[$this->uniqueField]); return false; } } return true; }
} elseif ($sortField === 'lastclock') { $sortFields = array(array('field' => 'lastclock', 'order' => $sortOrder), 'name_expanded', 'itemid'); } else { $sortFields = array('name_expanded', 'itemid'); } CArrayHelper::sort($items, $sortFields); if ($applications) { foreach ($applications as &$application) { $application['hostname'] = $hosts[$application['hostid']]['name']; $application['item_cnt'] = 0; } unset($application); // by default order by application name and application id $sortFields = $sortField === 'host' ? array(array('field' => 'hostname', 'order' => $sortOrder)) : array(); array_push($sortFields, 'name', 'applicationid'); CArrayHelper::sort($applications, $sortFields); } if (!$singleHostSelected) { // get host scripts $hostScripts = API::Script()->getScriptsByHosts($hostIds); // get templates screen count $screens = API::TemplateScreen()->get(array('hostids' => $hostIds, 'countOutput' => true, 'groupCount' => true)); $screens = zbx_toHash($screens, 'hostid'); foreach ($hosts as &$host) { $host['screens'] = isset($screens[$host['hostid']]); } unset($host); } } } if ($filter['showDetails']) {
/** * Get parent maps for current map. * * @param int $mapId * * @return array */ function getParentMaps($mapId) { $parentMaps = DBfetchArrayAssoc(DBselect('SELECT s.sysmapid,s.name' . ' FROM sysmaps s' . ' JOIN sysmaps_elements se ON se.sysmapid=s.sysmapid' . ' WHERE se.elementtype=' . SYSMAP_ELEMENT_TYPE_MAP . ' AND se.elementid=' . zbx_dbstr($mapId)), 'sysmapid'); CArrayHelper::sort($parentMaps, array('name')); return $parentMaps; }
$userid = CWebUser::$data['userid']; $userGroups = getUserGroupsByUserId($userid); $sql .= ' AND EXISTS (' . 'SELECT NULL' . ' FROM functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE t.triggerid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY f.triggerid' . ' HAVING MIN(r.permission)>' . PERM_DENY . ')'; } $sql .= ' AND ' . dbConditionInt('t.flags', array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED)) . ' GROUP BY e.objectid' . ' ORDER BY cnt_event desc'; $result = DBselect($sql, 100); while ($row = DBfetch($result)) { $triggersEventCount[$row['objectid']] = $row['cnt_event']; } $triggers = API::Trigger()->get(array('triggerids' => array_keys($triggersEventCount), 'output' => array('triggerid', 'description', 'expression', 'priority', 'flags', 'url', 'lastchange'), 'selectHosts' => array('hostid', 'status', 'name'), 'selectItems' => array('itemid', 'hostid', 'name', 'key_', 'value_type'), 'expandDescription' => true, 'preservekeys' => true, 'nopermissions' => true)); $hostIds = array(); foreach ($triggers as $triggerId => $trigger) { $hostIds[$trigger['hosts'][0]['hostid']] = $trigger['hosts'][0]['hostid']; $triggers[$triggerId]['cnt_event'] = $triggersEventCount[$triggerId]; } CArrayHelper::sort($triggers, array(array('field' => 'cnt_event', 'order' => ZBX_SORT_DOWN), 'host', 'description', 'priority')); $hosts = API::Host()->get(array('output' => array('hostid', 'status'), 'hostids' => $hostIds, 'selectGraphs' => API_OUTPUT_COUNT, 'selectScreens' => API_OUTPUT_COUNT, 'preservekeys' => true)); $scripts = API::Script()->getScriptsByHosts($hostIds); $monitoredHostIds = array(); foreach ($triggers as $trigger) { foreach ($trigger['hosts'] as $host) { if ($host['status'] == HOST_STATUS_MONITORED) { $monitoredHostIds[$host['hostid']] = true; } } } if ($monitoredHostIds) { $monitoredHosts = API::Host()->get(array('output' => array('hostid'), 'selectGroups' => array('groupid'), 'hostids' => array_keys($monitoredHostIds), 'preservekeys' => true)); } foreach ($triggers as $trigger) { foreach ($trigger['hosts'] as $host) {
/** * Validates the input parameters for the create() method. * * @param array $hosts hosts data array * * @throws APIException if the input is invalid. */ protected function validateCreate(array $hosts) { $host_db_fields = ['host' => null]; $groupids = []; foreach ($hosts as &$host) { // Validate mandatory fields. if (!check_db_fields($host_db_fields, $host)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Wrong fields for host "%1$s".', array_key_exists('host', $host) ? $host['host'] : '')); } // Validate "host" field. if (!preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/', $host['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for host name "%s".', $host['host'])); } // If visible name is not given or empty it should be set to host name. Required for duplicate checks. if (!array_key_exists('name', $host) || !trim($host['name'])) { $host['name'] = $host['host']; } // Validate "groups" field. if (!array_key_exists('groups', $host) || !is_array($host['groups']) || !$host['groups']) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('No groups for host "%1$s".', $host['host'])); } $groupids = array_merge($groupids, zbx_objectValues($host['groups'], 'groupid')); } unset($host); // Check for duplicate "host" and "name" fields. $duplicate = CArrayHelper::findDuplicate($hosts, 'host'); if ($duplicate) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate host. Host with the same host name "%s" already exists in data.', $duplicate['host'])); } $duplicate = CArrayHelper::findDuplicate($hosts, 'name'); if ($duplicate) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate host. Host with the same visible name "%s" already exists in data.', $duplicate['name'])); } // Validate permissions to host groups. if ($groupids) { $db_groups = API::HostGroup()->get(['output' => ['groupid'], 'groupids' => $groupids, 'editable' => true, 'preservekeys' => true]); } foreach ($hosts as $host) { foreach ($host['groups'] as $group) { if (!array_key_exists($group['groupid'], $db_groups)) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } } $inventory_fields = zbx_objectValues(getHostInventories(), 'db_field'); $status_validator = new CLimitedSetValidator(['values' => [HOST_STATUS_MONITORED, HOST_STATUS_NOT_MONITORED], 'messageInvalid' => _('Incorrect status for host "%1$s".')]); $host_names = []; foreach ($hosts as $host) { if (!array_key_exists('interfaces', $host) || !is_array($host['interfaces']) || !$host['interfaces']) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('No interfaces for host "%s".', $host['host'])); } if (array_key_exists('status', $host)) { $status_validator->setObjectName($host['host']); $this->checkValidator($host['status'], $status_validator); } if (array_key_exists('inventory', $host) && $host['inventory']) { if (array_key_exists('inventory_mode', $host) && $host['inventory_mode'] == HOST_INVENTORY_DISABLED) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set inventory fields for disabled inventory.')); } $fields = array_keys($host['inventory']); foreach ($fields as $field) { if (!in_array($field, $inventory_fields)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect inventory field "%s".', $field)); } } } // Collect technical and visible names to check if they exist in hosts and templates. $host_names['host'][$host['host']] = true; $host_names['name'][$host['name']] = true; } $filter = ['host' => array_keys($host_names['host']), 'name' => array_keys($host_names['name'])]; $hosts_exists = $this->get(['output' => ['host', 'name'], 'filter' => $filter, 'searchByAny' => true, 'nopermissions' => true]); foreach ($hosts_exists as $host_exists) { if (array_key_exists($host_exists['host'], $host_names['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same name "%s" already exists.', $host_exists['host'])); } if (array_key_exists($host_exists['name'], $host_names['name'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same visible name "%s" already exists.', $host_exists['name'])); } } $templates_exists = API::Template()->get(['output' => ['host', 'name'], 'filter' => $filter, 'searchByAny' => true, 'nopermissions' => true]); foreach ($templates_exists as $template_exists) { if (array_key_exists($template_exists['host'], $host_names['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same name "%s" already exists.', $template_exists['host'])); } if (array_key_exists($template_exists['name'], $host_names['name'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same visible name "%s" already exists.', $template_exists['name'])); } } $this->validateEncryption($hosts); }
function getUserFormData($userid, $isProfile = false) { $config = select_config(); $data = array('is_profile' => $isProfile); if (isset($userid)) { $users = API::User()->get(array('userids' => $userid, 'output' => API_OUTPUT_EXTEND)); $user = reset($users); } if (isset($userid) && (!isset($_REQUEST['form_refresh']) || isset($_REQUEST['register']))) { $data['alias'] = $user['alias']; $data['name'] = $user['name']; $data['surname'] = $user['surname']; $data['password1'] = null; $data['password2'] = null; $data['url'] = $user['url']; $data['autologin'] = $user['autologin']; $data['autologout'] = $user['autologout']; $data['lang'] = $user['lang']; $data['theme'] = $user['theme']; $data['refresh'] = $user['refresh']; $data['rows_per_page'] = $user['rows_per_page']; $data['user_type'] = $user['type']; $data['messages'] = getMessageSettings(); $userGroups = API::UserGroup()->get(array('userids' => $userid, 'output' => array('usrgrpid'))); $userGroup = zbx_objectValues($userGroups, 'usrgrpid'); $data['user_groups'] = zbx_toHash($userGroup); $data['user_medias'] = array(); $dbMedia = DBselect('SELECT m.mediaid,m.mediatypeid,m.period,m.sendto,m.severity,m.active' . ' FROM media m' . ' WHERE m.userid=' . zbx_dbstr($userid)); while ($dbMedium = DBfetch($dbMedia)) { $data['user_medias'][] = $dbMedium; } if ($data['autologout'] > 0) { $_REQUEST['autologout'] = $data['autologout']; } } else { $data['alias'] = getRequest('alias', ''); $data['name'] = getRequest('name', ''); $data['surname'] = getRequest('surname', ''); $data['password1'] = getRequest('password1', ''); $data['password2'] = getRequest('password2', ''); $data['url'] = getRequest('url', ''); $data['autologin'] = getRequest('autologin', 0); $data['autologout'] = getRequest('autologout', 900); $data['lang'] = getRequest('lang', 'en_gb'); $data['theme'] = getRequest('theme', THEME_DEFAULT); $data['refresh'] = getRequest('refresh', 30); $data['rows_per_page'] = getRequest('rows_per_page', 50); $data['user_type'] = getRequest('user_type', USER_TYPE_ZABBIX_USER); $data['user_groups'] = getRequest('user_groups', array()); $data['change_password'] = getRequest('change_password'); $data['user_medias'] = getRequest('user_medias', array()); // set messages $data['messages'] = getRequest('messages', array()); if (!isset($data['messages']['enabled'])) { $data['messages']['enabled'] = 0; } if (!isset($data['messages']['sounds.recovery'])) { $data['messages']['sounds.recovery'] = 'alarm_ok.wav'; } if (!isset($data['messages']['triggers.recovery'])) { $data['messages']['triggers.recovery'] = 0; } if (!isset($data['messages']['triggers.severities'])) { $data['messages']['triggers.severities'] = array(); } $data['messages'] = array_merge(getMessageSettings(), $data['messages']); } // authentication type if ($data['user_groups']) { $data['auth_type'] = getGroupAuthenticationType($data['user_groups'], GROUP_GUI_ACCESS_INTERNAL); } else { $data['auth_type'] = $userid === null ? $config['authentication_type'] : getUserAuthenticationType($userid, GROUP_GUI_ACCESS_INTERNAL); } // set autologout if ($data['autologin'] || !isset($data['autologout'])) { $data['autologout'] = 0; } // set media types if (!empty($data['user_medias'])) { $mediaTypeDescriptions = array(); $dbMediaTypes = DBselect('SELECT mt.mediatypeid,mt.description FROM media_type mt WHERE ' . dbConditionInt('mt.mediatypeid', zbx_objectValues($data['user_medias'], 'mediatypeid'))); while ($dbMediaType = DBfetch($dbMediaTypes)) { $mediaTypeDescriptions[$dbMediaType['mediatypeid']] = $dbMediaType['description']; } foreach ($data['user_medias'] as &$media) { $media['description'] = $mediaTypeDescriptions[$media['mediatypeid']]; } unset($media); CArrayHelper::sort($data['user_medias'], array('description', 'sendto')); } // set user rights if (!$data['is_profile']) { $data['groups'] = API::UserGroup()->get(array('usrgrpids' => $data['user_groups'], 'output' => array('usrgrpid', 'name'))); order_result($data['groups'], 'name'); $group_ids = array_values($data['user_groups']); if (count($group_ids) == 0) { $group_ids = array(-1); } $db_rights = DBselect('SELECT r.* FROM rights r WHERE ' . dbConditionInt('r.groupid', $group_ids)); // deny beat all, read-write beat read $tmp_permitions = array(); while ($db_right = DBfetch($db_rights)) { if (isset($tmp_permitions[$db_right['id']]) && $tmp_permitions[$db_right['id']] != PERM_DENY) { $tmp_permitions[$db_right['id']] = $db_right['permission'] == PERM_DENY ? PERM_DENY : max($tmp_permitions[$db_right['id']], $db_right['permission']); } else { $tmp_permitions[$db_right['id']] = $db_right['permission']; } } $data['user_rights'] = array(); foreach ($tmp_permitions as $id => $permition) { array_push($data['user_rights'], array('id' => $id, 'permission' => $permition)); } } return $data; }
* Display */ $data = array('form' => get_request('form'), 'displayNodes' => is_array(get_current_nodeid()) && $pageFilter->groupid == 0); if (!empty($data['form'])) { $data['maintenanceid'] = get_request('maintenanceid'); $data['form_refresh'] = get_request('form_refresh', 0); if (isset($data['maintenanceid']) && !isset($_REQUEST['form_refresh'])) { $dbMaintenance = reset($dbMaintenance); $data['mname'] = $dbMaintenance['name']; $data['maintenance_type'] = $dbMaintenance['maintenance_type']; $data['active_since'] = $dbMaintenance['active_since']; $data['active_till'] = $dbMaintenance['active_till']; $data['description'] = $dbMaintenance['description']; // time periods $data['timeperiods'] = $dbMaintenance['timeperiods']; CArrayHelper::sort($data['timeperiods'], array('timeperiod_type', 'start_date')); // get hosts $data['hostids'] = API::Host()->get(array('maintenanceids' => $data['maintenanceid'], 'real_hosts' => true, 'output' => array('hostid'), 'editable' => true)); $data['hostids'] = zbx_objectValues($data['hostids'], 'hostid'); // get groupids $data['groupids'] = API::HostGroup()->get(array('maintenanceids' => $data['maintenanceid'], 'real_hosts' => true, 'output' => array('groupid'), 'editable' => true)); $data['groupids'] = zbx_objectValues($data['groupids'], 'groupid'); } else { $data['mname'] = get_request('mname', ''); $data['maintenance_type'] = get_request('maintenance_type', 0); if (isset($_REQUEST['active_since'])) { $data['active_since'] = mktime($_REQUEST['active_since_hour'], $_REQUEST['active_since_minute'], 0, $_REQUEST['active_since_month'], $_REQUEST['active_since_day'], $_REQUEST['active_since_year']); } else { $data['active_since'] = strtotime('today'); } if (isset($_REQUEST['active_till'])) {
/** * Prepare data for trigger menu popup. * * @param array $trigger trigger data * @param string $trigger['triggerid'] trigger id * @param int $trigger['flags'] trigger flags (TRIGGER_FLAG_DISCOVERY*) * @param array $trigger['hosts'] hosts, used by trigger expression * @param string $trigger['hosts'][]['hostid'] host id * @param string $trigger['url'] url * @param array $items trigger items (optional) * @param string $items[]['name'] item name * @param array $items[]['params'] item url parameters ("name" => "value") * @param array $acknowledge acknowledge link parameters (optional) * @param string $acknowledge['eventid'] event id * @param string $acknowledge['screenid'] screen id (optional) * @param string $acknowledge['backurl'] return url (optional) * @param string $eventTime event navigation time parameter (optional) * * @return array */ function getMenuPopupTrigger(array $trigger, array $items = null, array $acknowledge = null, $eventTime = null) { if ($items) { CArrayHelper::sort($items, array('name')); } $data = array('type' => 'trigger', 'triggerid' => $trigger['triggerid'], 'items' => $items, 'acknowledge' => $acknowledge, 'eventTime' => $eventTime, 'configuration' => null, 'url' => resolveTriggerUrl($trigger)); if ((CWebUser::$data['type'] == USER_TYPE_ZABBIX_ADMIN || CWebUser::$data['type'] == USER_TYPE_SUPER_ADMIN) && $trigger['flags'] == ZBX_FLAG_DISCOVERY_NORMAL) { $host = reset($trigger['hosts']); $data['configuration'] = array('hostid' => $host['hostid'], 'switchNode' => id2nodeid($trigger['triggerid'])); } return $data; }
function make_small_eventlist($startEvent) { $config = select_config(); $table = new CTableInfo(_('No events found.')); $table->setHeader(array(_('Time'), _('Status'), _('Duration'), _('Age'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions'))); $clock = $startEvent['clock']; $events = API::Event()->get(array('source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER, 'objectids' => $startEvent['objectid'], 'eventid_till' => $startEvent['eventid'], 'output' => API_OUTPUT_EXTEND, 'select_acknowledges' => API_OUTPUT_COUNT, 'sortfield' => array('clock', 'eventid'), 'sortorder' => ZBX_SORT_DOWN, 'limit' => 20)); $sortFields = array(array('field' => 'clock', 'order' => ZBX_SORT_DOWN), array('field' => 'eventid', 'order' => ZBX_SORT_DOWN)); CArrayHelper::sort($events, $sortFields); $actions = getEventActionsStatHints(zbx_objectValues($events, 'eventid')); foreach ($events as $event) { $lclock = $clock; $duration = zbx_date2age($lclock, $event['clock']); $clock = $event['clock']; if (bccomp($startEvent['eventid'], $event['eventid']) == 0 && ($nextevent = get_next_event($event, $events))) { $duration = zbx_date2age($nextevent['clock'], $clock); } elseif (bccomp($startEvent['eventid'], $event['eventid']) == 0) { $duration = zbx_date2age($clock); } $eventStatusSpan = new CSpan(trigger_value2str($event['value'])); // add colors and blinking to span depending on configuration and trigger parameters addTriggerValueStyle($eventStatusSpan, $event['value'], $event['clock'], $event['acknowledged']); $ack = getEventAckState($event, true); $table->addRow(array(new CLink(zbx_date2str(_('d M Y H:i:s'), $event['clock']), 'tr_events.php?triggerid=' . $event['objectid'] . '&eventid=' . $event['eventid'], 'action'), $eventStatusSpan, $duration, zbx_date2age($event['clock']), $config['event_ack_enable'] ? $ack : null, isset($actions[$event['eventid']]) ? $actions[$event['eventid']] : SPACE)); } return $table; }
/** * Retrieve overview table object for items. * * @param array $hostIds * @param string $application name of application to filter * @param int $viewMode * * @return CTableInfo */ function getItemsDataOverview($hostIds, $application, $viewMode) { $sqlFrom = ''; $sqlWhere = ''; if ($application !== '') { $sqlFrom = 'applications a,items_applications ia,'; $sqlWhere = ' AND i.itemid=ia.itemid AND a.applicationid=ia.applicationid AND a.name=' . zbx_dbstr($application); } $dbItems = DBfetchArray(DBselect('SELECT DISTINCT h.hostid,h.name AS hostname,i.itemid,i.key_,i.value_type,i.units,' . 'i.name,t.priority,i.valuemapid,t.value AS tr_value,t.triggerid' . ' FROM hosts h,' . $sqlFrom . 'items i' . ' LEFT JOIN functions f ON f.itemid=i.itemid' . ' LEFT JOIN triggers t ON t.triggerid=f.triggerid AND t.status=' . TRIGGER_STATUS_ENABLED . ' WHERE ' . dbConditionInt('h.hostid', $hostIds) . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND h.hostid=i.hostid' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND ' . dbConditionInt('i.flags', array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED)) . $sqlWhere)); $dbItems = CMacrosResolverHelper::resolveItemNames($dbItems); CArrayHelper::sort($dbItems, array(array('field' => 'name_expanded', 'order' => ZBX_SORT_UP), array('field' => 'itemid', 'order' => ZBX_SORT_UP))); // fetch latest values $history = Manager::History()->getLast(zbx_toHash($dbItems, 'itemid'), 1, ZBX_HISTORY_PERIOD); // fetch data for the host JS menu $hosts = API::Host()->get(array('output' => array('name', 'hostid', 'status'), 'monitored_hosts' => true, 'hostids' => $hostIds, 'with_monitored_items' => true, 'preservekeys' => true, 'selectScreens' => $viewMode == STYLE_LEFT ? API_OUTPUT_COUNT : null)); $items = array(); foreach ($dbItems as $dbItem) { $name = $dbItem['name_expanded']; $dbItem['hostname'] = get_node_name_by_elid($dbItem['hostid'], null, NAME_DELIMITER) . $dbItem['hostname']; $hostNames[$dbItem['hostid']] = $dbItem['hostname']; // a little tricky check for attempt to overwrite active trigger (value=1) with // inactive or active trigger with lower priority. if (!isset($items[$name][$dbItem['hostname']]) || ($items[$name][$dbItem['hostname']]['tr_value'] == TRIGGER_VALUE_FALSE && $dbItem['tr_value'] == TRIGGER_VALUE_TRUE || ($items[$name][$dbItem['hostname']]['tr_value'] == TRIGGER_VALUE_FALSE || $dbItem['tr_value'] == TRIGGER_VALUE_TRUE) && $dbItem['priority'] > $items[$name][$dbItem['hostname']]['severity'])) { $items[$name][$dbItem['hostname']] = array('itemid' => $dbItem['itemid'], 'value_type' => $dbItem['value_type'], 'value' => isset($history[$dbItem['itemid']]) ? $history[$dbItem['itemid']][0]['value'] : null, 'units' => $dbItem['units'], 'name' => $name, 'valuemapid' => $dbItem['valuemapid'], 'severity' => $dbItem['priority'], 'tr_value' => $dbItem['tr_value'], 'triggerid' => $dbItem['triggerid']); } } $table = new CTableInfo(_('No items found.')); if (empty($hostNames)) { return $table; } $table->makeVerticalRotation(); order_result($hostNames); if ($viewMode == STYLE_TOP) { $header = array(new CCol(_('Items'), 'center')); foreach ($hostNames as $hostName) { $header[] = new CCol($hostName, 'vertical_rotation'); } $table->setHeader($header, 'vertical_header'); foreach ($items as $descr => $ithosts) { $tableRow = array(nbsp($descr)); foreach ($hostNames as $hostName) { $tableRow = getItemDataOverviewCells($tableRow, $ithosts, $hostName); } $table->addRow($tableRow); } } else { $scripts = API::Script()->getScriptsByHosts(zbx_objectValues($hosts, 'hostid')); $header = array(new CCol(_('Hosts'), 'center')); foreach ($items as $descr => $ithosts) { $header[] = new CCol($descr, 'vertical_rotation'); } $table->setHeader($header, 'vertical_header'); foreach ($hostNames as $hostId => $hostName) { $host = $hosts[$hostId]; $name = new CSpan($host['name'], 'link_menu'); $name->setMenuPopup(getMenuPopupHost($host, $scripts[$hostId])); $tableRow = array(new CCol($name)); foreach ($items as $ithosts) { $tableRow = getItemDataOverviewCells($tableRow, $ithosts, $hostName); } $table->addRow($tableRow); } } return $table; }
if ($_REQUEST['hostid'] > 0 || !$config['dropdown_first_entry']) { $hosts = API::Host()->get(array('templateids' => $_REQUEST['hostid'])); $options['hostids'] = zbx_objectValues($hosts, 'hostid'); } if (isset($_REQUEST['tpl_triggerid']) && $_REQUEST['tpl_triggerid'] > 0) { $options['filter']['templateid'] = $_REQUEST['tpl_triggerid']; } if (isset($_REQUEST['hostgroupid']) && $_REQUEST['hostgroupid'] > 0) { $options['groupids'] = $_REQUEST['hostgroupid']; } } // filter $filter = get_report2_filter($availabilityReportMode, $PAGE_GROUPS, $PAGE_HOSTS, $options); $rep2_wdgt->addFlicker($filter['form'], CProfile::get('web.avail_report.filter.state', 0)); $triggers = API::Trigger()->get($filter['options']); CArrayHelper::sort($triggers, array('host', 'description')); $table = new CTableInfo(_('No triggers defined.')); $table->setHeader(array(is_show_all_nodes() ? _('Node') : null, $_REQUEST['hostid'] == 0 || $availabilityReportMode == AVAILABILITY_REPORT_BY_TEMPLATE ? _('Host') : null, _('Name'), _('Problems'), _('Ok'), _('Unknown'), _('Graph'))); foreach ($triggers as $trigger) { $availability = calculate_availability($trigger['triggerid'], $_REQUEST['filter_timesince'], $_REQUEST['filter_timetill']); $true = new CSpan(sprintf('%.4f%%', $availability['true']), 'on'); $false = new CSpan(sprintf('%.4f%%', $availability['false']), 'off'); $unknown = new CSpan(sprintf('%.4f%%', $availability['unknown']), 'unknown'); $actions = new CLink(_('Show'), 'report2.php?filter_groupid=' . $_REQUEST['groupid'] . '&filter_hostid=' . $_REQUEST['hostid'] . '&triggerid=' . $trigger['triggerid']); $table->addRow(array(get_node_name_by_elid($trigger['hostid']), $_REQUEST['hostid'] == 0 || $availabilityReportMode == AVAILABILITY_REPORT_BY_TEMPLATE ? $trigger['hosts'][0]['name'] : null, new CLink($trigger['description'], 'events.php?triggerid=' . $trigger['triggerid']), $true, $false, $unknown, $actions)); } $rep2_wdgt->addItem(BR()); $rep2_wdgt->addItem($table); $rep2_wdgt->show(); } }
} else { $data['parentid'] = 0; $data['parentname'] = 'root'; } // get children $data['children'] = array(); if ($service['dependencies']) { $childServices = API::Service()->get(array('serviceids' => zbx_objectValues($service['dependencies'], 'servicedownid'), 'selectTrigger' => array('triggerid', 'description', 'expression'), 'output' => array('name', 'triggerid'), 'preservekeys' => true)); // expand trigger descriptions $triggers = zbx_objectValues($childServices, 'trigger'); $triggers = CMacrosResolverHelper::resolveTriggerNames($triggers); foreach ($service['dependencies'] as $dependency) { $childService = $childServices[$dependency['servicedownid']]; $data['children'][] = array('name' => $childService['name'], 'triggerid' => $childService['triggerid'], 'trigger' => !empty($childService['triggerid']) ? $triggers[$childService['trigger']['triggerid']]['description'] : '-', 'serviceid' => $dependency['servicedownid'], 'soft' => $dependency['soft']); } CArrayHelper::sort($data['children'], array('name', 'serviceid')); } } else { $data['name'] = getRequest('name', ''); $data['algorithm'] = getRequest('algorithm', SERVICE_ALGORITHM_MAX); $data['showsla'] = getRequest('showsla', 0); $data['goodsla'] = getRequest('goodsla', SERVICE_SLA); $data['sortorder'] = getRequest('sortorder', 0); $data['triggerid'] = getRequest('triggerid', 0); $data['parentid'] = getRequest('parentid', 0); $data['parentname'] = getRequest('parentname', ''); $data['children'] = getRequest('children', array()); } // get trigger if ($data['triggerid'] > 0) { $trigger = API::Trigger()->get(array('triggerids' => $data['triggerid'], 'output' => array('description'), 'selectHosts' => array('name'), 'expandDescription' => true));
array_unshift($header, new CCol(_('From'), 'center'), new CCol(_('Till'), 'center')); $max = $year == $currentYear ? date('W') - 1 : 52; for ($i = 0; $i <= $max; $i++) { $intervals[strtotime('+' . $i . ' week', $minTime)] = strtotime('+' . ($i + 1) . ' week', $minTime); } break; } // time till $maxTime = $year == $currentYear ? time() : mktime(0, 0, 0, 1, 1, $year + 1); // fetch alerts $alerts = array(); foreach (eventSourceObjects() as $sourceObject) { $alerts = array_merge($alerts, API::Alert()->get(array('output' => array('mediatypeid', 'userid', 'clock'), 'eventsource' => $sourceObject['source'], 'eventobject' => $sourceObject['object'], 'mediatypeids' => get_request('media_type') ? get_request('media_type') : null, 'time_from' => $minTime, 'time_till' => $maxTime))); } // sort alerts in chronological order so we could easily iterate through them later CArrayHelper::sort($alerts, array('clock')); $table->setHeader($header, 'vertical_header'); foreach ($intervals as $from => $till) { // interval start $row = array(zbx_date2str($dateFormat, $from)); // interval end, displayed only for week intervals if ($period == 'weekly') { $row[] = zbx_date2str($dateFormat, min($till, time())); } // counting alert count for each user and media type $summary = array(); foreach ($users as $userid => $alias) { $summary[$userid] = array(); $summary[$userid]['total'] = 0; $summary[$userid]['medias'] = array(); foreach ($media_types as $media_type_nr => $mt) {
if ($templateId) { $dbTemplates = API::Template()->get(array('templateids' => $templateId, 'selectGroups' => API_OUTPUT_EXTEND, 'selectParentTemplates' => array('templateid', 'name'), 'selectMacros' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND)); $data['dbTemplate'] = reset($dbTemplates); $data['original_templates'] = array(); foreach ($data['dbTemplate']['parentTemplates'] as $parentTemplate) { $data['original_templates'][$parentTemplate['templateid']] = $parentTemplate['templateid']; } } else { $data['original_templates'] = array(); } // description $data['description'] = $templateId && !hasRequest('form_refresh') ? $data['dbTemplate']['description'] : getRequest('description'); $templateIds = getRequest('templates', hasRequest('form_refresh') ? array() : $data['original_templates']); // linked templates $data['linkedTemplates'] = API::Template()->get(array('templateids' => $templateIds, 'output' => array('templateid', 'name'))); CArrayHelper::sort($data['linkedTemplates'], array('name')); $templateForm = new CView('configuration.template.edit', $data); $templateWidget->addItem($templateForm->render()); } else { $sortField = getRequest('sort', CProfile::get('web.' . $page['file'] . '.sort', 'name')); $sortOrder = getRequest('sortorder', CProfile::get('web.' . $page['file'] . '.sortorder', ZBX_SORT_UP)); CProfile::update('web.' . $page['file'] . '.sort', $sortField, PROFILE_TYPE_STR); CProfile::update('web.' . $page['file'] . '.sortorder', $sortOrder, PROFILE_TYPE_STR); $frmForm = new CForm(); $frmForm->cleanItems(); $frmForm->addItem(new CDiv(array(new CSubmit('form', _('Create template')), new CButton('form', _('Import'), 'redirect("conf.import.php?rules_preset=template")')))); $frmForm->addItem(new CVar('groupid', $_REQUEST['groupid'], 'filter_groupid_id')); $templateWidget->addPageHeader(_('CONFIGURATION OF TEMPLATES'), $frmForm); $frmGroup = new CForm('get'); $frmGroup->addItem(array(_('Group') . SPACE, $pageFilter->getGroupsCB())); $templateWidget->addHeader(_('Templates'), $frmGroup);
/** * Generate table for dashboard triggers popup. * * @see make_system_status * * @param array $triggers * @param string $backurl * @param array $actions * @param array $config * * @return CTableInfo */ function makeTriggersPopup(array $triggers, $backurl, array $actions, array $config) { $popupTable = (new CTableInfo())->setHeader([_('Host'), _('Issue'), _('Age'), _('Info'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions')]); CArrayHelper::sort($triggers, [['field' => 'lastchange', 'order' => ZBX_SORT_DOWN]]); foreach ($triggers as $trigger) { $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['event']['clock'], 'ns' => $trigger['event']['ns']))); // unknown triggers $unknown = ''; if ($trigger['state'] == TRIGGER_STATE_UNKNOWN) { $unknown = makeUnknownIcon($trigger['error']); } // ack if ($config['event_ack_enable']) { $ack = isset($trigger['event']['eventid']) ? getEventAckState($trigger['event'], $backurl) : (new CSpan(_('No events')))->addClass(ZBX_STYLE_GREY); } else { $ack = null; } // action $action = isset($trigger['event']['eventid']) && isset($actions[$trigger['event']['eventid']]) ? $actions[$trigger['event']['eventid']] : ''; $popupTable->addRow([$trigger['hosts'][0]['name'], getSeverityCell($trigger['priority'], $config, $description), zbx_date2age($trigger['lastchange']), $unknown, $ack, (new CCol($action))->addClass(ZBX_STYLE_NOWRAP)]); } return $popupTable; }
} else { $data['action']['def_shortdata'] = get_request('def_shortdata'); $data['action']['def_longdata'] = get_request('def_longdata'); $data['action']['r_shortdata'] = get_request('r_shortdata'); $data['action']['r_longdata'] = get_request('r_longdata'); } } } if (!$data['actionid'] && !hasRequest('form_refresh') && $data['eventsource'] == EVENT_SOURCE_TRIGGERS) { $data['action']['conditions'] = array(array('conditiontype' => CONDITION_TYPE_TRIGGER_VALUE, 'operator' => CONDITION_OPERATOR_EQUAL, 'value' => TRIGGER_VALUE_TRUE), array('conditiontype' => CONDITION_TYPE_MAINTENANCE, 'operator' => CONDITION_OPERATOR_NOT_IN, 'value' => '')); } $data['allowedConditions'] = get_conditions_by_eventsource($data['eventsource']); $data['allowedOperations'] = get_operations_by_eventsource($data['eventsource']); // 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($data['action']['conditions'], $sortFields); // new condition $data['new_condition'] = array('conditiontype' => isset($data['new_condition']['conditiontype']) ? $data['new_condition']['conditiontype'] : CONDITION_TYPE_TRIGGER_NAME, 'operator' => isset($data['new_condition']['operator']) ? $data['new_condition']['operator'] : CONDITION_OPERATOR_LIKE, 'value' => isset($data['new_condition']['value']) ? $data['new_condition']['value'] : ''); if (!str_in_array($data['new_condition']['conditiontype'], $data['allowedConditions'])) { $data['new_condition']['conditiontype'] = $data['allowedConditions'][0]; } // new operation if (!empty($data['new_operation'])) { if (!is_array($data['new_operation'])) { $data['new_operation'] = array('action' => 'create', 'operationtype' => 0, 'esc_period' => 0, 'esc_step_from' => 1, 'esc_step_to' => 1, 'evaltype' => 0); } } // render view $actionView = new CView('configuration.action.edit', $data); $actionView->render(); $actionView->show();
} order_result($prototypeList); $listBox = new CListBox('hostPrototypes', null, 8); $listBox->setAttribute('disabled', 'disabled'); $listBox->addItems($prototypeList); $hostList->addRow(_('Host prototypes'), $listBox); } } $divTabs->addTab('hostTab', _('Host'), $hostList); // templates $tmplList = new CFormList('tmpllist'); // create linked template table $linkedTemplateTable = new CTable(_('No templates linked.'), 'formElementTable'); $linkedTemplateTable->attr('id', 'linkedTemplateTable'); $linkedTemplates = API::Template()->get(array('templateids' => $templateIds, 'output' => array('templateid', 'name'))); CArrayHelper::sort($linkedTemplates, array('name')); // templates for normal hosts if (!$isDiscovered) { $linkedTemplateTable->setHeader(array(_('Name'), _('Action'))); $ignoredTemplates = array(); foreach ($linkedTemplates as $template) { $tmplList->addVar('templates[]', $template['templateid']); $linkedTemplateTable->addRow(array($template['name'], array(new CSubmit('unlink[' . $template['templateid'] . ']', _('Unlink'), null, 'link_menu'), SPACE, SPACE, isset($original_templates[$template['templateid']]) ? new CSubmit('unlink_and_clear[' . $template['templateid'] . ']', _('Unlink and clear'), null, 'link_menu') : SPACE)), null, 'conditions_' . $template['templateid']); $ignoredTemplates[$template['templateid']] = $template['name']; } $tmplList->addRow(_('Linked templates'), new CDiv($linkedTemplateTable, 'objectgroup inlineblock border_dotted ui-corner-all')); // create new linked template table $newTemplateTable = new CTable(null, 'formElementTable'); $newTemplateTable->attr('id', 'newTemplateTable'); $newTemplateTable->attr('style', 'min-width: 400px;'); $newTemplateTable->addRow(array(new CMultiSelect(array('name' => 'add_templates[]', 'objectName' => 'templates', 'ignored' => $ignoredTemplates))));
$items = API::Item()->get(array('output' => array('itemid', 'name'), 'selectHosts' => array('name'), 'itemids' => $itemIds, 'webitems' => true, 'preservekeys' => true)); foreach ($itemIds as $itemId) { if (!isset($items[$itemId])) { access_deny(); } } $hostNames = array(); foreach ($items as &$item) { $item['hostname'] = $item['hosts'][0]['name']; if (!in_array($item['hostname'], $hostNames)) { $hostNames[] = $item['hostname']; } } unset($item); // sort items CArrayHelper::sort($items, array('name', 'hostname', 'itemid')); /* * Display */ $timeline = CScreenBase::calculateTime(array('profileIdx' => getRequest('profileIdx', 'web.screens'), 'profileIdx2' => getRequest('profileIdx2'), 'updateProfile' => getRequest('updateProfile', true), 'period' => getRequest('period'), 'stime' => getRequest('stime'))); $graph = new CLineGraphDraw(getRequest('type')); $graph->setPeriod($timeline['period']); $graph->setSTime($timeline['stime']); // change how the graph will be displayed if more than one item is selected if (getRequest('batch')) { // set a default header if (count($hostNames) == 1) { $graph->setHeader($hostNames[0] . NAME_DELIMITER . _('Item values')); } else { $graph->setHeader(_('Item values')); }
// unset unchanged values $newItem = CArrayHelper::unsetEqualValues($newItem, $item, ['itemid']); // don't update the filter if it hasn't changed $conditionsChanged = false; if (count($newItem['filter']['conditions']) != count($item['filter']['conditions'])) { $conditionsChanged = true; } else { $conditions = $item['filter']['conditions']; foreach ($newItem['filter']['conditions'] as $i => $condition) { if (CArrayHelper::unsetEqualValues($condition, $conditions[$i])) { $conditionsChanged = true; break; } } } $filter = CArrayHelper::unsetEqualValues($newItem['filter'], $item['filter']); if (!isset($filter['evaltype']) && !isset($filter['formula']) && !$conditionsChanged) { unset($newItem['filter']); } $result = API::DiscoveryRule()->update($newItem); $result = DBend($result); } else { $result = API::DiscoveryRule()->create([$newItem]); } } if (hasRequest('add')) { show_messages($result, _('Discovery rule created'), _('Cannot add discovery rule')); } else { show_messages($result, _('Discovery rule updated'), _('Cannot update discovery rule')); } if ($result) {
$graph->setSTime($timeline['stime']); if (isset($_REQUEST['border'])) { $graph->setBorder(0); } $width = getRequest('width', 0); if ($width <= 0) { $width = $dbGraph['width']; } $height = getRequest('height', 0); if ($height <= 0) { $height = $dbGraph['height']; } $graph->setWidth($width); $graph->setHeight($height); // array sorting CArrayHelper::sort($dbGraph['gitems'], array(array('field' => 'sortorder', 'order' => ZBX_SORT_UP), array('field' => 'itemid', 'order' => ZBX_SORT_DOWN))); // get graph items foreach ($dbGraph['gitems'] as $gItem) { $graph->addItem($gItem['itemid'], $gItem['calc_fnc'], $gItem['color'], $gItem['type']); } $hostName = ''; foreach ($dbGraph['hosts'] as $gItemHost) { if ($hostName === '') { $hostName = $gItemHost['name']; } elseif ($hostName !== $gItemHost['name']) { $hostName = ''; break; } } $graph->setHeader($hostName === '' ? $dbGraph['name'] : $hostName . NAME_DELIMITER . $dbGraph['name']); if ($dbGraph['show_3d']) {
** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ $table = (new CTableInfo())->setHeader([_('Host group'), _('Without problems'), _('With problems'), _('Total')]); // get host groups $groups = API::HostGroup()->get(['output' => ['groupid', 'name'], 'groupids' => $data['filter']['groupids'], 'hostids' => isset($data['filter']['hostids']) ? $data['filter']['hostids'] : null, 'monitored_hosts' => true, 'preservekeys' => true]); CArrayHelper::sort($groups, ['name']); // get hosts $hosts = API::Host()->get(['output' => ['hostid', 'name'], 'selectGroups' => ['groupid'], 'groupids' => array_keys($groups), 'hostids' => isset($data['filter']['hostids']) ? $data['filter']['hostids'] : null, 'filter' => ['maintenance_status' => $data['filter']['maintenance']], 'monitored_hosts' => true, 'preservekeys' => true]); CArrayHelper::sort($hosts, ['name']); // get triggers $triggers = API::Trigger()->get(['output' => ['triggerid', 'priority'], 'selectHosts' => ['hostid'], 'search' => $data['filter']['trigger_name'] !== '' ? ['description' => $data['filter']['trigger_name']] : null, 'filter' => ['priority' => $data['filter']['severity'], 'value' => TRIGGER_VALUE_TRUE], 'maintenance' => $data['filter']['maintenance'], 'monitored' => true]); if ($data['filter']['extAck']) { $hosts_with_unack_triggers = []; $triggers_unack = API::Trigger()->get(['output' => ['triggerid'], 'selectHosts' => ['hostid'], 'search' => $data['filter']['trigger_name'] !== '' ? ['description' => $data['filter']['trigger_name']] : null, 'filter' => ['priority' => $data['filter']['severity'], 'value' => TRIGGER_VALUE_TRUE], 'withLastEventUnacknowledged' => true, 'maintenance' => $data['filter']['maintenance'], 'monitored' => true, 'preservekeys' => true]); foreach ($triggers_unack as $tunack) { foreach ($tunack['hosts'] as $unack_host) { $hosts_with_unack_triggers[$unack_host['hostid']] = $unack_host['hostid']; } } } $hosts_data = []; $problematic_host_list = []; $lastUnack_host_list = []; $highest_severity = [];
/** * Prepare data for trigger menu popup. * * @param array $trigger trigger data * @param string $trigger['triggerid'] trigger ID * @param int $trigger['flags'] trigger flags (TRIGGER_FLAG_DISCOVERY*) * @param array $trigger['hosts'] hosts, used by trigger expression * @param string $trigger['hosts'][]['hostid'] host ID * @param string $trigger['hosts'][]['name'] host name * @param string $trigger['hosts'][]['status'] host status * @param array $trigger['items'] trigger items * @param string $trigger['items'][]['itemid'] item ID * @param string $trigger['items'][]['hostid'] host ID * @param string $trigger['items'][]['name'] item name * @param string $trigger['items'][]['key_'] item key * @param string $trigger['items'][]['value_type'] type of information of the item * @param string $trigger['url'] trigger URL * @param array $acknowledge acknowledge link parameters (optional) * @param string $acknowledge['eventid'] event ID * @param string $acknowledge['screenid'] screen ID (optional) * @param string $acknowledge['backurl'] return URL (optional) * @param string $eventTime event navigation time parameter (optional) * * @return array */ public static function getTrigger(array $trigger, array $acknowledge = null, $eventTime = null) { $hosts = array(); $showEvents = true; foreach ($trigger['hosts'] as $host) { $hosts[$host['hostid']] = $host['name']; if ($host['status'] != HOST_STATUS_MONITORED) { $showEvents = false; } } $trigger['items'] = CMacrosResolverHelper::resolveItemNames($trigger['items']); foreach ($trigger['items'] as &$item) { $item['hostname'] = $hosts[$item['hostid']]; } unset($item); CArrayHelper::sort($trigger['items'], array('name', 'hostname', 'itemid')); $hostCount = count($hosts); $items = array(); foreach ($trigger['items'] as $item) { $items[] = array('name' => $hostCount > 1 ? $hosts[$item['hostid']] . NAME_DELIMITER . $item['name_expanded'] : $item['name_expanded'], 'params' => array('itemid' => $item['itemid'], 'action' => in_array($item['value_type'], array(ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64)) ? HISTORY_GRAPH : HISTORY_VALUES)); } $data = array('type' => 'trigger', 'groupid' => $trigger['groupid'], 'hostid' => $trigger['hostid'], 'triggerid' => $trigger['triggerid'], 'items' => $items, 'acknowledge' => $acknowledge, 'eventTime' => $eventTime, 'url' => resolveTriggerUrl($trigger)); if ($showEvents) { $data['showEvents'] = true; } if (in_array(CWebUser::$data['type'], array(USER_TYPE_ZABBIX_ADMIN, USER_TYPE_SUPER_ADMIN)) && $trigger['flags'] == ZBX_FLAG_DISCOVERY_NORMAL) { $data['configuration'] = true; } return $data; }
function get_accessible_groups_by_rights(&$rights, $user_type, $perm) { $result = []; $group_perm = []; foreach ($rights as $right) { $group_perm[$right['id']] = $right['permission']; } $dbHostGroups = DBselect('SELECT g.*,' . PERM_DENY . ' AS permission FROM groups g'); while ($dbHostGroup = DBfetch($dbHostGroups)) { if ($user_type == USER_TYPE_SUPER_ADMIN) { $dbHostGroup['permission'] = PERM_READ_WRITE; } elseif (isset($group_perm[$dbHostGroup['groupid']])) { $dbHostGroup['permission'] = $group_perm[$dbHostGroup['groupid']]; } else { $dbHostGroup['permission'] = PERM_DENY; } if ($dbHostGroup['permission'] < $perm) { continue; } $result[$dbHostGroup['groupid']] = $dbHostGroup; } CArrayHelper::sort($result, [['field' => 'name', 'order' => ZBX_SORT_UP]]); return $result; }
array_unshift($header, _('From'), _('Till')); $max = $year == $currentYear ? date('W') - 1 : 52; for ($i = 0; $i <= $max; $i++) { $intervals[strtotime('+' . $i . ' week', $minTime)] = strtotime('+' . ($i + 1) . ' week', $minTime); } break; } // time till $maxTime = $year == $currentYear ? time() : mktime(0, 0, 0, 1, 1, $year + 1); // fetch alerts $alerts = []; foreach (eventSourceObjects() as $sourceObject) { $alerts = array_merge($alerts, API::Alert()->get(['output' => ['mediatypeid', 'userid', 'clock'], 'eventsource' => $sourceObject['source'], 'eventobject' => $sourceObject['object'], 'mediatypeids' => getRequest('media_type') ? getRequest('media_type') : null, 'time_from' => $minTime, 'time_till' => $maxTime])); } // sort alerts in chronological order so we could easily iterate through them later CArrayHelper::sort($alerts, ['clock']); $table->setHeader($header); foreach ($intervals as $from => $till) { // interval start $row = [zbx_date2str($dateFormat, $from)]; // interval end, displayed only for week intervals if ($period == 'weekly') { $row[] = zbx_date2str($dateFormat, min($till, time())); } // counting alert count for each user and media type $summary = []; foreach ($users as $userid) { $summary[$userid] = []; $summary[$userid]['total'] = 0; $summary[$userid]['medias'] = []; foreach ($media_types as $media_type_nr => $mt) {
/** * Check duplicate step names. * * @throws APIException if duplicate step name is found. * * @param array $httpTest * @param array $dbHttpTest */ protected function checkDuplicateSteps(array $httpTest, array $dbHttpTest = array()) { if ($duplicate = CArrayHelper::findDuplicate($httpTest['steps'], 'name')) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Web scenario step "%1$s" already exists.', $duplicate['name'])); } }
/** * Sort array by multiple fields. * * @static * * @param array $array array to sort passed by reference * @param array $fields fields to sort, can be either string with field name or array with 'field' and 'order' keys */ public static function sort(array &$array, array $fields) { foreach ($fields as $fid => $field) { if (!is_array($field)) { $fields[$fid] = ['field' => $field, 'order' => ZBX_SORT_UP]; } } self::$fields = $fields; uasort($array, ['self', 'compare']); }
$ifm = get_request('filter_macro'); $ifv = get_request('filter_value'); $filter = isset($ifm, $ifv) ? $ifm . ':' . $ifv : ''; $item = array('interfaceid' => get_request('interfaceid'), 'name' => get_request('name'), 'description' => get_request('description'), 'key_' => get_request('key'), 'hostid' => get_request('hostid'), 'delay' => get_request('delay'), 'status' => get_request('status', ITEM_STATUS_DISABLED), 'type' => get_request('type'), 'snmp_community' => get_request('snmp_community'), 'snmp_oid' => get_request('snmp_oid'), 'trapper_hosts' => get_request('trapper_hosts'), 'port' => get_request('port'), 'snmpv3_contextname' => get_request('snmpv3_contextname'), 'snmpv3_securityname' => get_request('snmpv3_securityname'), 'snmpv3_securitylevel' => get_request('snmpv3_securitylevel'), 'snmpv3_authprotocol' => get_request('snmpv3_authprotocol'), 'snmpv3_authpassphrase' => get_request('snmpv3_authpassphrase'), 'snmpv3_privprotocol' => get_request('snmpv3_privprotocol'), 'snmpv3_privpassphrase' => get_request('snmpv3_privpassphrase'), 'delay_flex' => $db_delay_flex, 'authtype' => get_request('authtype'), 'username' => get_request('username'), 'password' => get_request('password'), 'publickey' => get_request('publickey'), 'privatekey' => get_request('privatekey'), 'params' => get_request('params'), 'ipmi_sensor' => get_request('ipmi_sensor'), 'lifetime' => get_request('lifetime'), 'filter' => $filter); if (hasRequest('itemid')) { $itemId = getRequest('itemid'); DBstart(); $dbItem = get_item_by_itemid_limited($itemId); // unset snmpv3 fields if ($item['snmpv3_securitylevel'] == ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV) { $item['snmpv3_authprotocol'] = ITEM_AUTHPROTOCOL_MD5; $item['snmpv3_privprotocol'] = ITEM_PRIVPROTOCOL_DES; } elseif ($item['snmpv3_securitylevel'] == ITEM_SNMPV3_SECURITYLEVEL_AUTHNOPRIV) { $item['snmpv3_privprotocol'] = ITEM_PRIVPROTOCOL_DES; } $item = CArrayHelper::unsetEqualValues($item, $dbItem); $item['itemid'] = $itemId; $result = API::DiscoveryRule()->update($item); $result = DBend($result); show_messages($result, _('Discovery rule updated'), _('Cannot update discovery rule')); } else { $result = API::DiscoveryRule()->create(array($item)); show_messages($result, _('Discovery rule created'), _('Cannot add discovery rule')); } if ($result) { unset($_REQUEST['itemid'], $_REQUEST['form']); clearCookies($result, $_REQUEST['hostid']); } } elseif (str_in_array(getRequest('go'), array('activate', 'disable')) && hasRequest('g_hostdruleid')) { $groupHostDiscoveryRuleId = getRequest('g_hostdruleid'); $enable = getRequest('go') == 'activate';
function sortOperations($eventsource, &$operations) { if ($eventsource == EVENT_SOURCE_TRIGGERS || $eventsource == EVENT_SOURCE_INTERNAL) { $esc_step_from = array(); $esc_step_to = array(); $esc_period = array(); $operationTypes = array(); foreach ($operations as $key => $operation) { $esc_step_from[$key] = $operation['esc_step_from']; $esc_step_to[$key] = $operation['esc_step_to']; $esc_period[$key] = $operation['esc_period']; $operationTypes[$key] = $operation['operationtype']; } array_multisort($esc_step_from, SORT_ASC, $esc_step_to, SORT_ASC, $esc_period, SORT_ASC, $operationTypes, SORT_ASC, $operations); } else { CArrayHelper::sort($operations, array('operationtype')); } }
/** * Generate table for dashboard triggers popup. * * @see make_system_status * * @param array $triggers * @param array $ackParams * @param array $actions * * @return CTableInfo */ function makeTriggersPopup(array $triggers, array $ackParams, array $actions) { $config = select_config(); $popupTable = new CTableInfo(); $popupTable->setAttribute('style', 'width: 400px;'); $popupTable->setHeader(array(is_show_all_nodes() ? _('Node') : null, _('Host'), _('Issue'), _('Age'), _('Info'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions'))); CArrayHelper::sort($triggers, array(array('field' => 'lastchange', 'order' => ZBX_SORT_DOWN))); foreach ($triggers as $trigger) { // unknown triggers $unknown = SPACE; if ($trigger['state'] == TRIGGER_STATE_UNKNOWN) { $unknown = new CDiv(SPACE, 'status_icon iconunknown'); $unknown->setHint($trigger['error'], '', 'on'); } // ack if ($config['event_ack_enable']) { $ack = isset($trigger['event']['eventid']) ? getEventAckState($trigger['event'], true, true, $ackParams) : _('No events'); } else { $ack = null; } // action $action = isset($trigger['event']['eventid']) && isset($actions[$trigger['event']['eventid']]) ? $actions[$trigger['event']['eventid']] : _('-'); $popupTable->addRow(array(get_node_name_by_elid($trigger['triggerid']), $trigger['hosts'][0]['name'], getSeverityCell($trigger['priority'], $trigger['description']), zbx_date2age($trigger['lastchange']), $unknown, $ack, $action)); } return $popupTable; }
/** * Check "mappings" field properties. * * @param array $valuemaps An array of value maps. * @param array $valuemaps[]['mappings'] An array of "mappings" data. * @param string $valuemaps[]['mappings'][]['value'] Original mapping value. * @param string $valuemaps[]['mappings'][]['newvalue'] Value to which the original value is mapped to. * * @throws APIException if the input is invalid. */ protected function checkMappings(array $valuemaps) { $required_fields = ['value', 'newvalue']; foreach ($valuemaps as $valuemap) { if (!array_key_exists('mappings', $valuemap)) { continue; } if (!is_array($valuemap['mappings'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.')); } elseif (!$valuemap['mappings']) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('At least one mapping should be given for value map "%1$s".', $valuemap['name'])); } foreach ($valuemap['mappings'] as $mapping) { if (!is_array($mapping)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.')); } $missing_keys = checkRequiredKeys($mapping, $required_fields); if ($missing_keys) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Mapping is missing parameters: %1$s for value map "%2$s".', implode(', ', $missing_keys), $valuemap['name'])); } else { foreach (['value', 'newvalue'] as $field) { if (is_array($mapping[$field])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.')); } } } if ($mapping['newvalue'] === '' || $mapping['newvalue'] === null || $mapping['newvalue'] === false) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Empty new value in value map "%1$s".', $valuemap['name'])); } } $duplicate = CArrayHelper::findDuplicate($valuemap['mappings'], 'value'); if ($duplicate) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate mapping value "%1$s" for value map "%2$s".', $duplicate['value'], $valuemap['name'])); } } }