Exemplo n.º 1
1
 public function bodyToString()
 {
     $this->cleanItems();
     $total = 0;
     // fetch accessible host ids
     $hosts = API::Host()->get(array('nodeids' => get_current_nodeid(true), 'output' => array('hostid'), 'preservekeys' => true));
     $hostIds = array_keys($hosts);
     if (remove_nodes_from_id($this->groupid) > 0) {
         $cond_from = ',hosts_groups hg';
         $cond_where = ' AND hg.hostid=h.hostid AND hg.groupid=' . zbx_dbstr($this->groupid);
     } else {
         $cond_from = '';
         $cond_where = andDbNode('h.hostid', $this->nodeid);
     }
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_TRUE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $avail = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_FALSE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $notav = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_UNKNOWN . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostIds) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $uncn = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $node = get_node_by_nodeid($this->nodeid);
     $header_str = _('Hosts info') . SPACE;
     if ($node > 0) {
         $header_str .= '(' . $node['name'] . ')' . SPACE;
     }
     if (remove_nodes_from_id($this->groupid) > 0) {
         $group = get_hostgroup_by_groupid($this->groupid);
         $header_str .= _('Group') . SPACE . '"' . $group['name'] . '"';
     } else {
         $header_str .= _('All groups');
     }
     $header = new CCol($header_str, 'header');
     if ($this->style == STYLE_HORISONTAL) {
         $header->setColspan(4);
     }
     $this->addRow($header);
     $avail = new CCol($avail . '  ' . _('Available'), 'avail');
     $notav = new CCol($notav . '  ' . _('Not available'), 'notav');
     $uncn = new CCol($uncn . '  ' . _('Unknown'), 'uncn');
     $total = new CCol($total . '  ' . _('Total'), 'total');
     if ($this->style == STYLE_HORISONTAL) {
         $this->addRow(array($avail, $notav, $uncn, $total));
     } else {
         $this->addRow($avail);
         $this->addRow($notav);
         $this->addRow($uncn);
         $this->addRow($total);
     }
     return parent::bodyToString();
 }
 protected function doAction()
 {
     $proxy = [];
     $this->getInputs($proxy, ['host', 'status', 'description', 'tls_connect', 'tls_accept', 'tls_issuer', 'tls_subject', 'tls_psk_identity', 'tls_psk']);
     if ($this->getInput('status', HOST_STATUS_PROXY_ACTIVE) == HOST_STATUS_PROXY_PASSIVE) {
         $proxy['interface'] = [];
         $this->getInputs($proxy['interface'], ['dns', 'ip', 'useip', 'port']);
     }
     DBstart();
     if ($this->hasInput('proxy_hostids')) {
         // skip discovered hosts
         $proxy['hosts'] = API::Host()->get(['output' => ['hostid'], 'hostids' => $this->getInput('proxy_hostids'), 'filter' => ['flags' => ZBX_FLAG_DISCOVERY_NORMAL]]);
     }
     $result = API::Proxy()->create([$proxy]);
     if ($result) {
         add_audit(AUDIT_ACTION_ADD, AUDIT_RESOURCE_PROXY, '[' . $this->getInput('host', '') . '] [' . reset($result['proxyids']) . ']');
     }
     $result = DBend($result);
     if ($result) {
         $response = new CControllerResponseRedirect('zabbix.php?action=proxy.list&uncheck=1');
         $response->setMessageOk(_('Proxy added'));
     } else {
         $response = new CControllerResponseRedirect('zabbix.php?action=proxy.edit');
         $response->setFormData($this->getInputAll());
         $response->setMessageError(_('Cannot add proxy'));
     }
     $this->setResponse($response);
 }
 /**
  * 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]));
 }
Exemplo n.º 4
0
function rightsForLink($idl)
{
    $glinks = DBfetchArray(DBselect('SELECT host1, host2
	FROM hosts_links WHERE hosts_links.id = ' . $idl));
    if (API::Host()->isWritable(array(1 * $glinks[0]['host1'])) and API::Host()->isWritable(array(1 * $glinks[0]['host2']))) {
        return true;
    }
    return false;
}
 /**
  * Checks is any of the given hosts are discovered.
  *
  * @param $hostIds
  *
  * @return bool
  */
 public function validate($hostIds)
 {
     $hosts = API::Host()->get(['output' => ['host'], 'hostids' => $hostIds, 'filter' => ['flags' => ZBX_FLAG_DISCOVERY_CREATED], 'limit' => 1]);
     if ($hosts) {
         $host = reset($hosts);
         $this->error($this->message, $host['host']);
         return false;
     }
     return true;
 }
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     // fetch hosts
     $hosts = API::Host()->get(array('output' => array('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 = array('output' => array('description', 'expression', 'priority', 'url', 'value', 'triggerid', 'lastchange', 'flags'), 'selectHosts' => array('hostid', 'name', 'status'), 'hostids' => $hostIds, 'monitored' => true, 'skipDependent' => true, 'sortfield' => 'description');
     // application filter
     if ($this->screenitem['application'] !== '') {
         $applications = API::Application()->get(array('output' => array('applicationid'), 'hostids' => $hostIds, 'search' => array('name' => $this->screenitem['application'])));
         $options['applicationids'] = zbx_objectValues($applications, 'applicationid');
     }
     $triggers = API::Trigger()->get($options);
     return $this->getOutput(getTriggersOverview($hosts, $triggers, $this->pageFile, $this->screenitem['style'], $this->screenid));
 }
Exemplo n.º 7
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $total = 0;
     // fetch accessible host ids
     $hosts = API::Host()->get(['output' => ['hostid'], 'preservekeys' => true]);
     $hostids = array_keys($hosts);
     if ($this->screenitem['resourceid'] != 0) {
         $cond_from = ',hosts_groups hg';
         $cond_where = ' AND hg.hostid=h.hostid AND hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']);
     } else {
         $cond_from = '';
         $cond_where = '';
     }
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_TRUE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $avail = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_FALSE . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $notav = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $db_host_cnt = DBselect('SELECT COUNT(DISTINCT h.hostid) AS cnt' . ' FROM hosts h' . $cond_from . ' WHERE h.available=' . HOST_AVAILABLE_UNKNOWN . ' AND h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')' . ' AND ' . dbConditionInt('h.hostid', $hostids) . $cond_where);
     $host_cnt = DBfetch($db_host_cnt);
     $uncn = $host_cnt['cnt'];
     $total += $host_cnt['cnt'];
     $avail = (new CCol($avail . '  ' . _('Available')))->addClass(ZBX_STYLE_GREEN);
     $notav = (new CCol($notav . '  ' . _('Not available')))->addClass(ZBX_STYLE_RED);
     $uncn = (new CCol($uncn . '  ' . _('Unknown')))->addClass(ZBX_STYLE_GREY);
     $total = new CCol($total . '  ' . _('Total'));
     $header = (new CDiv([new CTag('h4', true, _('Hosts info'))]))->addClass(ZBX_STYLE_DASHBRD_WIDGET_HEAD);
     if ($this->screenitem['resourceid'] != 0) {
         $groups = API::HostGroup()->get(['output' => ['name'], 'groupids' => [$this->screenitem['resourceid']]]);
         $header->addItem((new CList())->addItem([_('Group'), ':', SPACE, $groups[0]['name']]));
     }
     $table = new CTableInfo();
     if ($this->screenitem['style'] == STYLE_HORIZONTAL) {
         $table->addRow([$avail, $notav, $uncn, $total]);
     } else {
         $table->addRow($avail);
         $table->addRow($notav);
         $table->addRow($uncn);
         $table->addRow($total);
     }
     $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]));
 }
 protected function doAction()
 {
     $hosts = API::Host()->get(['output' => ['hostid'], 'filter' => ['proxy_hostid' => $this->getInput('proxyids'), 'status' => HOST_STATUS_NOT_MONITORED]]);
     foreach ($hosts as &$host) {
         $host['status'] = HOST_STATUS_MONITORED;
     }
     unset($host);
     $result = API::Host()->update($hosts);
     $updated = count($hosts);
     $response = new CControllerResponseRedirect('zabbix.php?action=proxy.list&uncheck=1');
     if ($result) {
         $response->setMessageOk(_n('Host enabled', 'Hosts enabled', $updated));
     } else {
         $response->setMessageError(_n('Cannot enable host', 'Cannot enable hosts', $updated));
     }
     $this->setResponse($response);
 }
 protected function doAction()
 {
     $filter = ['groupids' => null, 'maintenance' => null, 'severity' => null, 'trigger_name' => '', 'extAck' => 0];
     if (CProfile::get('web.dashconf.filter.enable', 0) == 1) {
         // groups
         if (CProfile::get('web.dashconf.groups.grpswitch', 0) == 0) {
             // null mean all groups
             $filter['groupids'] = null;
         } else {
             $filter['groupids'] = zbx_objectValues(CFavorite::get('web.dashconf.groups.groupids'), 'value');
             $hideHostGroupIds = zbx_objectValues(CFavorite::get('web.dashconf.groups.hide.groupids'), 'value');
             if ($hideHostGroupIds) {
                 // get all groups if no selected groups defined
                 if (!$filter['groupids']) {
                     $dbHostGroups = API::HostGroup()->get(['output' => ['groupid']]);
                     $filter['groupids'] = zbx_objectValues($dbHostGroups, 'groupid');
                 }
                 $filter['groupids'] = array_diff($filter['groupids'], $hideHostGroupIds);
                 // get available hosts
                 $dbAvailableHosts = API::Host()->get(['groupids' => $filter['groupids'], 'output' => ['hostid']]);
                 $availableHostIds = zbx_objectValues($dbAvailableHosts, 'hostid');
                 $dbDisabledHosts = API::Host()->get(['groupids' => $hideHostGroupIds, 'output' => ['hostid']]);
                 $disabledHostIds = zbx_objectValues($dbDisabledHosts, 'hostid');
                 $filter['hostids'] = array_diff($availableHostIds, $disabledHostIds);
             } else {
                 if (!$filter['groupids']) {
                     // null mean all groups
                     $filter['groupids'] = null;
                 }
             }
         }
         // hosts
         $maintenance = CProfile::get('web.dashconf.hosts.maintenance', 1);
         $filter['maintenance'] = $maintenance == 0 ? 0 : null;
         // triggers
         $severity = CProfile::get('web.dashconf.triggers.severity', null);
         $filter['severity'] = zbx_empty($severity) ? null : explode(';', $severity);
         $filter['severity'] = zbx_toHash($filter['severity']);
         $filter['trigger_name'] = CProfile::get('web.dashconf.triggers.name', '');
         $config = select_config();
         $filter['extAck'] = $config['event_ack_enable'] ? CProfile::get('web.dashconf.events.extAck', 0) : 0;
     }
     $this->setResponse(new CControllerResponseData(['filter' => $filter, 'user' => ['debug_mode' => $this->getDebugMode()]]));
 }
