Ejemplo n.º 1
0
function updateRegexp(array $regexp, array $expressions)
{
    try {
        $regexpId = $regexp['regexpid'];
        unset($regexp['regexpid']);
        // check existence
        if (!getRegexp($regexpId)) {
            throw new Exception(_('Regular expression does not exist.'));
        }
        // check required fields
        $dbFields = array('name' => null);
        if (!check_db_fields($dbFields, $regexp)) {
            throw new Exception(_('Incorrect arguments passed to function') . ' [updateRegexp]');
        }
        // check duplicate name
        $dbRegexp = DBfetch(DBselect('SELECT re.regexpid' . ' FROM regexps re' . ' WHERE re.name=' . zbx_dbstr($regexp['name']) . andDbNode('re.regexpid')));
        if ($dbRegexp && bccomp($regexpId, $dbRegexp['regexpid']) != 0) {
            throw new Exception(_s('Regular expression "%s" already exists.', $regexp['name']));
        }
        rewriteRegexpExpressions($regexpId, $expressions);
        DB::update('regexps', array('values' => $regexp, 'where' => array('regexpid' => $regexpId)));
    } catch (Exception $e) {
        error($e->getMessage());
        return false;
    }
    return true;
}
 /**
  * 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]));
 }
Ejemplo n.º 3
0
/**
 * Use words instead of dates where it makes sense (today, tomorrow, yesterday).
 *
 * @package FeM\sPof\template\smartyPlugins
 * @author dangerground
 * @since 1.0
 *
 * @api
 *
 * @param string $string
 * @param string $default_date (optional)
 * @param bool $time (optional)
 *
 * @return string
 */
function smarty_modifier_prettydate($string, $default_date = '', $time = true)
{
    require_once SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php';
    if ($string != '') {
        $timestamp = smarty_make_timestamp($string);
    } elseif ($default_date != '') {
        $timestamp = smarty_make_timestamp($default_date);
    } else {
        return '';
    }
    // prepare time
    $pdate = date('Ymd', $timestamp);
    if ($pdate == date('Ymd')) {
        // Today
        return '<strong>' . _s('Heute') . '</strong>' . ($time ? ', ' . date('H:i', $timestamp) : '');
    } elseif ($pdate == date('Ymd', strtotime('+1 day'))) {
        // Tomorrow
        return _s('Morgen') . ($time ? ', ' . date('H:i', $timestamp) : '');
    } elseif ($pdate == date('Ymd', strtotime('-1 day'))) {
        // Yesterday
        return _s('Gestern') . ($time ? ', ' . date('H:i', $timestamp) : '');
    } else {
        // any other day
        return date('d.m.Y' . ($time ? ' H:i' : ''), $timestamp);
    }
}
Ejemplo n.º 4
0
 /**
  * Validate comma-separated IP address ranges.
  *
  * @param string $ranges
  *
  * @return bool
  */
 public function validate($ranges)
 {
     if (!is_string($ranges)) {
         $this->setError(_s('Invalid IP address range "%1$s": must be a string.', $this->stringify($ranges)));
         return false;
     }
     if ($ranges === '') {
         $this->setError(_('IP address range cannot be empty.'));
         return false;
     }
     $this->maxIPCount = 0;
     $this->maxIPRange = '';
     foreach (explode(',', $ranges) as $range) {
         $range = trim($range, " \t\r\n");
         if (!$this->isValidMask($range) && !$this->isValidRange($range)) {
             $this->setError(_s('Invalid IP address range "%1$s".', $range));
             return false;
         }
     }
     if ($this->ipRangeLimit != 0 && bccomp($this->maxIPCount, $this->ipRangeLimit) > 0) {
         $this->setError(_s('IP range "%1$s" exceeds "%2$s" address limit.', $this->maxIPRange, $this->ipRangeLimit));
         return false;
     }
     return true;
 }
