/**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     // fetch hosts
     $hosts = API::Host()->get(['output' => ['hostid', 'status'], 'selectGraphs' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'selectScreens' => $this->screenitem['style'] == STYLE_LEFT ? API_OUTPUT_COUNT : null, 'groupids' => $this->screenitem['resourceid'], 'preservekeys' => true]);
     $hostids = array_keys($hosts);
     $options = ['output' => ['triggerid', 'expression', 'description', 'url', 'value', 'priority', 'lastchange', 'flags'], 'selectHosts' => ['hostid', 'name', 'status'], 'selectItems' => ['itemid', 'hostid', 'name', 'key_', 'value_type'], 'hostids' => $hostids, 'monitored' => true, 'skipDependent' => true, 'sortfield' => 'description', 'preservekeys' => true];
     // application filter
     if ($this->screenitem['application'] !== '') {
         $applications = API::Application()->get(['output' => [], 'hostids' => $hostids, 'search' => ['name' => $this->screenitem['application']], 'preservekeys' => true]);
         $options['applicationids'] = array_keys($applications);
     }
     $triggers = API::Trigger()->get($options);
     $triggers = CMacrosResolverHelper::resolveTriggerUrls($triggers);
     /*
      * Each screen cell with "Triggers overview" depends on one specific group which in this case is 'resourceid'.
      * Pass it as 'groupid' to menu pop-up "Events" link.
      */
     foreach ($triggers as &$trigger) {
         $trigger['groupid'] = $this->screenitem['resourceid'];
     }
     unset($trigger);
     $groups = API::HostGroup()->get(['output' => ['name'], 'groupids' => [$this->screenitem['resourceid']]]);
     $header = (new CDiv([new CTag('h4', true, _('Triggers overview')), (new CList())->addItem([_('Group'), ':', SPACE, $groups[0]['name']])]))->addClass(ZBX_STYLE_DASHBRD_WIDGET_HEAD);
     $table = getTriggersOverview($hosts, $triggers, $this->pageFile, $this->screenitem['style'], $this->screenid);
     $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT);
     return $this->getOutput(new CUiWidget(uniqid(), [$header, $table, $footer]));
 }
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     // if screen is defined in template, then 'real_resourceid' is defined and should be used
     if (!empty($this->screenitem['real_resourceid'])) {
         $this->screenitem['resourceid'] = $this->screenitem['real_resourceid'];
     }
     if ($this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM && !empty($this->hostid)) {
         $newitemid = get_same_item_for_host($this->screenitem['resourceid'], $this->hostid);
         $this->screenitem['resourceid'] = !empty($newitemid) ? $newitemid : 0;
     }
     if ($this->screenitem['resourceid'] == 0) {
         $table = (new CTableInfo())->setHeader([_('Timestamp'), _('Item')]);
         return $this->getOutput($table);
     }
     $items = CMacrosResolverHelper::resolveItemNames([get_item_by_itemid($this->screenitem['resourceid'])]);
     $item = reset($items);
     switch ($item['value_type']) {
         case ITEM_VALUE_TYPE_TEXT:
         case ITEM_VALUE_TYPE_LOG:
             $orderField = 'id';
             break;
         case ITEM_VALUE_TYPE_FLOAT:
         case ITEM_VALUE_TYPE_UINT64:
         default:
             $orderField = ['itemid', 'clock'];
     }
     $host = get_host_by_itemid($this->screenitem['resourceid']);
     $table = (new CTableInfo())->setHeader([_('Timestamp'), _('Value')]);
     $stime = zbxDateToTime($this->timeline['stime']);
     $histories = API::History()->get(['history' => $item['value_type'], 'itemids' => $this->screenitem['resourceid'], 'output' => API_OUTPUT_EXTEND, 'sortorder' => ZBX_SORT_DOWN, 'sortfield' => $orderField, 'limit' => $this->screenitem['elements'], 'time_from' => $stime, 'time_till' => $stime + $this->timeline['period']]);
     foreach ($histories as $history) {
         switch ($item['value_type']) {
             case ITEM_VALUE_TYPE_FLOAT:
                 sscanf($history['value'], '%f', $value);
                 break;
             case ITEM_VALUE_TYPE_TEXT:
             case ITEM_VALUE_TYPE_STR:
             case ITEM_VALUE_TYPE_LOG:
                 $value = $this->screenitem['style'] ? new CJsScript($history['value']) : $history['value'];
                 break;
             default:
                 $value = $history['value'];
                 break;
         }
         if ($item['valuemapid'] > 0) {
             $value = applyValueMap($value, $item['valuemapid']);
         }
         if ($this->screenitem['style'] == 0) {
             $value = new CPre($value);
         }
         $table->addRow([zbx_date2str(DATE_TIME_FORMAT_SECONDS, $history['clock']), $value]);
     }
     $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT);
     return $this->getOutput((new CUiWidget(uniqid(), [$table, $footer]))->setHeader($host['name'] . NAME_DELIMITER . $item['name_expanded']));
 }
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     // if screen is defined in template, then 'real_resourceid' is defined and should be used
     if (!empty($this->screenitem['real_resourceid'])) {
         $this->screenitem['resourceid'] = $this->screenitem['real_resourceid'];
     }
     if ($this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM && !empty($this->hostid)) {
         $newitemid = get_same_item_for_host($this->screenitem['resourceid'], $this->hostid);
         $this->screenitem['resourceid'] = !empty($newitemid) ? $newitemid : 0;
     }
     if ($this->screenitem['resourceid'] == 0) {
         $table = new CTableInfo(_('No values found.'));
         $table->setHeader(array(_('Timestamp'), _('Item')));
         return $this->getOutput($table);
     }
     $items = CMacrosResolverHelper::resolveItemNames(array(get_item_by_itemid($this->screenitem['resourceid'])));
     $item = reset($items);
     switch ($item['value_type']) {
         case ITEM_VALUE_TYPE_TEXT:
         case ITEM_VALUE_TYPE_LOG:
             $orderField = 'id';
             break;
         case ITEM_VALUE_TYPE_FLOAT:
         case ITEM_VALUE_TYPE_UINT64:
         default:
             $orderField = array('itemid', 'clock');
     }
     $host = get_host_by_itemid($this->screenitem['resourceid']);
     $table = new CTableInfo(_('No values found.'));
     $table->setHeader(array(_('Timestamp'), $host['name'] . NAME_DELIMITER . $item['name_expanded']));
     $stime = zbxDateToTime($this->timeline['stime']);
     $histories = API::History()->get(array('history' => $item['value_type'], 'itemids' => $this->screenitem['resourceid'], 'output' => API_OUTPUT_EXTEND, 'sortorder' => ZBX_SORT_DOWN, 'sortfield' => $orderField, 'limit' => $this->screenitem['elements'], 'time_from' => $stime, 'time_till' => $stime + $this->timeline['period']));
     foreach ($histories as $history) {
         switch ($item['value_type']) {
             case ITEM_VALUE_TYPE_FLOAT:
                 sscanf($history['value'], '%f', $value);
                 break;
             case ITEM_VALUE_TYPE_TEXT:
             case ITEM_VALUE_TYPE_STR:
             case ITEM_VALUE_TYPE_LOG:
                 $value = $this->screenitem['style'] ? new CJsScript($history['value']) : $history['value'];
                 break;
             default:
                 $value = $history['value'];
                 break;
         }
         if ($item['valuemapid'] > 0) {
             $value = applyValueMap($value, $item['valuemapid']);
         }
         $class = $this->screenitem['style'] ? null : 'pre';
         $table->addRow(array(zbx_date2str(DATE_TIME_FORMAT_SECONDS, $history['clock']), new CCol($value, $class)));
     }
     return $this->getOutput($table);
 }
Example #4
0
 public function addItem($itemid, $calc_fnc = CALC_FNC_AVG, $color = null, $type = null)
 {
     $items = CMacrosResolverHelper::resolveItemNames(array(get_item_by_itemid($itemid)));
     $this->items[$this->num] = reset($items);
     $host = get_host_by_hostid($this->items[$this->num]['hostid']);
     $this->items[$this->num]['host'] = $host['host'];
     $this->items[$this->num]['hostname'] = $host['name'];
     $this->items[$this->num]['color'] = is_null($color) ? 'Dark Green' : $color;
     $this->items[$this->num]['calc_fnc'] = is_null($calc_fnc) ? CALC_FNC_AVG : $calc_fnc;
     $this->items[$this->num]['calc_type'] = is_null($type) ? GRAPH_ITEM_SIMPLE : $type;
     $this->num++;
 }
Example #5
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     // prevent from resolving macros in configuration page
     if ($this->mode != SCREEN_MODE_PREVIEW && $this->mode != SCREEN_MODE_SLIDESHOW) {
         return $this->getOutput(new CIFrame($this->screenitem['url'], $this->screenitem['width'], $this->screenitem['height'], 'auto'));
     } elseif ($this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM && $this->hostid == 0) {
         return $this->getOutput((new CTableInfo())->setNoDataMessage(_('No host selected.')));
     }
     $resolveHostMacros = $this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM || $this->isTemplatedScreen;
     $url = CMacrosResolverHelper::resolveScreenElementURL(['config' => $resolveHostMacros ? 'screenElementURL' : 'screenElementURLUser', 'url' => $this->screenitem['url'], 'hostid' => $resolveHostMacros ? $this->hostid : 0]);
     $this->screenitem['url'] = $url ? $url : $this->screenitem['url'];
     return $this->getOutput(new CIFrame($this->screenitem['url'], $this->screenitem['width'], $this->screenitem['height'], 'auto'));
 }