Exemplo n.º 10
0
 protected function checkPermissions()
 {
     if ($this->getUserType() < USER_TYPE_ZABBIX_USER) {
         return false;
     }
     if ($this->hasInput('groupid') && $this->getInput('groupid') != 0) {
         $groups = API::HostGroup()->get(['output' => [], 'groupids' => [$this->getInput('groupid')]]);
         if (!$groups) {
             return false;
         }
     }
     if ($this->hasInput('hostid') && $this->getInput('hostid') != 0) {
         $hosts = API::Host()->get(['output' => [], 'hostids' => [$this->getInput('hostid')]]);
         if (!$hosts) {
             return false;
         }
     }
     return true;
 }
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     // fetch hosts
     $hosts = API::Host()->get(array('output' => array('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 = array('output' => array('description', 'expression', 'priority', 'url', 'value', 'triggerid', 'lastchange', 'flags'), 'selectHosts' => array('hostid', 'name', 'status'), 'selectItems' => array('itemid', 'hostid', 'name', 'key_', 'value_type'), 'hostids' => $hostIds, 'monitored' => true, 'skipDependent' => true, 'sortfield' => 'description');
     // application filter
     if ($this->screenitem['application'] !== '') {
         $applications = API::Application()->get(array('output' => array('applicationid'), 'hostids' => $hostIds, 'search' => array('name' => $this->screenitem['application'])));
         $options['applicationids'] = zbx_objectValues($applications, 'applicationid');
     }
     $triggers = API::Trigger()->get($options);
     /*
      * 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);
     return $this->getOutput(getTriggersOverview($hosts, $triggers, $this->pageFile, $this->screenitem['style'], $this->screenid));
 }
 protected function doAction()
 {
     $filter = ['groupids' => null, 'maintenance' => null];
     if (CProfile::get('web.dashconf.filter.enable', 0) == 1) {
         // groups
         if (CProfile::get('web.dashconf.groups.grpswitch', 0) == 0) {
             // null mean all groups
             $filter['groupids'] = null;
         } else {
             $filter['groupids'] = zbx_objectValues(CFavorite::get('web.dashconf.groups.groupids'), 'value');
             $hideHostGroupIds = zbx_objectValues(CFavorite::get('web.dashconf.groups.hide.groupids'), 'value');
             if ($hideHostGroupIds) {
                 // get all groups if no selected groups defined
                 if (!$filter['groupids']) {
                     $dbHostGroups = API::HostGroup()->get(['output' => ['groupid']]);
                     $filter['groupids'] = zbx_objectValues($dbHostGroups, 'groupid');
                 }
                 $filter['groupids'] = array_diff($filter['groupids'], $hideHostGroupIds);
                 // get available hosts
                 $dbAvailableHosts = API::Host()->get(['groupids' => $filter['groupids'], 'output' => ['hostid']]);
                 $availableHostIds = zbx_objectValues($dbAvailableHosts, 'hostid');
                 $dbDisabledHosts = API::Host()->get(['groupids' => $hideHostGroupIds, 'output' => ['hostid']]);
                 $disabledHostIds = zbx_objectValues($dbDisabledHosts, 'hostid');
                 $filter['hostids'] = array_diff($availableHostIds, $disabledHostIds);
             } else {
                 if (!$filter['groupids']) {
                     // null mean all groups
                     $filter['groupids'] = null;
                 }
             }
         }
         // hosts
         $maintenance = CProfile::get('web.dashconf.hosts.maintenance', 1);
         $filter['maintenance'] = $maintenance == 0 ? 0 : null;
     }
     $this->setResponse(new CControllerResponseData(['filter' => $filter, 'user' => ['debug_mode' => $this->getDebugMode()]]));
 }
Exemplo n.º 13
0
 protected function inherit($graph, $hostids = null)
 {
     $graphTemplates = API::Template()->get(array('itemids' => zbx_objectValues($graph['gitems'], 'itemid'), 'output' => array('templateid'), 'nopermissions' => true));
     if (empty($graphTemplates)) {
         return true;
     }
     $graphTemplate = reset($graphTemplates);
     $chdHosts = API::Host()->get(array('templateids' => $graphTemplate['templateid'], 'output' => array('hostid', 'host'), 'preservekeys' => true, 'hostids' => $hostids, 'nopermissions' => true, 'templated_hosts' => true));
     $graph = $this->get(array('graphids' => $graph['graphid'], 'nopermissions' => true, 'filter' => array('flags' => null), 'selectGraphItems' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND));
     $graph = reset($graph);
     foreach ($chdHosts as $chdHost) {
         $tmpGraph = $graph;
         $tmpGraph['templateid'] = $graph['graphid'];
         $tmpGraph['gitems'] = getSameGraphItemsForHost($tmpGraph['gitems'], $chdHost['hostid']);
         if (!$tmpGraph['gitems']) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" cannot inherit. No required items on "%2$s".', $tmpGraph['name'], $chdHost['host']));
         }
         if ($tmpGraph['ymax_itemid'] > 0) {
             $ymaxItemid = getSameGraphItemsForHost(array(array('itemid' => $tmpGraph['ymax_itemid'])), $chdHost['hostid']);
             if (!$ymaxItemid) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" cannot inherit. No required items on "%2$s" (Ymax value item).', $tmpGraph['name'], $chdHost['host']));
             }
             $ymaxItemid = reset($ymaxItemid);
             $tmpGraph['ymax_itemid'] = $ymaxItemid['itemid'];
         }
         if ($tmpGraph['ymin_itemid'] > 0) {
             $yminItemid = getSameGraphItemsForHost(array(array('itemid' => $tmpGraph['ymin_itemid'])), $chdHost['hostid']);
             if (!$yminItemid) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" cannot inherit. No required items on "%2$s" (Ymin value item).', $tmpGraph['name'], $chdHost['host']));
             }
             $yminItemid = reset($yminItemid);
             $tmpGraph['ymin_itemid'] = $yminItemid['itemid'];
         }
         // check if templated graph exists
         $chdGraphs = $this->get(array('filter' => array('templateid' => $tmpGraph['graphid'], 'flags' => array(ZBX_FLAG_DISCOVERY_PROTOTYPE, ZBX_FLAG_DISCOVERY_NORMAL)), 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'hostids' => $chdHost['hostid']));
         if ($chdGraph = reset($chdGraphs)) {
             if ($tmpGraph['name'] !== $chdGraph['name']) {
                 $graphExists = $this->get(array('output' => array('graphid'), 'hostids' => $chdHost['hostid'], 'filter' => array('name' => $tmpGraph['name'], 'flags' => null), 'nopermissions' => true, 'limit' => 1));
                 if ($graphExists) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s".', $tmpGraph['name'], $chdHost['host']));
                 }
             } elseif ($chdGraph['flags'] != $tmpGraph['flags']) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Graph with same name but other type exist.'));
             }
             $tmpGraph['graphid'] = $chdGraph['graphid'];
             $this->updateReal($tmpGraph, $chdGraph);
         } else {
             $chdGraph = $this->get(array('filter' => array('name' => $tmpGraph['name'], 'flags' => null), 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'nopermissions' => true, 'hostids' => $chdHost['hostid']));
             if ($chdGraph = reset($chdGraph)) {
                 if ($chdGraph['templateid'] != 0) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s" (inherited from another template).', $tmpGraph['name'], $chdHost['host']));
                 } elseif ($chdGraph['flags'] != $tmpGraph['flags']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('Graph with same name but other type exist.'));
                 }
                 $chdGraphItemItems = array();
                 foreach (array(API::Item(), API::ItemPrototype()) as $api) {
                     $chdGraphItemItems += $api->get(array('output' => array('key_', 'hostid', 'itemid'), 'itemids' => zbx_objectValues($chdGraph['gitems'], 'itemid'), 'preservekeys' => true));
                 }
                 if (count($chdGraph['gitems']) == count($tmpGraph['gitems'])) {
                     foreach ($tmpGraph['gitems'] as $gitem) {
                         foreach ($chdGraph['gitems'] as $chdGraphItem) {
                             $chdGraphItemItem = $chdGraphItemItems[$chdGraphItem['itemid']];
                             if ($gitem['key_'] == $chdGraphItemItem['key_'] && bccomp($chdHost['hostid'], $chdGraphItemItem['hostid']) == 0) {
                                 continue 2;
                             }
                         }
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s" (items are not identical).', $tmpGraph['name'], $chdHost['host']));
                     }
                     $tmpGraph['graphid'] = $chdGraph['graphid'];
                     $this->updateReal($tmpGraph, $chdGraph);
                 } else {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s" (items are not identical).', $tmpGraph['name'], $chdHost['host']));
                 }
             } else {
                 $graphid = $this->createReal($tmpGraph);
                 $tmpGraph['graphid'] = $graphid;
             }
         }
         $this->inherit($tmpGraph);
     }
 }
Exemplo n.º 14
0
//PAGE_TYPE_IMAGE;
require_once dirname(__FILE__) . '/include/page_header.php';
// VAR	TYPE	OPTIONAL	FLAGS	VALIDATION	EXCEPTION
$fields = array('graphid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, null), 'period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'profileIdx' => array(T_ZBX_STR, O_OPT, null, null, null), 'profileIdx2' => array(T_ZBX_STR, O_OPT, null, null, null), 'updateProfile' => array(T_ZBX_STR, O_OPT, null, null, null), 'border' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'width' => array(T_ZBX_INT, O_OPT, P_NZERO, '{}>0', null), 'height' => array(T_ZBX_INT, O_OPT, P_NZERO, '{}>0', null));
check_fields($fields);
/*
 * Permissions
 */
$dbGraph = API::Graph()->get(array('graphids' => $_REQUEST['graphid'], 'output' => API_OUTPUT_EXTEND, 'expandName' => 1));
//    _ex($dbGraph,0);
if (!$dbGraph) {
    access_deny();
} else {
    $dbGraph = reset($dbGraph);
}
$host = API::Host()->get(array('nodeids' => get_current_nodeid(true), 'graphids' => $_REQUEST['graphid'], 'output' => API_OUTPUT_EXTEND, 'templated_hosts' => true));
$host = reset($host);
/*
 * Display
 */
$timeline = CScreenBase::calculateTime(array('profileIdx' => get_request('profileIdx', 'web.screens'), 'profileIdx2' => get_request('profileIdx2'), 'updateProfile' => get_request('updateProfile', true), 'period' => get_request('period'), 'stime' => get_request('stime')));
CProfile::update('web.screens.graphid', $_REQUEST['graphid'], PROFILE_TYPE_ID);
$chartHeader = '';
if (id2nodeid($dbGraph['graphid']) != get_current_nodeid()) {
    $chartHeader = get_node_name_by_elid($dbGraph['graphid'], true, NAME_DELIMITER);
}
$chartHeader .= $host['name'] . NAME_DELIMITER . $dbGraph['name'];
$graph = new CLineGraphDraw_Zabbix($dbGraph['graphtype']);
$graph->setHeader($chartHeader);
$graph->setPeriod($timeline['period']);
$graph->setSTime($timeline['stime']);
 protected function inherit($applications, $hostids = null)
 {
     if (empty($applications)) {
         return $applications;
     }
     $applications = zbx_toHash($applications, 'applicationid');
     $chdHosts = API::Host()->get(array('output' => array('hostid', 'host'), 'templateids' => zbx_objectValues($applications, 'hostid'), 'hostids' => $hostids, 'preservekeys' => 1, 'nopermissions' => 1, 'templated_hosts' => 1));
     if (empty($chdHosts)) {
         return true;
     }
     $insertApplications = array();
     $updateApplications = array();
     foreach ($chdHosts as $hostid => $host) {
         $templateids = zbx_toHash($host['templates'], 'templateid');
         // skip applications not from parent templates of current host
         $parentApplications = array();
         foreach ($applications as $parentApplicationId => $parentApplication) {
             if (isset($templateids[$parentApplication['hostid']])) {
                 $parentApplications[$parentApplicationId] = $parentApplication;
             }
         }
         // check existing items to decide insert or update
         $exApplications = $this->get(array('output' => API_OUTPUT_EXTEND, 'hostids' => $hostid, 'preservekeys' => true, 'nopermissions' => true));
         $exApplicationsNames = zbx_toHash($exApplications, 'name');
         $exApplicationsTpl = zbx_toHash($exApplications, 'templateid');
         foreach ($parentApplications as $parentApplicationId => $parentApplication) {
             $exApplication = null;
             // update by templateid
             if (isset($exApplicationsTpl[$parentApplicationId])) {
                 $exApplication = $exApplicationsTpl[$parentApplicationId];
             }
             // update by name
             if (isset($parentApplication['name']) && isset($exApplicationsNames[$parentApplication['name']])) {
                 $exApplication = $exApplicationsNames[$parentApplication['name']];
                 if ($exApplication['templateid'] > 0 && !idcmp($exApplication['templateid'], $parentApplication['applicationid'])) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Application "%1$s" already exists for host "%2$s".', $exApplication['name'], $host['name']));
                 }
             }
             $newApplication = $parentApplication;
             $newApplication['hostid'] = $host['hostid'];
             $newApplication['templateid'] = $parentApplication['applicationid'];
             if ($exApplication) {
                 $newApplication['applicationid'] = $exApplication['applicationid'];
                 $updateApplications[] = $newApplication;
             } else {
                 $insertApplications[] = $newApplication;
             }
         }
     }
     $this->createReal($insertApplications);
     $this->updateReal($updateApplications);
     $inheritedApplications = array_merge($insertApplications, $updateApplications);
     $this->inherit($inheritedApplications);
     return true;
 }
Exemplo n.º 16
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     // selectGroups
     if ($options['selectGroups'] !== null && $options['selectGroups'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'maintenanceid', 'groupid', 'maintenances_groups');
         $groups = API::HostGroup()->get(['output' => $options['selectGroups'], 'hostgroupids' => $relationMap->getRelatedIds(), 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $groups, 'groups');
     }
     // selectHosts
     if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'maintenanceid', 'hostid', 'maintenances_hosts');
         $groups = API::Host()->get(['output' => $options['selectHosts'], 'hostids' => $relationMap->getRelatedIds(), 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $groups, 'hosts');
     }
     // selectTimeperiods
     if ($options['selectTimeperiods'] !== null && $options['selectTimeperiods'] != API_OUTPUT_COUNT) {
         $relationMap = $this->createRelationMap($result, 'maintenanceid', 'timeperiodid', 'maintenances_windows');
         $timeperiods = API::getApiService()->select('timeperiods', ['output' => $options['selectTimeperiods'], 'filter' => ['timeperiodid' => $relationMap->getRelatedIds()], 'preservekeys' => true]);
         $result = $relationMap->mapMany($result, $timeperiods, 'timeperiods');
     }
     return $result;
 }
Exemplo n.º 17
0
 /**
  * Get map data.
  *
  * @param array  $options
  * @param array  $options['groupids']					HostGroup IDs
  * @param array  $options['hostids']					Host IDs
  * @param bool   $options['monitored_hosts']			only monitored Hosts
  * @param bool   $options['templated_hosts']			include templates in result
  * @param bool   $options['with_items']					only with items
  * @param bool   $options['with_monitored_items']		only with monitored items
  * @param bool   $options['with_triggers'] only with	triggers
  * @param bool   $options['with_monitored_triggers']	only with monitored triggers
  * @param bool   $options['with_httptests'] only with	http tests
  * @param bool   $options['with_monitored_httptests']	only with monitored http tests
  * @param bool   $options['with_graphs']				only with graphs
  * @param bool   $options['editable']					only with read-write permission. Ignored for SuperAdmins
  * @param int    $options['count']						count Hosts, returned column name is rowscount
  * @param string $options['pattern']					search hosts by pattern in host names
  * @param int    $options['limit']						limit selection
  * @param string $options['sortorder']
  * @param string $options['sortfield']
  *
  * @return array|boolean Host data as array or false if error
  */
 public function get(array $options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $sqlParts = array('select' => array('sysmaps' => 's.sysmapid'), 'from' => array('sysmaps' => 'sysmaps s'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('sysmapids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_EXTEND, 'selectSelements' => null, 'selectLinks' => null, 'selectIconMap' => null, 'selectUrls' => null, 'countOutput' => null, 'expandUrls' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // sysmapids
     if (!is_null($options['sysmapids'])) {
         zbx_value2array($options['sysmapids']);
         $sqlParts['where']['sysmapid'] = dbConditionInt('s.sysmapid', $options['sysmapids']);
     }
     // search
     if (!is_null($options['search'])) {
         zbx_db_search('sysmaps s', $options, $sqlParts);
     }
     // filter
     if (!is_null($options['filter'])) {
         $this->dbFilter('sysmaps s', $options, $sqlParts);
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $sysmapids = array();
     $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
     while ($sysmap = DBfetch($res)) {
         if ($options['countOutput']) {
             $result = $sysmap['rowscount'];
         } else {
             $sysmapids[$sysmap['sysmapid']] = $sysmap['sysmapid'];
             // originally we intended not to pass those parameters if advanced labels are off, but they might be useful
             // leaving this block commented
             // if (isset($sysmap['label_format']) && ($sysmap['label_format'] == SYSMAP_LABEL_ADVANCED_OFF)) {
             // 	unset($sysmap['label_string_hostgroup'], $sysmap['label_string_host'], $sysmap['label_string_trigger'], $sysmap['label_string_map'], $sysmap['label_string_image']);
             // }
             $result[$sysmap['sysmapid']] = $sysmap;
         }
     }
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         if ($result) {
             $linkTriggers = array();
             $dbLinkTriggers = DBselect('SELECT slt.triggerid,sl.sysmapid' . ' FROM sysmaps_link_triggers slt,sysmaps_links sl' . ' WHERE ' . dbConditionInt('sl.sysmapid', $sysmapids) . ' AND sl.linkid=slt.linkid');
             while ($linkTrigger = DBfetch($dbLinkTriggers)) {
                 $linkTriggers[$linkTrigger['sysmapid']] = $linkTrigger['triggerid'];
             }
             if ($linkTriggers) {
                 $trigOptions = array('triggerids' => $linkTriggers, 'editable' => $options['editable'], 'output' => array('triggerid'), 'preservekeys' => true);
                 $allTriggers = API::Trigger()->get($trigOptions);
                 foreach ($linkTriggers as $id => $triggerid) {
                     if (!isset($allTriggers[$triggerid])) {
                         unset($result[$id], $sysmapids[$id]);
                     }
                 }
             }
             $hostsToCheck = array();
             $mapsToCheck = array();
             $triggersToCheck = array();
             $hostGroupsToCheck = array();
             $selements = array();
             $dbSelements = DBselect('SELECT se.* FROM sysmaps_elements se WHERE ' . dbConditionInt('se.sysmapid', $sysmapids));
             while ($selement = DBfetch($dbSelements)) {
                 $selements[$selement['selementid']] = $selement;
                 switch ($selement['elementtype']) {
                     case SYSMAP_ELEMENT_TYPE_HOST:
                         $hostsToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                     case SYSMAP_ELEMENT_TYPE_MAP:
                         $mapsToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                     case SYSMAP_ELEMENT_TYPE_TRIGGER:
                         $triggersToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                     case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
                         $hostGroupsToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                 }
             }
             if ($hostsToCheck) {
                 $allowedHosts = API::Host()->get(array('hostids' => $hostsToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('hostid')));
                 foreach ($hostsToCheck as $elementid) {
                     if (!isset($allowedHosts[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
             if ($mapsToCheck) {
                 $allowedMaps = $this->get(array('sysmapids' => $mapsToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('sysmapid')));
                 foreach ($mapsToCheck as $elementid) {
                     if (!isset($allowedMaps[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_MAP && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
             if ($triggersToCheck) {
                 $allowedTriggers = API::Trigger()->get(array('triggerids' => $triggersToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('triggerid')));
                 foreach ($triggersToCheck as $elementid) {
                     if (!isset($allowedTriggers[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_TRIGGER && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
             if ($hostGroupsToCheck) {
                 $allowedHostGroups = API::HostGroup()->get(array('groupids' => $hostGroupsToCheck, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => array('groupid')));
                 foreach ($hostGroupsToCheck as $elementid) {
                     if (!isset($allowedHostGroups[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     if ($result) {
         $result = $this->addRelatedObjects($options, $result);
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Exemplo n.º 18
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;
 }
Exemplo n.º 19
0
    $hostIds[$trigger['hosts'][0]['hostid']] = $trigger['hosts'][0]['hostid'];
    $triggers[$triggerId]['cnt_event'] = $triggersEventCount[$triggerId];
}
CArrayHelper::sort($triggers, array(array('field' => 'cnt_event', 'order' => ZBX_SORT_DOWN), 'host', 'description', 'priority'));
$hosts = API::Host()->get(array('output' => array('hostid', 'status'), 'hostids' => $hostIds, 'selectGraphs' => API_OUTPUT_COUNT, 'selectScreens' => API_OUTPUT_COUNT, 'preservekeys' => true));
$scripts = API::Script()->getScriptsByHosts($hostIds);
$monitoredHostIds = array();
foreach ($triggers as $trigger) {
    foreach ($trigger['hosts'] as $host) {
        if ($host['status'] == HOST_STATUS_MONITORED) {
            $monitoredHostIds[$host['hostid']] = true;
        }
    }
}
if ($monitoredHostIds) {
    $monitoredHosts = API::Host()->get(array('output' => array('hostid'), 'selectGroups' => array('groupid'), 'hostids' => array_keys($monitoredHostIds), 'preservekeys' => true));
}
foreach ($triggers as $trigger) {
    foreach ($trigger['hosts'] as $host) {
        if ($host['status'] == HOST_STATUS_MONITORED) {
            // Pass a monitored 'hostid' and corresponding first 'groupid' to menu pop-up "Events" link.
            $trigger['hostid'] = $host['hostid'];
            $trigger['groupid'] = $monitoredHosts[$trigger['hostid']]['groups'][0]['groupid'];
            break;
        } else {
            // Unmonitored will have disabled "Events" link and there is no 'groupid' or 'hostid'.
            $trigger['hostid'] = 0;
            $trigger['groupid'] = 0;
        }
    }
    $hostId = $trigger['hosts'][0]['hostid'];
    }
}
$r_form = new CForm('get');
$r_form->addItem(array(_('Group'), SPACE, $pageFilter->getGroupsCB(true), SPACE));
$r_form->addItem(array(_('Grouping by'), SPACE, $inventoryFieldsComboBox));
$hostinvent_wdgt->addHeader(_('Hosts'), $r_form);
$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')));
Exemplo n.º 21
0
define('ZBX_PAGE_DO_JS_REFRESH', 1);
require_once dirname(__FILE__) . '/include/page_header.php';
// VAR	TYPE	OPTIONAL	FLAGS	VALIDATION	EXCEPTION
$fields = array('groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'hostid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'tr_groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'tr_hostid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'elementid' => array(T_ZBX_INT, O_OPT, P_SYS | P_NZERO, DB_ID, null), 'screenname' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'step' => array(T_ZBX_INT, O_OPT, P_SYS, BETWEEN(0, 65535), null), 'period' => array(T_ZBX_INT, O_OPT, P_SYS, null, null), 'stime' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'reset' => array(T_ZBX_STR, O_OPT, P_SYS, IN("'reset'"), null), 'fullscreen' => array(T_ZBX_INT, O_OPT, P_SYS, IN('0,1'), null), 'favobj' => array(T_ZBX_STR, O_OPT, P_ACT, null, null), 'favref' => array(T_ZBX_STR, O_OPT, P_ACT, NOT_EMPTY, null), 'favid' => array(T_ZBX_INT, O_OPT, P_ACT, null, null), 'favaction' => array(T_ZBX_STR, O_OPT, P_ACT, IN("'add','remove','flop'"), null), 'favstate' => array(T_ZBX_INT, O_OPT, P_ACT, NOT_EMPTY, null));
check_fields($fields);
/*
 * Permissions
 */
// validate group IDs
$validateGroupIds = array_filter(array(get_request('groupid'), get_request('tr_groupid')));
if ($validateGroupIds && !API::HostGroup()->isReadable($validateGroupIds)) {
    access_deny();
}
// validate host IDs
$validateHostIds = array_filter(array(get_request('hostid'), get_request('tr_hostid')));
if ($validateHostIds && !API::Host()->isReadable($validateHostIds)) {
    access_deny();
}
if (get_request('elementid')) {
    $screens = API::Screen()->get(array('screenids' => array($_REQUEST['elementid']), 'output' => array('screenid')));
    if (!$screens) {
        access_deny();
    }
}
/*
 * Filter
 */
if (isset($_REQUEST['favobj'])) {
    if ($_REQUEST['favobj'] == 'filter') {
        CProfile::update('web.screens.filter.state', $_REQUEST['favstate'], PROFILE_TYPE_INT);
    }
Exemplo n.º 22
0
/**
 * Create and return a DIV with web monitoring overview.
 *
 * @param array $filter
 * @param array $filter['groupids']
 * @param bool  $filter['maintenance']
 *
 * @return CDiv
 */
function make_webmon_overview($filter)
{
    $groups = API::HostGroup()->get(array('groupids' => $filter['groupids'], 'hostids' => isset($filter['hostids']) ? $filter['hostids'] : null, 'monitored_hosts' => true, 'with_monitored_httptests' => true, 'output' => array('groupid', 'name'), 'preservekeys' => true));
    foreach ($groups as &$group) {
        $group['nodename'] = get_node_name_by_elid($group['groupid']);
    }
    unset($group);
    CArrayHelper::sort($groups, array(array('field' => 'nodename', 'order' => ZBX_SORT_UP), array('field' => 'name', 'order' => ZBX_SORT_UP)));
    $groupIds = array_keys($groups);
    $availableHosts = API::Host()->get(array('groupids' => $groupIds, 'hostids' => isset($filter['hostids']) ? $filter['hostids'] : null, 'monitored_hosts' => true, 'filter' => array('maintenance_status' => $filter['maintenance']), 'output' => array('hostid'), 'preservekeys' => true));
    $availableHostIds = array_keys($availableHosts);
    $table = new CTableInfo(_('No web scenarios found.'));
    $table->setHeader(array(is_show_all_nodes() ? _('Node') : null, _('Host group'), _('Ok'), _('Failed'), _('Unknown')));
    $data = array();
    // fetch links between HTTP tests and host groups
    $result = DbFetchArray(DBselect('SELECT DISTINCT ht.httptestid,hg.groupid' . ' FROM httptest ht,hosts_groups hg' . ' WHERE ht.hostid=hg.hostid' . ' AND ' . dbConditionInt('hg.hostid', $availableHostIds) . ' AND ' . dbConditionInt('hg.groupid', $groupIds)));
    // fetch HTTP test execution data
    $httpTestData = Manager::HttpTest()->getLastData(zbx_objectValues($result, 'httptestid'));
    foreach ($result as $row) {
        if (!isset($httpTestData[$row['httptestid']])) {
            $data[$row['groupid']]['unknown'] = empty($data[$row['groupid']]['unknown']) ? 1 : ++$data[$row['groupid']]['unknown'];
        } elseif ($httpTestData[$row['httptestid']]['lastfailedstep'] != 0) {
            $data[$row['groupid']]['failed'] = empty($data[$row['groupid']]['failed']) ? 1 : ++$data[$row['groupid']]['failed'];
        } else {
            $data[$row['groupid']]['ok'] = empty($data[$row['groupid']]['ok']) ? 1 : ++$data[$row['groupid']]['ok'];
        }
    }
    foreach ($groups as $group) {
        if (!empty($data[$group['groupid']])) {
            $table->addRow(array(is_show_all_nodes() ? $group['nodename'] : null, $group['name'], new CSpan(empty($data[$group['groupid']]['ok']) ? 0 : $data[$group['groupid']]['ok'], 'off'), new CSpan(empty($data[$group['groupid']]['failed']) ? 0 : $data[$group['groupid']]['failed'], empty($data[$group['groupid']]['failed']) ? 'off' : 'on'), new CSpan(empty($data[$group['groupid']]['unknown']) ? 0 : $data[$group['groupid']]['unknown'], 'unknown')));
        }
    }
    $script = new CJSScript(get_js("jQuery('#hat_webovr_footer').html('" . _s('Updated: %s', zbx_date2str(_('H:i:s'))) . "')"));
    return new CDiv(array($table, $script));
}
Exemplo n.º 23
0
$_REQUEST['go'] = get_request('go', 'none');
$_REQUEST['params'] = get_request($paramsFieldName, '');
unset($_REQUEST[$paramsFieldName]);
/*
 * Permissions
 */
if (get_request('itemid', false)) {
    $item = API::DiscoveryRule()->get(array('itemids' => $_REQUEST['itemid'], 'output' => API_OUTPUT_EXTEND, 'selectHosts' => array('status', 'flags'), 'editable' => true));
    $item = reset($item);
    if (!$item) {
        access_deny();
    }
    $_REQUEST['hostid'] = $item['hostid'];
    $host = reset($item['hosts']);
} else {
    $hosts = API::Host()->get(array('hostids' => $_REQUEST['hostid'], 'output' => array('status', 'flags'), 'templated_hosts' => true, 'editable' => true));
    $host = reset($hosts);
    if (!$host) {
        access_deny();
    }
}
/*
 * Ajax
 */
if (isset($_REQUEST['favobj'])) {
    if ($_REQUEST['favobj'] == 'filter') {
        CProfile::update('web.host_discovery.filter.state', $_REQUEST['favstate'], PROFILE_TYPE_INT);
    }
}
if ($page['type'] == PAGE_TYPE_JS || $page['type'] == PAGE_TYPE_HTML_BLOCK) {
    require_once dirname(__FILE__) . '/include/page_footer.php';
Exemplo n.º 24
0
    foreach ($proxies as $proxyId => $proxy) {
        if (isset($queueData[$proxyId])) {
            $proxyData = $queueData[$proxyId];
        } else {
            $proxyData = ['delay5' => 0, 'delay10' => 0, 'delay30' => 0, 'delay60' => 0, 'delay300' => 0, 'delay600' => 0];
        }
        $table->addRow([$proxy['host'], getSeverityCell(TRIGGER_SEVERITY_NOT_CLASSIFIED, $severityConfig, $proxyData['delay5'], !$proxyData['delay5']), getSeverityCell(TRIGGER_SEVERITY_INFORMATION, $severityConfig, $proxyData['delay10'], !$proxyData['delay10']), getSeverityCell(TRIGGER_SEVERITY_WARNING, $severityConfig, $proxyData['delay30'], !$proxyData['delay30']), getSeverityCell(TRIGGER_SEVERITY_AVERAGE, $severityConfig, $proxyData['delay60'], !$proxyData['delay60']), getSeverityCell(TRIGGER_SEVERITY_HIGH, $severityConfig, $proxyData['delay300'], !$proxyData['delay300']), getSeverityCell(TRIGGER_SEVERITY_DISASTER, $severityConfig, $proxyData['delay600'], !$proxyData['delay600'])]);
    }
} elseif ($config == QUEUE_DETAILS) {
    $queueData = zbx_toHash($queueData, 'itemid');
    $items = API::Item()->get(['output' => ['itemid', 'hostid', 'name', 'key_'], 'selectHosts' => ['name'], 'itemids' => array_keys($queueData), 'webitems' => true, 'preservekeys' => true]);
    $items = CMacrosResolverHelper::resolveItemNames($items);
    // get hosts for queue items
    $hostIds = zbx_objectValues($items, 'hostid');
    $hostIds = array_keys(array_flip($hostIds));
    $hosts = API::Host()->get(['output' => ['hostid', 'proxy_hostid'], 'hostids' => $hostIds, 'preservekeys' => true]);
    // get proxies for those hosts
    $proxyHostIds = [];
    foreach ($hosts as $host) {
        if ($host['proxy_hostid']) {
            $proxyHostIds[$host['proxy_hostid']] = $host['proxy_hostid'];
        }
    }
    if ($proxyHostIds) {
        $proxies = API::Proxy()->get(['proxyids' => $proxyHostIds, 'output' => ['proxyid', 'host'], 'preservekeys' => true]);
    }
    $table->setHeader([_('Scheduled check'), _('Delayed by'), _('Host'), _('Name')]);
    $i = 0;
    foreach ($queueData as $itemData) {
        if (!isset($items[$itemData['itemid']])) {
            continue;
Exemplo n.º 25
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;
        }
    }
}
Exemplo n.º 26
0
         $this->data['new_operation']['opcommand']['script'] = $userScript['name'];
     }
 }
 $cmdList = new CTable(null, 'formElementTable');
 $cmdList->attr('style', 'min-width: 310px;');
 $cmdList->setHeader(array(_('Target'), _('Action')));
 $addCmdBtn = new CButton('add', _('New'), 'javascript: showOpCmdForm(0, "new");', 'link_menu');
 $cmdList->addRow(new CRow(new CCol($addCmdBtn, null, 3), null, 'opCmdListFooter'));
 // add participations
 if (!isset($this->data['new_operation']['opcommand_grp'])) {
     $this->data['new_operation']['opcommand_grp'] = array();
 }
 if (!isset($this->data['new_operation']['opcommand_hst'])) {
     $this->data['new_operation']['opcommand_hst'] = array();
 }
 $hosts = API::Host()->get(array('hostids' => zbx_objectValues($this->data['new_operation']['opcommand_hst'], 'hostid'), 'output' => array('hostid', 'name'), 'preservekeys' => true, 'editable' => true));
 $this->data['new_operation']['opcommand_hst'] = array_values($this->data['new_operation']['opcommand_hst']);
 foreach ($this->data['new_operation']['opcommand_hst'] as $ohnum => $cmd) {
     $this->data['new_operation']['opcommand_hst'][$ohnum]['name'] = $cmd['hostid'] > 0 ? $hosts[$cmd['hostid']]['name'] : '';
 }
 order_result($this->data['new_operation']['opcommand_hst'], 'name');
 $groups = API::HostGroup()->get(array('groupids' => zbx_objectValues($this->data['new_operation']['opcommand_grp'], 'groupid'), 'output' => array('groupid', 'name'), 'preservekeys' => true, 'editable' => true));
 $this->data['new_operation']['opcommand_grp'] = array_values($this->data['new_operation']['opcommand_grp']);
 foreach ($this->data['new_operation']['opcommand_grp'] as $ognum => $cmd) {
     $this->data['new_operation']['opcommand_grp'][$ognum]['name'] = $groups[$cmd['groupid']]['name'];
 }
 order_result($this->data['new_operation']['opcommand_grp'], 'name');
 // js add commands
 $jsInsert = 'addPopupValues(' . zbx_jsvalue(array('object' => 'hostid', 'values' => $this->data['new_operation']['opcommand_hst'])) . ');';
 $jsInsert .= 'addPopupValues(' . zbx_jsvalue(array('object' => 'groupid', 'values' => $this->data['new_operation']['opcommand_grp'])) . ');';
 zbx_add_post_js($jsInsert);
Exemplo n.º 27
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     // adding groups
     if ($options['selectGroups'] !== null && $options['selectGroups'] != API_OUTPUT_COUNT) {
         foreach ($result as $scriptId => $script) {
             $result[$scriptId]['groups'] = API::HostGroup()->get(array('output' => $options['selectGroups'], 'groupids' => $script['groupid'] ? $script['groupid'] : null, 'editable' => $script['host_access'] == PERM_READ_WRITE ? true : null));
         }
     }
     // adding hosts
     if ($options['selectHosts'] !== null && $options['selectHosts'] != API_OUTPUT_COUNT) {
         $processedGroups = array();
         foreach ($result as $scriptId => $script) {
             if (isset($processedGroups[$script['groupid'] . '_' . $script['host_access']])) {
                 $result[$scriptId]['hosts'] = $result[$processedGroups[$script['groupid'] . '_' . $script['host_access']]]['hosts'];
             } else {
                 $result[$scriptId]['hosts'] = API::Host()->get(array('output' => $options['selectHosts'], 'groupids' => $script['groupid'] ? $script['groupid'] : null, 'hostids' => $options['hostids'] ? $options['hostids'] : null, 'editable' => $script['host_access'] == PERM_READ_WRITE ? true : null));
                 $processedGroups[$script['groupid'] . '_' . $script['host_access']] = $scriptId;
             }
         }
     }
     return $result;
 }
Exemplo n.º 28
0
 $possibleInventoryFields = zbx_toHash($possibleInventoryFields, 'db_field');
 if ($data['filterField'] !== '' && $data['filterFieldValue'] !== '' && !isset($possibleInventoryFields[$data['filterField']])) {
     error(_s('Impossible to filter by inventory field "%s", which does not exist.', $data['filterField']));
 } else {
     // if we are filtering by field, this field is also required
     if ($data['filterField'] !== '' && $data['filterFieldValue'] !== '') {
         $requiredInventoryFields[] = $data['filterField'];
     }
     $options = ['output' => ['hostid', 'name', 'status'], 'selectInventory' => $requiredInventoryFields, 'withInventory' => true, 'selectGroups' => API_OUTPUT_EXTEND];
     if ($data['pageFilter']->groupid > 0) {
         $options['groupids'] = $data['pageFilter']->groupid;
     }
     if ($data['filterField'] !== '' && $data['filterFieldValue'] !== '') {
         $options['searchInventory'] = [$data['filterField'] => [$data['filterFieldValue']]];
     }
     $data['hosts'] = API::Host()->get($options);
     // filter exact matches
     if ($data['filterField'] !== '' && $data['filterFieldValue'] !== '' && $data['filterExact'] != 0) {
         $needle = mb_strtolower($data['filterFieldValue']);
         foreach ($data['hosts'] as $num => $host) {
             $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]];
Exemplo n.º 29
0
require_once dirname(__FILE__) . '/include/config.inc.php';
$page['title'] = _('Status of Web monitoring');
$page['file'] = 'httpmon.php';
$page['hist_arg'] = array('groupid', 'hostid');
define('ZBX_PAGE_DO_REFRESH', 1);
require_once dirname(__FILE__) . '/include/page_header.php';
//		VAR				TYPE		OPTIONAL	FLAGS	VALIDATION	EXCEPTION
$fields = array('fullscreen' => array(T_ZBX_INT, O_OPT, P_SYS, IN('0,1'), null), 'groupid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null), 'hostid' => array(T_ZBX_INT, O_OPT, P_SYS, DB_ID, null));
check_fields($fields);
/*
 * Permissions
 */
if (get_request('groupid') && !API::HostGroup()->isReadable(array($_REQUEST['groupid']))) {
    access_deny();
}
if (get_request('hostid') && !API::Host()->isReadable(array($_REQUEST['hostid']))) {
    access_deny();
}
validate_sort_and_sortorder('name', ZBX_SORT_DOWN);
$options = array('groups' => array('real_hosts' => true, 'with_httptests' => true), 'hosts' => array('with_monitored_items' => true, 'with_httptests' => true), 'hostid' => get_request('hostid', null), 'groupid' => get_request('groupid', null));
$pageFilter = new CPageFilter($options);
$_REQUEST['groupid'] = $pageFilter->groupid;
$_REQUEST['hostid'] = $pageFilter->hostid;
$displayNodes = is_array(get_current_nodeid()) && $pageFilter->groupid == 0 && $pageFilter->hostid == 0;
$r_form = new CForm('get');
$r_form->addVar('fullscreen', $_REQUEST['fullscreen']);
$r_form->addItem(array(_('Group') . SPACE, $pageFilter->getGroupsCB(true)));
$r_form->addItem(array(SPACE . _('Host') . SPACE, $pageFilter->getHostsCB(true)));
$httpmon_wdgt = new CWidget();
$httpmon_wdgt->addPageHeader(_('STATUS OF WEB MONITORING'), get_icon('fullscreen', array('fullscreen' => $_REQUEST['fullscreen'])));
$httpmon_wdgt->addHeader(_('Web scenarios'), $r_form);
Exemplo n.º 30
0
function get_item_function_info($expr)
{
    $value_type = array(ITEM_VALUE_TYPE_UINT64 => _('Numeric (integer 64bit)'), ITEM_VALUE_TYPE_FLOAT => _('Numeric (float)'), ITEM_VALUE_TYPE_STR => _('Character'), ITEM_VALUE_TYPE_LOG => _('Log'), ITEM_VALUE_TYPE_TEXT => _('Text'));
    $type_of_value_type = array(ITEM_VALUE_TYPE_UINT64 => T_ZBX_INT, ITEM_VALUE_TYPE_FLOAT => T_ZBX_DBL, ITEM_VALUE_TYPE_STR => T_ZBX_STR, ITEM_VALUE_TYPE_LOG => T_ZBX_STR, ITEM_VALUE_TYPE_TEXT => T_ZBX_STR);
    $function_info = array('band' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'abschange' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'avg' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'change' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'count' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'date' => array('value_type' => 'YYYYMMDD', 'type' => T_ZBX_INT, 'validation' => '{}>=19700101&&{}<=99991231'), 'dayofmonth' => array('value_type' => '1-31', 'type' => T_ZBX_INT, 'validation' => '{}>=1&&{}<=31'), 'dayofweek' => array('value_type' => '1-7', 'type' => T_ZBX_INT, 'validation' => IN('1,2,3,4,5,6,7')), 'delta' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'diff' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'fuzzytime' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'iregexp' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'last' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'logeventid' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'logseverity' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'logsource' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'max' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'min' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'nodata' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'now' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'prev' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'regexp' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'str' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'strlen' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'sum' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'time' => array('value_type' => 'HHMMSS', 'type' => T_ZBX_INT, 'validation' => 'zbx_strlen({})==6'));
    $expressionData = new CTriggerExpression();
    if ($expressionData->parse($expr)) {
        if (isset($expressionData->macros[0])) {
            $result = array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1'));
        } elseif (isset($expressionData->usermacros[0]) || isset($expressionData->lldmacros[0])) {
            $result = array('value_type' => $value_type[ITEM_VALUE_TYPE_FLOAT], 'type' => T_ZBX_STR, 'validation' => 'preg_match("/^' . ZBX_PREG_NUMBER . '$/u", {})');
        } elseif (isset($expressionData->expressions[0])) {
            $exprPart = reset($expressionData->expressions);
            if (!isset($function_info[$exprPart['functionName']])) {
                return EXPRESSION_FUNCTION_UNKNOWN;
            }
            $hostFound = API::Host()->get(array('filter' => array('host' => array($exprPart['host'])), 'templated_hosts' => true));
            if (!$hostFound) {
                return EXPRESSION_HOST_UNKNOWN;
            }
            $itemFound = API::Item()->get(array('output' => array('value_type'), 'hostids' => zbx_objectValues($hostFound, 'hostid'), 'filter' => array('key_' => array($exprPart['item'])), 'webitems' => true));
            if (!$itemFound) {
                $itemFound = API::ItemPrototype()->get(array('output' => array('value_type'), 'hostids' => zbx_objectValues($hostFound, 'hostid'), 'filter' => array('key_' => array($exprPart['item']))));
                if (!$itemFound) {
                    return EXPRESSION_HOST_ITEM_UNKNOWN;
                }
            }
            $itemFound = reset($itemFound);
            $result = $function_info[$exprPart['functionName']];
            if (is_array($result['value_type'])) {
                $result['value_type'] = $result['value_type'][$itemFound['value_type']];
                $result['type'] = $result['type'][$itemFound['value_type']];
                if ($result['type'] == T_ZBX_INT || $result['type'] == T_ZBX_DBL) {
                    $result['type'] = T_ZBX_STR;
                    $result['validation'] = 'preg_match("/^' . ZBX_PREG_NUMBER . '$/u",{})';
                }
            }
        } else {
            return EXPRESSION_NOT_A_MACRO_ERROR;
        }
    }
    return $result;
}