Ejemplo n.º 5
0
 /**
  * Validate date and time format.
  *
  * @param string $data			import data
  * @param array  $parent_data	data's parent array
  * @param string $path			XML path (for error reporting)
  *
  * @throws Exception			if the date or time is invalid
  */
 public function validateDateTime($data, array $parent_data = null, $path)
 {
     if (!preg_match('/^20[0-9]{2}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[01])T(2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]Z$/', $data)) {
         throw new Exception(_s('Invalid tag "%1$s": %2$s.', $path, _s('"%1$s" is expected', _x('YYYY-MM-DDThh:mm:ssZ', 'XML date and time format'))));
     }
     return $data;
 }
Ejemplo n.º 6
0
 /**
  * Convert string with xml data to php array.
  *
  * @throws Exception
  *
  * @param string $string
  *
  * @return array
  */
 public function read($string)
 {
     libxml_use_internal_errors(true);
     libxml_disable_entity_loader(true);
     $result = simplexml_load_string($string, null, LIBXML_IMPORT_FLAGS);
     if (!$result) {
         $errors = libxml_get_errors();
         libxml_clear_errors();
         foreach ($errors as $error) {
             $text = '';
             switch ($error->level) {
                 case LIBXML_ERR_WARNING:
                     $text .= _s('XML file contains warning %1$s:', $error->code);
                     break;
                 case LIBXML_ERR_ERROR:
                     $text .= _s('XML file contains error %1$s:', $error->code);
                     break;
                 case LIBXML_ERR_FATAL:
                     $text .= _s('XML file contains fatal error %1$s:', $error->code);
                     break;
             }
             $text .= trim($error->message) . ' [ Line: ' . $error->line . ' | Column: ' . $error->column . ' ]';
             throw new Exception($text);
         }
     }
     $xml = new XMLReader();
     $xml->xml($string);
     $array = $this->xmlToArray($xml);
     $xml->close();
     return $array;
 }
Ejemplo n.º 7
0
function gp($key, $param = '')
{
    if (empty($param)) {
        list($key, $param) = explode(':', $key);
    }
    $val = $_POST[$key];
    return _s($val, $param);
}
Ejemplo n.º 8
0
 /**
  * convert string with data in JSON format to php array.
  *
  * @param string $string
  *
  * @return array
  */
 public function read($string)
 {
     $data = (new CJson())->decode($string, true);
     if ($data === null) {
         throw new Exception(_s('Cannot read JSON: %1$s.', json_last_error_msg()));
     }
     return $data;
 }
Ejemplo n.º 9
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     global $page;
     // rewrite page file
     $page['file'] = $this->pageFile;
     $table = make_system_status(['groupids' => null, 'hostids' => null, 'maintenance' => null, 'trigger_name' => '', 'severity' => null, 'limit' => null, 'extAck' => 0], $this->pageFile . '?screenid=' . $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('hat_syssum', [$table, $footer]))->setHeader(_('Status of Zabbix')));
 }
Ejemplo n.º 10
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     global $page;
     // rewrite page file
     $page['file'] = $this->pageFile;
     $item = new CUIWidget('hat_syssum', make_system_status(array('groupids' => null, 'hostids' => null, 'maintenance' => null, 'severity' => null, 'limit' => null, 'extAck' => 0, 'screenid' => $this->screenid)));
     $item->setHeader(_('Status of Zabbix'), SPACE);
     $item->setFooter(_s('Updated: %s', zbx_date2str(_('H:i:s'))));
     return $this->getOutput($item);
 }