Example #6
0
 /**
  * Prepare data for favourite graphs menu popup.
  *
  * @return array
  */
 public static function getFavouriteGraphs()
 {
     $graphs = $simpeGraphs = array();
     $favourites = CFavorite::get('web.favorite.graphids');
     if ($favourites) {
         $graphIds = $itemIds = $dbGraphs = $dbItems = array();
         foreach ($favourites as $favourite) {
             if ($favourite['source'] === 'itemid') {
                 $itemIds[$favourite['value']] = $favourite['value'];
             } else {
                 $graphIds[$favourite['value']] = $favourite['value'];
             }
         }
         if ($graphIds) {
             $dbGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'selectHosts' => array('hostid', 'host'), 'expandName' => true, 'graphids' => $graphIds, 'preservekeys' => true));
         }
         if ($itemIds) {
             $dbItems = API::Item()->get(array('output' => array('itemid', 'hostid', 'name', 'key_'), 'selectHosts' => array('hostid', 'host'), 'itemids' => $itemIds, 'webitems' => true, 'preservekeys' => true));
             $dbItems = CMacrosResolverHelper::resolveItemNames($dbItems);
         }
         foreach ($favourites as $favourite) {
             $sourceId = $favourite['value'];
             if ($favourite['source'] === 'itemid') {
                 if (isset($dbItems[$sourceId])) {
                     $dbItem = $dbItems[$sourceId];
                     $dbHost = reset($dbItem['hosts']);
                     $simpeGraphs[] = array('id' => $sourceId, 'label' => $dbHost['host'] . NAME_DELIMITER . $dbItem['name_expanded']);
                 }
             } else {
                 if (isset($dbGraphs[$sourceId])) {
                     $dbGraph = $dbGraphs[$sourceId];
                     $dbHost = reset($dbGraph['hosts']);
                     $graphs[] = array('id' => $sourceId, 'label' => $dbHost['host'] . NAME_DELIMITER . $dbGraph['name']);
                 }
             }
         }
     }
     return array('type' => 'favouriteGraphs', 'graphs' => $graphs, 'simpleGraphs' => $simpeGraphs);
 }
 /**
  * Retrieves items created for item prototype given as resource for this screen item
  * and returns array of the item IDs, ordered by item name.
  *
  * @return array
  */
 protected function getCreatedItemIds()
 {
     if (!$this->createdItemIds) {
         $itemPrototype = $this->getItemPrototype();
         if ($itemPrototype) {
             // get all created (discovered) items for current host
             $allCreatedItems = API::Item()->get(array('output' => array('itemid', 'name', 'key_', 'hostid'), 'hostids' => array($itemPrototype['discoveryRule']['hostid']), 'selectItemDiscovery' => array('itemid', 'parent_itemid'), 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_CREATED)));
             // collect those items where parent item is item prototype selected for this screen item as resource
             $createdItems = array();
             foreach ($allCreatedItems as $item) {
                 if ($item['itemDiscovery']['parent_itemid'] == $itemPrototype['itemid']) {
                     $createdItems[] = $item;
                 }
             }
             $createdItems = CMacrosResolverHelper::resolveItemNames($createdItems);
             foreach ($createdItems as $item) {
                 $this->createdItemIds[$item['itemid']] = $item['name_expanded'];
             }
             natsort($this->createdItemIds);
             $this->createdItemIds = array_keys($this->createdItemIds);
         }
     }
     return $this->createdItemIds;
 }
Example #8
0
/**
 * Create DIV with latest problem triggers.
 *
 * If no sortfield and sortorder are defined, the sort indicater in the column name will not be displayed.
 *
 * @param array  $filter['screenid']
 * @param array  $filter['groupids']
 * @param array  $filter['hostids']
 * @param array  $filter['maintenance']
 * @param int    $filter['extAck']
 * @param int    $filter['severity']
 * @param int    $filter['limit']
 * @param string $filter['sortfield']
 * @param string $filter['sortorder']
 * @param string $filter['backUrl']
 *
 * @return CDiv
 */
