protected function doAction()
 {
     $data = ['sid' => $this->getUserSID(), 'eventids' => $this->getInput('eventids'), 'message' => $this->getInput('message', ''), 'acknowledge_type' => $this->getInput('acknowledge_type', ZBX_ACKNOWLEDGE_SELECTED), 'backurl' => $this->getInput('backurl', 'tr_status.php'), 'unack_problem_events_count' => 0, 'unack_events_count' => 0];
     if (count($this->getInput('eventids')) == 1) {
         $events = API::Event()->get(['output' => [], 'eventids' => $this->getInput('eventids'), 'source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER, 'select_acknowledges' => ['clock', 'message', 'alias', 'name', 'surname']]);
         if ($events) {
             $data['event'] = ['acknowledges' => $events[0]['acknowledges']];
             order_result($data['acknowledges'], 'clock', ZBX_SORT_DOWN);
         }
     }
     $events = API::Event()->get(['output' => ['objectid', 'acknowledged', 'value'], 'eventids' => $this->getInput('eventids'), 'source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER]);
     $triggerids = [];
     foreach ($events as $event) {
         if ($event['acknowledged'] == EVENT_ACKNOWLEDGED) {
             $data['unack_problem_events_count']++;
             $data['unack_events_count']++;
         } elseif ($event['value'] == TRIGGER_VALUE_FALSE) {
             $data['unack_problem_events_count']++;
         }
         $triggerids[$event['objectid']] = true;
     }
     $triggerids = array_keys($triggerids);
     $data['unack_problem_events_count'] += API::Event()->get(['countOutput' => true, 'source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER, 'objectids' => $triggerids, 'filter' => ['acknowledged' => EVENT_NOT_ACKNOWLEDGED, 'value' => TRIGGER_VALUE_TRUE]]);
     $data['unack_events_count'] += API::Event()->get(['countOutput' => true, 'source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER, 'objectids' => $triggerids, 'filter' => ['acknowledged' => EVENT_NOT_ACKNOWLEDGED]]);
     $response = new CControllerResponseData($data);
     $response->setTitle(_('Alarm acknowledgements'));
     $this->setResponse($response);
 }
Ejemplo n.º 2
0
 protected function doAction()
 {
     $sortField = $this->getInput('sort', CProfile::get('web.proxies.php.sort', 'host'));
     $sortOrder = $this->getInput('sortorder', CProfile::get('web.proxies.php.sortorder', ZBX_SORT_UP));
     CProfile::update('web.proxies.php.sort', $sortField, PROFILE_TYPE_STR);
     CProfile::update('web.proxies.php.sortorder', $sortOrder, PROFILE_TYPE_STR);
     $config = select_config();
     $data = ['uncheck' => $this->hasInput('uncheck'), 'sort' => $sortField, 'sortorder' => $sortOrder, 'config' => ['max_in_table' => $config['max_in_table']]];
     $data['proxies'] = API::Proxy()->get(['output' => ['proxyid', 'host', 'status', 'lastaccess', 'tls_connect', 'tls_accept'], 'selectHosts' => ['hostid', 'name', 'status'], 'sortfield' => $sortField, 'limit' => $config['search_limit'] + 1, 'editable' => true, 'preservekeys' => true]);
     // sorting & paging
     order_result($data['proxies'], $sortField, $sortOrder);
     $url = (new CUrl('zabbix.php'))->setArgument('action', 'proxy.list');
     $data['paging'] = getPagingLine($data['proxies'], $sortOrder, $url);
     foreach ($data['proxies'] as &$proxy) {
         order_result($proxy['hosts'], 'name');
     }
     unset($proxy);
     // get proxy IDs for a *selected* page
     $proxyIds = array_keys($data['proxies']);
     if ($proxyIds) {
         // calculate performance
         $dbPerformance = DBselect('SELECT h.proxy_hostid,SUM(1.0/i.delay) AS qps' . ' FROM hosts h,items i' . ' WHERE h.hostid=i.hostid' . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.delay<>0' . ' AND i.flags<>' . ZBX_FLAG_DISCOVERY_PROTOTYPE . ' AND ' . dbConditionInt('h.proxy_hostid', $proxyIds) . ' GROUP BY h.proxy_hostid');
         while ($performance = DBfetch($dbPerformance)) {
             $data['proxies'][$performance['proxy_hostid']]['perf'] = round($performance['qps'], 2);
         }
         // get items
         $items = API::Item()->get(['proxyids' => $proxyIds, 'groupCount' => true, 'countOutput' => true, 'webitems' => true, 'monitored' => true]);
         foreach ($items as $item) {
             $data['proxies'][$item['proxy_hostid']]['item_count'] = $item['rowscount'];
         }
     }
     $response = new CControllerResponseData($data);
     $response->setTitle(_('Configuration of proxies'));
     $this->setResponse($response);
 }
 protected function doAction()
 {
     $sortField = $this->getInput('sort', CProfile::get('web.media_types.php.sort', 'description'));
     $sortOrder = $this->getInput('sortorder', CProfile::get('web.media_types.php.sortorder', ZBX_SORT_UP));
     CProfile::update('web.media_type.php.sort', $sortField, PROFILE_TYPE_STR);
     CProfile::update('web.media_types.php.sortorder', $sortOrder, PROFILE_TYPE_STR);
     $config = select_config();
     $data = ['uncheck' => $this->hasInput('uncheck'), 'sort' => $sortField, 'sortorder' => $sortOrder];
     // get media types
     $data['mediatypes'] = API::Mediatype()->get(['output' => ['mediatypeid', 'description', 'type', 'smtp_server', 'smtp_helo', 'smtp_email', 'exec_path', 'gsm_modem', 'username', 'status'], 'limit' => $config['search_limit'] + 1, 'editable' => true, 'preservekeys' => true]);
     if ($data['mediatypes']) {
         // get media types used in actions
         $actions = API::Action()->get(['output' => ['actionid', 'name'], 'selectOperations' => ['operationtype', 'opmessage'], 'mediatypeids' => array_keys($data['mediatypes'])]);
         foreach ($data['mediatypes'] as &$mediaType) {
             $mediaType['typeid'] = $mediaType['type'];
             $mediaType['type'] = media_type2str($mediaType['type']);
             $mediaType['listOfActions'] = [];
             foreach ($actions as $action) {
                 foreach ($action['operations'] as $operation) {
                     if ($operation['operationtype'] == OPERATION_TYPE_MESSAGE && $operation['opmessage']['mediatypeid'] == $mediaType['mediatypeid']) {
                         $mediaType['listOfActions'][$action['actionid']] = ['actionid' => $action['actionid'], 'name' => $action['name']];
                     }
                 }
             }
             order_result($mediaType['listOfActions'], 'name');
         }
         unset($mediaType);
         order_result($data['mediatypes'], $sortField, $sortOrder);
     }
     $url = (new CUrl('zabbix.php'))->setArgument('action', 'mediatype.list');
     $data['paging'] = getPagingLine($data['mediatypes'], $sortOrder, $url);
     $response = new CControllerResponseData($data);
     $response->setTitle(_('Configuration of media types'));
     $this->setResponse($response);
 }
 protected function doAction()
 {
     $sortField = $this->getInput('sort', CProfile::get('web.scripts.php.sort', 'name'));
     $sortOrder = $this->getInput('sortorder', CProfile::get('web.scripts.php.sortorder', ZBX_SORT_UP));
     CProfile::update('web.scripts.php.sort', $sortField, PROFILE_TYPE_STR);
     CProfile::update('web.scripts.php.sortorder', $sortOrder, PROFILE_TYPE_STR);
     $config = select_config();
     $data = ['uncheck' => $this->hasInput('uncheck'), 'sort' => $sortField, 'sortorder' => $sortOrder];
     // list of scripts
     $data['scripts'] = API::Script()->get(['output' => ['scriptid', 'name', 'command', 'host_access', 'usrgrpid', 'groupid', 'type', 'execute_on'], 'editable' => true, 'limit' => $config['search_limit'] + 1]);
     // sorting & paging
     order_result($data['scripts'], $sortField, $sortOrder);
     $url = (new CUrl('zabbix.php'))->setArgument('action', 'script.list');
     $data['paging'] = getPagingLine($data['scripts'], $sortOrder, $url);
     // find script host group name and user group name. set to '' if all host/user groups used.
     $usrgrpids = [];
     $groupids = [];
     foreach ($data['scripts'] as &$script) {
         $script['userGroupName'] = null;
         // all user groups
         $script['hostGroupName'] = null;
         // all host groups
         if ($script['usrgrpid'] != 0) {
             $usrgrpids[] = $script['usrgrpid'];
         }
         if ($script['groupid'] != 0) {
             $groupids[] = $script['groupid'];
         }
     }
     unset($script);
     if ($usrgrpids) {
         $userGroups = API::UserGroup()->get(['output' => ['name'], 'usrgrpids' => $usrgrpids, 'preservekeys' => true]);
         foreach ($data['scripts'] as &$script) {
             if ($script['usrgrpid'] != 0 && array_key_exists($script['usrgrpid'], $userGroups)) {
                 $script['userGroupName'] = $userGroups[$script['usrgrpid']]['name'];
             }
             unset($script['usrgrpid']);
         }
         unset($script);
     }
     if ($groupids) {
         $hostGroups = API::HostGroup()->get(['output' => ['name'], 'groupids' => $groupids, 'preservekeys' => true]);
         foreach ($data['scripts'] as &$script) {
             if ($script['groupid'] != 0 && array_key_exists($script['groupid'], $hostGroups)) {
                 $script['hostGroupName'] = $hostGroups[$script['groupid']]['name'];
             }
             unset($script['groupid']);
         }
         unset($script);
     }
     $response = new CControllerResponseData($data);
     $response->setTitle(_('Configuration of scripts'));
     $this->setResponse($response);
 }
Ejemplo n.º 5
0
function discovery_check_type2str($type = null)
{
    $discovery_types = array(SVC_SSH => S_SSH, SVC_LDAP => S_LDAP, SVC_SMTP => S_SMTP, SVC_FTP => S_FTP, SVC_HTTP => S_HTTP, SVC_POP => S_POP, SVC_NNTP => S_NNTP, SVC_IMAP => S_IMAP, SVC_TCP => S_TCP, SVC_AGENT => S_ZABBIX_AGENT, SVC_SNMPv1 => S_SNMPV1_AGENT, SVC_SNMPv2 => S_SNMPV2_AGENT, SVC_SNMPv3 => S_SNMPV3_AGENT, SVC_ICMPPING => S_ICMPPING);
    if (is_null($type)) {
        order_result($discovery_types);
        return $discovery_types;
    } else {
        if (isset($discovery_types[$type])) {
            return $discovery_types[$type];
        } else {
            return S_UNKNOWN;
        }
    }
}
 protected function doAction()
 {
     // default values
     $data = ['sid' => $this->getUserSID(), 'scriptid' => 0, 'name' => '', 'type' => ZBX_SCRIPT_TYPE_CUSTOM_SCRIPT, 'execute_on' => ZBX_SCRIPT_EXECUTE_ON_AGENT, 'command' => '', 'commandipmi' => '', 'description' => '', 'usrgrpid' => 0, 'groupid' => 0, 'host_access' => 0, 'confirmation' => '', 'enable_confirmation' => 0, 'hgstype' => 0];
     // get values from the dabatase
     if ($this->hasInput('scriptid')) {
         $scripts = API::Script()->get(['output' => ['scriptid', 'name', 'type', 'execute_on', 'command', 'description', 'usrgrpid', 'groupid', 'host_access', 'confirmation'], 'scriptids' => $this->getInput('scriptid')]);
         $script = $scripts[0];
         $data['scriptid'] = $script['scriptid'];
         $data['name'] = $script['name'];
         $data['type'] = $script['type'];
         $data['execute_on'] = $script['execute_on'];
         $data['command'] = $script['type'] == ZBX_SCRIPT_TYPE_CUSTOM_SCRIPT ? $script['command'] : '';
         $data['commandipmi'] = $script['type'] == ZBX_SCRIPT_TYPE_IPMI ? $script['command'] : '';
         $data['description'] = $script['description'];
         $data['usrgrpid'] = $script['usrgrpid'];
         $data['groupid'] = $script['groupid'];
         $data['host_access'] = $script['host_access'];
         $data['confirmation'] = $script['confirmation'];
         $data['enable_confirmation'] = $script['confirmation'] !== '';
         $data['hgstype'] = $script['groupid'] != 0 ? 1 : 0;
     }
     // overwrite with input variables
     $this->getInputs($data, ['name', 'type', 'execute_on', 'command', 'commandipmi', 'description', 'usrgrpid', 'groupid', 'host_access', 'confirmation', 'enable_confirmation', 'hgstype']);
     // get host group
     if ($data['groupid'] == 0) {
         $data['hostgroup'] = null;
     } else {
         $hostgroups = API::HostGroup()->get(['groupids' => [$data['groupid']], 'output' => ['groupid', 'name']]);
         $hostgroup = $hostgroups[0];
         $data['hostgroup'][] = ['id' => $hostgroup['groupid'], 'name' => $hostgroup['name']];
     }
     // get list of user groups
     $usergroups = API::UserGroup()->get(['output' => ['usrgrpid', 'name']]);
     order_result($usergroups, 'name');
     $data['usergroups'] = $usergroups;
     $response = new CControllerResponseData($data);
     $response->setTitle(_('Configuration of scripts'));
     $this->setResponse($response);
 }
$table = new CTableInfo(_('No hosts found.'));
$table->setHeader(array(make_sorting_header($groupFieldTitle === '' ? _('Field') : $groupFieldTitle, 'inventory_field', $sortField, $sortOrder), make_sorting_header(_('Host count'), 'host_count', $sortField, $sortOrder)));
// to show a report, we will need a host group and a field to aggregate
if ($pageFilter->groupsSelected && $groupFieldTitle !== '') {
    $options = array('output' => array('hostid', 'name'), 'selectInventory' => array($_REQUEST['groupby']), 'withInventory' => true);
    if ($pageFilter->groupid > 0) {
        $options['groupids'] = $pageFilter->groupid;
    }
    $hosts = API::Host()->get($options);
    // aggregating data by chosen field value
    $report = array();
    foreach ($hosts as $host) {
        if ($host['inventory'][$_REQUEST['groupby']] !== '') {
            // same names with different letter casing are considered the same
            $lowerValue = mb_strtolower($host['inventory'][$_REQUEST['groupby']]);
            if (!isset($report[$lowerValue])) {
                $report[$lowerValue] = array('inventory_field' => $host['inventory'][$_REQUEST['groupby']], 'host_count' => 1);
            } else {
                $report[$lowerValue]['host_count'] += 1;
            }
        }
    }
    order_result($report, $sortField, $sortOrder);
    foreach ($report as $rep) {
        $row = array(new CSpan(zbx_str2links($rep['inventory_field']), 'pre'), new CLink($rep['host_count'], 'hostinventories.php?filter_field=' . $_REQUEST['groupby'] . '&filter_field_value=' . urlencode($rep['inventory_field']) . '&filter_set=1&filter_exact=1' . url_param('groupid')));
        $table->addRow($row);
    }
}
$hostinvent_wdgt->addItem($table);
$hostinvent_wdgt->show();
require_once dirname(__FILE__) . '/include/page_footer.php';
Ejemplo n.º 8
0
    $cbFilter = new CSpan(S_DISABLED, 'red underline pointer');
    $cbFilter->setAttribute('onclick', "\$('dashform').enable(); create_var('" . $dashForm->getName() . "', 'filterEnable', 1, true);");
}
$dashForm->addRow(S_DASHBOARD_FILTER, $cbFilter);
$dashForm->addVar('groupids', $groupids);
$cmbGroups = new CComboBox('grpswitch', $grpswitch, 'submit();');
$cmbGroups->addItem(0, S_ALL_S);
$cmbGroups->addItem(1, S_SELECTED);
if (!$filterEnable) {
    $cmbGroups->setAttribute('disabled', 'disabled');
}
$dashForm->addRow(S_HOST_GROUPS, $cmbGroups);
if ($grpswitch == 1) {
    $options = array('nodeids' => get_current_nodeid(true), 'groupids' => $groupids, 'output' => API_OUTPUT_EXTEND);
    $groups = CHostGroup::get($options);
    order_result($groups, 'name');
    $lstGroups = new CListBox('del_groups[]', null, 15);
    $lstGroups->setAttribute('style', 'width: 200px;');
    foreach ($groups as $gnum => $group) {
        $lstGroups->addItem($group['groupid'], get_node_name_by_elid($group['groupid'], true, ':') . $group['name']);
    }
    if (!$filterEnable) {
        $lstGroups->setAttribute('disabled', 'disabled');
    }
    $addButton = new CButton('add', S_ADD, "return PopUp('popup_right.php?dstfrm=" . $dashForm->getName() . "&permission=" . PERM_READ_WRITE . "',450,450);");
    if (!$filterEnable) {
        $addButton->setAttribute('disabled', 'disabled');
    }
    $delButton = new CButton('delete', S_DELETE_SELECTED);
    if (!$filterEnable) {
        $delButton->setAttribute('disabled', 'disabled');
     $name[] = new CLink($sourceTemplate['name'], '?parent_discoveryid=' . $hostPrototype['sourceDiscoveryRuleId'], 'unknown');
     $name[] = NAME_DELIMITER;
 }
 $name[] = new CLink($hostPrototype['name'], '?form=update&parent_discoveryid=' . $discoveryRule['itemid'] . '&hostid=' . $hostPrototype['hostid']);
 // template list
 if (empty($hostPrototype['templates'])) {
     $hostTemplates = '-';
 } else {
     $hostTemplates = array();
     order_result($hostPrototype['templates'], 'name');
     foreach ($hostPrototype['templates'] as $template) {
         $caption = array();
         $caption[] = new CLink($template['name'], 'templates.php?form=update&templateid=' . $template['templateid'], 'unknown');
         $linkedTemplates = $this->data['linkedTemplates'][$template['templateid']]['parentTemplates'];
         if ($linkedTemplates) {
             order_result($linkedTemplates, 'name');
             $caption[] = ' (';
             foreach ($linkedTemplates as $tpl) {
                 $caption[] = new CLink($tpl['name'], 'templates.php?form=update&templateid=' . $tpl['templateid'], 'unknown');
                 $caption[] = ', ';
             }
             array_pop($caption);
             $caption[] = ')';
         }
         $hostTemplates[] = $caption;
         $hostTemplates[] = ', ';
     }
     if ($hostTemplates) {
         array_pop($hostTemplates);
     }
 }
Ejemplo n.º 10
0
function drawMapLinkLabels(&$im, $map, $mapInfo, $resolveMacros = true)
{
    global $colors;
    $links = $map['links'];
    $selements = $map['selements'];
    foreach ($links as $link) {
        if (empty($link['label'])) {
            continue;
        }
        $selement1 = $selements[$link['selementid1']];
        list($x1, $y1) = get_icon_center_by_selement($selement1, $mapInfo[$link['selementid1']], $map);
        $selement2 = $selements[$link['selementid2']];
        list($x2, $y2) = get_icon_center_by_selement($selement2, $mapInfo[$link['selementid2']], $map);
        if (isset($selement1['elementsubtype']) && $selement1['elementsubtype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) {
            if ($selement1['areatype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) {
                $w = $selement1['width'];
                $h = $selement1['height'];
            } else {
                $w = $map['width'];
                $h = $map['height'];
            }
            list($x1, $y1) = calculateMapAreaLinkCoord($x1, $y1, $w, $h, $x2, $y2);
        }
        if (isset($selement2['elementsubtype']) && $selement2['elementsubtype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) {
            if ($selement2['areatype'] == SYSMAP_ELEMENT_AREA_TYPE_CUSTOM) {
                $w = $selement2['width'];
                $h = $selement2['height'];
            } else {
                $w = $map['width'];
                $h = $map['height'];
            }
            list($x2, $y2) = calculateMapAreaLinkCoord($x2, $y2, $w, $h, $x1, $y1);
        }
        $drawtype = $link['drawtype'];
        $color = convertColor($im, $link['color']);
        $linktriggers = $link['linktriggers'];
        order_result($linktriggers, 'triggerid');
        if (!empty($linktriggers)) {
            $max_severity = 0;
            $triggers = array();
            foreach ($linktriggers as $link_trigger) {
                if ($link_trigger['triggerid'] == 0) {
                    continue;
                }
                $id = $link_trigger['linktriggerid'];
                $triggers[$id] = zbx_array_merge($link_trigger, get_trigger_by_triggerid($link_trigger['triggerid']));
                if ($triggers[$id]['status'] == TRIGGER_STATUS_ENABLED && $triggers[$id]['value'] == TRIGGER_VALUE_TRUE) {
                    if ($triggers[$id]['priority'] >= $max_severity) {
                        $drawtype = $triggers[$id]['drawtype'];
                        $color = convertColor($im, $triggers[$id]['color']);
                        $max_severity = $triggers[$id]['priority'];
                    }
                }
            }
        }
        $label = $link['label'];
        $label = str_replace("\r", '', $label);
        $strings = explode("\n", $label);
        $box_width = 0;
        $box_height = 0;
        foreach ($strings as $snum => $str) {
            $strings[$snum] = $resolveMacros ? CMacrosResolverHelper::resolveMapLabelMacros($str) : $str;
        }
        foreach ($strings as $str) {
            $dims = imageTextSize(8, 0, $str);
            $box_width = $box_width > $dims['width'] ? $box_width : $dims['width'];
            $box_height += $dims['height'] + 2;
        }
        $boxX_left = round(($x1 + $x2) / 2 - $box_width / 2 - 6);
        $boxX_right = round(($x1 + $x2) / 2 + $box_width / 2 + 6);
        $boxY_top = round(($y1 + $y2) / 2 - $box_height / 2 - 4);
        $boxY_bottom = round(($y1 + $y2) / 2 + $box_height / 2 + 2);
        switch ($drawtype) {
            case MAP_LINK_DRAWTYPE_DASHED_LINE:
            case MAP_LINK_DRAWTYPE_DOT:
                dashedRectangle($im, $boxX_left, $boxY_top, $boxX_right, $boxY_bottom, $color);
                break;
            case MAP_LINK_DRAWTYPE_BOLD_LINE:
                imagerectangle($im, $boxX_left - 1, $boxY_top - 1, $boxX_right + 1, $boxY_bottom + 1, $color);
                // break; is not ne
            // break; is not ne
            case MAP_LINK_DRAWTYPE_LINE:
            default:
                imagerectangle($im, $boxX_left, $boxY_top, $boxX_right, $boxY_bottom, $color);
        }
        imagefilledrectangle($im, $boxX_left + 1, $boxY_top + 1, $boxX_right - 1, $boxY_bottom - 1, $colors['White']);
        $increasey = 4;
        foreach ($strings as $str) {
            $dims = imageTextSize(8, 0, $str);
            $labelx = ($x1 + $x2) / 2 - $dims['width'] / 2;
            $labely = $boxY_top + $increasey;
            imagetext($im, 8, 0, $labelx, $labely + $dims['height'], $colors['Black'], $str);
            $increasey += $dims['height'] + 2;
        }
    }
}
Ejemplo n.º 11
0
 /**
  * Get Service data
  *
  * @param _array $options
  * @param array $options['nodeids'] Node IDs
  * @param array $options['groupids'] ServiceGroup IDs
  * @param array $options['hostids'] Service IDs
  * @param boolean $options['monitored_hosts'] only monitored Services
  * @param boolean $options['templated_hosts'] include templates in result
  * @param boolean $options['with_items'] only with items
  * @param boolean $options['with_historical_items'] only with historical items
  * @param boolean $options['with_triggers'] only with triggers
  * @param boolean $options['with_httptests'] only with http tests
  * @param boolean $options['with_graphs'] only with graphs
  * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
  * @param boolean $options['selectGroups'] select ServiceGroups
  * @param boolean $options['selectTemplates'] select Templates
  * @param boolean $options['selectItems'] select Items
  * @param boolean $options['selectTriggers'] select Triggers
  * @param boolean $options['selectGraphs'] select Graphs
  * @param boolean $options['selectApplications'] select Applications
  * @param boolean $options['selectMacros'] select Macros
  * @param int $options['count'] count Services, returned column name is rowscount
  * @param string $options['pattern'] search hosts by pattern in Service name
  * @param string $options['extendPattern'] search hosts by pattern in Service name, ip and DNS
  * @param int $options['limit'] limit selection
  * @param string $options['sortfield'] field to sort by
  * @param string $options['sortorder'] sort order
  * @return array|boolean Service data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     // allowed columns for sorting
     $sortColumns = array('dserviceid', 'dhostid', 'ip');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('dservices' => 'ds.dserviceid'), 'from' => array('dservices' => 'dservices ds'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'dserviceids' => null, 'dhostids' => null, 'dcheckids' => null, 'druleids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectDRules' => null, 'selectDHosts' => null, 'selectDChecks' => null, 'selectHosts' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['dservices']);
         $dbTable = DB::getSchema('dservices');
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 's.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $userType) {
     } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) {
     } elseif (!is_null($options['editable']) && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         return array();
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // dserviceids
     if (!is_null($options['dserviceids'])) {
         zbx_value2array($options['dserviceids']);
         $sqlParts['where']['dserviceid'] = dbConditionInt('ds.dserviceid', $options['dserviceids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids);
         }
     }
     // dhostids
     if (!is_null($options['dhostids'])) {
         zbx_value2array($options['dhostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['dhostid'] = 'ds.dhostid';
         }
         $sqlParts['where'][] = dbConditionInt('ds.dhostid', $options['dhostids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['dhostid'] = 'ds.dhostid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('ds.dhostid', $nodeids);
         }
     }
     // dcheckids
     if (!is_null($options['dcheckids'])) {
         zbx_value2array($options['dcheckids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['dcheckid'] = 'dc.dcheckid';
         }
         $sqlParts['from']['dhosts'] = 'dhosts dh';
         $sqlParts['from']['dchecks'] = 'dchecks dc';
         $sqlParts['where'][] = dbConditionInt('dc.dcheckid', $options['dcheckids']);
         $sqlParts['where']['dhds'] = 'dh.hostid=ds.hostid';
         $sqlParts['where']['dcdh'] = 'dc.druleid=dh.druleid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['dcheckid'] = 'dc.dcheckid';
         }
     }
     // druleids
     if (!is_null($options['druleids'])) {
         zbx_value2array($options['druleids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['druleid'] = 'dh.druleid';
         }
         $sqlParts['from']['dhosts'] = 'dhosts dh';
         $sqlParts['where']['druleid'] = dbConditionInt('dh.druleid', $options['druleids']);
         $sqlParts['where']['dhds'] = 'dh.dhostid=ds.dhostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['druleid'] = 'dh.druleid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('dh.druleid', $nodeids);
         }
     }
     // node check !!!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['dservices'] = 'ds.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT ds.dserviceid) as rowscount');
         //groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('dservices ds', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('dservices ds', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'ds');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     //-------
     $dserviceids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     //SDI($sql);
     $res = DBselect($sql, $sqlLimit);
     while ($dservice = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $dservice;
             } else {
                 $result = $dservice['rowscount'];
             }
         } else {
             $dserviceids[$dservice['dserviceid']] = $dservice['dserviceid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$dservice['dserviceid']] = array('dserviceid' => $dservice['dserviceid']);
             } else {
                 if (!isset($result[$dservice['dserviceid']])) {
                     $result[$dservice['dserviceid']] = array();
                 }
                 if (!is_null($options['selectDRules']) && !isset($result[$dservice['dserviceid']]['drules'])) {
                     $result[$dservice['dserviceid']]['drules'] = array();
                 }
                 if (!is_null($options['selectDHosts']) && !isset($result[$dservice['dserviceid']]['dhosts'])) {
                     $result[$dservice['dserviceid']]['dhosts'] = array();
                 }
                 if (!is_null($options['selectDChecks']) && !isset($result[$dservice['dserviceid']]['dchecks'])) {
                     $result[$dservice['dserviceid']]['dchecks'] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$dservice['dserviceid']]['hosts'])) {
                     $result[$dservice['dserviceid']]['hosts'] = array();
                 }
                 // druleids
                 if (isset($dservice['druleid']) && is_null($options['selectDRules'])) {
                     if (!isset($result[$dservice['dserviceid']]['drules'])) {
                         $result[$dservice['dserviceid']]['drules'] = array();
                     }
                     $result[$dservice['dserviceid']]['drules'][] = array('druleid' => $dservice['druleid']);
                 }
                 // dhostids
                 if (isset($dservice['dhostid']) && is_null($options['selectDHosts'])) {
                     if (!isset($result[$dservice['dserviceid']]['dhosts'])) {
                         $result[$dservice['dserviceid']]['dhosts'] = array();
                     }
                     $result[$dservice['dserviceid']]['dhosts'][] = array('dhostid' => $dservice['dhostid']);
                 }
                 // dcheckids
                 if (isset($dservice['dcheckid']) && is_null($options['selectDChecks'])) {
                     if (!isset($result[$dservice['dserviceid']]['dchecks'])) {
                         $result[$dservice['dserviceid']]['dchecks'] = array();
                     }
                     $result[$dservice['dserviceid']]['dchecks'][] = array('dcheckid' => $dservice['dcheckid']);
                 }
                 $result[$dservice['dserviceid']] += $dservice;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // Adding Objects
     // select_drules
     if (!is_null($options['selectDRules'])) {
         $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1);
         if (is_array($options['selectDRules']) || str_in_array($options['selectDRules'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDRules'];
             $drules = API::DRule()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($drules, 'name');
             }
             foreach ($drules as $druleid => $drule) {
                 unset($drules[$druleid]['dservices']);
                 $count = array();
                 foreach ($drule['dservices'] as $dnum => $dservice) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$dservice['dserviceid']])) {
                             $count[$dservice['dserviceid']] = 0;
                         }
                         $count[$dservice['dserviceid']]++;
                         if ($count[$dservice['dserviceid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$dservice['dserviceid']]['drules'][] =& $drules[$druleid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectDRules']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $drules = API::DRule()->get($objParams);
             $drules = zbx_toHash($drules, 'dserviceid');
             foreach ($result as $dserviceid => $dservice) {
                 if (isset($drules[$dserviceid])) {
                     $result[$dserviceid]['drules'] = $drules[$dserviceid]['rowscount'];
                 } else {
                     $result[$dserviceid]['drules'] = 0;
                 }
             }
         }
     }
     // selectDHosts
     if (!is_null($options['selectDHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1);
         if (is_array($options['selectDHosts']) || str_in_array($options['selectDHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDHosts'];
             $dhosts = API::DHost()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($dhosts, 'dhostid');
             }
             foreach ($dhosts as $dhostid => $dhost) {
                 unset($dhosts[$dhostid]['dservices']);
                 foreach ($dhost['dservices'] as $snum => $dservice) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$dservice['dserviceid']])) {
                             $count[$dservice['dserviceid']] = 0;
                         }
                         $count[$dservice['dserviceid']]++;
                         if ($count[$dservice['dserviceid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$dservice['dserviceid']]['dhosts'][] =& $dhosts[$dhostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectDHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $dhosts = API::DHost()->get($objParams);
             $dhosts = zbx_toHash($dhosts, 'dhostid');
             foreach ($result as $dserviceid => $dservice) {
                 if (isset($dhosts[$dserviceid])) {
                     $result[$dserviceid]['dhosts'] = $dhosts[$dserviceid]['rowscount'];
                 } else {
                     $result[$dserviceid]['dhosts'] = 0;
                 }
             }
         }
     }
     // selectHosts
     if (!is_null($options['selectHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1, 'sortfield' => 'status');
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectHosts'];
             $hosts = API::Host()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($hosts, 'hostid');
             }
             foreach ($hosts as $hostid => $host) {
                 unset($hosts[$hostid]['dservices']);
                 foreach ($host['dservices'] as $dnum => $dservice) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$dservice['dserviceid']])) {
                             $count[$dservice['dserviceid']] = 0;
                         }
                         $count[$dservice['dserviceid']]++;
                         if ($count[$dservice['dserviceid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$dservice['dserviceid']]['hosts'][] =& $hosts[$hostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $hosts = API::Host()->get($objParams);
             $hosts = zbx_toHash($hosts, 'hostid');
             foreach ($result as $dserviceid => $dservice) {
                 if (isset($hosts[$dserviceid])) {
                     $result[$dserviceid]['hosts'] = $hosts[$dserviceid]['rowscount'];
                 } else {
                     $result[$dserviceid]['hosts'] = 0;
                 }
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Ejemplo n.º 12
0
if (getRequest('favobj') === 'timeline' && hasRequest('elementid') && hasRequest('period')) {
    navigation_bar_calc('web.hostscreen', getRequest('elementid'), true);
}
if ($page['type'] == PAGE_TYPE_JS || $page['type'] == PAGE_TYPE_HTML_BLOCK) {
    require_once dirname(__FILE__) . '/include/page_footer.php';
    exit;
}
/*
 * Display
 */
$data = array('hostid' => getRequest('hostid', 0), 'fullscreen' => $_REQUEST['fullscreen'], 'screenid' => getRequest('screenid', CProfile::get('web.hostscreen.screenid', null)), 'period' => getRequest('period'), 'stime' => getRequest('stime'));
CProfile::update('web.hostscreen.screenid', $data['screenid'], PROFILE_TYPE_ID);
// get screen list
$data['screens'] = API::TemplateScreen()->get(array('hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND));
$data['screens'] = zbx_toHash($data['screens'], 'screenid');
order_result($data['screens'], 'name');
// get screen
$screenid = null;
if (!empty($data['screens'])) {
    $screen = !isset($data['screens'][$data['screenid']]) ? reset($data['screens']) : $data['screens'][$data['screenid']];
    if (!empty($screen['screenid'])) {
        $screenid = $screen['screenid'];
    }
}
$data['screen'] = API::TemplateScreen()->get(array('screenids' => $screenid, 'hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND, 'selectScreenItems' => API_OUTPUT_EXTEND));
$data['screen'] = reset($data['screen']);
// get host
if (!empty($data['screen']['hostid'])) {
    $data['host'] = get_host_by_hostid($data['screen']['hostid']);
}
// render view
$sortLink = new CUrl();
$sortLink->setArgument('parent_discoveryid', $this->data['parent_discoveryid']);
$sortLink = $sortLink->getUrl();
$itemTable->setHeader(array(new CCheckBox('all_items', null, "checkAll('" . $itemForm->getName() . "', 'all_items', 'group_itemid');"), make_sorting_header(_('Name'), 'name', $sortLink), make_sorting_header(_('Key'), 'key_', $sortLink), make_sorting_header(_('Interval'), 'delay', $sortLink), make_sorting_header(_('History'), 'history', $sortLink), make_sorting_header(_('Trends'), 'trends', $sortLink), make_sorting_header(_('Type'), 'type', $sortLink), _('Applications'), make_sorting_header(_('Status'), 'status', $sortLink)));
foreach ($this->data['items'] as $item) {
    $description = array();
    if (!empty($item['templateid'])) {
        $template_host = get_realhost_by_itemid($item['templateid']);
        $templateDiscoveryRuleId = get_realrule_by_itemid_and_hostid($this->data['parent_discoveryid'], $template_host['hostid']);
        $description[] = new CLink($template_host['name'], '?parent_discoveryid=' . $templateDiscoveryRuleId, 'unknown');
        $description[] = NAME_DELIMITER;
    }
    $description[] = new CLink($item['name_expanded'], '?form=update&itemid=' . $item['itemid'] . '&parent_discoveryid=' . $this->data['parent_discoveryid']);
    $status = new CLink(itemIndicator($item['status']), '?group_itemid=' . $item['itemid'] . '&parent_discoveryid=' . $this->data['parent_discoveryid'] . '&go=' . ($item['status'] ? 'activate' : 'disable'), itemIndicatorStyle($item['status']));
    if (!empty($item['applications'])) {
        order_result($item['applications'], 'name');
        $applications = zbx_objectValues($item['applications'], 'name');
        $applications = implode(', ', $applications);
        if (empty($applications)) {
            $applications = '-';
        }
    } else {
        $applications = '-';
    }
    $itemTable->addRow(array(new CCheckBox('group_itemid[' . $item['itemid'] . ']', null, null, $item['itemid']), $description, $item['key_'], $item['delay'], $item['history'], in_array($item['value_type'], array(ITEM_VALUE_TYPE_STR, ITEM_VALUE_TYPE_LOG, ITEM_VALUE_TYPE_TEXT)) ? '' : $item['trends'], item_type2str($item['type']), new CCol($applications, 'wraptext'), $status));
}
// create go buttons
$goComboBox = new CComboBox('go');
$goOption = new CComboItem('activate', _('Enable selected'));
$goOption->setAttribute('confirm', _('Enable selected item prototypes?'));
$goComboBox->addItem($goOption);
Ejemplo n.º 14
0
$param1SecCount = [['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT, 'M' => $metrics], ['C' => _('Time shift'), 'T' => T_ZBX_INT]];
$param1Sec = [['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT]];
$param1Str = [['C' => 'T', 'T' => T_ZBX_STR]];
$param2SecCount = [['C' => 'V', 'T' => T_ZBX_STR], ['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT, 'M' => $metrics]];
$param3SecVal = [['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT, 'M' => $metrics], ['C' => 'V', 'T' => T_ZBX_STR], ['C' => 'O', 'T' => T_ZBX_STR], ['C' => _('Time shift'), 'T' => T_ZBX_INT]];
$param3SecPercent = [['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT, 'M' => $metrics], ['C' => _('Time shift'), 'T' => T_ZBX_INT], ['C' => _('Percentage') . ' (P)', 'T' => T_ZBX_DBL]];
$paramSecIntCount = [['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT, 'M' => $metrics], ['C' => _('Mask'), 'T' => T_ZBX_STR], ['C' => _('Time shift'), 'T' => T_ZBX_INT]];
$paramForecast = [['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT, 'M' => $metrics], ['C' => _('Time shift'), 'T' => T_ZBX_INT], ['C' => _('Time') . ' (t)', 'T' => T_ZBX_INT], ['C' => _('Fit'), 'T' => T_ZBX_STR], ['C' => _('Mode'), 'T' => T_ZBX_STR]];
$paramTimeleft = [['C' => _('Last of') . ' (T)', 'T' => T_ZBX_INT, 'M' => $metrics], ['C' => _('Time shift'), 'T' => T_ZBX_INT], ['C' => _('Threshold'), 'T' => T_ZBX_DBL], ['C' => _('Fit'), 'T' => T_ZBX_STR]];
$allowedTypesAny = [ITEM_VALUE_TYPE_FLOAT => 1, ITEM_VALUE_TYPE_STR => 1, ITEM_VALUE_TYPE_LOG => 1, ITEM_VALUE_TYPE_UINT64 => 1, ITEM_VALUE_TYPE_TEXT => 1];
$allowedTypesNumeric = [ITEM_VALUE_TYPE_FLOAT => 1, ITEM_VALUE_TYPE_UINT64 => 1];
$allowedTypesStr = [ITEM_VALUE_TYPE_STR => 1, ITEM_VALUE_TYPE_LOG => 1, ITEM_VALUE_TYPE_TEXT => 1];
$allowedTypesLog = [ITEM_VALUE_TYPE_LOG => 1];
$allowedTypesInt = [ITEM_VALUE_TYPE_UINT64 => 1];
$functions = ['abschange[<]' => ['description' => _('Absolute difference between last and previous value is < N'), 'allowed_types' => $allowedTypesAny], 'abschange[>]' => ['description' => _('Absolute difference between last and previous value is > N'), 'allowed_types' => $allowedTypesAny], 'abschange[=]' => ['description' => _('Absolute difference between last and previous value is = N'), 'allowed_types' => $allowedTypesAny], 'abschange[<>]' => ['description' => _('Absolute difference between last and previous value is NOT N'), 'allowed_types' => $allowedTypesAny], 'avg[<]' => ['description' => _('Average value of a period T is < N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'avg[>]' => ['description' => _('Average value of a period T is > N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'avg[=]' => ['description' => _('Average value of a period T is = N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'avg[<>]' => ['description' => _('Average value of a period T is NOT N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'delta[<]' => ['description' => _('Difference between MAX and MIN value of a period T is < N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'delta[>]' => ['description' => _('Difference between MAX and MIN value of a period T is > N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'delta[=]' => ['description' => _('Difference between MAX and MIN value of a period T is = N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'delta[<>]' => ['description' => _('Difference between MAX and MIN value of a period T is NOT N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'change[<]' => ['description' => _('Difference between last and previous value is < N'), 'allowed_types' => $allowedTypesAny], 'change[>]' => ['description' => _('Difference between last and previous value is > N'), 'allowed_types' => $allowedTypesAny], 'change[=]' => ['description' => _('Difference between last and previous value is = N'), 'allowed_types' => $allowedTypesAny], 'change[<>]' => ['description' => _('Difference between last and previous value is NOT N'), 'allowed_types' => $allowedTypesAny], 'count[<]' => ['description' => _('Number of successfully retrieved values V (which fulfill operator O) for period T is < N'), 'params' => $param3SecVal, 'allowed_types' => $allowedTypesAny], 'count[>]' => ['description' => _('Number of successfully retrieved values V (which fulfill operator O) for period T is > N'), 'params' => $param3SecVal, 'allowed_types' => $allowedTypesAny], 'count[=]' => ['description' => _('Number of successfully retrieved values V (which fulfill operator O) for period T is = N'), 'params' => $param3SecVal, 'allowed_types' => $allowedTypesAny], 'count[<>]' => ['description' => _('Number of successfully retrieved values V (which fulfill operator O) for period T is NOT N'), 'params' => $param3SecVal, 'allowed_types' => $allowedTypesAny], 'diff[=]' => ['description' => _('Difference between last and preceding values, then N = 1, 0 - otherwise'), 'allowed_types' => $allowedTypesAny], 'diff[<>]' => ['description' => _('Difference between last and preceding values, then N NOT 1, 0 - otherwise'), 'allowed_types' => $allowedTypesAny], 'last[<]' => ['description' => _('Last (most recent) T value is < N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesAny], 'last[>]' => ['description' => _('Last (most recent) T value is > N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesAny], 'last[=]' => ['description' => _('Last (most recent) T value is = N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesAny], 'last[<>]' => ['description' => _('Last (most recent) T value is NOT N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesAny], 'max[<]' => ['description' => _('Maximum value for period T is < N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'max[>]' => ['description' => _('Maximum value for period T is > N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'max[=]' => ['description' => _('Maximum value for period T is = N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'max[<>]' => ['description' => _('Maximum value for period T is NOT N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'min[<]' => ['description' => _('Minimum value for period T is < N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'min[>]' => ['description' => _('Minimum value for period T is > N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'min[=]' => ['description' => _('Minimum value for period T is = N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'min[<>]' => ['description' => _('Minimum value for period T is NOT N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'percentile[<]' => ['description' => _('Percentile P of a period T is < N'), 'params' => $param3SecPercent, 'allowed_types' => $allowedTypesNumeric], 'percentile[>]' => ['description' => _('Percentile P of a period T is > N'), 'params' => $param3SecPercent, 'allowed_types' => $allowedTypesNumeric], 'percentile[=]' => ['description' => _('Percentile P of a period T is = N'), 'params' => $param3SecPercent, 'allowed_types' => $allowedTypesNumeric], 'percentile[<>]' => ['description' => _('Percentile P of a period T is NOT N'), 'params' => $param3SecPercent, 'allowed_types' => $allowedTypesNumeric], 'prev[<]' => ['description' => _('Previous value is < N'), 'allowed_types' => $allowedTypesAny], 'prev[>]' => ['description' => _('Previous value is > N'), 'allowed_types' => $allowedTypesAny], 'prev[=]' => ['description' => _('Previous value is = N'), 'allowed_types' => $allowedTypesAny], 'prev[<>]' => ['description' => _('Previous value is NOT N'), 'allowed_types' => $allowedTypesAny], 'str[=]' => ['description' => _('Find string V in last (most recent) value. N = 1 - if found, 0 - otherwise'), 'params' => $param2SecCount, 'allowed_types' => $allowedTypesAny], 'str[<>]' => ['description' => _('Find string V in last (most recent) value. N NOT 1 - if found, 0 - otherwise'), 'params' => $param2SecCount, 'allowed_types' => $allowedTypesAny], 'strlen[<]' => ['description' => _('Length of last (most recent) T value in characters is < N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesStr], 'strlen[>]' => ['description' => _('Length of last (most recent) T value in characters is > N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesStr], 'strlen[=]' => ['description' => _('Length of last (most recent) T value in characters is = N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesStr], 'strlen[<>]' => ['description' => _('Length of last (most recent) T value in characters is NOT N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesStr], 'sum[<]' => ['description' => _('Sum of values of a period T is < N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'sum[>]' => ['description' => _('Sum of values of a period T is > N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'sum[=]' => ['description' => _('Sum of values of a period T is = N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'sum[<>]' => ['description' => _('Sum of values of a period T is NOT N'), 'params' => $param1SecCount, 'allowed_types' => $allowedTypesNumeric], 'date[<]' => ['description' => _('Current date is < N'), 'allowed_types' => $allowedTypesAny], 'date[>]' => ['description' => _('Current date is > N'), 'allowed_types' => $allowedTypesAny], 'date[=]' => ['description' => _('Current date is = N'), 'allowed_types' => $allowedTypesAny], 'date[<>]' => ['description' => _('Current date is NOT N'), 'allowed_types' => $allowedTypesAny], 'dayofweek[<]' => ['description' => _('Day of week is < N'), 'allowed_types' => $allowedTypesAny], 'dayofweek[>]' => ['description' => _('Day of week is > N'), 'allowed_types' => $allowedTypesAny], 'dayofweek[=]' => ['description' => _('Day of week is = N'), 'allowed_types' => $allowedTypesAny], 'dayofweek[<>]' => ['description' => _('Day of week is NOT N'), 'allowed_types' => $allowedTypesAny], 'dayofmonth[<]' => ['description' => _('Day of month is < N'), 'allowed_types' => $allowedTypesAny], 'dayofmonth[>]' => ['description' => _('Day of month is > N'), 'allowed_types' => $allowedTypesAny], 'dayofmonth[=]' => ['description' => _('Day of month is = N'), 'allowed_types' => $allowedTypesAny], 'dayofmonth[<>]' => ['description' => _('Day of month is NOT N'), 'allowed_types' => $allowedTypesAny], 'fuzzytime[=]' => ['description' => _('Difference between item timestamp value and Zabbix server timestamp is over T seconds, then N = 0, 1 - otherwise'), 'params' => $param1Sec, 'allowed_types' => $allowedTypesAny], 'fuzzytime[<>]' => ['description' => _('Difference between item timestamp value and Zabbix server timestamp is over T seconds, then N NOT 0, 1 - otherwise'), 'params' => $param1Sec, 'allowed_types' => $allowedTypesAny], 'regexp[=]' => ['description' => _('Regular expression V matching last value in period T, then N = 1, 0 - otherwise'), 'params' => $param2SecCount, 'allowed_types' => $allowedTypesAny], 'regexp[<>]' => ['description' => _('Regular expression V matching last value in period T, then N NOT 1, 0 - otherwise'), 'params' => $param2SecCount, 'allowed_types' => $allowedTypesAny], 'iregexp[=]' => ['description' => _('Regular expression V matching last value in period T, then N = 1, 0 - otherwise (non case-sensitive)'), 'params' => $param2SecCount, 'allowed_types' => $allowedTypesAny], 'iregexp[<>]' => ['description' => _('Regular expression V matching last value in period T, then N NOT 1, 0 - otherwise (non case-sensitive)'), 'params' => $param2SecCount, 'allowed_types' => $allowedTypesAny], 'logeventid[=]' => ['description' => _('Event ID of last log entry matching regular expression T, then N = 1, 0 - otherwise'), 'params' => $param1Str, 'allowed_types' => $allowedTypesLog], 'logeventid[<>]' => ['description' => _('Event ID of last log entry matching regular expression T, then N NOT 1, 0 - otherwise'), 'params' => $param1Str, 'allowed_types' => $allowedTypesLog], 'logseverity[<]' => ['description' => _('Log severity of the last log entry is < N'), 'allowed_types' => $allowedTypesLog], 'logseverity[>]' => ['description' => _('Log severity of the last log entry is > N'), 'allowed_types' => $allowedTypesLog], 'logseverity[=]' => ['description' => _('Log severity of the last log entry is = N'), 'allowed_types' => $allowedTypesLog], 'logseverity[<>]' => ['description' => _('Log severity of the last log entry is NOT N'), 'allowed_types' => $allowedTypesLog], 'logsource[=]' => ['description' => _('Log source of the last log entry matching parameter T, then N = 1, 0 - otherwise'), 'params' => $param1Str, 'allowed_types' => $allowedTypesLog], 'logsource[<>]' => ['description' => _('Log source of the last log entry matching parameter T, then N NOT 1, 0 - otherwise'), 'params' => $param1Str, 'allowed_types' => $allowedTypesLog], 'now[<]' => ['description' => _('Number of seconds since the Epoch is < N'), 'allowed_types' => $allowedTypesAny], 'now[>]' => ['description' => _('Number of seconds since the Epoch is > N'), 'allowed_types' => $allowedTypesAny], 'now[=]' => ['description' => _('Number of seconds since the Epoch is = N'), 'allowed_types' => $allowedTypesAny], 'now[<>]' => ['description' => _('Number of seconds since the Epoch is NOT N'), 'allowed_types' => $allowedTypesAny], 'time[<]' => ['description' => _('Current time is < N'), 'allowed_types' => $allowedTypesAny], 'time[>]' => ['description' => _('Current time is > N'), 'allowed_types' => $allowedTypesAny], 'time[=]' => ['description' => _('Current time is = N'), 'allowed_types' => $allowedTypesAny], 'time[<>]' => ['description' => _('Current time is NOT N'), 'allowed_types' => $allowedTypesAny], 'nodata[=]' => ['description' => _('No data received during period of time T, then N = 1, 0 - otherwise'), 'params' => $param1Sec, 'allowed_types' => $allowedTypesAny], 'nodata[<>]' => ['description' => _('No data received during period of time T, then N NOT 1, 0 - otherwise'), 'params' => $param1Sec, 'allowed_types' => $allowedTypesAny], 'band[=]' => ['description' => _('Bitwise AND of last (most recent) T value and mask is = N'), 'params' => $paramSecIntCount, 'allowed_types' => $allowedTypesInt], 'band[<>]' => ['description' => _('Bitwise AND of last (most recent) T value and mask is NOT N'), 'params' => $paramSecIntCount, 'allowed_types' => $allowedTypesInt], 'forecast[<]' => ['description' => _('Forecast for next t seconds based on period T is < N'), 'params' => $paramForecast, 'allowed_types' => $allowedTypesNumeric], 'forecast[>]' => ['description' => _('Forecast for next t seconds based on period T is > N'), 'params' => $paramForecast, 'allowed_types' => $allowedTypesNumeric], 'forecast[=]' => ['description' => _('Forecast for next t seconds based on period T is = N'), 'params' => $paramForecast, 'allowed_types' => $allowedTypesNumeric], 'forecast[<>]' => ['description' => _('Forecast for next t seconds based on period T is NOT N'), 'params' => $paramForecast, 'allowed_types' => $allowedTypesNumeric], 'timeleft[<]' => ['description' => _('Time to reach threshold estimated based on period T is < N'), 'params' => $paramTimeleft, 'allowed_types' => $allowedTypesNumeric], 'timeleft[>]' => ['description' => _('Time to reach threshold estimated based on period T is > N'), 'params' => $paramTimeleft, 'allowed_types' => $allowedTypesNumeric], 'timeleft[=]' => ['description' => _('Time to reach threshold estimated based on period T is = N'), 'params' => $paramTimeleft, 'allowed_types' => $allowedTypesNumeric], 'timeleft[<>]' => ['description' => _('Time to reach threshold estimated based on period T is NOT N'), 'params' => $paramTimeleft, 'allowed_types' => $allowedTypesNumeric]];
order_result($functions, 'description');
//	VAR		TYPE	OPTIONAL FLAGS	VALIDATION	EXCEPTION
$fields = ['dstfrm' => [T_ZBX_STR, O_MAND, P_SYS, NOT_EMPTY, null], 'dstfld1' => [T_ZBX_STR, O_MAND, P_SYS, NOT_EMPTY, null], 'expression' => [T_ZBX_STR, O_OPT, null, null, null], 'itemid' => [T_ZBX_INT, O_OPT, null, null, 'isset({insert})'], 'parent_discoveryid' => [T_ZBX_INT, O_OPT, null, null, null], 'expr_type' => [T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({insert})'], 'params' => [T_ZBX_STR, O_OPT, null, 0, null], 'paramtype' => [T_ZBX_INT, O_OPT, null, IN(PARAM_TYPE_TIME . ',' . PARAM_TYPE_COUNTS), 'isset({insert})'], 'value' => [T_ZBX_STR, O_OPT, null, NOT_EMPTY, 'isset({insert})'], 'insert' => [T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null], 'cancel' => [T_ZBX_STR, O_OPT, P_SYS, null, null]];
check_fields($fields);
$dstfrm = getRequest('dstfrm', 0);
$dstfld1 = getRequest('dstfld1', '');
$itemId = getRequest('itemid', 0);
$value = getRequest('value', 0);
$params = getRequest('params', []);
$paramType = getRequest('paramtype');
$exprType = getRequest('expr_type', 'last[=]');
// opening the popup when editing an expression in the trigger constructor
if (isset($_REQUEST['expression']) && $_REQUEST['dstfld1'] == 'expr_temp') {
    $_REQUEST['expression'] = utf8RawUrlDecode($_REQUEST['expression']);
    $expressionData = new CTriggerExpression();
    $result = $expressionData->parse(getRequest('expression'));
Ejemplo n.º 15
0
/**
 * Creates and returns the trigger overview table for the given hosts.
 *
 * @param array  $hostIds
 * @param string $application	name of application to filter
 * @param string $pageFile		the page where the element is displayed
 * @param int    $viewMode		table display style: either hosts on top, or host on the left side
 * @param string $screenId		the ID of the screen, that contains the trigger overview table
 *
 * @return CTableInfo
 */
function getTriggersOverview($hostIds, $application, $pageFile, $viewMode = null, $screenId = null)
{
    if (is_null($viewMode)) {
        $viewMode = CProfile::get('web.overview.view.style', STYLE_TOP);
    }
    // get application ids
    $applicationIds = null;
    if ($application !== '') {
        $dbApplications = API::Application()->get(array('hostids' => $hostIds, 'filter' => array('name' => $application), 'output' => array('applicationid')));
        $applicationIds = zbx_objectValues($dbApplications, 'applicationid');
        $hostIds = null;
    }
    // get triggers
    $dbTriggers = API::Trigger()->get(array('hostids' => $hostIds, 'applicationids' => $applicationIds, 'monitored' => true, 'skipDependent' => true, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => array('hostid', 'name'), 'sortfield' => 'description'));
    // get hosts
    $hostIds = array();
    foreach ($dbTriggers as $trigger) {
        $host = reset($trigger['hosts']);
        $hostIds[$host['hostid']] = $host['hostid'];
    }
    $hosts = API::Host()->get(array('output' => array('name', 'hostid', 'status'), 'hostids' => $hostIds, 'preservekeys' => true, 'selectScreens' => $viewMode == STYLE_LEFT ? API_OUTPUT_COUNT : null));
    $triggers = array();
    $hostNames = array();
    foreach ($dbTriggers as $trigger) {
        $host = reset($trigger['hosts']);
        $host['name'] = get_node_name_by_elid($host['hostid'], null, NAME_DELIMITER) . $host['name'];
        $trigger['description'] = CMacrosResolverHelper::resolveTriggerReference($trigger['expression'], $trigger['description']);
        $hostNames[$host['hostid']] = $host['name'];
        // a little tricky check for attempt to overwrite active trigger (value=1) with
        // inactive or active trigger with lower priority.
        if (!isset($triggers[$trigger['description']][$host['name']]) || ($triggers[$trigger['description']][$host['name']]['value'] == TRIGGER_VALUE_FALSE && $trigger['value'] == TRIGGER_VALUE_TRUE || ($triggers[$trigger['description']][$host['name']]['value'] == TRIGGER_VALUE_FALSE || $trigger['value'] == TRIGGER_VALUE_TRUE) && $trigger['priority'] > $triggers[$trigger['description']][$host['name']]['priority'])) {
            $triggers[$trigger['description']][$host['name']] = array('hostid' => $host['hostid'], 'triggerid' => $trigger['triggerid'], 'value' => $trigger['value'], 'lastchange' => $trigger['lastchange'], 'priority' => $trigger['priority'], 'flags' => $trigger['flags'], 'url' => $trigger['url'], 'hosts' => array($host));
        }
    }
    $triggerTable = new CTableInfo(_('No triggers found.'));
    if (empty($hostNames)) {
        return $triggerTable;
    }
    $triggerTable->makeVerticalRotation();
    order_result($hostNames);
    if ($viewMode == STYLE_TOP) {
        // header
        $header = array(new CCol(_('Triggers'), 'center'));
        foreach ($hostNames as $hostName) {
            $header[] = new CCol($hostName, 'vertical_rotation');
        }
        $triggerTable->setHeader($header, 'vertical_header');
        // data
        foreach ($triggers as $description => $triggerHosts) {
            $columns = array(nbsp($description));
            foreach ($hostNames as $hostName) {
                $columns[] = getTriggerOverviewCells(isset($triggerHosts[$hostName]) ? $triggerHosts[$hostName] : null, $pageFile, $screenId);
            }
            $triggerTable->addRow($columns);
        }
    } else {
        // header
        $header = array(new CCol(_('Host'), 'center'));
        foreach ($triggers as $description => $triggerHosts) {
            $header[] = new CCol($description, 'vertical_rotation');
        }
        $triggerTable->setHeader($header, 'vertical_header');
        // data
        $scripts = API::Script()->getScriptsByHosts(zbx_objectValues($hosts, 'hostid'));
        foreach ($hostNames as $hostId => $hostName) {
            $name = new CSpan($hostName, 'link_menu');
            $name->setMenuPopup(getMenuPopupHost($hosts[$hostId], $scripts[$hostId]));
            $columns = array($name);
            foreach ($triggers as $triggerHosts) {
                $columns[] = getTriggerOverviewCells(isset($triggerHosts[$hostName]) ? $triggerHosts[$hostName] : null, $pageFile, $screenId);
            }
            $triggerTable->addRow($columns);
        }
    }
    return $triggerTable;
}
Ejemplo n.º 16
0
                    $haystack = mb_strtolower($data['hosts'][$num]['inventory'][$data['filterField']]);
                    if ($haystack !== $needle) {
                        unset($data['hosts'][$num]);
                    }
                }
            }
            $sort_fields = ['pr_name' => 'name', 'pr_type' => 'type', 'pr_os' => 'os', 'pr_serialno_a' => 'serialno_a', 'pr_tag' => 'tag', 'pr_macaddress_a' => 'macaddress_a'];
            if (array_key_exists($sortField, $sort_fields)) {
                // copying an inventory field into the upper array level for sorting
                foreach ($data['hosts'] as &$host) {
                    $host[$sortField] = $host['inventory'][$sort_fields[$sortField]];
                }
                unset($host);
            }
            $limit = $data['config']['search_limit'] + 1;
            order_result($data['hosts'], $sortField, $sortOrder);
            if ($sortOrder == ZBX_SORT_UP) {
                $data['hosts'] = array_slice($data['hosts'], 0, $limit);
            } else {
                $data['hosts'] = array_slice($data['hosts'], -$limit, $limit);
            }
            order_result($data['hosts'], $sortField, $sortOrder);
        }
    }
    $url = (new CUrl('hostinventories.php'))->setArgument('groupid', $data['pageFilter']->groupid);
    $data['paging'] = getPagingLine($data['hosts'], $sortOrder, $url);
    $hostinventoriesView = new CView('inventory.host.list', $data);
    $hostinventoriesView->render();
    $hostinventoriesView->show();
}
require_once dirname(__FILE__) . '/include/page_footer.php';
Ejemplo n.º 17
0
function discovery_object_status2str($status = null)
{
    $discoveryStatus = [DOBJECT_STATUS_UP => _x('Up', 'discovery status'), DOBJECT_STATUS_DOWN => _x('Down', 'discovery status'), DOBJECT_STATUS_DISCOVER => _('Discovered'), DOBJECT_STATUS_LOST => _('Lost')];
    if (is_null($status)) {
        order_result($discoveryStatus);
        return $discoveryStatus;
    } elseif (isset($discoveryStatus[$status])) {
        return $discoveryStatus[$status];
    } else {
        return _('Unknown');
    }
}
Ejemplo n.º 18
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     // select_drules
     if ($options['selectDRules'] !== null && $options['selectDRules'] !== API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'dcheckid', 'druleid');
         $drules = API::DRule()->get(array('output' => $options['selectDRules'], 'druleids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
         if (!is_null($options['limitSelects'])) {
             order_result($drules, 'name');
         }
         $result = $relationMap->mapMany($result, $drules, 'drules', $options['limitSelects']);
     }
     return $result;
 }
Ejemplo n.º 19
0
    clearCookies($goResult, $_REQUEST['hostid']);
}
/*
 * Display
 */
if (isset($_REQUEST['form'])) {
    $data = getItemFormData(array('is_discovery_rule' => true));
    $data['page_header'] = _('CONFIGURATION OF DISCOVERY RULES');
    // render view
    $itemView = new CView('configuration.item.edit', $data);
    $itemView->render();
    $itemView->show();
} else {
    $data = array('hostid' => get_request('hostid', 0), 'host' => $host, 'showErrorColumn' => $host['status'] != HOST_STATUS_TEMPLATE);
    $sortfield = getPageSortField('name');
    // discoveries
    $data['discoveries'] = API::DiscoveryRule()->get(array('hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'selectItems' => API_OUTPUT_COUNT, 'selectGraphs' => API_OUTPUT_COUNT, 'selectTriggers' => API_OUTPUT_COUNT, 'selectHostPrototypes' => API_OUTPUT_COUNT, 'sortfield' => $sortfield, 'limit' => $config['search_limit'] + 1));
    $data['discoveries'] = CMacrosResolverHelper::resolveItemNames($data['discoveries']);
    if ($sortfield === 'status') {
        orderItemsByStatus($data['discoveries'], getPageSortOrder());
    } else {
        order_result($data['discoveries'], $sortfield, getPageSortOrder());
    }
    // paging
    $data['paging'] = getPagingLine($data['discoveries'], array('itemid'), array('hostid' => get_request('hostid')));
    // render view
    $discoveryView = new CView('configuration.host.discovery.list', $data);
    $discoveryView->render();
    $discoveryView->show();
}
require_once dirname(__FILE__) . '/include/page_footer.php';
Ejemplo n.º 20
0
 public function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     $itemids = array_keys($result);
     // adding applications
     if ($options['selectApplications'] !== null && $options['selectApplications'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'itemid', 'applicationid', 'items_applications');
         $applications = API::Application()->get(array('output' => $options['selectApplications'], 'applicationids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
         $result = $relationMap->mapMany($result, $applications, 'applications');
     }
     // adding interfaces
     if ($options['selectInterfaces'] !== null && $options['selectInterfaces'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'itemid', 'interfaceid');
         $interfaces = API::HostInterface()->get(array('output' => $options['selectInterfaces'], 'interfaceids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true));
         $result = $relationMap->mapMany($result, $interfaces, 'interfaces');
     }
     // adding triggers
     if (!is_null($options['selectTriggers'])) {
         if ($options['selectTriggers'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'itemid', 'triggerid', 'functions');
             $triggers = API::Trigger()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             if (!is_null($options['limitSelects'])) {
                 order_result($triggers, 'description');
             }
             $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']);
         } else {
             $triggers = API::Trigger()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids));
             $triggers = zbx_toHash($triggers, 'itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($triggers[$itemid])) {
                     $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['triggers'] = 0;
                 }
             }
         }
     }
     // adding graphs
     if (!is_null($options['selectGraphs'])) {
         if ($options['selectGraphs'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'itemid', 'graphid', 'graphs_items');
             $graphs = API::Graph()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             if (!is_null($options['limitSelects'])) {
                 order_result($graphs, 'name');
             }
             $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']);
         } else {
             $graphs = API::Graph()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids));
             $graphs = zbx_toHash($graphs, 'itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($graphs[$itemid])) {
                     $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['graphs'] = 0;
                 }
             }
         }
     }
     // adding discoveryrule
     if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) {
         $relationMap = new CRelationMap();
         // discovered items
         $dbRules = DBselect('SELECT id1.itemid,id2.parent_itemid' . ' FROM item_discovery id1,item_discovery id2,items i' . ' WHERE ' . dbConditionInt('id1.itemid', $itemids) . ' AND id1.parent_itemid=id2.itemid' . ' AND i.itemid=id1.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_CREATED);
         while ($rule = DBfetch($dbRules)) {
             $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']);
         }
         // item prototypes
         // TODO: this should not be in the item API
         $dbRules = DBselect('SELECT id.parent_itemid,id.itemid' . ' FROM item_discovery id,items i' . ' WHERE ' . dbConditionInt('id.itemid', $itemids) . ' AND i.itemid=id.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_PROTOTYPE);
         while ($rule = DBfetch($dbRules)) {
             $relationMap->addRelation($rule['itemid'], $rule['parent_itemid']);
         }
         $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true));
         $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule');
     }
     // adding item discovery
     if ($options['selectItemDiscovery'] !== null) {
         $itemDiscoveries = API::getApiService()->select('item_discovery', array('output' => $this->outputExtend($options['selectItemDiscovery'], array('itemdiscoveryid', 'itemid')), 'filter' => array('itemid' => array_keys($result)), 'preservekeys' => true));
         $relationMap = $this->createRelationMap($itemDiscoveries, 'itemid', 'itemdiscoveryid');
         $itemDiscoveries = $this->unsetExtraFields($itemDiscoveries, array('itemid', 'itemdiscoveryid'), $options['selectItemDiscovery']);
         $result = $relationMap->mapOne($result, $itemDiscoveries, 'itemDiscovery');
     }
     // adding history data
     $requestedOutput = array();
     if ($this->outputIsRequested('lastclock', $options['output'])) {
         $requestedOutput['lastclock'] = true;
     }
     if ($this->outputIsRequested('lastns', $options['output'])) {
         $requestedOutput['lastns'] = true;
     }
     if ($this->outputIsRequested('lastvalue', $options['output'])) {
         $requestedOutput['lastvalue'] = true;
     }
     if ($this->outputIsRequested('prevvalue', $options['output'])) {
         $requestedOutput['prevvalue'] = true;
     }
     if ($requestedOutput) {
         $history = Manager::History()->getLast($result, 2, ZBX_HISTORY_PERIOD);
         foreach ($result as &$item) {
             $lastHistory = isset($history[$item['itemid']][0]) ? $history[$item['itemid']][0] : null;
             $prevHistory = isset($history[$item['itemid']][1]) ? $history[$item['itemid']][1] : null;
             if (isset($requestedOutput['lastclock'])) {
                 $item['lastclock'] = $lastHistory ? $lastHistory['clock'] : '0';
             }
             if (isset($requestedOutput['lastns'])) {
                 $item['lastns'] = $lastHistory ? $lastHistory['ns'] : '0';
             }
             if (isset($requestedOutput['lastvalue'])) {
                 $item['lastvalue'] = $lastHistory ? $lastHistory['value'] : '0';
             }
             if (isset($requestedOutput['prevvalue'])) {
                 $item['prevvalue'] = $prevHistory ? $prevHistory['value'] : '0';
             }
         }
         unset($item);
     }
     return $result;
 }
$usersTable = new CTableInfo(_('No users found.'));
$usersTable->setHeader(array(new CCheckBox('all_users', null, "checkAll('" . $usersForm->getName() . "', 'all_users', 'group_userid');"), make_sorting_header(_('Alias'), 'alias', $this->data['sort'], $this->data['sortorder']), make_sorting_header(_x('Name', 'user first name'), 'name', $this->data['sort'], $this->data['sortorder']), make_sorting_header(_('Surname'), 'surname', $this->data['sort'], $this->data['sortorder']), make_sorting_header(_('User type'), 'type', $this->data['sort'], $this->data['sortorder']), _('Groups'), _('Is online?'), _('Login'), _('Frontend access'), _('Debug mode'), _('Status')));
foreach ($this->data['users'] as $user) {
    $userId = $user['userid'];
    $session = $this->data['usersSessions'][$userId];
    // online time
    if ($session['lastaccess']) {
        $onlineTime = $user['autologout'] == 0 || ZBX_USER_ONLINE_TIME < $user['autologout'] ? ZBX_USER_ONLINE_TIME : $user['autologout'];
        $online = $session['lastaccess'] + $onlineTime >= time() ? new CCol(_('Yes') . ' (' . zbx_date2str(DATE_TIME_FORMAT_SECONDS, $session['lastaccess']) . ')', 'enabled') : new CCol(_('No') . ' (' . zbx_date2str(DATE_TIME_FORMAT_SECONDS, $session['lastaccess']) . ')', 'disabled');
    } else {
        $online = new CCol(_('No'), 'disabled');
    }
    // blocked
    $blocked = $user['attempt_failed'] >= ZBX_LOGIN_ATTEMPTS ? new CLink(_('Blocked'), 'users.php?action=user.massunblock&group_userid[]=' . $userId, 'on') : new CSpan(_('Ok'), 'green');
    // user groups
    order_result($user['usrgrps'], 'name');
    $usersGroups = array();
    $i = 0;
    foreach ($user['usrgrps'] as $userGroup) {
        $i++;
        if ($i > $this->data['config']['max_in_table']) {
            $usersGroups[] = ' &hellip;';
            break;
        }
        if ($usersGroups) {
            $usersGroups[] = ', ';
        }
        $usersGroups[] = new CLink($userGroup['name'], 'usergrps.php?form=update&usrgrpid=' . $userGroup['usrgrpid'], $userGroup['gui_access'] == GROUP_GUI_ACCESS_DISABLED || $userGroup['users_status'] == GROUP_STATUS_DISABLED ? 'disabled' : 'enabled');
    }
    // user type style
    $userTypeStyle = 'enabled';
Ejemplo n.º 22
0
    // render view
    $itemView = new CView('configuration.item.prototype.edit', $data);
    $itemView->render();
    $itemView->show();
} 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);
    $config = select_config();
    $data = ['form' => getRequest('form'), 'parent_discoveryid' => getRequest('parent_discoveryid'), 'hostid' => $discoveryRule['hostid'], 'sort' => $sortField, 'sortorder' => $sortOrder];
    $data['items'] = API::ItemPrototype()->get(['discoveryids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'selectApplications' => API_OUTPUT_EXTEND, 'sortfield' => $sortField, 'limit' => $config['search_limit'] + 1]);
    foreach ($data['items'] as &$item) {
        if ($item['value_type'] == ITEM_VALUE_TYPE_STR || $item['value_type'] == ITEM_VALUE_TYPE_LOG || $item['value_type'] == ITEM_VALUE_TYPE_TEXT) {
            $item['trends'] = '';
        }
        if ($item['type'] == ITEM_TYPE_TRAPPER || $item['type'] == ITEM_TYPE_SNMPTRAP) {
            $item['delay'] = '';
        }
    }
    unset($item);
    $data['items'] = CMacrosResolverHelper::resolveItemNames($data['items']);
    order_result($data['items'], $sortField, $sortOrder);
    $url = (new CUrl('disc_prototypes.php'))->setArgument('parent_discoveryid', $data['parent_discoveryid']);
    $data['paging'] = getPagingLine($data['items'], $sortOrder, $url);
    // render view
    $itemView = new CView('configuration.item.prototype.list', $data);
    $itemView->render();
    $itemView->show();
}
require_once dirname(__FILE__) . '/include/page_footer.php';
Ejemplo n.º 23
0
 /**
  * Get Host data
  *
  * {@source}
  * @access public
  * @static
  * @since 1.8
  * @version 1
  *
  * @param _array $options
  * @param array $options['nodeids'] Node IDs
  * @param array $options['groupids'] HostGroup IDs
  * @param array $options['hostids'] Host IDs
  * @param boolean $options['monitored_hosts'] only monitored Hosts
  * @param boolean $options['templated_hosts'] include templates in result
  * @param boolean $options['with_items'] only with items
  * @param boolean $options['with_monitored_items'] only with monitored items
  * @param boolean $options['with_historical_items'] only with historical items
  * @param boolean $options['with_triggers'] only with triggers
  * @param boolean $options['with_monitored_triggers'] only with monitored triggers
  * @param boolean $options['with_httptests'] only with http tests
  * @param boolean $options['with_monitored_httptests'] only with monitored http tests
  * @param boolean $options['with_graphs'] only with graphs
  * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
  * @param int $options['extendoutput'] return all fields for Hosts
  * @param boolean $options['select_groups'] select HostGroups
  * @param boolean $options['select_templates'] select Templates
  * @param boolean $options['select_items'] select Items
  * @param boolean $options['select_triggers'] select Triggers
  * @param boolean $options['select_graphs'] select Graphs
  * @param boolean $options['select_applications'] select Applications
  * @param boolean $options['select_macros'] select Macros
  * @param boolean $options['select_profile'] select Profile
  * @param int $options['count'] count Hosts, returned column name is rowscount
  * @param string $options['pattern'] search hosts by pattern in Host name
  * @param string $options['extendPattern'] search hosts by pattern in Host name, ip and DNS
  * @param int $options['limit'] limit selection
  * @param string $options['sortfield'] field to sort by
  * @param string $options['sortorder'] sort order
  * @return array|boolean Host data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $result = array();
     $nodeCheck = false;
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $sort_columns = array('hostid', 'host', 'status', 'dns', 'ip');
     // allowed columns for sorting
     $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     // allowed output options for [ select_* ] params
     $sql_parts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'proxyids' => null, 'templateids' => null, 'itemids' => null, 'triggerids' => null, 'maintenanceids' => null, 'graphids' => null, 'dhostids' => null, 'dserviceids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'proxy_hosts' => null, 'with_items' => null, 'with_monitored_items' => null, 'with_historical_items' => null, 'with_triggers' => null, 'with_monitored_triggers' => null, 'with_httptests' => null, 'with_monitored_httptests' => null, 'with_graphs' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_groups' => null, 'selectParentTemplates' => null, 'select_items' => null, 'select_triggers' => null, 'select_graphs' => null, 'select_dhosts' => null, 'select_dservices' => null, 'select_applications' => null, 'select_macros' => null, 'select_profile' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($def_options, $options);
     if (!is_null($options['extendoutput'])) {
         $options['output'] = API_OUTPUT_EXTEND;
         if (!is_null($options['select_groups'])) {
             $options['select_groups'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['selectParentTemplates'])) {
             $options['selectParentTemplates'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_items'])) {
             $options['select_items'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_triggers'])) {
             $options['select_triggers'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_graphs'])) {
             $options['select_graphs'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_applications'])) {
             $options['select_applications'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_macros'])) {
             $options['select_macros'] = API_OUTPUT_EXTEND;
         }
     }
     if (is_array($options['output'])) {
         unset($sql_parts['select']['hosts']);
         $sql_parts['select']['hostid'] = ' h.hostid';
         foreach ($options['output'] as $key => $field) {
             $sql_parts['select'][$field] = ' h.' . $field;
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $sql_parts['where'][] = 'EXISTS (' . ' SELECT hh.hostid ' . ' FROM hosts hh, hosts_groups hgg, rights r, users_groups ug ' . ' WHERE hh.hostid=h.hostid ' . ' AND hh.hostid=hgg.hostid ' . ' AND r.id=hgg.groupid ' . ' AND r.groupid=ug.usrgrpid ' . ' AND ug.userid=' . $userid . ' AND r.permission>=' . $permission . ' AND NOT EXISTS( ' . ' SELECT hggg.groupid ' . ' FROM hosts_groups hggg, rights rr, users_groups gg ' . ' WHERE hggg.hostid=hgg.hostid ' . ' AND rr.id=hggg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . ' )) ';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         $sql_parts['where']['hostid'] = DBcondition('h.hostid', $options['hostids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('h.hostid', $nodeids);
         }
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['groupid'] = 'hg.groupid';
         }
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
         $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['groupid'] = 'hg.groupid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('hg.groupid', $nodeids);
         }
     }
     // proxyids
     if (!is_null($options['proxyids'])) {
         zbx_value2array($options['proxyids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['proxy_hostid'] = 'h.proxy_hostid';
         }
         $sql_parts['where'][] = DBcondition('h.proxy_hostid', $options['proxyids']);
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['templateid'] = 'ht.templateid';
         }
         $sql_parts['from']['hosts_templates'] = 'hosts_templates ht';
         $sql_parts['where'][] = DBcondition('ht.templateid', $options['templateids']);
         $sql_parts['where']['hht'] = 'h.hostid=ht.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['templateid'] = 'ht.templateid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('ht.templateid', $nodeids);
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['itemid'] = 'i.itemid';
         }
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where'][] = DBcondition('i.itemid', $options['itemids']);
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('i.itemid', $nodeids);
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['triggerid'] = 'f.triggerid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']);
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('f.triggerid', $nodeids);
         }
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['graphid'] = 'gi.graphid';
         }
         $sql_parts['from']['graphs_items'] = 'graphs_items gi';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where'][] = DBcondition('gi.graphid', $options['graphids']);
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('gi.graphid', $nodeids);
         }
     }
     // dhostids
     if (!is_null($options['dhostids'])) {
         zbx_value2array($options['dhostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['dhostid'] = 'ds.dhostid';
         }
         $sql_parts['from']['dservices'] = 'dservices ds';
         $sql_parts['where'][] = DBcondition('ds.dhostid', $options['dhostids']);
         $sql_parts['where']['dsh'] = 'ds.ip=h.ip';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['dhostid'] = 'ds.dhostid';
         }
     }
     // dserviceids
     if (!is_null($options['dserviceids'])) {
         zbx_value2array($options['dserviceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['dserviceid'] = 'ds.dserviceid';
         }
         $sql_parts['from']['dservices'] = 'dservices ds';
         $sql_parts['where'][] = DBcondition('ds.dserviceid', $options['dserviceids']);
         $sql_parts['where']['dsh'] = 'ds.ip=h.ip';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['dserviceid'] = 'ds.dserviceid';
         }
     }
     // maintenanceids
     if (!is_null($options['maintenanceids'])) {
         zbx_value2array($options['maintenanceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['maintenanceid'] = 'mh.maintenanceid';
         }
         $sql_parts['from']['maintenances_hosts'] = 'maintenances_hosts mh';
         $sql_parts['where'][] = DBcondition('mh.maintenanceid', $options['maintenanceids']);
         $sql_parts['where']['hmh'] = 'h.hostid=mh.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['maintenanceid'] = 'mh.maintenanceid';
         }
     }
     // node check !!!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sql_parts['where'][] = DBin_node('h.hostid', $nodeids);
     }
     // monitored_hosts, templated_hosts
     if (!is_null($options['monitored_hosts'])) {
         $sql_parts['where']['status'] = 'h.status=' . HOST_STATUS_MONITORED;
     } else {
         if (!is_null($options['templated_hosts'])) {
             $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')';
         } else {
             if (!is_null($options['proxy_hosts'])) {
                 $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')';
             } else {
                 $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')';
             }
         }
     }
     // with_items, with_monitored_items, with_historical_items
     if (!is_null($options['with_items'])) {
         $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid )';
     } else {
         if (!is_null($options['with_monitored_items'])) {
             $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND i.status=' . ITEM_STATUS_ACTIVE . ')';
         } else {
             if (!is_null($options['with_historical_items'])) {
                 $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND (i.status=' . ITEM_STATUS_ACTIVE . ' OR i.status=' . ITEM_STATUS_NOTSUPPORTED . ') AND i.lastvalue IS NOT NULL)';
             }
         }
     }
     // with_triggers, with_monitored_triggers
     if (!is_null($options['with_triggers'])) {
         $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid)';
     } else {
         if (!is_null($options['with_monitored_triggers'])) {
             $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid ' . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')';
         }
     }
     // with_httptests, with_monitored_httptests
     if (!is_null($options['with_httptests'])) {
         $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid)';
     } else {
         if (!is_null($options['with_monitored_httptests'])) {
             $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid ' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')';
         }
     }
     // with_graphs
     if (!is_null($options['with_graphs'])) {
         $sql_parts['where'][] = 'EXISTS( ' . ' SELECT DISTINCT i.itemid ' . ' FROM items i, graphs_items gi ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=gi.itemid)';
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sql_parts['select']['hosts'] = 'h.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sql_parts['select'] = array('count(DISTINCT h.hostid) as rowscount');
         //groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sql_parts['group'] as $key => $fields) {
                 $sql_parts['select'][$key] = $fields;
             }
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('hosts h', $options, $sql_parts);
     }
     // filter
     if (is_array($options['filter'])) {
         zbx_db_filter('hosts h', $options, $sql_parts);
     }
     // order
     // restrict not allowed columns for sorting
     $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : '';
     if (!zbx_empty($options['sortfield'])) {
         $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP;
         $sql_parts['order'][$options['sortfield']] = 'h.' . $options['sortfield'] . ' ' . $sortorder;
         if (!str_in_array('h.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('h.*', $sql_parts['select'])) {
             $sql_parts['select'][$options['sortfield']] = 'h.' . $options['sortfield'];
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //-------
     $hostids = array();
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['group'] = array_unique($sql_parts['group']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_group = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['group'])) {
         $sql_where .= ' GROUP BY ' . implode(',', $sql_parts['group']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_group . $sql_order;
     //SDI($sql);
     $res = DBselect($sql, $sql_limit);
     while ($host = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $host;
             } else {
                 $result = $host['rowscount'];
             }
         } else {
             $hostids[$host['hostid']] = $host['hostid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$host['hostid']] = array('hostid' => $host['hostid']);
             } else {
                 if (!isset($result[$host['hostid']])) {
                     $result[$host['hostid']] = array();
                 }
                 if (!is_null($options['select_groups']) && !isset($result[$host['hostid']]['groups'])) {
                     $result[$host['hostid']]['groups'] = array();
                 }
                 if (!is_null($options['selectParentTemplates']) && !isset($result[$host['hostid']]['parentTemplates'])) {
                     $result[$host['hostid']]['parentTemplates'] = array();
                 }
                 if (!is_null($options['select_items']) && !isset($result[$host['hostid']]['items'])) {
                     $result[$host['hostid']]['items'] = array();
                 }
                 if (!is_null($options['select_profile']) && !isset($result[$host['hostid']]['profile'])) {
                     $result[$host['hostid']]['profile'] = array();
                     $result[$host['hostid']]['profile_ext'] = array();
                 }
                 if (!is_null($options['select_triggers']) && !isset($result[$host['hostid']]['triggers'])) {
                     $result[$host['hostid']]['triggers'] = array();
                 }
                 if (!is_null($options['select_graphs']) && !isset($result[$host['hostid']]['graphs'])) {
                     $result[$host['hostid']]['graphs'] = array();
                 }
                 if (!is_null($options['select_dhosts']) && !isset($result[$host['hostid']]['dhosts'])) {
                     $result[$host['hostid']]['dhosts'] = array();
                 }
                 if (!is_null($options['select_dservices']) && !isset($result[$host['hostid']]['dservices'])) {
                     $result[$host['hostid']]['dservices'] = array();
                 }
                 if (!is_null($options['select_applications']) && !isset($result[$host['hostid']]['applications'])) {
                     $result[$host['hostid']]['applications'] = array();
                 }
                 if (!is_null($options['select_macros']) && !isset($result[$host['hostid']]['macros'])) {
                     $result[$host['hostid']]['macros'] = array();
                 }
                 //					if(!is_null($options['select_maintenances']) && !isset($result[$host['hostid']]['maintenances'])){
                 //						$result[$host['hostid']]['maintenances'] = array();
                 //					}
                 // groupids
                 if (isset($host['groupid']) && is_null($options['select_groups'])) {
                     if (!isset($result[$host['hostid']]['groups'])) {
                         $result[$host['hostid']]['groups'] = array();
                     }
                     $result[$host['hostid']]['groups'][] = array('groupid' => $host['groupid']);
                     unset($host['groupid']);
                 }
                 // templateids
                 if (isset($host['templateid'])) {
                     if (!isset($result[$host['hostid']]['templates'])) {
                         $result[$host['hostid']]['templates'] = array();
                     }
                     $result[$host['hostid']]['templates'][] = array('templateid' => $host['templateid']);
                     unset($host['templateid']);
                 }
                 // triggerids
                 if (isset($host['triggerid']) && is_null($options['select_triggers'])) {
                     if (!isset($result[$host['hostid']]['triggers'])) {
                         $result[$host['hostid']]['triggers'] = array();
                     }
                     $result[$host['hostid']]['triggers'][] = array('triggerid' => $host['triggerid']);
                     unset($host['triggerid']);
                 }
                 // itemids
                 if (isset($host['itemid']) && is_null($options['select_items'])) {
                     if (!isset($result[$host['hostid']]['items'])) {
                         $result[$host['hostid']]['items'] = array();
                     }
                     $result[$host['hostid']]['items'][] = array('itemid' => $host['itemid']);
                     unset($host['itemid']);
                 }
                 // graphids
                 if (isset($host['graphid']) && is_null($options['select_graphs'])) {
                     if (!isset($result[$host['hostid']]['graphs'])) {
                         $result[$host['hostid']]['graphs'] = array();
                     }
                     $result[$host['hostid']]['graphs'][] = array('graphid' => $host['graphid']);
                     unset($host['graphid']);
                 }
                 // dhostids
                 if (isset($host['dhostid']) && is_null($options['select_dhosts'])) {
                     if (!isset($result[$host['hostid']]['dhosts'])) {
                         $result[$host['hostid']]['dhosts'] = array();
                     }
                     $result[$host['hostid']]['dhosts'][] = array('dhostid' => $host['dhostid']);
                     unset($host['dhostid']);
                 }
                 // dserviceids
                 if (isset($host['dserviceid']) && is_null($options['select_dservices'])) {
                     if (!isset($result[$host['hostid']]['dservices'])) {
                         $result[$host['hostid']]['dservices'] = array();
                     }
                     $result[$host['hostid']]['dservices'][] = array('dserviceid' => $host['dserviceid']);
                     unset($host['dserviceid']);
                 }
                 // maintenanceids
                 if (isset($host['maintenanceid'])) {
                     if (!isset($result[$host['hostid']]['maintenanceid'])) {
                         $result[$host['hostid']]['maintenances'] = array();
                     }
                     $result[$host['hostid']]['maintenances'][] = array('maintenanceid' => $host['maintenanceid']);
                     //						unset($host['maintenanceid']);
                 }
                 //---
                 $result[$host['hostid']] += $host;
             }
         }
     }
     Copt::memoryPick();
     if (!is_null($options['countOutput'])) {
         if (is_null($options['preservekeys'])) {
             $result = zbx_cleanHashes($result);
         }
         return $result;
     }
     // Adding Objects
     // Adding Groups
     if (!is_null($options['select_groups']) && str_in_array($options['select_groups'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_groups'], 'hostids' => $hostids, 'preservekeys' => 1);
         $groups = CHostgroup::get($obj_params);
         foreach ($groups as $groupid => $group) {
             $ghosts = $group['hosts'];
             unset($group['hosts']);
             foreach ($ghosts as $num => $host) {
                 $result[$host['hostid']]['groups'][] = $group;
             }
         }
     }
     // Adding Profiles
     if (!is_null($options['select_profile'])) {
         $sql = 'SELECT hp.* ' . ' FROM hosts_profiles hp ' . ' WHERE ' . DBcondition('hp.hostid', $hostids);
         $db_profile = DBselect($sql);
         while ($profile = DBfetch($db_profile)) {
             $result[$profile['hostid']]['profile'] = $profile;
         }
         $sql = 'SELECT hpe.* ' . ' FROM hosts_profiles_ext hpe ' . ' WHERE ' . DBcondition('hpe.hostid', $hostids);
         $db_profile_ext = DBselect($sql);
         while ($profile_ext = DBfetch($db_profile_ext)) {
             $result[$profile_ext['hostid']]['profile_ext'] = $profile_ext;
         }
     }
     // Adding Templates
     if (!is_null($options['selectParentTemplates'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'preservekeys' => 1);
         if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['selectParentTemplates'];
             $templates = CTemplate::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($templates, 'host');
             }
             foreach ($templates as $templateid => $template) {
                 unset($templates[$templateid]['hosts']);
                 $count = array();
                 foreach ($template['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['parentTemplates'][] =& $templates[$templateid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['selectParentTemplates']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $templates = CTemplate::get($obj_params);
                 $templates = zbx_toHash($templates, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($templates[$hostid])) {
                         $result[$hostid]['templates'] = $templates[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['templates'] = 0;
                     }
                 }
             }
         }
     }
     // Adding Items
     if (!is_null($options['select_items'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_items']) || str_in_array($options['select_items'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_items'];
             $items = CItem::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($items, 'description');
             }
             foreach ($items as $itemid => $item) {
                 unset($items[$itemid]['hosts']);
                 foreach ($item['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['items'][] =& $items[$itemid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_items']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $items = CItem::get($obj_params);
                 $items = zbx_toHash($items, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($items[$hostid])) {
                         $result[$hostid]['items'] = $items[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['items'] = 0;
                     }
                 }
             }
         }
     }
     // Adding triggers
     if (!is_null($options['select_triggers'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_triggers']) || str_in_array($options['select_triggers'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_triggers'];
             $triggers = CTrigger::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($triggers, 'description');
             }
             foreach ($triggers as $triggerid => $trigger) {
                 unset($triggers[$triggerid]['hosts']);
                 foreach ($trigger['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['triggers'][] =& $triggers[$triggerid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_triggers']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $triggers = CTrigger::get($obj_params);
                 $triggers = zbx_toHash($triggers, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($triggers[$hostid])) {
                         $result[$hostid]['triggers'] = $triggers[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['triggers'] = 0;
                     }
                 }
             }
         }
     }
     // Adding graphs
     if (!is_null($options['select_graphs'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_graphs']) || str_in_array($options['select_graphs'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_graphs'];
             $graphs = CGraph::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($graphs, 'name');
             }
             foreach ($graphs as $graphid => $graph) {
                 unset($graphs[$graphid]['hosts']);
                 foreach ($graph['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['graphs'][] =& $graphs[$graphid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_graphs']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $graphs = CGraph::get($obj_params);
                 $graphs = zbx_toHash($graphs, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($graphs[$hostid])) {
                         $result[$hostid]['graphs'] = $graphs[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['graphs'] = 0;
                     }
                 }
             }
         }
     }
     // Adding discovery hosts
     if (!is_null($options['select_dhosts'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_dhosts']) || str_in_array($options['select_dhosts'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_dhosts'];
             $dhosts = CDHost::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($dhosts, 'dhostid');
             }
             foreach ($dhosts as $dhostid => $dhost) {
                 unset($dhosts[$dhostid]['hosts']);
                 foreach ($dhost['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['dhosts'][] =& $dhosts[$dhostid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_dhosts']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $dhosts = CDHost::get($obj_params);
                 $dhosts = zbx_toHash($dhosts, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($dhosts[$hostid])) {
                         $result[$hostid]['dhosts'] = $dhosts[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['dhosts'] = 0;
                     }
                 }
             }
         }
     }
     // Adding applications
     if (!is_null($options['select_applications'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_applications']) || str_in_array($options['select_applications'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_applications'];
             $applications = CApplication::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($applications, 'name');
             }
             foreach ($applications as $applicationid => $application) {
                 unset($applications[$applicationid]['hosts']);
                 foreach ($application['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['applications'][] =& $applications[$applicationid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_applications']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $applications = CApplication::get($obj_params);
                 $applications = zbx_toHash($applications, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($applications[$hostid])) {
                         $result[$hostid]['applications'] = $applications[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['applications'] = 0;
                     }
                 }
             }
         }
     }
     // Adding macros
     if (!is_null($options['select_macros']) && str_in_array($options['select_macros'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_macros'], 'hostids' => $hostids, 'preservekeys' => 1);
         $macros = CUserMacro::get($obj_params);
         foreach ($macros as $macroid => $macro) {
             $mhosts = $macro['hosts'];
             unset($macro['hosts']);
             foreach ($mhosts as $num => $host) {
                 $result[$host['hostid']]['macros'][] = $macro;
             }
         }
     }
     Copt::memoryPick();
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Ejemplo n.º 24
0
/*
 * Display
 */
if (isset($_REQUEST['form'])) {
    $data = ['form_refresh' => getRequest('form_refresh'), 'regexpid' => getRequest('regexpid')];
    if (isset($_REQUEST['regexpid']) && !isset($_REQUEST['form_refresh'])) {
        $regExp = DBfetch(DBSelect('SELECT re.name,re.test_string' . ' FROM regexps re' . ' WHERE re.regexpid=' . zbx_dbstr($_REQUEST['regexpid'])));
        $data['name'] = $regExp['name'];
        $data['test_string'] = $regExp['test_string'];
        $data['expressions'] = DBfetchArray(DBselect('SELECT e.expressionid,e.expression,e.expression_type,e.exp_delimiter,e.case_sensitive' . ' FROM expressions e' . ' WHERE e.regexpid=' . zbx_dbstr($_REQUEST['regexpid']) . ' ORDER BY e.expression_type'));
    } else {
        $data['name'] = getRequest('name', '');
        $data['test_string'] = getRequest('test_string', '');
        $data['expressions'] = getRequest('expressions', [['expression' => '', 'expression_type' => EXPRESSION_TYPE_INCLUDED, 'exp_delimiter' => ',', 'case_sensitive' => 0]]);
    }
    $view = new CView('administration.general.regularexpressions.edit', $data);
} else {
    $data = ['regexps' => [], 'regexpids' => []];
    $dbRegExp = DBselect('SELECT re.* FROM regexps re');
    while ($regExp = DBfetch($dbRegExp)) {
        $regExp['expressions'] = [];
        $data['regexps'][$regExp['regexpid']] = $regExp;
        $data['regexpids'][$regExp['regexpid']] = $regExp['regexpid'];
    }
    order_result($data['regexps'], 'name');
    $data['db_exps'] = DBfetchArray(DBselect('SELECT e.*' . ' FROM expressions e' . ' WHERE ' . dbConditionInt('e.regexpid', $data['regexpids']) . ' ORDER BY e.expression_type'));
    $view = new CView('administration.general.regularexpressions.list', $data);
}
$view->render();
$view->show();
require_once dirname(__FILE__) . '/include/page_footer.php';
Ejemplo n.º 25
0
        case AUDIT_ACTION_ENABLE:
            $action = _('Enabled');
            break;
        case AUDIT_ACTION_DISABLE:
            $action = _('Disabled');
            break;
        default:
            $action = _('Unknown action');
    }
    $audit['action'] = $action;
    $audit['resourcetype'] = audit_resource2str($audit['resourcetype']);
    if (empty($audit['details'])) {
        $audit['details'] = DBfetchArray(DBselect('SELECT ad.table_name,ad.field_name,ad.oldvalue,ad.newvalue' . ' FROM auditlog_details ad' . ' WHERE ad.auditid=' . zbx_dbstr($audit['auditid'])));
    }
    $data['actions'][$audit['auditid']] = $audit;
}
if (!empty($data['actions'])) {
    order_result($data['actions'], 'clock', ZBX_SORT_DOWN);
}
// get paging
$data['paging'] = getPagingLine($data['actions'], ZBX_SORT_DOWN, new CUrl('auditlogs.php'));
// get timeline
unset($sqlWhere['from'], $sqlWhere['till']);
$sql = 'SELECT MIN(a.clock) AS clock' . ' FROM auditlog a,users u' . ' WHERE a.userid=u.userid' . implode('', $sqlWhere);
$firstAudit = DBfetch(DBselect($sql, $config['search_limit'] + 1));
$data['timeline'] = ['period' => $effectivePeriod, 'starttime' => date(TIMESTAMP_FORMAT, $firstAudit ? $firstAudit['clock'] : null), 'usertime' => isset($_REQUEST['stime']) ? date(TIMESTAMP_FORMAT, zbxDateToTime($data['stime']) + $effectivePeriod) : null];
// render view
$auditView = new CView('administration.auditlogs.list', $data);
$auditView->render();
$auditView->show();
require_once dirname(__FILE__) . '/include/page_footer.php';
$hostinvent_wdgt->addItem(BR());
$table = new CTableInfo(_('No hosts defined.'));
$table->setHeader(array(make_sorting_header($groupFieldTitle === '' ? _('Field') : $groupFieldTitle, 'inventory_field'), make_sorting_header(_('Host count'), 'host_count')));
// to show a report, we will need a host group and a field to aggregate
if ($pageFilter->groupsSelected && $groupFieldTitle !== '') {
    $options = array('output' => array('hostid', 'name'), 'selectInventory' => array($_REQUEST['groupby']), 'withInventory' => true);
    if ($pageFilter->groupid > 0) {
        $options['groupids'] = $pageFilter->groupid;
    }
    $hosts = API::Host()->get($options);
    // aggregating data by chosen field value
    $report = array();
    foreach ($hosts as $host) {
        if ($host['inventory'][$_REQUEST['groupby']] !== '') {
            $lowerValue = zbx_strtolower($host['inventory'][$_REQUEST['groupby']]);
            if (!isset($report[$lowerValue])) {
                $report[$lowerValue] = array('inventory_field' => $host['inventory'][$_REQUEST['groupby']], 'host_count' => 1);
            } else {
                $report[$lowerValue]['host_count'] += 1;
            }
        }
    }
    order_result($report, getPageSortField('host_count'), getPageSortOrder());
    foreach ($report as $rep) {
        $row = array(new CSpan($rep['inventory_field'], 'pre'), new CLink($rep['host_count'], 'hostinventories.php?filter_field=' . $_REQUEST['groupby'] . '&filter_field_value=' . urlencode($rep['inventory_field']) . '&filter_set=1&filter_exact=1' . url_param('groupid')));
        $table->addRow($row);
    }
}
$hostinvent_wdgt->addItem($table);
$hostinvent_wdgt->show();
require_once dirname(__FILE__) . '/include/page_footer.php';
Ejemplo n.º 27
0
 public function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     $itemids = array_keys($result);
     // adding applications
     if ($options['selectApplications'] !== null && $options['selectApplications'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'itemid', 'applicationid', 'items_applications');
         $applications = API::Application()->get(array('output' => $options['selectApplications'], 'applicationids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
         $result = $relationMap->mapMany($result, $applications, 'applications');
     }
     // adding triggers
     if (!is_null($options['selectTriggers'])) {
         if ($options['selectTriggers'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'itemid', 'triggerid', 'functions');
             $triggers = API::TriggerPrototype()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             if (!is_null($options['limitSelects'])) {
                 order_result($triggers, 'description');
             }
             $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']);
         } else {
             $triggers = API::TriggerPrototype()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids));
             $triggers = zbx_toHash($triggers, 'itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($triggers[$itemid])) {
                     $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['triggers'] = 0;
                 }
             }
         }
     }
     // adding graphs
     if (!is_null($options['selectGraphs'])) {
         if ($options['selectGraphs'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'itemid', 'graphid', 'graphs_items');
             $graphs = API::GraphPrototype()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             if (!is_null($options['limitSelects'])) {
                 order_result($graphs, 'name');
             }
             $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']);
         } else {
             $graphs = API::GraphPrototype()->get(array('countOutput' => true, 'groupCount' => true, 'itemids' => $itemids));
             $graphs = zbx_toHash($graphs, 'itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($graphs[$itemid])) {
                     $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['graphs'] = 0;
                 }
             }
         }
     }
     // adding discoveryrule
     if ($options['selectDiscoveryRule'] !== null && $options['selectDiscoveryRule'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'itemid', 'parent_itemid', 'item_discovery');
         $discoveryRules = API::DiscoveryRule()->get(array('output' => $options['selectDiscoveryRule'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true));
         $result = $relationMap->mapOne($result, $discoveryRules, 'discoveryRule');
     }
     return $result;
 }
Ejemplo n.º 28
0
        $tr_hostids[$tr_hosts['hostid']] = $tr_hosts['hostid'];
    }
}
$scripts_by_hosts = Cscript::getScriptsByHosts($tr_hostids);
if ($show_events != EVENTS_OPTION_NOEVENT) {
    $ev_options = array('nodeids' => get_current_nodeid(), 'triggerids' => zbx_objectValues($triggers, 'triggerid'), 'nopermissions' => 1, 'output' => API_OUTPUT_EXTEND, 'time_from' => time() - $config['event_expire'] * 86400, 'time_till' => time(), 'sortfield' => 'eventid', 'sortorder' => ZBX_SORT_DOWN);
    switch ($show_events) {
        case EVENTS_OPTION_ALL:
            break;
        case EVENTS_OPTION_NOT_ACK:
            $ev_options['acknowledged'] = 0;
            $ev_options['value'] = TRIGGER_VALUE_TRUE;
            break;
    }
    $events = CEvent::get($ev_options);
    order_result($events, 'clock', ZBX_SORT_DOWN);
    foreach ($events as $enum => $event) {
        $triggers[$event['objectid']]['events'][] = $event;
    }
}
foreach ($triggers as $tnum => $trigger) {
    $trigger['desc'] = $description = expand_trigger_description($trigger['triggerid']);
    $items = array();
    $used_hosts = array();
    foreach ($trigger['hosts'] as $th) {
        $used_hosts[$th['hostid']] = $th['host'];
    }
    $used_host_count = count($used_hosts);
    foreach ($trigger['items'] as $inum => $item) {
        $item_description = item_description($item);
        //if we have items from different hosts, we must prefix a host name
Ejemplo n.º 29
0
 if ($pageFilter->hostid > 0) {
     $options['hostids'] = $pageFilter->hostid;
 } elseif ($pageFilter->groupid > 0) {
     $options['groupids'] = $pageFilter->groupid;
 }
 $httpTests = API::HttpTest()->get($options);
 $paging = getPagingLine($httpTests);
 $httpTests = API::HttpTest()->get(array('httptestids' => zbx_objectValues($httpTests, 'httptestid'), 'preservekeys' => true, 'output' => API_OUTPUT_EXTEND, 'selectHosts' => array('name', 'status'), 'selectSteps' => API_OUTPUT_COUNT));
 foreach ($httpTests as &$httpTest) {
     $httpTest['host'] = reset($httpTest['hosts']);
     $httpTest['hostname'] = $httpTest['host']['name'];
     unset($httpTest['hosts']);
 }
 unset($httpTest);
 $httpTests = resolveHttpTestMacros($httpTests, true, false);
 order_result($httpTests, getPageSortField('name'), getPageSortOrder());
 // fetch the latest results of the web scenario
 $lastHttpTestData = Manager::HttpTest()->getLastData(array_keys($httpTests));
 foreach ($httpTests as $httpTest) {
     $lastData = isset($lastHttpTestData[$httpTest['httptestid']]) ? $lastHttpTestData[$httpTest['httptestid']] : null;
     // test has history data
     if ($lastData) {
         $lastcheck = zbx_date2str(_('d M Y H:i:s'), $lastData['lastcheck']);
         if ($lastData['lastfailedstep'] != 0) {
             $step_data = get_httpstep_by_no($httpTest['httptestid'], $lastData['lastfailedstep']);
             $status['msg'] = _s('Step "%1$s" [%2$s of %3$s] failed: %4$s', $step_data['name'], $lastData['lastfailedstep'], $httpTest['steps'], $lastData['error']);
             $status['style'] = 'disabled';
         } else {
             $status['msg'] = _('OK');
             $status['style'] = 'enabled';
         }
Ejemplo n.º 30
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $this->dataId = 'discovery';
     $sort_field = $this->data['sort'];
     $sort_order = $this->data['sortorder'];
     $druleid = $this->data['druleid'];
     // discovery rules
     $options = ['output' => ['druleid', 'name'], 'selectDHosts' => ['dhostid', 'status', 'lastup', 'lastdown'], 'filter' => ['status' => DRULE_STATUS_ACTIVE]];
     if ($druleid > 0) {
         $options['druleids'] = $druleid;
         // set selected discovery rule id
     }
     $drules = API::DRule()->get($options);
     if ($drules) {
         order_result($drules, 'name');
     }
     // discovery services
     $options = ['selectHosts' => ['hostid', 'name', 'status'], 'output' => ['dserviceid', 'type', 'key_', 'port', 'status', 'lastup', 'lastdown', 'ip', 'dns'], 'sortfield' => $sort_field, 'sortorder' => $sort_order, 'limitSelects' => 1];
     if ($druleid > 0) {
         $options['druleids'] = $druleid;
     } else {
         $options['druleids'] = zbx_objectValues($drules, 'druleid');
     }
     $dservices = API::DService()->get($options);
     // user macros
     $macros = API::UserMacro()->get(['output' => ['macro', 'value'], 'globalmacro' => true]);
     $macros = zbx_toHash($macros, 'macro');
     // services
     $services = [];
     foreach ($dservices as $dservice) {
         $key_ = $dservice['key_'];
         if ($key_ !== '') {
             if (array_key_exists($key_, $macros)) {
                 $key_ = $macros[$key_]['value'];
             }
             $key_ = ': ' . $key_;
         }
         $service_name = discovery_check_type2str($dservice['type']) . discovery_port2str($dservice['type'], $dservice['port']) . $key_;
         $services[$service_name] = 1;
     }
     ksort($services);
     // discovery services to hash
     $dservices = zbx_toHash($dservices, 'dserviceid');
     // discovery hosts
     $dhosts = API::DHost()->get(['druleids' => zbx_objectValues($drules, 'druleid'), 'selectDServices' => ['dserviceid', 'ip', 'dns', 'type', 'status', 'key_'], 'output' => ['dhostid', 'lastdown', 'lastup', 'druleid']]);
     $dhosts = zbx_toHash($dhosts, 'dhostid');
     $header = [make_sorting_header(_('Discovered device'), 'ip', $sort_field, $sort_order, 'zabbix.php?action=discovery.view'), _('Monitored host'), _('Uptime') . '/' . _('Downtime')];
     foreach ($services as $name => $foo) {
         $header[] = (new CColHeader($name))->addClass('vertical_rotation');
     }
     // create table
     $table = (new CTableInfo())->makeVerticalRotation()->setHeader($header);
     foreach ($drules as $drule) {
         $discovery_info = [];
         foreach ($drule['dhosts'] as $dhost) {
             if ($dhost['status'] == DHOST_STATUS_DISABLED) {
                 $hclass = 'disabled';
                 $htime = $dhost['lastdown'];
             } else {
                 $hclass = 'enabled';
                 $htime = $dhost['lastup'];
             }
             // $primary_ip stores the primary host ip of the dhost
             $primary_ip = '';
             foreach ($dhosts[$dhost['dhostid']]['dservices'] as $dservice) {
                 $dservice = $dservices[$dservice['dserviceid']];
                 $hostName = '';
                 $host = reset($dservices[$dservice['dserviceid']]['hosts']);
                 if (!is_null($host)) {
                     $hostName = $host['name'];
                 }
                 if ($primary_ip !== '') {
                     if ($primary_ip === $dservice['ip']) {
                         $htype = 'primary';
                     } else {
                         $htype = 'slave';
                     }
                 } else {
                     $primary_ip = $dservice['ip'];
                     $htype = 'primary';
                 }
                 if (!array_key_exists($dservice['ip'], $discovery_info)) {
                     $discovery_info[$dservice['ip']] = ['ip' => $dservice['ip'], 'dns' => $dservice['dns'], 'type' => $htype, 'class' => $hclass, 'host' => $hostName, 'time' => $htime];
                 }
                 if ($dservice['status'] == DSVC_STATUS_DISABLED) {
                     $class = ZBX_STYLE_INACTIVE_BG;
                     $time = 'lastdown';
                 } else {
                     $class = ZBX_STYLE_ACTIVE_BG;
                     $time = 'lastup';
                 }
                 $key_ = $dservice['key_'];
                 if ($key_ !== '') {
                     if (array_key_exists($key_, $macros)) {
                         $key_ = $macros[$key_]['value'];
                     }
                     $key_ = NAME_DELIMITER . $key_;
                 }
                 $service_name = discovery_check_type2str($dservice['type']) . discovery_port2str($dservice['type'], $dservice['port']) . $key_;
                 $discovery_info[$dservice['ip']]['services'][$service_name] = ['class' => $class, 'time' => $dservice[$time]];
             }
         }
         if ($druleid == 0 && $discovery_info) {
             $col = new CCol([bold($drule['name']), SPACE . '(' . _n('%d device', '%d devices', count($discovery_info)) . ')']);
             $col->setColSpan(count($services) + 3);
             $table->addRow($col);
         }
         order_result($discovery_info, $sort_field, $sort_order);
         foreach ($discovery_info as $ip => $h_data) {
             $dns = $h_data['dns'] == '' ? '' : ' (' . $h_data['dns'] . ')';
             $row = [$h_data['type'] == 'primary' ? (new CSpan($ip . $dns))->addClass($h_data['class']) : new CSpan(SPACE . SPACE . $ip . $dns), new CSpan(array_key_exists('host', $h_data) ? $h_data['host'] : ''), (new CSpan($h_data['time'] == 0 || $h_data['type'] === 'slave' ? '' : convert_units(['value' => time() - $h_data['time'], 'units' => 'uptime'])))->addClass($h_data['class'])];
             foreach ($services as $name => $foo) {
                 $class = null;
                 $time = SPACE;
                 $hint = (new CDiv(SPACE))->addClass($class);
                 $hint_table = null;
                 if (array_key_exists($name, $h_data['services'])) {
                     $class = $h_data['services'][$name]['class'];
                     $time = $h_data['services'][$name]['time'];
                     $hint_table = (new CTableInfo())->setAttribute('style', 'width: auto;');
                     if ($class == ZBX_STYLE_ACTIVE_BG) {
                         $hint_table->setHeader(_('Uptime'));
                     } else {
                         $hint_table->setHeader(_('Downtime'));
                     }
                     $hint_table->addRow((new CCol(zbx_date2age($h_data['services'][$name]['time'])))->addClass($class));
                 }
                 $column = (new CCol($hint))->addClass($class);
                 if (!is_null($hint_table)) {
                     $column->setHint($hint_table);
                 }
                 $row[] = $column;
             }
             $table->addRow($row);
         }
     }
     return $this->getOutput($table, true, $this->data);
 }