Ejemplo n.º 11
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     // if screen is defined in template, then 'real_resourceid' is defined and should be used
     if (!empty($this->screenitem['real_resourceid'])) {
         $this->screenitem['resourceid'] = $this->screenitem['real_resourceid'];
     }
     if ($this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM && !empty($this->hostid)) {
         $newitemid = get_same_item_for_host($this->screenitem['resourceid'], $this->hostid);
         $this->screenitem['resourceid'] = !empty($newitemid) ? $newitemid : 0;
     }
     if ($this->screenitem['resourceid'] == 0) {
         $table = (new CTableInfo())->setHeader([_('Timestamp'), _('Item')]);
         return $this->getOutput($table);
     }
     $items = CMacrosResolverHelper::resolveItemNames([get_item_by_itemid($this->screenitem['resourceid'])]);
     $item = reset($items);
     switch ($item['value_type']) {
         case ITEM_VALUE_TYPE_TEXT:
         case ITEM_VALUE_TYPE_LOG:
             $orderField = 'id';
             break;
         case ITEM_VALUE_TYPE_FLOAT:
         case ITEM_VALUE_TYPE_UINT64:
         default:
             $orderField = ['itemid', 'clock'];
     }
     $host = get_host_by_itemid($this->screenitem['resourceid']);
     $table = (new CTableInfo())->setHeader([_('Timestamp'), _('Value')]);
     $stime = zbxDateToTime($this->timeline['stime']);
     $histories = API::History()->get(['history' => $item['value_type'], 'itemids' => $this->screenitem['resourceid'], 'output' => API_OUTPUT_EXTEND, 'sortorder' => ZBX_SORT_DOWN, 'sortfield' => $orderField, 'limit' => $this->screenitem['elements'], 'time_from' => $stime, 'time_till' => $stime + $this->timeline['period']]);
     foreach ($histories as $history) {
         switch ($item['value_type']) {
             case ITEM_VALUE_TYPE_FLOAT:
                 sscanf($history['value'], '%f', $value);
                 break;
             case ITEM_VALUE_TYPE_TEXT:
             case ITEM_VALUE_TYPE_STR:
             case ITEM_VALUE_TYPE_LOG:
                 $value = $this->screenitem['style'] ? new CJsScript($history['value']) : $history['value'];
                 break;
             default:
                 $value = $history['value'];
                 break;
         }
         if ($item['valuemapid'] > 0) {
             $value = applyValueMap($value, $item['valuemapid']);
         }
         if ($this->screenitem['style'] == 0) {
             $value = new CPre($value);
         }
         $table->addRow([zbx_date2str(DATE_TIME_FORMAT_SECONDS, $history['clock']), $value]);
     }
     $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT);
     return $this->getOutput((new CUiWidget(uniqid(), [$table, $footer]))->setHeader($host['name'] . NAME_DELIMITER . $item['name_expanded']));
 }
Ejemplo n.º 12
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $header = (new CDiv([new CTag('h4', true, _('Triggers 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([_('Host'), ':', SPACE, $groups[0]['name']]));
     }
     $table = (new CTriggersInfo($this->screenitem['resourceid']))->setOrientation($this->screenitem['style']);
     $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]));
 }
Ejemplo n.º 13
0
 /**
  * Base validation function.
  *
  * @param array  $data    import data
  * @param string $format  format of import source
  *
  * @return array		Validator does some manipulation for the incoming data. For example, converts empty tags to
  *						an array, if desired. Converted array is returned.
  */
 public function validate(array $data, $format)
 {
     $rules = ['type' => XML_ARRAY, 'rules' => ['zabbix_export' => ['type' => XML_ARRAY | XML_REQUIRED, 'check_unexpected' => false, 'rules' => ['version' => ['type' => XML_STRING | XML_REQUIRED]]]]];
     $data = (new CXmlValidatorGeneral($rules, $format))->validate($data, '/');
     $version = $data['zabbix_export']['version'];
     if (!array_key_exists($version, $this->versionValidators)) {
         throw new Exception(_s('Invalid tag "%1$s": %2$s.', '/zabbix_export/version', _('unsupported version number')));
     }
     $data['zabbix_export'] = (new $this->versionValidators[$version]($format))->validate($data['zabbix_export'], '/zabbix_export');
     return $data;
 }