function make_latest_issues(array $filter = array())
{
    // hide the sort indicator if no sortfield and sortorder are given
    $showSortIndicator = isset($filter['sortfield']) || isset($filter['sortorder']);
    if (!isset($filter['sortfield'])) {
        $filter['sortfield'] = 'lastchange';
    }
    if (!isset($filter['sortorder'])) {
        $filter['sortorder'] = ZBX_SORT_DOWN;
    }
    $options = array('groupids' => $filter['groupids'], 'hostids' => isset($filter['hostids']) ? $filter['hostids'] : null, 'monitored' => true, 'maintenance' => $filter['maintenance'], 'filter' => array('priority' => $filter['severity'], 'value' => TRIGGER_VALUE_TRUE));
    $triggers = API::Trigger()->get(array_merge($options, array('withLastEventUnacknowledged' => isset($filter['extAck']) && $filter['extAck'] == EXTACK_OPTION_UNACK ? true : null, 'skipDependent' => true, 'output' => array('triggerid', 'state', 'error', 'url', 'expression', 'description', 'priority', 'lastchange'), 'selectHosts' => array('hostid', 'name'), 'selectLastEvent' => array('eventid', 'acknowledged', 'objectid', 'clock', 'ns'), 'sortfield' => $filter['sortfield'], 'sortorder' => $filter['sortorder'], 'limit' => isset($filter['limit']) ? $filter['limit'] : DEFAULT_LATEST_ISSUES_CNT)));
    // don't use withLastEventUnacknowledged and skipDependent because of performance issues
    $triggersTotalCount = API::Trigger()->get(array_merge($options, array('countOutput' => true)));
    // get acknowledges
    $eventIds = array();
    foreach ($triggers as $trigger) {
        if ($trigger['lastEvent']) {
            $eventIds[] = $trigger['lastEvent']['eventid'];
        }
    }
    if ($eventIds) {
        $eventAcknowledges = API::Event()->get(array('eventids' => $eventIds, 'select_acknowledges' => API_OUTPUT_EXTEND, 'preservekeys' => true));
    }
    foreach ($triggers as $tnum => $trigger) {
        // if trigger is lost (broken expression) we skip it
        if (empty($trigger['hosts'])) {
            unset($triggers[$tnum]);
            continue;
        }
        $host = reset($trigger['hosts']);
        $trigger['hostid'] = $host['hostid'];
        $trigger['hostname'] = $host['name'];
        if ($trigger['lastEvent']) {
            $trigger['lastEvent']['acknowledges'] = isset($eventAcknowledges[$trigger['lastEvent']['eventid']]) ? $eventAcknowledges[$trigger['lastEvent']['eventid']]['acknowledges'] : null;
        }
        $triggers[$tnum] = $trigger;
    }
    $hostIds = zbx_objectValues($triggers, 'hostid');
    // get hosts
    $hosts = API::Host()->get(array('hostids' => $hostIds, 'output' => array('hostid', 'name', 'status', 'maintenance_status', 'maintenance_type', 'maintenanceid'), 'selectScreens' => API_OUTPUT_COUNT, 'preservekeys' => true));
    // actions
    $actions = getEventActionsStatHints($eventIds);
    // ack params
    $ackParams = isset($filter['screenid']) ? array('screenid' => $filter['screenid']) : array();
    $config = select_config();
    // indicator of sort field
    if ($showSortIndicator) {
        $sortDiv = new CDiv(SPACE, $filter['sortorder'] === ZBX_SORT_DOWN ? 'icon_sortdown default_cursor' : 'icon_sortup default_cursor');
        $sortDiv->addStyle('float: left');
        $hostHeaderDiv = new CDiv(array(_('Host'), SPACE));
        $hostHeaderDiv->addStyle('float: left');
        $issueHeaderDiv = new CDiv(array(_('Issue'), SPACE));
        $issueHeaderDiv->addStyle('float: left');
        $lastChangeHeaderDiv = new CDiv(array(_('Time'), SPACE));
        $lastChangeHeaderDiv->addStyle('float: left');
    }
    $table = new CTableInfo(_('No events found.'));
    $table->setHeader(array(is_show_all_nodes() ? _('Node') : null, $showSortIndicator && $filter['sortfield'] === 'hostname' ? array($hostHeaderDiv, $sortDiv) : _('Host'), $showSortIndicator && $filter['sortfield'] === 'priority' ? array($issueHeaderDiv, $sortDiv) : _('Issue'), $showSortIndicator && $filter['sortfield'] === 'lastchange' ? array($lastChangeHeaderDiv, $sortDiv) : _('Last change'), _('Age'), _('Info'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions')));
    $scripts = API::Script()->getScriptsByHosts($hostIds);
    // triggers
    foreach ($triggers as $trigger) {
        $host = $hosts[$trigger['hostid']];
        $hostName = new CSpan($host['name'], 'link_menu');
        $hostName->setMenuPopup(getMenuPopupHost($host, $scripts[$host['hostid']]));
        // add maintenance icon with hint if host is in maintenance
        $maintenanceIcon = null;
        if ($host['maintenance_status']) {
            $maintenanceIcon = new CDiv(null, 'icon-maintenance-abs');
            // get maintenance
            $maintenances = API::Maintenance()->get(array('maintenanceids' => $host['maintenanceid'], 'output' => API_OUTPUT_EXTEND, 'limit' => 1));
            if ($maintenance = reset($maintenances)) {
                $hint = $maintenance['name'] . ' [' . ($host['maintenance_type'] ? _('Maintenance without data collection') : _('Maintenance with data collection')) . ']';
                if (isset($maintenance['description'])) {
                    // double quotes mandatory
                    $hint .= "\n" . $maintenance['description'];
                }
                $maintenanceIcon->setHint($hint);
                $maintenanceIcon->addClass('pointer');
            }
            $hostName->addClass('left-to-icon-maintenance-abs');
        }
        $hostDiv = new CDiv(array($hostName, $maintenanceIcon), 'maintenance-abs-cont');
        // unknown triggers
        $unknown = SPACE;
        if ($trigger['state'] == TRIGGER_STATE_UNKNOWN) {
            $unknown = new CDiv(SPACE, 'status_icon iconunknown');
            $unknown->setHint($trigger['error'], '', 'on');
        }
        // trigger has events
        if ($trigger['lastEvent']) {
            // description
            $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['lastEvent']['clock'], 'ns' => $trigger['lastEvent']['ns'])));
            // ack
            $ack = getEventAckState($trigger['lastEvent'], empty($filter['backUrl']) ? true : $filter['backUrl'], true, $ackParams);
        } else {
            // description
            $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['lastchange'], 'ns' => '999999999')));
            // ack
            $ack = new CSpan(_('No events'), 'unknown');
        }
        // description
        if (!zbx_empty($trigger['url'])) {
            $description = new CLink($description, resolveTriggerUrl($trigger), null, null, true);
        } else {
            $description = new CSpan($description, 'pointer');
        }
        $description = new CCol($description, getSeverityStyle($trigger['priority']));
        if ($trigger['lastEvent']) {
            $description->setHint(make_popup_eventlist($trigger['triggerid'], $trigger['lastEvent']['eventid']), '', '', false);
        }
        // clock
        $clock = new CLink(zbx_date2str(_('d M Y H:i:s'), $trigger['lastchange']), 'events.php?triggerid=' . $trigger['triggerid'] . '&source=0&show_unknown=1&nav_time=' . $trigger['lastchange']);
        // actions
        $actionHint = $trigger['lastEvent'] && isset($actions[$trigger['lastEvent']['eventid']]) ? $actions[$trigger['lastEvent']['eventid']] : SPACE;
        $table->addRow(array(get_node_name_by_elid($trigger['triggerid']), $hostDiv, $description, $clock, zbx_date2age($trigger['lastchange']), $unknown, $ack, $actionHint));
    }
    // initialize blinking
    zbx_add_post_js('jqBlink.blink();');
    $script = new CJSScript(get_js("jQuery('#hat_lastiss_footer').html('" . _s('Updated: %s', zbx_date2str(_('H:i:s'))) . "')"));
    $infoDiv = new CDiv(_n('%1$d of %2$d issue is shown', '%1$d of %2$d issues are shown', count($triggers), $triggersTotalCount));
    $infoDiv->addStyle('text-align: right; padding-right: 3px;');
    return new CDiv(array($table, $infoDiv, $script));
}
Example #9
0
function drawMapLabels(&$im, $map, $mapInfo, $resolveMacros = true)
{
    global $colors;
    if ($map['label_type'] == MAP_LABEL_TYPE_NOTHING && $map['label_format'] == SYSMAP_LABEL_ADVANCED_OFF) {
        return;
    }
    $selements = $map['selements'];
    $allStrings = '';
    $labelLines = array();
    $statusLines = array();
    foreach ($selements as $sid => $selement) {
        if (isset($selement['elementsubtype']) && $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS) {
            unset($selements[$sid]);
        }
    }
    // set label type and custom label text for all selements
    foreach ($selements as $selementId => $selement) {
        $selements[$selementId]['label_type'] = $map['label_type'];
        if ($map['label_format'] == SYSMAP_LABEL_ADVANCED_OFF) {
            continue;
        }
        switch ($selement['elementtype']) {
            case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
                $selements[$selementId]['label_type'] = $map['label_type_hostgroup'];
                if ($map['label_type_hostgroup'] == MAP_LABEL_TYPE_CUSTOM) {
                    $selements[$selementId]['label'] = $map['label_string_hostgroup'];
                }
                break;
            case SYSMAP_ELEMENT_TYPE_HOST:
                $selements[$selementId]['label_type'] = $map['label_type_host'];
                if ($map['label_type_host'] == MAP_LABEL_TYPE_CUSTOM) {
                    $selements[$selementId]['label'] = $map['label_string_host'];
                }
                break;
            case SYSMAP_ELEMENT_TYPE_TRIGGER:
                $selements[$selementId]['label_type'] = $map['label_type_trigger'];
                if ($map['label_type_trigger'] == MAP_LABEL_TYPE_CUSTOM) {
                    $selements[$selementId]['label'] = $map['label_string_trigger'];
                }
                break;
            case SYSMAP_ELEMENT_TYPE_MAP:
                $selements[$selementId]['label_type'] = $map['label_type_map'];
                if ($map['label_type_map'] == MAP_LABEL_TYPE_CUSTOM) {
                    $selements[$selementId]['label'] = $map['label_string_map'];
                }
                break;
            case SYSMAP_ELEMENT_TYPE_IMAGE:
                $selements[$selementId]['label_type'] = $map['label_type_image'];
                if ($map['label_type_image'] == MAP_LABEL_TYPE_CUSTOM) {
                    $selements[$selementId]['label'] = $map['label_string_image'];
                }
                break;
        }
    }
    foreach ($selements as $selementId => $selement) {
        if (!isset($labelLines[$selementId])) {
            $labelLines[$selementId] = array();
        }
        if (!isset($statusLines[$selementId])) {
            $statusLines[$selementId] = array();
        }
        $msg = $resolveMacros ? CMacrosResolverHelper::resolveMapLabelMacrosAll($selement) : $selement['label'];
        $allStrings .= $msg;
        $msgs = explode("\n", $msg);
        foreach ($msgs as $msg) {
            $labelLines[$selementId][] = array('msg' => $msg);
        }
        $elementInfo = $mapInfo[$selementId];
        foreach (array('problem', 'unack', 'maintenance', 'ok', 'status') as $caption) {
            if (!isset($elementInfo['info'][$caption]) || zbx_empty($elementInfo['info'][$caption]['msg'])) {
                continue;
            }
            $statusLines[$selementId][] = array('msg' => $elementInfo['info'][$caption]['msg'], 'color' => $elementInfo['info'][$caption]['color']);
            $allStrings .= $elementInfo['info'][$caption]['msg'];
        }
    }
    $allLabelsSize = imageTextSize(8, 0, str_replace("\r", '', str_replace("\n", '', $allStrings)));
    $labelFontHeight = $allLabelsSize['height'];
    $labelFontBaseline = $allLabelsSize['baseline'];
    $elementsHostIds = array();
    foreach ($selements as $selement) {
        if ($selement['label_type'] != MAP_LABEL_TYPE_IP) {
            continue;
        }
        if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST) {
            $elementsHostIds[] = $selement['elementid'];
        }
    }
    if (!empty($elementsHostIds)) {
        $mapHosts = API::Host()->get(array('hostids' => $elementsHostIds, 'output' => array('hostid'), 'selectInterfaces' => API_OUTPUT_EXTEND));
        $mapHosts = zbx_toHash($mapHosts, 'hostid');
    }
    // draw
    foreach ($selements as $selementId => $selement) {
        if (empty($selement) || $selement['label_type'] == MAP_LABEL_TYPE_NOTHING) {
            continue;
        }
        $elementInfo = $mapInfo[$selementId];
        $hl_color = null;
        $st_color = null;
        if (!isset($_REQUEST['noselements']) && $map['highlight'] % 2 == SYSMAP_HIGHLIGHT_ON) {
            if ($elementInfo['icon_type'] == SYSMAP_ELEMENT_ICON_ON) {
                $hl_color = true;
            }
            if ($elementInfo['icon_type'] == SYSMAP_ELEMENT_ICON_MAINTENANCE) {
                $st_color = true;
            }
            if ($elementInfo['icon_type'] == SYSMAP_ELEMENT_ICON_DISABLED) {
                $st_color = true;
            }
        }
        if (in_array($selement['elementtype'], array(SYSMAP_ELEMENT_TYPE_HOST_GROUP, SYSMAP_ELEMENT_TYPE_MAP)) && !is_null($hl_color)) {
            $st_color = null;
        } elseif (!is_null($st_color)) {
            $hl_color = null;
        }
        $labelLocation = is_null($selement['label_location']) || $selement['label_location'] < 0 ? $map['label_location'] : $selement['label_location'];
        $label = array();
        if ($selement['label_type'] == MAP_LABEL_TYPE_IP && $selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST) {
            $interface = reset($mapHosts[$selement['elementid']]['interfaces']);
            $label[] = array('msg' => $interface['ip']);
            $label = array_merge($label, $statusLines[$selementId]);
        } elseif ($selement['label_type'] == MAP_LABEL_TYPE_STATUS) {
            $label = $statusLines[$selementId];
        } elseif ($selement['label_type'] == MAP_LABEL_TYPE_NAME) {
            $label[] = array('msg' => $elementInfo['name']);
            $label = array_merge($label, $statusLines[$selementId]);
        } else {
            $label = array_merge($labelLines[$selementId], $statusLines[$selementId]);
        }
        if (empty($label)) {
            continue;
        }
        $w = 0;
        foreach ($label as $str) {
            $dims = imageTextSize(8, 0, $str['msg']);
            $w = max($w, $dims['width']);
        }
        $h = count($label) * $labelFontHeight;
        $x = $selement['x'];
        $y = $selement['y'];
        $image = get_png_by_selement($elementInfo);
        $iconX = imagesx($image);
        $iconY = imagesy($image);
        if (!is_null($hl_color)) {
            $icon_hl = 14;
        } elseif (!is_null($st_color)) {
            $icon_hl = 6;
        } else {
            $icon_hl = 2;
        }
        switch ($labelLocation) {
            case MAP_LABEL_LOC_TOP:
                $y_rec = $y - $icon_hl - $h - 6;
                $x_rec = $x + $iconX / 2 - $w / 2;
                break;
            case MAP_LABEL_LOC_LEFT:
                $y_rec = $y - $h / 2 + $iconY / 2;
                $x_rec = $x - $icon_hl - $w;
                break;
            case MAP_LABEL_LOC_RIGHT:
                $y_rec = $y - $h / 2 + $iconY / 2;
                $x_rec = $x + $iconX + $icon_hl;
                break;
            case MAP_LABEL_LOC_BOTTOM:
            default:
                $y_rec = $y + $iconY + $icon_hl;
                $x_rec = $x + $iconX / 2 - $w / 2;
        }
        $increasey = 12;
        foreach ($label as $line) {
            if (zbx_empty($line['msg'])) {
                continue;
            }
            $str = str_replace("\r", '', $line['msg']);
            $color = isset($line['color']) ? $line['color'] : $colors['Black'];
            $dims = imageTextSize(8, 0, $str);
            if ($labelLocation == MAP_LABEL_LOC_TOP || $labelLocation == MAP_LABEL_LOC_BOTTOM) {
                $x_label = $x + ceil($iconX / 2) - ceil($dims['width'] / 2);
            } elseif ($labelLocation == MAP_LABEL_LOC_LEFT) {
                $x_label = $x_rec + $w - $dims['width'];
            } else {
                $x_label = $x_rec;
            }
            imagefilledrectangle($im, $x_label - 1, $y_rec + $increasey - $labelFontHeight + $labelFontBaseline, $x_label + $dims['width'] + 1, $y_rec + $increasey + $labelFontBaseline, $colors['White']);
            imagetext($im, 8, 0, $x_label, $y_rec + $increasey, $color, $str);
            $increasey += $labelFontHeight + 1;
        }
    }
}
Example #10
0
        }
    }
} else {
    if (preg_match('/^([a-z]+)\\[([=><]{1,2})\\]$/i', $exprType, $matches)) {
        $function = $matches[1];
        $operator = $matches[2];
        if (!isset($functions[$exprType])) {
            unset($function);
        }
    }
    // fetch item
    $item = API::Item()->get(['output' => ['itemid', 'hostid', 'name', 'key_', 'value_type'], 'selectHosts' => ['host', 'name'], 'itemids' => $itemId, 'webitems' => true, 'filter' => ['flags' => null]]);
    $item = reset($item);
}
if ($itemId) {
    $items = CMacrosResolverHelper::resolveItemNames([$item]);
    $item = $items[0];
    $itemValueType = $item['value_type'];
    $itemKey = $item['key_'];
    $itemHostData = reset($item['hosts']);
    $description = $itemHostData['name'] . NAME_DELIMITER . $item['name_expanded'];
} else {
    $itemKey = '';
    $description = '';
    $itemValueType = null;
}
if (is_null($paramType) && isset($functions[$exprType]['params']['M'])) {
    $paramType = is_array($functions[$exprType]['params']['M']) ? reset($functions[$exprType]['params']['M']) : $functions[$exprType]['params']['M'];
} elseif (is_null($paramType)) {
    $paramType = PARAM_TYPE_TIME;
}
Example #11
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';
Example #12
0
 * Display
 */