Ejemplo n.º 14
0
 /**
  * Uses the user credentials sent with the HTTP-Header to authenticate the user calling the API.
  *
  * œ@api
  *
  * @throws \FeM\sPof\exception\BasicAuthException
  *
  * @return boolean True, if user with the given password was authenticated successfully, else false.
  */
 public final function authenticate()
 {
     if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
         throw new \FeM\sPof\exception\BasicAuthException(_s('Missing authentication credentials'));
     }
     $user_id = User::getIdByCredentials($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
     if ($user_id === false) {
         throw new \FeM\sPof\exception\BasicAuthException(_s('Wrong user and/or password.'));
     }
     return $user_id;
 }
Ejemplo n.º 15
0
 /**
  * Wrapper for calling the self::$show-method. This wrapper is necessary to call
  *
  * @internal
  *
  * @param string $show
  * @throws \FeM\sPof\exception\NotImplementedException
  * @return mixed content
  */
 public function executeShow($show = null)
 {
     // call show met
     if ($show === null) {
         $show = \FeM\sPof\Router::getShow($show);
     }
     if (!method_exists(get_called_class(), $show)) {
         throw new \FeM\sPof\exception\NotImplementedException(_s('Could not find the show method. "%s::%s"', get_called_class(), $show));
     }
     return $this->{$show}();
 }
Ejemplo n.º 16
0
 /**
  * Converts file extension to associated import format.
  *
  * @static
  * @throws Exception
  *
  * @param string $ext
  *
  * @return string
  */
 public static function fileExt2ImportFormat($ext)
 {
     switch ($ext) {
         case 'xml':
             return CImportReaderFactory::XML;
         case 'json':
             return CImportReaderFactory::JSON;
         default:
             throw new Exception(_s('Unsupported import file extension "%1$s".', $ext));
     }
 }
Ejemplo n.º 17
0
 public function setMessage($value = null)
 {
     if (is_null($value)) {
         $value = _('Are you sure you want perform this action?');
     }
     if (!is_string($value)) {
         return $this->error(_s('Incorrect value for setMessage(): "%s".', $value));
     }
     // if message will contain single quotes, it will break everything, so it must be escaped
     $this->msg = zbx_jsvalue($value, false, false);
     $this->setAction(null);
 }
Ejemplo n.º 18
0
 /**
  * Check if connected database version matches with frontend version.
  *
  * @return bool
  */
 public function checkDbVersion()
 {
     if (!$this->checkDbVersionTable()) {
         return false;
     }
     $version = DBfetch(DBselect('SELECT dv.mandatory,dv.optional FROM dbversion dv'));
     if ($version['mandatory'] != ZABBIX_DB_VERSION) {
         $this->setError(_s('The frontend does not match Zabbix database. Current database version (mandatory/optional): %d/%d. Required mandatory version: %d. Contact your system administrator.', $version['mandatory'], $version['optional'], ZABBIX_DB_VERSION));
         return false;
     }
     return true;
 }
Ejemplo n.º 19
0
 /**
  * Returns an error message depending on input parameters.
  *
  * @param string $key
  * @param int $pos
  *
  * @return string
  */
 private function errorMessage($key, $pos)
 {
     for ($i = $pos, $chunk = '', $maxChunkSize = 50; isset($key[$i]); $i++) {
         if (0x80 != (0xc0 & ord($key[$i])) && $maxChunkSize-- == 0) {
             break;
         }
         $chunk .= $key[$i];
     }
     if (isset($key[$i])) {
         $chunk .= ' ...';
     }
     return _s('incorrect syntax near "%1$s"', $chunk);
 }