if ($hostId > 0) {
    $data = [];
    // host scripts
    $data['hostScripts'] = API::Script()->getScriptsByHosts([$hostId]);
    // inventory info
    $data['tableTitles'] = getHostInventories();
    $data['tableTitles'] = zbx_toHash($data['tableTitles'], 'db_field');
    $inventoryFields = array_keys($data['tableTitles']);
    // overview tab
    $data['host'] = API::Host()->get(['output' => ['hostid', 'host', 'name', 'status', 'maintenance_status', 'maintenanceid', 'maintenance_type', 'description'], 'selectInterfaces' => API_OUTPUT_EXTEND, 'selectItems' => API_OUTPUT_COUNT, 'selectTriggers' => API_OUTPUT_COUNT, 'selectScreens' => API_OUTPUT_COUNT, 'selectInventory' => $inventoryFields, 'selectGraphs' => API_OUTPUT_COUNT, 'selectApplications' => API_OUTPUT_COUNT, 'selectDiscoveries' => API_OUTPUT_COUNT, 'selectHttpTests' => API_OUTPUT_COUNT, 'hostids' => $hostId, 'preservekeys' => true]);
    $data['host'] = reset($data['host']);
    unset($data['host']['inventory']['hostid']);
    // resolve macros
    $data['host']['interfaces'] = CMacrosResolverHelper::resolveHostInterfaces($data['host']['interfaces']);
    if ($data['host']['maintenance_status'] == HOST_MAINTENANCE_STATUS_ON) {
        $data['maintenances'] = API::Maintenance()->get(['maintenanceids' => [$data['host']['maintenanceid']], 'output' => ['name', 'description'], 'preservekeys' => true]);
    }
    // get permissions
    $userType = CWebUser::getType();
    if ($userType == USER_TYPE_SUPER_ADMIN) {
        $data['rwHost'] = true;
    } elseif ($userType == USER_TYPE_ZABBIX_ADMIN) {
        $rwHost = API::Host()->get(['output' => ['hostid'], 'hostids' => $hostId, 'editable' => true]);
        $data['rwHost'] = (bool) $rwHost;
    } else {
        $data['rwHost'] = false;
    }
    // view generation
    $hostinventoriesView = new CView('inventory.host.view', $data);
Example #13
0
 /**
  * Init screen data.
  *
  * @param array		$options
  * @param array		$options['itemids']
  * @param string	$options['filter']
  * @param int		$options['filterTask']
  * @param int		$options['markColor']
  * @param boolean	$options['plaintext']
  * @param array		$options['items']
  * @param array		$options['item']
  */
 public function __construct(array $options = array())
 {
     parent::__construct($options);
     $this->resourcetype = SCREEN_RESOURCE_HISTORY;
     // mandatory
     $this->itemids = isset($options['itemids']) ? $options['itemids'] : null;
     $this->filter = isset($options['filter']) ? $options['filter'] : null;
     $this->filterTask = isset($options['filter_task']) ? $options['filter_task'] : null;
     $this->markColor = isset($options['mark_color']) ? $options['mark_color'] : MARK_COLOR_RED;
     // optional
     $this->items = isset($options['items']) ? $options['items'] : null;
     $this->item = isset($options['item']) ? $options['item'] : null;
     $this->plaintext = isset($options['plaintext']) ? $options['plaintext'] : false;
     if (empty($this->items)) {
         $this->items = API::Item()->get(array('nodeids' => get_current_nodeid(), 'itemids' => $this->itemids, 'webitems' => true, 'selectHosts' => array('name'), 'output' => array('itemid', 'hostid', 'name', 'key_', 'value_type', 'valuemapid'), 'preservekeys' => true));
         $this->items = CMacrosResolverHelper::resolveItemNames($this->items);
         $this->item = reset($this->items);
     }
 }
Example #14
0
/**
 * Generate table for dashboard triggers popup.
 *
 * @see make_system_status
 *
 * @param array $triggers
 * @param string $backurl
 * @param array $actions
 * @param array $config
 *
 * @return CTableInfo
 */
function makeTriggersPopup(array $triggers, $backurl, array $actions, array $config)
{
    $popupTable = (new CTableInfo())->setHeader([_('Host'), _('Issue'), _('Age'), _('Info'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions')]);
    CArrayHelper::sort($triggers, [['field' => 'lastchange', 'order' => ZBX_SORT_DOWN]]);
    foreach ($triggers as $trigger) {
        $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['event']['clock'], 'ns' => $trigger['event']['ns'])));
        // unknown triggers
        $unknown = '';
        if ($trigger['state'] == TRIGGER_STATE_UNKNOWN) {
            $unknown = makeUnknownIcon($trigger['error']);
        }
        // ack
        if ($config['event_ack_enable']) {
            $ack = isset($trigger['event']['eventid']) ? getEventAckState($trigger['event'], $backurl) : (new CSpan(_('No events')))->addClass(ZBX_STYLE_GREY);
        } else {
            $ack = null;
        }
        // action
        $action = isset($trigger['event']['eventid']) && isset($actions[$trigger['event']['eventid']]) ? $actions[$trigger['event']['eventid']] : '';
        $popupTable->addRow([$trigger['hosts'][0]['name'], getSeverityCell($trigger['priority'], $config, $description), zbx_date2age($trigger['lastchange']), $unknown, $ack, (new CCol($action))->addClass(ZBX_STYLE_NOWRAP)]);
    }
    return $popupTable;
}
Example #15
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $output = [];
     $items = API::Item()->get(['output' => ['itemid', 'hostid', 'name', 'key_', 'value_type', 'valuemapid'], 'selectHosts' => ['name'], 'itemids' => $this->itemids, 'webitems' => true, 'preservekeys' => true]);
     $items = CMacrosResolverHelper::resolveItemNames($items);
     $stime = zbxDateToTime($this->timeline['stime']);
     $firstItem = reset($items);
     $iv_string = [ITEM_VALUE_TYPE_LOG => 1, ITEM_VALUE_TYPE_TEXT => 1];
     $iv_numeric = [ITEM_VALUE_TYPE_FLOAT => 1, ITEM_VALUE_TYPE_UINT64 => 1];
     if ($this->action == HISTORY_VALUES || $this->action == HISTORY_LATEST) {
         $options = ['history' => $firstItem['value_type'], 'itemids' => $this->itemids, 'output' => API_OUTPUT_EXTEND, 'sortorder' => ZBX_SORT_DOWN];
         if ($this->action == HISTORY_LATEST) {
             $options['limit'] = 500;
         } elseif ($this->action == HISTORY_VALUES) {
             $config = select_config();
             // interval start value is non-inclusive, hence the + 1 second
             $options['time_from'] = $stime + 1;
             $options['time_till'] = $stime + $this->timeline['period'];
             $options['limit'] = $config['search_limit'];
         }
         // text log
         if (isset($iv_string[$firstItem['value_type']])) {
             $isManyItems = count($items) > 1;
             $useLogItem = $firstItem['value_type'] == ITEM_VALUE_TYPE_LOG;
             $useEventLogItem = strpos($firstItem['key_'], 'eventlog[') === 0;
             if (empty($this->plaintext)) {
                 $historyTable = (new CTableInfo())->setHeader([(new CColHeader(_('Timestamp')))->addClass(ZBX_STYLE_CELL_WIDTH), $isManyItems ? _('Item') : null, $useLogItem ? (new CColHeader(_('Local time')))->addClass(ZBX_STYLE_CELL_WIDTH) : null, $useEventLogItem && $useLogItem ? (new CColHeader(_('Source')))->addClass(ZBX_STYLE_CELL_WIDTH) : null, $useEventLogItem && $useLogItem ? (new CColHeader(_('Severity')))->addClass(ZBX_STYLE_CELL_WIDTH) : null, $useEventLogItem && $useLogItem ? (new CColHeader(_('Event ID')))->addClass(ZBX_STYLE_CELL_WIDTH) : null, _('Value')]);
             }
             if ($this->filter !== '' && in_array($this->filterTask, [FILTER_TASK_SHOW, FILTER_TASK_HIDE])) {
                 $options['search'] = ['value' => $this->filter];
                 if ($this->filterTask == FILTER_TASK_HIDE) {
                     $options['excludeSearch'] = 1;
                 }
             }
             $options['sortfield'] = 'id';
             $historyData = API::History()->get($options);
             foreach ($historyData as $data) {
                 $data['value'] = rtrim($data['value'], " \t\r\n");
                 if (empty($this->plaintext)) {
                     $item = $items[$data['itemid']];
                     $host = reset($item['hosts']);
                     $color = null;
                     if ($this->filter !== '') {
                         $haystack = mb_strtolower($data['value']);
                         $needle = mb_strtolower($this->filter);
                         $pos = mb_strpos($haystack, $needle);
                         if ($pos !== false && $this->filterTask == FILTER_TASK_MARK) {
                             $color = $this->markColor;
                         } elseif ($pos === false && $this->filterTask == FILTER_TASK_INVERT_MARK) {
                             $color = $this->markColor;
                         }
                         switch ($color) {
                             case MARK_COLOR_RED:
                                 $color = ZBX_STYLE_RED;
                                 break;
                             case MARK_COLOR_GREEN:
                                 $color = ZBX_STYLE_GREEN;
                                 break;
                             case MARK_COLOR_BLUE:
                                 $color = ZBX_STYLE_BLUE;
                                 break;
                         }
                     }
                     $row = [];
                     $row[] = (new CCol(zbx_date2str(DATE_TIME_FORMAT_SECONDS, $data['clock'])))->addClass(ZBX_STYLE_NOWRAP)->addClass($color);
                     if ($isManyItems) {
                         $row[] = (new CCol($host['name'] . NAME_DELIMITER . $item['name_expanded']))->addClass($color);
                     }
                     if ($useLogItem) {
                         $row[] = $data['timestamp'] != 0 ? (new CCol(zbx_date2str(DATE_TIME_FORMAT_SECONDS, $data['timestamp'])))->addClass(ZBX_STYLE_NOWRAP)->addClass($color) : '';
                         // if this is a eventLog item, showing additional info
                         if ($useEventLogItem) {
                             $row[] = (new CCol($data['source']))->addClass(ZBX_STYLE_NOWRAP)->addClass($color);
                             $row[] = $data['severity'] != 0 ? (new CCol(get_item_logtype_description($data['severity'])))->addClass(ZBX_STYLE_NOWRAP)->addClass(get_item_logtype_style($data['severity'])) : '';
                             $row[] = $data['logeventid'] != 0 ? (new CCol($data['logeventid']))->addClass(ZBX_STYLE_NOWRAP)->addClass($color) : '';
                         }
                     }
                     $row[] = (new CCol(new CPre(zbx_nl2br($data['value']))))->addClass($color);
                     $historyTable->addRow($row);
                 } else {
                     $output[] = zbx_date2str(DATE_TIME_FORMAT_SECONDS, $data['clock']) . ' ' . $data['clock'] . ' ' . htmlspecialchars($data['value']);
                 }
             }
             if (empty($this->plaintext)) {
                 $output[] = $historyTable;
             }
         } else {
             if (empty($this->plaintext)) {
                 $historyTable = (new CTableInfo())->setHeader([(new CColHeader(_('Timestamp')))->addClass(ZBX_STYLE_CELL_WIDTH), _('Value')]);
             }
             $options['sortfield'] = ['itemid', 'clock'];
             $historyData = API::History()->get($options);
             foreach ($historyData as $data) {
                 $item = $items[$data['itemid']];
                 $value = rtrim($data['value'], " \t\r\n");
                 // format the value as float
                 if ($item['value_type'] == ITEM_VALUE_TYPE_FLOAT) {
                     sscanf($data['value'], '%f', $value);
                 }
                 // html table
                 if (empty($this->plaintext)) {
                     if ($item['valuemapid']) {
                         $value = applyValueMap($value, $item['valuemapid']);
                     }
                     $historyTable->addRow([(new CCol(zbx_date2str(DATE_TIME_FORMAT_SECONDS, $data['clock'])))->addClass(ZBX_STYLE_NOWRAP), new CPre(zbx_nl2br($value))]);
                 } else {
                     $output[] = zbx_date2str(DATE_TIME_FORMAT_SECONDS, $data['clock']) . ' ' . $data['clock'] . ' ' . htmlspecialchars($value);
                 }
             }
             if (empty($this->plaintext)) {
                 $output[] = $historyTable;
             }
         }
     }
     // time control
     if (!$this->plaintext && str_in_array($this->action, [HISTORY_VALUES, HISTORY_GRAPH, HISTORY_BATCH_GRAPH])) {
         $graphDims = getGraphDims();
         $this->timeline['starttime'] = date(TIMESTAMP_FORMAT, get_min_itemclock_by_itemid($firstItem['itemid']));
         $this->dataId = 'historyGraph';
         $timeControlData = ['periodFixed' => CProfile::get('web.history.timelinefixed', 1), 'sliderMaximumTimePeriod' => ZBX_MAX_PERIOD];
         if (($this->action == HISTORY_GRAPH || $this->action == HISTORY_BATCH_GRAPH) && !isset($iv_string[$firstItem['value_type']])) {
             $containerId = 'graph_cont1';
             $output[] = (new CDiv())->addClass('center')->setId($containerId);
             $timeControlData['id'] = $this->getDataId();
             $timeControlData['containerid'] = $containerId;
             $timeControlData['src'] = $this->getGraphUrl($this->itemids);
             $timeControlData['objDims'] = $graphDims;
             $timeControlData['loadSBox'] = 1;
             $timeControlData['loadImage'] = 1;
             $timeControlData['dynamic'] = 1;
         } else {
             $timeControlData['id'] = $this->getDataId();
             $timeControlData['mainObject'] = 1;
         }
         if ($this->mode == SCREEN_MODE_JS) {
             $timeControlData['dynamic'] = 0;
             return 'timeControl.addObject("' . $this->getDataId() . '", ' . CJs::encodeJson($this->timeline) . ', ' . CJs::encodeJson($timeControlData) . ');';
         } else {
             zbx_add_post_js('timeControl.addObject("' . $this->getDataId() . '", ' . CJs::encodeJson($this->timeline) . ', ' . CJs::encodeJson($timeControlData) . ');');
         }
     }
     if (!empty($this->plaintext)) {
         return $output;
     } else {
         if ($this->mode != SCREEN_MODE_JS) {
             $flickerfreeData = ['itemids' => $this->itemids, 'action' => $this->action == HISTORY_BATCH_GRAPH ? HISTORY_GRAPH : $this->action, 'filter' => $this->filter, 'filterTask' => $this->filterTask, 'markColor' => $this->markColor];
             return $this->getOutput($output, true, $flickerfreeData);
         }
     }
 }