Ejemplo n.º 20
0
 /**
  * Показываем дату с учетом сдвига времени
  *
  * @param int $var Время в Unix формате
  *
  * @return string
  */
 public static function displayDate($var)
 {
     //TODO: Исправить время сдвига
     $shift = (Config::$timeshift + App::user()->get()->config()->timeShift) * 3600;
     if (date('Y', $var) == date('Y', time())) {
         if (date('z', $var + $shift) == date('z', time() + $shift)) {
             return _s('Today') . ', ' . date("H:i", $var + $shift);
         }
         if (date('z', $var + $shift) == date('z', time() + $shift) - 1) {
             return _s('Yesterday') . ', ' . date("H:i", $var + $shift);
         }
     }
     return date("d.m.Y / H:i", $var + $shift);
 }
 /**
  * Checks if the given source-object pair is valid.
  *
  * @param $value
  *
  * @return bool
  */
 public function validate($value)
 {
     $pairs = $this->pairs;
     $objects = $pairs[$value['source']];
     if (!isset($objects[$value['object']])) {
         $supportedObjects = '';
         foreach ($objects as $object => $i) {
             $supportedObjects .= $object . ' - ' . eventObject($object) . ', ';
         }
         $this->setError(_s('Incorrect event object "%1$s" (%2$s) for event source "%3$s" (%4$s), only the following objects are supported: %5$s.', $value['object'], eventObject($value['object']), $value['source'], eventSource($value['source']), rtrim($supportedObjects, ', ')));
         return false;
     }
     return true;
 }
Ejemplo n.º 22
0
 /**
  * Checks if the given IP address is a valid IPv4 or IPv6 address. If IP address is invalid, sets an error
  * and returns false. Otherwise returns true.
  *
  * @param string $ip
  *
  * @return bool
  */
 public function validate($ip)
 {
     if (!is_string($ip)) {
         $this->setError(_s('Invalid IP address "%1$s": must be a string.', $this->stringify($ip)));
         return false;
     }
     if ($ip === '') {
         $this->setError(_('IP address cannot be empty.'));
         return false;
     }
     if (!$this->isValidIPv4($ip) && !$this->isValidIPv6($ip)) {
         $this->setError(_s('Invalid IP address "%1$s".', $ip));
         return false;
     }
     return true;
 }
Ejemplo n.º 23
0
 /**
  * Returns an error message depending on input parameters.
  *
  * @param string $source
  * @param int $pos
  *
  * @return string
  */
 private function errorMessage($source, $pos)
 {
     if (!isset($source[$pos])) {
         return $pos == 0 ? _('macro is empty') : _('unexpected end of macro');
     }
     for ($p = $pos, $chunk = '', $maxChunkSize = 50; isset($source[$p]); $p++) {
         if (0x80 != (0xc0 & ord($source[$p])) && $maxChunkSize-- == 0) {
             break;
         }
         $chunk .= $source[$p];
     }
     if (isset($source[$p])) {
         $chunk .= ' ...';
     }
     return _s('incorrect syntax near "%1$s"', $chunk);
 }
Ejemplo n.º 24
0
 /**
  * Returns an error message depending on input parameters.
  *
  * @param string $key
  * @param int $pos
  *
  * @return string
  */
 private function errorMessage($key, $pos)
 {
     if (!isset($key[$pos])) {
         return $pos == 0 ? _('key is empty') : _('unexpected end of key');
     }
     for ($i = $pos, $chunk = '', $maxChunkSize = 50; isset($key[$i]); $i++) {
         if (0x80 != (0xc0 & ord($key[$i])) && $maxChunkSize-- == 0) {
             break;
         }
         $chunk .= $key[$i];
     }
     if (isset($key[$i])) {
         $chunk .= ' ...';
     }
     return _s('incorrect syntax near "%1$s"', $chunk);
 }
Ejemplo n.º 25
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]));
 }
Ejemplo n.º 26
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $hostids = [];
     $dbHostGroups = DBselect('SELECT DISTINCT hg.hostid FROM hosts_groups hg WHERE hg.groupid=' . zbx_dbstr($this->screenitem['resourceid']));
     while ($dbHostGroup = DBfetch($dbHostGroups)) {
         $hostids[$dbHostGroup['hostid']] = $dbHostGroup['hostid'];
     }
     // application filter
     $applicationIds = null;
     if ($this->screenitem['application'] !== '') {
         $applications = API::Application()->get(['output' => ['applicationid'], 'hostids' => $hostids, 'search' => ['name' => $this->screenitem['application']]]);
         $applicationIds = zbx_objectValues($applications, 'applicationid');
     }
     $groups = API::HostGroup()->get(['output' => ['name'], 'groupids' => [$this->screenitem['resourceid']]]);
     $header = (new CDiv([new CTag('h4', true, _('Data overview')), (new CList())->addItem([_('Group'), ':', SPACE, $groups[0]['name']])]))->addClass(ZBX_STYLE_DASHBRD_WIDGET_HEAD);
     $table = getItemsDataOverview($hostids, $applicationIds, $this->screenitem['style']);
     $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]));
 }
Ejemplo n.º 27
0
 /**
  * Assign values to the text fields
  *
  * @param array $option
  */
 protected function assignText(array &$option)
 {
     if (isset($this->form->input[$option['name']])) {
         $option['value'] = trim($this->form->input[$option['name']]);
         unset($this->form->input[$option['name']]);
         // Применяем лимитер
         if (isset($option['limit'])) {
             $this->limiter($option);
         }
         if (isset($option['required']) && empty($option['value'])) {
             // Проверка на обязательное поле
             $option['error'] = _s('This field is required');
             $this->form->validate = false;
             $this->form->isValid = false;
         }
         $this->form->output[$option['name']] = $this->filter($option);
     } else {
         $this->form->isValid = false;
     }
 }
Ejemplo n.º 28
0
 /**
  * Process screen.
  *
  * @return CDiv (screen inside container)
  */
 public function get()
 {
     $status = get_status();
     $server = $status['zabbix_server'] == _('Yes') ? (new CSpan(_('running')))->addClass(ZBX_STYLE_GREEN) : (new CSpan(_('not running')))->addClass(ZBX_STYLE_RED);
     $user_link = CWebUser::$data['alias'];
     if (!CWebUser::isGuest()) {
         $user_link = new CLink($user_link, 'profile.php');
     }
     $server_link = _('Zabbix server');
     if (CWebUser::$data['type'] == USER_TYPE_SUPER_ADMIN) {
         $server_link = new CLink($server_link, 'zabbix.php?action=report.status');
     }
     $table = new CTableInfo();
     $table->addRow(_('Users (online)') . NAME_DELIMITER . $status['users_count'] . '(' . $status['users_online'] . ')');
     $table->addRow(new CCol([_('Logged in as'), SPACE, $user_link]));
     $table->addRow(new CCol([$server_link, SPACE, _('is'), SPACE, $server]));
     $table->addRow(new CCol([_('Hosts (m/n/t)') . NAME_DELIMITER . $status['hosts_count'] . '(', (new CSpan($status['hosts_count_monitored']))->addClass(ZBX_STYLE_GREEN), '/', (new CSpan($status['hosts_count_not_monitored']))->addClass(ZBX_STYLE_RED), '/', (new CSpan($status['hosts_count_template']))->addClass(ZBX_STYLE_GREY), ')']));
     $table->addRow(new CCol([_('Items (m/d/n)') . NAME_DELIMITER . $status['items_count'] . '(', (new CSpan($status['items_count_monitored']))->addClass(ZBX_STYLE_GREEN), '/', (new CSpan($status['items_count_disabled']))->addClass(ZBX_STYLE_RED), '/', (new CSpan($status['items_count_not_supported']))->addClass(ZBX_STYLE_GREY), ')']));
     $table->addRow(new CCol([_('Triggers (e/d)[p/o]') . NAME_DELIMITER . $status['triggers_count'] . '(' . $status['triggers_count_enabled'] . '/' . $status['triggers_count_disabled'] . ')[', (new CSpan($status['triggers_count_on']))->addClass(ZBX_STYLE_GREEN), '/', (new CSpan($status['triggers_count_off']))->addClass(ZBX_STYLE_RED), ']']));
     $footer = (new CList())->addItem(_s('Updated: %s', zbx_date2str(TIME_FORMAT_SECONDS)))->addClass(ZBX_STYLE_DASHBRD_WIDGET_FOOT);
     return $this->getOutput((new CUiWidget(uniqid(), [$table, $footer]))->setHeader(_('Zabbix server info')));
 }