Example #16
0
/**
 * Generate table for dashboard triggers popup.
 *
 * @see make_system_status
 *
 * @param array $triggers
 * @param array $ackParams
 * @param array $actions
 * @param array $config
 *
 * @return CTableInfo
 */
function makeTriggersPopup(array $triggers, array $ackParams, array $actions, array $config)
{
    $popupTable = new CTableInfo();
    $popupTable->setAttribute('style', 'width: 400px;');
    $popupTable->setHeader(array(_('Host'), _('Issue'), _('Age'), _('Info'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions')));
    CArrayHelper::sort($triggers, array(array('field' => 'lastchange', 'order' => ZBX_SORT_DOWN)));
    $triggers = CMacrosResolverHelper::resolveTriggerNames($triggers);
    foreach ($triggers as $trigger) {
        // unknown triggers
        $unknown = SPACE;
        if ($trigger['state'] == TRIGGER_STATE_UNKNOWN) {
            $unknown = new CDiv(SPACE, 'status_icon iconunknown');
            $unknown->setHint($trigger['error'], 'on');
        }
        // ack
        if ($config['event_ack_enable']) {
            $ack = isset($trigger['event']['eventid']) ? getEventAckState($trigger['event'], true, true, $ackParams) : _('No events');
        } else {
            $ack = null;
        }
        // action
        $action = isset($trigger['event']['eventid']) && isset($actions[$trigger['event']['eventid']]) ? $actions[$trigger['event']['eventid']] : _('-');
        $popupTable->addRow(array($trigger['hosts'][0]['name'], getSeverityCell($trigger['priority'], $trigger['description']), zbx_date2age($trigger['lastchange']), $unknown, $ack, $action));
    }
    return $popupTable;
}
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
require_once dirname(__FILE__) . '/js/monitoring.triggerComment.js.php';
$commentWidget = new CWidget('triggerComment');
$commentWidget->addPageHeader(_('TRIGGER DESCRIPTION'));
// create form
$commentForm = new CForm();
$commentForm->setName('commentForm');
$commentForm->addVar('triggerid', $this->data['triggerid']);
// create form list
$commentFormList = new CFormList('commentFormList');
$commentTextArea = new CTextArea('comments', CMacrosResolverHelper::resolveTriggerDescription($this->data['trigger']), array('rows' => 25, 'width' => ZBX_TEXTAREA_BIG_WIDTH, 'readonly' => $this->data['isCommentExist']));
$commentTextArea->attr('autofocus', 'autofocus');
$commentFormList->addRow(_('Description'), $commentTextArea);
// append tabs to form
$commentTab = new CTabView();
$commentTab->addTab('commentTab', _s('Description for "%s".', $this->data['trigger']['description']), $commentFormList);
$commentForm->addItem($commentTab);
// append buttons to form
$updateButton = new CSubmit('update', _('Update'));
$updateButton->setEnabled(!$this->data['isCommentExist']);
if ($this->data['isCommentExist']) {
    $editButton = new CButton('edit', _('Edit'));
    $editButton->setEnabled($this->data['isTriggerEditable']);
} else {
    $editButton = null;
}
Example #18
0
/**
 * Retrieve overview table object for items.
 *
 * @param array  $hostIds
 * @param string $application name of application to filter
 * @param int    $viewMode
 *
 * @return CTableInfo
 */
function getItemsDataOverview($hostIds, $application, $viewMode)
{
    $sqlFrom = '';
    $sqlWhere = '';
    if ($application !== '') {
        $sqlFrom = 'applications a,items_applications ia,';
        $sqlWhere = ' AND i.itemid=ia.itemid AND a.applicationid=ia.applicationid AND a.name=' . zbx_dbstr($application);
    }
    $dbItems = DBfetchArray(DBselect('SELECT DISTINCT h.hostid,h.name AS hostname,i.itemid,i.key_,i.value_type,i.units,' . 'i.name,t.priority,i.valuemapid,t.value AS tr_value,t.triggerid' . ' FROM hosts h,' . $sqlFrom . 'items i' . ' LEFT JOIN functions f ON f.itemid=i.itemid' . ' LEFT JOIN triggers t ON t.triggerid=f.triggerid AND t.status=' . TRIGGER_STATUS_ENABLED . ' WHERE ' . dbConditionInt('h.hostid', $hostIds) . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND h.hostid=i.hostid' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND ' . dbConditionInt('i.flags', array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_CREATED)) . $sqlWhere));
    $dbItems = CMacrosResolverHelper::resolveItemNames($dbItems);
    CArrayHelper::sort($dbItems, array(array('field' => 'name_expanded', 'order' => ZBX_SORT_UP), array('field' => 'itemid', 'order' => ZBX_SORT_UP)));
    // fetch latest values
    $history = Manager::History()->getLast(zbx_toHash($dbItems, 'itemid'), 1, ZBX_HISTORY_PERIOD);
    // fetch data for the host JS menu
    $hosts = API::Host()->get(array('output' => array('name', 'hostid', 'status'), 'monitored_hosts' => true, 'hostids' => $hostIds, 'with_monitored_items' => true, 'preservekeys' => true, 'selectScreens' => $viewMode == STYLE_LEFT ? API_OUTPUT_COUNT : null));
    $items = array();
    foreach ($dbItems as $dbItem) {
        $name = $dbItem['name_expanded'];
        $dbItem['hostname'] = get_node_name_by_elid($dbItem['hostid'], null, NAME_DELIMITER) . $dbItem['hostname'];
        $hostNames[$dbItem['hostid']] = $dbItem['hostname'];
        // a little tricky check for attempt to overwrite active trigger (value=1) with
        // inactive or active trigger with lower priority.
        if (!isset($items[$name][$dbItem['hostname']]) || ($items[$name][$dbItem['hostname']]['tr_value'] == TRIGGER_VALUE_FALSE && $dbItem['tr_value'] == TRIGGER_VALUE_TRUE || ($items[$name][$dbItem['hostname']]['tr_value'] == TRIGGER_VALUE_FALSE || $dbItem['tr_value'] == TRIGGER_VALUE_TRUE) && $dbItem['priority'] > $items[$name][$dbItem['hostname']]['severity'])) {
            $items[$name][$dbItem['hostname']] = array('itemid' => $dbItem['itemid'], 'value_type' => $dbItem['value_type'], 'value' => isset($history[$dbItem['itemid']]) ? $history[$dbItem['itemid']][0]['value'] : null, 'units' => $dbItem['units'], 'name' => $name, 'valuemapid' => $dbItem['valuemapid'], 'severity' => $dbItem['priority'], 'tr_value' => $dbItem['tr_value'], 'triggerid' => $dbItem['triggerid']);
        }
    }
    $table = new CTableInfo(_('No items found.'));
    if (empty($hostNames)) {
        return $table;
    }
    $table->makeVerticalRotation();
    order_result($hostNames);
    if ($viewMode == STYLE_TOP) {
        $header = array(new CCol(_('Items'), 'center'));
        foreach ($hostNames as $hostName) {
            $header[] = new CCol($hostName, 'vertical_rotation');
        }
        $table->setHeader($header, 'vertical_header');
        foreach ($items as $descr => $ithosts) {
            $tableRow = array(nbsp($descr));
            foreach ($hostNames as $hostName) {
                $tableRow = getItemDataOverviewCells($tableRow, $ithosts, $hostName);
            }
            $table->addRow($tableRow);
        }
    } else {
        $scripts = API::Script()->getScriptsByHosts(zbx_objectValues($hosts, 'hostid'));
        $header = array(new CCol(_('Hosts'), 'center'));
        foreach ($items as $descr => $ithosts) {
            $header[] = new CCol($descr, 'vertical_rotation');
        }
        $table->setHeader($header, 'vertical_header');
        foreach ($hostNames as $hostId => $hostName) {
            $host = $hosts[$hostId];
            $name = new CSpan($host['name'], 'link_menu');
            $name->setMenuPopup(getMenuPopupHost($host, $scripts[$hostId]));
            $tableRow = array(new CCol($name));
            foreach ($items as $ithosts) {
                $tableRow = getItemDataOverviewCells($tableRow, $ithosts, $hostName);
            }
            $table->addRow($tableRow);
        }
    }
    return $table;
}
Example #19
0
if (!check_fields($fields)) {
    exit;
}
if ($httptestid = getRequest('httptestid', false)) {
    if (!API::HttpTest()->isReadable(array($_REQUEST['httptestid']))) {
        access_deny();
    }
    $color = array('current' => 0, 0 => array('next' => '1'), 1 => array('color' => 'Red', 'next' => '2'), 2 => array('color' => 'Dark Green', 'next' => '3'), 3 => array('color' => 'Blue', 'next' => '4'), 4 => array('color' => 'Dark Yellow', 'next' => '5'), 5 => array('color' => 'Cyan', 'next' => '6'), 6 => array('color' => 'Gray', 'next' => '7'), 7 => array('color' => 'Dark Red', 'next' => '8'), 8 => array('color' => 'Green', 'next' => '9'), 9 => array('color' => 'Dark Blue', 'next' => '10'), 10 => array('color' => 'Yellow', 'next' => '11'), 11 => array('color' => 'Black', 'next' => '1'));
    $items = array();
    $dbItems = DBselect('SELECT i.itemid' . ' FROM httpstepitem hi,items i,httpstep hs' . ' WHERE i.itemid=hi.itemid' . ' AND hs.httptestid=' . zbx_dbstr($httptestid) . ' AND hs.httpstepid=hi.httpstepid' . ' AND hi.type=' . zbx_dbstr(getRequest('http_item_type', HTTPSTEP_ITEM_TYPE_TIME)) . ' ORDER BY hs.no DESC');
    while ($item = DBfetch($dbItems)) {
        $itemColor = $color[$color['current'] = $color[$color['current']]['next']]['color'];
        $items[] = array('itemid' => $item['itemid'], 'color' => $itemColor);
    }
    $httpTest = get_httptest_by_httptestid($httptestid);
    $name = CMacrosResolverHelper::resolveHttpTestName($httpTest['hostid'], $httpTest['name']);
} elseif ($items = getRequest('items', array())) {
    asort_by_key($items, 'sortorder');
    $dbItems = API::Item()->get(array('itemids' => zbx_objectValues($items, 'itemid'), 'output' => array('itemid'), 'filter' => array('flags' => array(ZBX_FLAG_DISCOVERY_NORMAL, ZBX_FLAG_DISCOVERY_PROTOTYPE, ZBX_FLAG_DISCOVERY_CREATED)), 'webitems' => true, 'preservekeys' => true));
    foreach ($items as $item) {
        if (!isset($dbItems[$item['itemid']])) {
            access_deny();
        }
    }
    $name = getRequest('name', '');
} else {
    show_error_message(_('No items defined.'));
    exit;
}
/*
 * Display
Example #20
0
function getLastEvents($options)
{
    if (!isset($options['limit'])) {
        $options['limit'] = 15;
    }
    $triggerOptions = array('filter' => array(), 'skipDependent' => 1, 'selectHosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND, 'sortfield' => 'lastchange', 'sortorder' => ZBX_SORT_DOWN, 'limit' => $options['triggerLimit']);
    $eventOptions = array('source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER, 'output' => API_OUTPUT_EXTEND, 'sortfield' => array('clock', 'eventid'), 'sortorder' => ZBX_SORT_DOWN);
    if (isset($options['eventLimit'])) {
        $eventOptions['limit'] = $options['eventLimit'];
    }
    if (isset($options['nodeids'])) {
        $triggerOptions['nodeids'] = $options['nodeids'];
    }
    if (isset($options['priority'])) {
        $triggerOptions['filter']['priority'] = $options['priority'];
    }
    if (isset($options['monitored'])) {
        $triggerOptions['monitored'] = $options['monitored'];
    }
    if (isset($options['lastChangeSince'])) {
        $triggerOptions['lastChangeSince'] = $options['lastChangeSince'];
        $eventOptions['time_from'] = $options['lastChangeSince'];
    }
    if (isset($options['value'])) {
        $triggerOptions['filter']['value'] = $options['value'];
        $eventOptions['value'] = $options['value'];
    }
    // triggers
    $triggers = API::Trigger()->get($triggerOptions);
    $triggers = zbx_toHash($triggers, 'triggerid');
    // events
    $eventOptions['objectids'] = zbx_objectValues($triggers, 'triggerid');
    $events = API::Event()->get($eventOptions);
    $sortClock = array();
    $sortEvent = array();
    foreach ($events as $enum => $event) {
        if (!isset($triggers[$event['objectid']])) {
            continue;
        }
        $events[$enum]['trigger'] = $triggers[$event['objectid']];
        $events[$enum]['host'] = reset($events[$enum]['trigger']['hosts']);
        $sortClock[$enum] = $event['clock'];
        $sortEvent[$enum] = $event['eventid'];
        //expanding description for the state where event was
        $merged_event = array_merge($event, $triggers[$event['objectid']]);
        $events[$enum]['trigger']['description'] = CMacrosResolverHelper::resolveEventDescription($merged_event);
    }
    array_multisort($sortClock, SORT_DESC, $sortEvent, SORT_DESC, $events);
    return $events;
}
Example #21
0
function make_trigger_details($trigger)
{
    $hosts = reset($trigger['hosts']);
    $hostId = $hosts['hostid'];
    $hosts = API::Host()->get(array('output' => array('name', 'hostid', 'status'), 'hostids' => $hostId, 'selectScreens' => API_OUTPUT_COUNT, 'preservekeys' => true));
    $host = reset($hosts);
    $scripts = API::Script()->getScriptsByHosts($hostId);
    $hostName = new CSpan($host['name'], 'link_menu');
    $hostName->setMenuPopup(getMenuPopupHost($host, $scripts ? reset($scripts) : null));
    $table = new CTableInfo();
    if (is_show_all_nodes()) {
        $table->addRow(array(_('Node'), get_node_name_by_elid($trigger['triggerid'])));
    }
    $table->addRow(array(_('Host'), $hostName));
    $table->addRow(array(_('Trigger'), CMacrosResolverHelper::resolveTriggerName($trigger)));
    $table->addRow(array(_('Severity'), getSeverityCell($trigger['priority'])));
    $table->addRow(array(_('Expression'), explode_exp($trigger['expression'], true, true)));
    $table->addRow(array(_('Event generation'), _('Normal') . (TRIGGER_MULT_EVENT_ENABLED == $trigger['type'] ? SPACE . '+' . SPACE . _('Multiple PROBLEM events') : '')));
    $table->addRow(array(_('Disabled'), TRIGGER_STATUS_ENABLED == $trigger['status'] ? new CCol(_('No'), 'off') : new CCol(_('Yes'), 'on')));
    return $table;
}
Example #22
0
    }
    // step response time
    $respTimeItem = $httpStepItemsByType[HTTPSTEP_ITEM_TYPE_TIME];
    if (!$status['afterError'] && isset($itemHistory[$respTimeItem['itemid']]) && $itemHistory[$respTimeItem['itemid']][0]['value'] > 0) {
        $respTime = formatHistoryValue($itemHistory[$respTimeItem['itemid']][0]['value'], $respTimeItem);
    } else {
        $respTime = UNKNOWN_VALUE;
    }
    // step response code
    $respItem = $httpStepItemsByType[HTTPSTEP_ITEM_TYPE_RSPCODE];
    if (!$status['afterError'] && isset($itemHistory[$respItem['itemid']]) && $itemHistory[$respItem['itemid']][0]['value'] > 0) {
        $resp = formatHistoryValue($itemHistory[$respItem['itemid']][0]['value'], $respItem);
    } else {
        $resp = UNKNOWN_VALUE;
    }
    $httpdetailsTable->addRow(array(CMacrosResolverHelper::resolveHttpTestName($httpTest['hostid'], $httpstep_data['name']), $speed, $respTime, $resp, new CSpan($status['msg'], $status['style'])));
}
if (!isset($httpTestData['lastfailedstep'])) {
    $status['msg'] = _('Never executed');
    $status['style'] = 'unknown';
} elseif ($httpTestData['lastfailedstep'] != 0) {
    $status['msg'] = $httpTestData['error'] === null ? _('Unknown error') : _s('Error: %1$s', $httpTestData['error']);
    $status['style'] = 'disabled';
} else {
    $status['msg'] = _('OK');
    $status['style'] = 'enabled';
}
$httpdetailsTable->addRow(array(bold(_('TOTAL')), SPACE, bold($totalTime['value'] ? formatHistoryValue($totalTime['value'], $totalTime) : UNKNOWN_VALUE), SPACE, new CSpan($status['msg'], $status['style'] . ' bold')));
$httpdetailsWidget->addItem($httpdetailsTable);
$httpdetailsWidget->show();
echo SBR;
 /**
  * Create CMacrosResolver object and store in static variable.
  *
  * @static
  */
 private static function init()
 {
     if (self::$macrosResolver === null) {
         self::$macrosResolver = new CMacrosResolver();
     }
 }
 /**
  * Adds items from template to hosts.
  *
  * @param array		$data
  *
  * @return bool
  */
 public function syncTemplates(array $data)
 {
     $data['templateids'] = zbx_toArray($data['templateids']);
     $data['hostids'] = zbx_toArray($data['hostids']);
     $triggerPrototypes = $this->get(['output' => ['triggerid', 'expression', 'description', 'url', 'status', 'priority', 'comments', 'type'], 'hostids' => $data['templateids'], 'preservekeys' => true]);
     $triggerPrototypes = CMacrosResolverHelper::resolveTriggerExpressions($triggerPrototypes);
     foreach ($triggerPrototypes as $triggerPrototype) {
         $this->inherit($triggerPrototype, $data['hostids']);
     }
     return true;
 }
Example #25
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';
 /**
  * Prepare data for trigger menu popup.
  *
  * @param array  $trigger							trigger data
  * @param string $trigger['triggerid']				trigger ID
  * @param int    $trigger['flags']					trigger flags (TRIGGER_FLAG_DISCOVERY*)
  * @param array  $trigger['hosts']					hosts, used by trigger expression
  * @param string $trigger['hosts'][]['hostid']		host ID
  * @param string $trigger['hosts'][]['name']		host name
  * @param string $trigger['hosts'][]['status']		host status
  * @param array  $trigger['items']					trigger items
  * @param string $trigger['items'][]['itemid']		item ID
  * @param string $trigger['items'][]['hostid']		host ID
  * @param string $trigger['items'][]['name']		item name
  * @param string $trigger['items'][]['key_']		item key
  * @param string $trigger['items'][]['value_type']	type of information of the item
  * @param string $trigger['url']					trigger URL
  * @param array  $acknowledge						acknowledge link parameters (optional)
  * @param string $acknowledge['eventid']			event ID
  * @param string $acknowledge['screenid']			screen ID (optional)
  * @param string $acknowledge['backurl']			return URL (optional)
  * @param string $eventTime							event navigation time parameter (optional)
  *
  * @return array
  */
 public static function getTrigger(array $trigger, array $acknowledge = null, $eventTime = null)
 {
     $hosts = array();
     $showEvents = true;
     foreach ($trigger['hosts'] as $host) {
         $hosts[$host['hostid']] = $host['name'];
         if ($host['status'] != HOST_STATUS_MONITORED) {
             $showEvents = false;
         }
     }
     $trigger['items'] = CMacrosResolverHelper::resolveItemNames($trigger['items']);
     foreach ($trigger['items'] as &$item) {
         $item['hostname'] = $hosts[$item['hostid']];
     }
     unset($item);
     CArrayHelper::sort($trigger['items'], array('name', 'hostname', 'itemid'));
     $hostCount = count($hosts);
     $items = array();
     foreach ($trigger['items'] as $item) {
         $items[] = array('name' => $hostCount > 1 ? $hosts[$item['hostid']] . NAME_DELIMITER . $item['name_expanded'] : $item['name_expanded'], 'params' => array('itemid' => $item['itemid'], 'action' => in_array($item['value_type'], array(ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64)) ? HISTORY_GRAPH : HISTORY_VALUES));
     }
     $data = array('type' => 'trigger', 'groupid' => $trigger['groupid'], 'hostid' => $trigger['hostid'], 'triggerid' => $trigger['triggerid'], 'items' => $items, 'acknowledge' => $acknowledge, 'eventTime' => $eventTime, 'url' => resolveTriggerUrl($trigger));
     if ($showEvents) {
         $data['showEvents'] = true;
     }
     if (in_array(CWebUser::$data['type'], array(USER_TYPE_ZABBIX_ADMIN, USER_TYPE_SUPER_ADMIN)) && $trigger['flags'] == ZBX_FLAG_DISCOVERY_NORMAL) {
         $data['configuration'] = true;
     }
     return $data;
 }
Example #27
0
         break;
     case 'year':
         $period_start = mktime(0, 0, 0, 1, 1, date('Y'));
         break;
     case 24:
     case 24 * 7:
     case 24 * 30:
     case 24 * DAY_IN_YEAR:
         $period_start = $period_end - $period * 3600;
         break;
 }
 // fetch services
 $services = API::Service()->get(array('output' => array('name', 'serviceid', 'showsla', 'goodsla', 'algorithm'), 'selectParent' => array('serviceid'), 'selectDependencies' => array('servicedownid', 'soft', 'linkid'), 'selectTrigger' => array('description', 'triggerid', 'expression'), 'preservekeys' => true, 'sortfield' => 'sortorder', 'sortorder' => ZBX_SORT_UP));
 // expand trigger descriptions
 $triggers = zbx_objectValues($services, 'trigger');
 $triggers = CMacrosResolverHelper::resolveTriggerNames($triggers);
 foreach ($services as &$service) {
     if ($service['trigger']) {
         $service['trigger'] = $triggers[$service['trigger']['triggerid']];
     }
 }
 unset($service);
 // fetch sla
 $slaData = API::Service()->getSla(array('intervals' => array(array('from' => $period_start, 'to' => $period_end))));
 // expand problem trigger descriptions
 foreach ($slaData as &$serviceSla) {
     foreach ($serviceSla['problems'] as &$problemTrigger) {
         $problemTrigger['description'] = $triggers[$problemTrigger['triggerid']]['description'];
     }
     unset($problemTrigger);
 }
 if ($hostDiscoveryRules) {
     $hostDiscoveryRules = CMacrosResolverHelper::resolveItemNames($hostDiscoveryRules);
     $discoveryRuleList = array();
     foreach ($hostDiscoveryRules as $discoveryRule) {
         $discoveryRuleList[$discoveryRule['itemid']] = $discoveryRule['name_expanded'];
     }
     order_result($discoveryRuleList);
     $hostDiscoveryRuleids = array_keys($discoveryRuleList);
     $listBox = new CListBox('discoveryRules', null, 8);
     $listBox->setAttribute('disabled', 'disabled');
     $listBox->addItems($discoveryRuleList);
     $templateList->addRow(_('Discovery rules'), $listBox);
     // item prototypes
     $hostItemPrototypes = API::ItemPrototype()->get(array('hostids' => $templateid, 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND));
     if ($hostItemPrototypes) {
         $hostItemPrototypes = CMacrosResolverHelper::resolveItemNames($hostItemPrototypes);
         $prototypeList = array();
         foreach ($hostItemPrototypes as $itemPrototype) {
             $prototypeList[$itemPrototype['itemid']] = $itemPrototype['name_expanded'];
         }
         order_result($prototypeList);
         $listBox = new CListBox('itemsPrototypes', null, 8);
         $listBox->setAttribute('disabled', 'disabled');
         $listBox->addItems($prototypeList);
         $templateList->addRow(_('Item prototypes'), $listBox);
     }
     // Trigger prototypes
     $hostTriggerPrototypes = API::TriggerPrototype()->get(array('hostids' => $templateid, 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND));
     if (!empty($hostTriggerPrototypes)) {
         $prototypeList = array();
         foreach ($hostTriggerPrototypes as $triggerPrototype) {
Example #29
0
 /**
  * Returns all the scripts that are available on each given host.
  *
  * @param $hostIds
  *
  * @return array (an array of scripts in the form of array($hostId => array($script1, $script2, ...), ...) )
  */
 public function getScriptsByHosts($hostIds)
 {
     zbx_value2array($hostIds);
     $scriptsByHost = array();
     if (!$hostIds) {
         return $scriptsByHost;
     }
     foreach ($hostIds as $hostId) {
         $scriptsByHost[$hostId] = array();
     }
     $scripts = $this->get(array('output' => API_OUTPUT_EXTEND, 'selectHosts' => array('hostid'), 'hostids' => $hostIds, 'sortfield' => 'name', 'preservekeys' => true));
     if ($scripts) {
         // resolve macros
         $macrosData = array();
         foreach ($scripts as $scriptId => $script) {
             if (!empty($script['confirmation'])) {
                 foreach ($script['hosts'] as $host) {
                     if (isset($scriptsByHost[$host['hostid']])) {
                         $macrosData[$host['hostid']][$scriptId] = $script['confirmation'];
                     }
                 }
             }
         }
         if ($macrosData) {
             $macrosData = CMacrosResolverHelper::resolve(array('config' => 'scriptConfirmation', 'data' => $macrosData));
         }
         foreach ($scripts as $scriptId => $script) {
             $hosts = $script['hosts'];
             unset($script['hosts']);
             // set script to host
             foreach ($hosts as $host) {
                 $hostId = $host['hostid'];
                 if (isset($scriptsByHost[$hostId])) {
                     $size = count($scriptsByHost[$hostId]);
                     $scriptsByHost[$hostId][$size] = $script;
                     // set confirmation text with resolved macros
                     if (isset($macrosData[$hostId][$scriptId]) && $script['confirmation']) {
                         $scriptsByHost[$hostId][$size]['confirmation'] = $macrosData[$hostId][$scriptId];
                     }
                 }
             }
         }
     }
     return $scriptsByHost;
 }
Example #30
0
 /**
  * Checks that none of the given triggers is inherited from a template.
  *
  * @throws APIException     if one of the triggers is inherited
  *
  * @param array $triggerIds
  */
 protected function checkNotInherited(array $triggerIds)
 {
     $trigger = DBfetch(DBselect('SELECT t.triggerid,t.description,t.expression' . ' FROM triggers t' . ' WHERE ' . dbConditionInt('t.triggerid', $triggerIds) . 'AND t.templateid IS NOT NULL', 1));
     if ($trigger) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot delete templated trigger "%1$s:%2$s".', $trigger['description'], CMacrosResolverHelper::resolveTriggerExpression($trigger['expression'])));
     }
 }