Ejemplo n.º 29
0
 protected function checkSelementInput(&$selements, $method)
 {
     $update = $method == 'updateSelements';
     $delete = $method == 'deleteSelements';
     // permissions
     if ($update || $delete) {
         $selementDbFields = array('selementid' => null);
         $dbSelements = $this->fetchSelementsByIds(zbx_objectValues($selements, 'selementid'));
         if ($update) {
             $selements = $this->extendFromObjects($selements, $dbSelements, array('elementtype', 'elementid'));
         }
     } else {
         $selementDbFields = array('sysmapid' => null, 'elementid' => null, 'elementtype' => null, 'iconid_off' => null, 'urls' => array());
     }
     foreach ($selements as &$selement) {
         if (!check_db_fields($selementDbFields, $selement)) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Wrong fields for element.'));
         }
         if ($update || $delete) {
             if (!isset($dbSelements[$selement['selementid']])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
             }
             $dbSelement = array_merge($dbSelements[$selement['selementid']], $selement);
         } else {
             $dbSelement = $selement;
         }
         if (isset($selement['iconid_off']) && $selement['iconid_off'] == 0) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('No icon for map element "%s".', $selement['label']));
         }
         if ($this->checkCircleSelementsLink($dbSelement['sysmapid'], $dbSelement['elementid'], $dbSelement['elementtype'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Circular link cannot be created for map element "%s".', $dbSelement['label']));
         }
     }
     unset($selement);
     // check permissions to used objects
     $this->checkSelementPermissions($selements);
     return $update || $delete ? $dbSelements : true;
 }
Ejemplo n.º 30
0
        $httpTest['hostname'] = $httpTest['host']['name'];
        unset($httpTest['hosts']);
    }
    unset($httpTest);
    $httpTests = resolveHttpTestMacros($httpTests, true, false);
    order_result($httpTests, getPageSortField('name'), getPageSortOrder());
    // fetch the latest results of the web scenario
    $lastHttpTestData = Manager::HttpTest()->getLastData(array_keys($httpTests));
    foreach ($httpTests as $httpTest) {
        $lastData = isset($lastHttpTestData[$httpTest['httptestid']]) ? $lastHttpTestData[$httpTest['httptestid']] : null;
        // test has history data
        if ($lastData) {
            $lastcheck = zbx_date2str(_('d M Y H:i:s'), $lastData['lastcheck']);
            if ($lastData['lastfailedstep'] != 0) {
                $step_data = get_httpstep_by_no($httpTest['httptestid'], $lastData['lastfailedstep']);
                $status['msg'] = _s('Step "%1$s" [%2$s of %3$s] failed: %4$s', $step_data['name'], $lastData['lastfailedstep'], $httpTest['steps'], $lastData['error']);
                $status['style'] = 'disabled';
            } else {
                $status['msg'] = _('OK');
                $status['style'] = 'enabled';
            }
        } else {
            $lastcheck = _('Never');
            $status['msg'] = _('Unknown');
            $status['style'] = 'unknown';
        }
        $cpsan = new CSpan($httpTest['hostname'], $httpTest['host']['status'] == HOST_STATUS_NOT_MONITORED ? 'not-monitored' : '');
        $table->addRow(new CRow(array($displayNodes ? get_node_name_by_elid($httpTest['httptestid'], true) : null, $_REQUEST['hostid'] > 0 ? null : $cpsan, new CLink($httpTest['name'], 'httpdetails.php?httptestid=' . $httpTest['httptestid']), $httpTest['steps'], $lastcheck, new CSpan($status['msg'], $status['style']))));
    }
} else {
    $tmp = array();