public static function call($method, $params, $sessionid = null) { // List of methods without params $notifications = array('apiinfo.version' => 1, 'user.logout' => 1); if (is_null($params) && !isset($notifications[$method])) { return array('error' => ZBX_API_ERROR_PARAMETERS, 'data' => _('Empty parameters')); } // list of methods which does not require authentication $withoutAuth = array('user.login' => 1, 'user.checkAuthentication' => 1, 'apiinfo.version' => 1); // Authentication if (!isset($withoutAuth[$method]) || !zbx_empty($sessionid)) { // compatibility mode if ($method == 'user.authenticate') { $method = 'user.login'; } if (!zbx_empty($sessionid)) { $usr = self::callAPI('user.checkAuthentication', $sessionid); if (!isset($usr['result'])) { return array('error' => ZBX_API_ERROR_NO_AUTH, 'data' => _('Not authorized')); } } elseif (!isset($withoutAuth[$method])) { return array('error' => ZBX_API_ERROR_NO_AUTH, 'data' => _('Not authorized')); } } return self::callAPI($method, $params); }
public function connect() { // connection already established if ($this->ds) { return true; } $this->bound = 0; if (!($this->ds = ldap_connect($this->cnf['host'], $this->cnf['port']))) { error('LDAP: couldn\'t connect to LDAP server.'); return false; } // set protocol version and dependend options if ($this->cnf['version']) { if (!ldap_set_option($this->ds, LDAP_OPT_PROTOCOL_VERSION, $this->cnf['version'])) { error('Setting LDAP Protocol version ' . $this->cnf['version'] . ' failed.'); } else { // use TLS (needs version 3) if (isset($this->cnf['starttls']) && !ldap_start_tls($this->ds)) { error('Starting TLS failed.'); } // needs version 3 if (!zbx_empty($this->cnf['referrals']) && !ldap_set_option($this->ds, LDAP_OPT_REFERRALS, $this->cnf['referrals'])) { error('Setting LDAP referrals to off failed.'); } } } // set deref mode if (isset($this->cnf['deref']) && !ldap_set_option($this->ds, LDAP_OPT_DEREF, $this->cnf['deref'])) { error('Setting LDAP Deref mode ' . $this->cnf['deref'] . ' failed.'); } return true; }
/** * Validates the given string and checks if it contains LLD macros. */ public function validate($value) { if (!parent::validate($value)) { return false; } // check if a string contains an LLD macro if (!zbx_empty($value) && !preg_match('/(\\{#' . ZBX_PREG_MACRO_NAME_LLD . '\\})+/', $value)) { $this->error($this->messageMacro); return false; } return true; }
/** * Creates a UL list. * * @param mixed $value a single or an array of values to add to the list * @param string $class HTML class * @param string $emptyString text to display if the list is empty */ public function __construct($value = null, $class = null, $emptyString = null) { parent::__construct('ul', 'yes'); $this->tag_end = ''; $this->addItem($value); $this->addClass($class); if (is_null($value)) { $emptyString = !zbx_empty($emptyString) ? $emptyString : _('List is empty'); $this->addItem($emptyString, 'empty'); $this->emptyList = true; } }
/** * Checks if expression is valid. * * @static * * @param $regExp * * @throws Exception * @return bool */ public static function isValid($regExp) { if (zbx_empty($regExp)) { throw new Exception('Empty expression', self::ERROR_REGEXP_EMPTY); } if ($regExp[0] == '@') { $regExp = substr($regExp, 1); $sql = 'SELECT r.regexpid' . ' FROM regexps r' . ' WHERE r.name=' . zbx_dbstr($regExp); if (!DBfetch(DBselect($sql))) { throw new Exception(_('Global expression does not exist.'), self::ERROR_REGEXP_NOT_EXISTS); } } return true; }
/** * Recursive function for processing nested arrays. * * @param array $array * @param null $parentName name of parent node */ protected function fromArray(array $array, $parentName = null) { foreach ($array as $name => $value) { if ($newName = $this->mapName($parentName)) { $this->xmlWriter->startElement($newName); } else { $this->xmlWriter->startElement($name); } if (is_array($value)) { $this->fromArray($value, $name); } elseif (!zbx_empty($value)) { $this->xmlWriter->text($value); } $this->xmlWriter->endElement(); } }
/** * Process screen. * * @return CDiv (screen inside container) */ public function get() { $this->dataId = 'graph_' . $this->screenitem['screenitemid'] . '_' . $this->screenitem['screenid']; $resourceid = !empty($this->screenitem['real_resourceid']) ? $this->screenitem['real_resourceid'] : $this->screenitem['resourceid']; $containerid = 'graph_container_' . $this->screenitem['screenitemid'] . '_' . $this->screenitem['screenid']; $graphDims = getGraphDims(); $graphDims['graphHeight'] = $this->screenitem['height']; $graphDims['width'] = $this->screenitem['width']; // get time control $timeControlData = array('id' => $this->getDataId(), 'containerid' => $containerid, 'objDims' => $graphDims, 'loadImage' => 1, 'periodFixed' => CProfile::get('web.screens.timelinefixed', 1), 'sliderMaximumTimePeriod' => ZBX_MAX_PERIOD); // host feature if ($this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM && !empty($this->hostid)) { $newitemid = get_same_item_for_host($resourceid, $this->hostid); $resourceid = !empty($newitemid) ? $newitemid : ''; } if ($this->mode == SCREEN_MODE_PREVIEW && !empty($resourceid)) { $this->action = 'history.php?action=showgraph&itemid=' . $resourceid . '&period=' . $this->timeline['period'] . '&stime=' . $this->timeline['stimeNow'] . $this->getProfileUrlParams(); } if (!zbx_empty($resourceid) && $this->mode != SCREEN_MODE_EDIT) { if ($this->mode == SCREEN_MODE_PREVIEW) { $timeControlData['loadSBox'] = 1; } } $timeControlData['src'] = zbx_empty($resourceid) ? 'chart3.php?' : 'chart.php?itemid=' . $resourceid . '&' . $this->screenitem['url'] . '&width=' . $this->screenitem['width'] . '&height=' . $this->screenitem['height']; $timeControlData['src'] .= $this->mode == SCREEN_MODE_EDIT ? '&period=3600&stime=' . date(TIMESTAMP_FORMAT, time()) : '&period=' . $this->timeline['period'] . '&stime=' . $this->timeline['stimeNow']; $timeControlData['src'] .= $this->getProfileUrlParams(); // output if ($this->mode == SCREEN_MODE_JS) { return 'timeControl.addObject("' . $this->getDataId() . '", ' . zbx_jsvalue($this->timeline) . ', ' . zbx_jsvalue($timeControlData) . ')'; } else { if ($this->mode == SCREEN_MODE_SLIDESHOW) { insert_js('timeControl.addObject("' . $this->getDataId() . '", ' . zbx_jsvalue($this->timeline) . ', ' . zbx_jsvalue($timeControlData) . ');'); } else { zbx_add_post_js('timeControl.addObject("' . $this->getDataId() . '", ' . zbx_jsvalue($this->timeline) . ', ' . zbx_jsvalue($timeControlData) . ');'); } if ($this->mode == SCREEN_MODE_EDIT || $this->mode == SCREEN_MODE_SLIDESHOW) { $item = new CDiv(); } elseif ($this->mode == SCREEN_MODE_PREVIEW) { $item = new CLink(null, 'history.php?action=showgraph&itemid=' . $resourceid . '&period=' . $this->timeline['period'] . '&stime=' . $this->timeline['stimeNow']); } $item->setAttribute('id', $containerid); return $this->getOutput($item); } }
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()]])); }
/** * Checks if the given string is: * - empty * - not too long * - matches a certain regex * * @param string $value * * @return bool */ public function validate($value) { if (zbx_empty($value)) { if ($this->empty) { return true; } else { $this->error($this->messageEmpty); return false; } } if ($this->maxLength && zbx_strlen($value) > $this->maxLength) { $this->error($this->messageMaxLength, $this->maxLength); return false; } if ($this->regex && !zbx_empty($value) && !preg_match($this->regex, $value)) { $this->error($this->messageRegex, $value); return false; } return true; }
/** * Validate single time period. * Time period is a string with format: * 'day1-day2,time1-time2;' (day2 and ';' are optional) * Examples: * 5-7,00:00-09:00 * 5,0:00-9:00 * * @param string $period * * @return bool */ protected function validateSinglePeriod($period) { $daysRegExp = '(?P<day1>[1-7])(-(?P<day2>[1-7]))?'; $time1RegExp = '(?P<hour1>20|21|22|23|24|[0-1]\\d|\\d):(?P<min1>[0-5]\\d)'; $time2RegExp = '(?P<hour2>20|21|22|23|24|[0-1]\\d|\\d):(?P<min2>[0-5]\\d)'; if (!preg_match('#^' . $daysRegExp . ',' . $time1RegExp . '-' . $time2RegExp . '$#', $period, $matches)) { $this->setError(_s('Incorrect time period "%1$s".', $period)); return false; } if ($matches['hour2'] == '24' && $matches['min2'] != 0) { $this->setError(_s('Incorrect time period "%1$s".', $period)); return false; } if (!zbx_empty($matches['day2']) && $matches['day1'] > $matches['day2']) { $this->setError(_s('Incorrect time period "%1$s" start day must be less or equal to end day.', $period)); return false; } if ($matches['hour1'] > $matches['hour2'] || $matches['hour1'] == $matches['hour2'] && $matches['min1'] >= $matches['min2']) { $this->setError(_s('Incorrect time period "%1$s" start time must be less than end time.', $period)); return false; } return true; }
public static function arrayToDOM(&$dom, $array, $parentKey = null) { if (!is_null($parentKey)) { $parentNode = $dom->appendChild(new DOMElement($parentKey)); } else { $parentNode = $dom; } foreach ($array as $key => $value) { if (is_numeric($key)) { $key = rtrim($parentKey, 's'); } if (is_array($value)) { $child = self::arrayToDOM($dom, $value, $key); $parentNode->appendChild($child); //SDI($dom->saveXML($parentNode)); } else { if (!zbx_empty($value)) { $n = $parentNode->appendChild(new DOMElement($key)); $n->appendChild(new DOMText($value)); } } } return $parentNode; }
function shedule2str($timeperiod) { $timeperiod['hour'] = floor($timeperiod['start_time'] / SEC_PER_HOUR); $timeperiod['minute'] = floor(($timeperiod['start_time'] - $timeperiod['hour'] * SEC_PER_HOUR) / SEC_PER_MIN); if ($timeperiod['hour'] < 10) { $timeperiod['hour'] = '0' . $timeperiod['hour']; } if ($timeperiod['minute'] < 10) { $timeperiod['minute'] = '0' . $timeperiod['minute']; } if ($timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_ONETIME) { $str = zbx_date2str(DATE_TIME_FORMAT, $timeperiod['start_date']); } elseif ($timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_DAILY) { $str = _n('At %1$s:%2$s on every day', 'At %1$s:%2$s on every %3$s days', $timeperiod['hour'], $timeperiod['minute'], $timeperiod['every']); } elseif ($timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_WEEKLY) { $days = ''; $dayofweek = zbx_num2bitstr($timeperiod['dayofweek'], true); $length = strlen($dayofweek); for ($i = 0; $i < $length; $i++) { if ($dayofweek[$i] == 1) { if (!zbx_empty($days)) { $days .= ', '; } $days .= getDayOfWeekCaption($i + 1); } } $str = _n('At %1$s:%2$s on every %3$s of every week', 'At %1$s:%2$s on every %3$s of every %4$s weeks', $timeperiod['hour'], $timeperiod['minute'], $days, $timeperiod['every']); } elseif ($timeperiod['timeperiod_type'] == TIMEPERIOD_TYPE_MONTHLY) { $months = ''; $month = zbx_num2bitstr($timeperiod['month'], true); $length = strlen($month); for ($i = 0; $i < $length; $i++) { if ($month[$i] == 1) { if (!zbx_empty($months)) { $months .= ', '; } $months .= getMonthCaption($i + 1); } } if ($timeperiod['dayofweek'] > 0) { $days = ''; $dayofweek = zbx_num2bitstr($timeperiod['dayofweek'], true); $length = strlen($dayofweek); for ($i = 0; $i < $length; $i++) { if ($dayofweek[$i] == 1) { if (!zbx_empty($days)) { $days .= ', '; } $days .= getDayOfWeekCaption($i + 1); } } $every = ''; switch ($timeperiod['every']) { case 1: $every = _('First'); break; case 2: $every = _('Second'); break; case 3: $every = _('Third'); break; case 4: $every = _('Fourth'); break; case 5: $every = _('Last'); break; } $str = _s('At %1$s:%2$s on %3$s %4$s of every %5$s', $timeperiod['hour'], $timeperiod['minute'], $every, $days, $months); } else { $str = _s('At %1$s:%2$s on day %3$s of every %4$s', $timeperiod['hour'], $timeperiod['minute'], $timeperiod['day'], $months); } } return $str; }
/** * Get history data * * {@source} * @access public * @static * @since 1.8.3 * @version 1.3 * * @param array $options * @param array $options['itemids'] * @param boolean $options['editable'] * @param string $options['pattern'] * @param int $options['limit'] * @param string $options['order'] * @return array|int item data as array or false if error */ public static function get($options = array()) { global $USER_DETAILS; $nodeCheck = false; $result = array(); $sort_columns = array('itemid', 'clock'); // allowed columns for sorting $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND); // allowed output options for [ select_* ] params $sql_parts = array('select' => array('history' => 'h.itemid'), 'from' => array(), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $def_options = array('history' => ITEM_VALUE_TYPE_UINT64, 'nodeids' => null, 'hostids' => null, 'itemids' => null, 'triggerids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'time_from' => null, 'time_till' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'groupCount' => null, 'groupOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null); $options = zbx_array_merge($def_options, $options); switch ($options['history']) { case ITEM_VALUE_TYPE_LOG: $sql_parts['from']['history'] = 'history_log h'; $sort_columns[] = 'id'; break; case ITEM_VALUE_TYPE_TEXT: $sql_parts['from']['history'] = 'history_text h'; $sort_columns[] = 'id'; break; case ITEM_VALUE_TYPE_STR: $sql_parts['from']['history'] = 'history_str h'; break; case ITEM_VALUE_TYPE_UINT64: $sql_parts['from']['history'] = 'history_uint h'; break; case ITEM_VALUE_TYPE_FLOAT: default: $sql_parts['from']['history'] = 'history h'; } // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == $USER_DETAILS['type'] || $options['nopermissions']) { } else { $itemOptions = array('editable' => $options['editable'], 'preservekeys' => 1); if (!is_null($options['itemids'])) { $itemOptions['itemids'] = $options['itemids']; } $items = CItem::get($itemOptions); $options['itemids'] = array_keys($items); } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); $sql_parts['where']['itemid'] = DBcondition('h.itemid', $options['itemids']); if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.itemid', $nodeids); } } // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['hostid'] = 'i.hostid'; } $sql_parts['from']['items'] = 'items i'; $sql_parts['where']['i'] = DBcondition('i.hostid', $options['hostids']); $sql_parts['where']['hi'] = 'h.itemid=i.itemid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('i.hostid', $nodeids); } } // node check !!!!! // should be last, after all ****IDS checks if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.itemid', $nodeids); } // time_from if (!is_null($options['time_from'])) { $sql_parts['select']['clock'] = 'h.clock'; $sql_parts['where']['clock_from'] = 'h.clock>=' . $options['time_from']; } // time_till if (!is_null($options['time_till'])) { $sql_parts['select']['clock'] = 'h.clock'; $sql_parts['where']['clock_till'] = 'h.clock<=' . $options['time_till']; } // filter if (is_array($options['filter'])) { zbx_db_filter($sql_parts['from']['history'], $options, $sql_parts); } // search if (is_array($options['search'])) { zbx_db_search($sql_parts['from']['history'], $options, $sql_parts); } // output if ($options['output'] == API_OUTPUT_EXTEND) { unset($sql_parts['select']['clock']); $sql_parts['select']['history'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sql_parts['select'] = array('count(DISTINCT h.hostid) as rowscount'); //groupCount if (!is_null($options['groupCount'])) { foreach ($sql_parts['group'] as $key => $fields) { $sql_parts['select'][$key] = $fields; } } } // groupOutput $groupOutput = false; if (!is_null($options['groupOutput'])) { if (str_in_array('h.' . $options['groupOutput'], $sql_parts['select']) || str_in_array('h.*', $sql_parts['select'])) { $groupOutput = true; } } // order // restrict not allowed columns for sorting $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : ''; if (!zbx_empty($options['sortfield'])) { $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP; if ($options['sortfield'] == 'clock') { $sql_parts['order']['itemid'] = 'h.itemid ' . $sortorder; } $sql_parts['order'][$options['sortfield']] = 'h.' . $options['sortfield'] . ' ' . $sortorder; if (!str_in_array('h.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('h.*', $sql_parts['select'])) { $sql_parts['select'][$options['sortfield']] = 'h.' . $options['sortfield']; } } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sql_parts['limit'] = $options['limit']; } //--------------- $itemids = array(); $triggerids = array(); $sql_parts['select'] = array_unique($sql_parts['select']); $sql_parts['from'] = array_unique($sql_parts['from']); $sql_parts['where'] = array_unique($sql_parts['where']); $sql_parts['order'] = array_unique($sql_parts['order']); $sql_select = ''; $sql_from = ''; $sql_where = ''; $sql_order = ''; if (!empty($sql_parts['select'])) { $sql_select .= implode(',', $sql_parts['select']); } if (!empty($sql_parts['from'])) { $sql_from .= implode(',', $sql_parts['from']); } if (!empty($sql_parts['where'])) { $sql_where .= implode(' AND ', $sql_parts['where']); } if (!empty($sql_parts['order'])) { $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']); } $sql_limit = $sql_parts['limit']; $sql = 'SELECT ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_order; $db_res = DBselect($sql, $sql_limit); //SDI($sql); $count = 0; $group = array(); while ($data = DBfetch($db_res)) { if ($options['countOutput']) { $result = $data; } else { $itemids[$data['itemid']] = $data['itemid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$count] = array('itemid' => $data['itemid']); } else { $result[$count] = array(); // hostids if (isset($data['hostid'])) { if (!isset($result[$count]['hosts'])) { $result[$count]['hosts'] = array(); } $result[$count]['hosts'][] = array('hostid' => $data['hostid']); unset($data['hostid']); } // triggerids if (isset($data['triggerid'])) { if (!isset($result[$count]['triggers'])) { $result[$count]['triggers'] = array(); } $result[$count]['triggers'][] = array('triggerid' => $data['triggerid']); unset($data['triggerid']); } // itemids // if(isset($data['itemid']) && !is_null($options['itemids'])){ // if(!isset($result[$count]['items'])) $result[$count]['items'] = array(); // $result[$count]['items'][] = array('itemid' => $data['itemid']); // } $result[$count] += $data; // grouping if ($groupOutput) { $dataid = $data[$options['groupOutput']]; if (!isset($group[$dataid])) { $group[$dataid] = array(); } $group[$dataid][] = $result[$count]; } $count++; } } } COpt::memoryPick(); if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
function make_latest_data() { global $USER_DETAILS; $available_hosts = get_accessible_hosts_by_user($USER_DETAILS, PERM_READ_ONLY, PERM_RES_IDS_ARRAY); while ($db_app = DBfetch($db_applications)) { $db_items = DBselect('SELECT DISTINCT i.* ' . ' FROM items i,items_applications ia' . ' WHERE ia.applicationid=' . $db_app['applicationid'] . ' AND i.itemid=ia.itemid' . ' AND i.status=' . ITEM_STATUS_ACTIVE . order_by('i.description,i.itemid,i.lastclock')); $app_rows = array(); $item_cnt = 0; while ($db_item = DBfetch($db_items)) { $description = item_description($db_item); if (!zbx_empty($_REQUEST['select']) && !zbx_stristr($description, $_REQUEST['select'])) { continue; } ++$item_cnt; if (!uint_in_array($db_app['applicationid'], $_REQUEST['applications']) && !isset($show_all_apps)) { continue; } if (isset($db_item['lastclock'])) { $lastclock = date(S_DATE_FORMAT_YMDHMS, $db_item['lastclock']); } else { $lastclock = new CCol('-', 'center'); } $lastvalue = format_lastvalue($db_item); if (isset($db_item['lastvalue']) && isset($db_item['prevvalue']) && $db_item['value_type'] == 0 && $db_item['lastvalue'] - $db_item['prevvalue'] != 0) { if ($db_item['lastvalue'] - $db_item['prevvalue'] < 0) { $change = convert_units($db_item['lastvalue'] - $db_item['prevvalue'], $db_item['units']); } else { $change = '+' . convert_units($db_item['lastvalue'] - $db_item['prevvalue'], $db_item['units']); } $change = nbsp($change); } else { $change = new CCol('-', 'center'); } if ($db_item['value_type'] == ITEM_VALUE_TYPE_FLOAT || $db_item['value_type'] == ITEM_VALUE_TYPE_UINT64) { $actions = new CLink(S_GRAPH, 'history.php?action=showgraph&itemid=' . $db_item['itemid'], 'action'); } else { $actions = new CLink(S_HISTORY, 'history.php?action=showvalues&period=3600&itemid=' . $db_item['itemid'], 'action'); } array_push($app_rows, new CRow(array(is_show_all_nodes() ? SPACE : null, $_REQUEST['hostid'] > 0 ? NULL : SPACE, str_repeat(SPACE, 6) . $description, $lastclock, new CCol($lastvalue, $lastvalue == '-' ? 'center' : null), $change, $actions))); } if ($item_cnt > 0) { if (uint_in_array($db_app['applicationid'], $_REQUEST['applications']) || isset($show_all_apps)) { $link = new CLink(new CImg('images/general/opened.gif'), '?close=1&applicationid=' . $db_app['applicationid'] . url_param('groupid') . url_param('hostid') . url_param('applications') . url_param('select')); } else { $link = new CLink(new CImg('images/general/closed.gif'), '?open=1&applicationid=' . $db_app['applicationid'] . url_param('groupid') . url_param('hostid') . url_param('applications') . url_param('select')); } $col = new CCol(array($link, SPACE, bold($db_app['name']), SPACE . '(' . $item_cnt . SPACE . S_ITEMS . ')')); $col->setColSpan(5); $table->ShowRow(array(get_node_name_by_elid($db_app['hostid']), $_REQUEST['hostid'] > 0 ? NULL : $db_app['host'], $col)); $any_app_exist = true; foreach ($app_rows as $row) { $table->ShowRow($row); } } } }
$groupids = zbx_toHash($groupids); $grpswitch = get_request('grpswitch', 0); $maintenance = get_request('maintenance', 0); $extAck = get_request('extAck', 0); $severity = get_request('trgSeverity', array()); $severity = array_keys($severity); } else { $filterEnable = CProfile::get('web.dashconf.filter.enable', 0); $groupids = get_favorites('web.dashconf.groups.groupids'); $groupids = zbx_objectValues($groupids, 'value'); $groupids = zbx_toHash($groupids); $grpswitch = CProfile::get('web.dashconf.groups.grpswitch', 0); $maintenance = CProfile::get('web.dashconf.hosts.maintenance', 1); $extAck = CProfile::get('web.dashconf.events.extAck', 0); $severity = CProfile::get('web.dashconf.triggers.severity', '0;1;2;3;4;5'); $severity = zbx_empty($severity) ? array() : explode(';', $severity); } $dashForm->addVar('filterEnable', $filterEnable); if ($filterEnable) { $cbFilter = new CSpan(S_ENABLED, 'green underline pointer'); $cbFilter->setAttribute('onclick', "create_var('" . $dashForm->getName() . "', 'filterEnable', 0, true);"); } else { $cbFilter = new CSpan(S_DISABLED, 'red underline pointer'); $cbFilter->setAttribute('onclick', "\$('dashform').enable(); create_var('" . $dashForm->getName() . "', 'filterEnable', 1, true);"); } $dashForm->addRow(S_DASHBOARD_FILTER, $cbFilter); $dashForm->addVar('groupids', $groupids); $cmbGroups = new CComboBox('grpswitch', $grpswitch, 'submit();'); $cmbGroups->addItem(0, S_ALL_S); $cmbGroups->addItem(1, S_SELECTED); if (!$filterEnable) {
/** * Resolve user macros in trigger expression. * * @static * * @param array $trigger * @param array $trigger['triggerid'] * @param array $trigger['expression'] * * @return string */ public static function resolveTriggerExpressionUserMacro(array $trigger) { if (zbx_empty($trigger['expression'])) { return $trigger['expression']; } self::init(); $triggers = self::$macrosResolver->resolve(array('config' => 'triggerExpressionUser', 'data' => zbx_toHash(array($trigger), 'triggerid'))); $trigger = reset($triggers); return $trigger['expression']; }
case 'hat_stszbx': $stszbx = make_status_of_zbx(); $stszbx->show(); break; } } } if (PAGE_TYPE_JS == $page['type'] || PAGE_TYPE_HTML_BLOCK == $page['type']) { exit; } $admin = uint_in_array($USER_DETAILS['type'], array(USER_TYPE_ZABBIX_ADMIN, USER_TYPE_SUPER_ADMIN)); $rows_per_page = $USER_DETAILS['rows_per_page']; $search_wdgt = new CWidget('search_wdgt'); $search = get_request('search', ''); // Header if (zbx_empty($search)) { $search = 'Search pattern is empty'; } $search_wdgt->addHeader(array(S_SEARCH_BIG . ': ', bold($search)), SPACE); //------------- $left_tab = new CTable(); $left_tab->setCellPadding(3); $left_tab->setCellSpacing(3); $left_tab->setAttribute('border', 0); $right_tab = new CTable(); $right_tab->setCellPadding(3); $right_tab->setCellSpacing(3); $right_tab->setAttribute('border', 0); // FIND Hosts $params = array('nodeids' => get_current_nodeid(), 'extendoutput' => true, 'pattern' => $search, 'extend_pattern' => true, 'limit' => $rows_per_page, 'order' => 'host'); $db_hosts = CHost::get($params);
} if ($show_events != EVENTS_OPTION_NOEVENT && !empty($trigger['events'])) { $open_close = new CDiv(SPACE, 'filterclosed'); $open_close->setAttribute('data-switcherid', $trigger['triggerid']); } else { if ($show_events == EVENTS_OPTION_NOEVENT) { $open_close = null; } else { $open_close = SPACE; } } $severity_col = new CCol(get_severity_description($trigger['priority']), get_severity_style($trigger['priority'], $trigger['value'])); if ($show_event_col) { $severity_col->setColSpan(2); } $table->addRow(array($open_close, $config['event_ack_enable'] ? $show_event_col ? null : new CCheckBox('triggers[' . $trigger['triggerid'] . ']', 'no', null, $trigger['triggerid']) : null, $severity_col, $status, $lastchange, zbx_date2age($trigger['lastchange']), $show_event_col ? SPACE : NULL, $to_ack, get_node_name_by_elid($trigger['triggerid']), $host, $tr_desc, new CLink(zbx_empty($trigger['comments']) ? S_ADD : S_SHOW, 'tr_comments.php?triggerid=' . $trigger['triggerid'])), 'even_row'); if ($show_events != EVENTS_OPTION_NOEVENT) { $i = 1; foreach ($trigger['events'] as $enum => $row_event) { $i++; $status = new CSpan(trigger_value2str($row_event['value']), get_trigger_value_style($row_event['value'])); if ($config['event_ack_enable']) { if ($row_event['value'] == TRIGGER_VALUE_TRUE) { if ($row_event['acknowledged'] == 1) { $acks_cnt = DBfetch(DBselect('SELECT COUNT(*) as cnt FROM acknowledges WHERE eventid=' . $row_event['eventid'])); $ack = array(new CSpan(S_YES, 'off'), SPACE . '(' . $acks_cnt['cnt'] . SPACE, new CLink(S_SHOW, 'acknow.php?eventid=' . $row_event['eventid'] . '&backurl=' . $page['file']), ')'); } else { $ack = new CLink(S_NOT_ACKNOWLEDGED, 'acknow.php?eventid=' . $row_event['eventid'] . '&backurl=' . $page['file'], 'on'); } } else { $ack = SPACE;
/** * Apply filter conditions to sql built query. * * @param string $table * @param array $options * @param array $sqlParts * * @return bool */ protected function dbFilter($table, $options, &$sqlParts) { list($table, $tableShort) = explode(' ', $table); $tableSchema = DB::getSchema($table); $filter = []; foreach ($options['filter'] as $field => $value) { // skip missing fields and text fields (not supported by Oracle) // skip empty values if (!isset($tableSchema['fields'][$field]) || $tableSchema['fields'][$field]['type'] == DB::FIELD_TYPE_TEXT || zbx_empty($value)) { continue; } zbx_value2array($value); $fieldName = $this->fieldId($field, $tableShort); $filter[$field] = DB::isNumericFieldType($tableSchema['fields'][$field]['type']) ? dbConditionInt($fieldName, $value) : dbConditionString($fieldName, $value); } if ($filter) { if (isset($sqlParts['where']['filter'])) { $filter[] = $sqlParts['where']['filter']; } if (is_null($options['searchByAny']) || $options['searchByAny'] === false || count($filter) == 1) { $sqlParts['where']['filter'] = implode(' AND ', $filter); } else { $sqlParts['where']['filter'] = '(' . implode(' OR ', $filter) . ')'; } return true; } return false; }
/** * Update maintenances. * * @param array $maintenances * * @return boolean */ public function update(array $maintenances) { $maintenances = zbx_toArray($maintenances); $maintenanceids = zbx_objectValues($maintenances, 'maintenanceid'); // validate maintenance permissions if (self::$userData['type'] == USER_TYPE_ZABBIX_USER) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } $updMaintenances = $this->get(['maintenanceids' => zbx_objectValues($maintenances, 'maintenanceid'), 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'selectGroups' => ['groupid'], 'selectHosts' => ['hostid'], 'selectTimeperiods' => API_OUTPUT_EXTEND, 'preservekeys' => true]); $maintenanceNamesChanged = []; foreach ($maintenances as $maintenance) { if (!isset($updMaintenances[$maintenance['maintenanceid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } if (isset($maintenance['name']) && !zbx_empty($maintenance['name']) && $updMaintenances[$maintenance['maintenanceid']]['name'] !== $maintenance['name']) { if (isset($maintenanceNamesChanged[$maintenance['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Maintenance "%1$s" already exists.', $maintenance['name'])); } else { $maintenanceNamesChanged[$maintenance['name']] = $maintenance['name']; } } } // check if maintenance already exists if ($maintenanceNamesChanged) { $dbMaintenances = $this->get(['output' => ['name'], 'filter' => ['name' => $maintenanceNamesChanged], 'nopermissions' => true, 'limit' => 1]); if ($dbMaintenances) { $dbMaintenance = reset($dbMaintenances); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Maintenance "%1$s" already exists.', $dbMaintenance['name'])); } } $hostids = []; $groupids = []; foreach ($maintenances as $maintenance) { // validate maintenance active since if (!validateUnixTime($maintenance['active_since'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active since'))); } // validate maintenance active till if (!validateUnixTime($maintenance['active_till'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active till'))); } // validate maintenance active interval if ($maintenance['active_since'] > $maintenance['active_till']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Maintenance "Active since" value cannot be bigger than "Active till".')); } // validate timeperiods if (!array_key_exists('timeperiods', $maintenance) || !is_array($maintenance['timeperiods']) || !$maintenance['timeperiods']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one maintenance period must be created.')); } foreach ($maintenance['timeperiods'] as $timeperiod) { if (!is_array($timeperiod)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one maintenance period must be created.')); } } $hostids = array_merge($hostids, $maintenance['hostids']); $groupids = array_merge($groupids, $maintenance['groupids']); } // validate hosts & groups if (empty($hostids) && empty($groupids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one host or group should be selected.')); } // validate hosts permissions $options = ['hostids' => $hostids, 'editable' => true, 'output' => ['hostid'], 'preservekeys' => true]; $updHosts = API::Host()->get($options); foreach ($hostids as $hostid) { if (!isset($updHosts[$hostid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // validate groups permissions $options = ['groupids' => $groupids, 'editable' => true, 'output' => ['groupid'], 'preservekeys' => true]; $updGroups = API::HostGroup()->get($options); foreach ($groupids as $groupid) { if (!isset($updGroups[$groupid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $this->removeSecondsFromTimes($maintenances); $update = []; foreach ($maintenances as $mnum => $maintenance) { $dbFields = ['maintenanceid' => null]; // validate fields if (!check_db_fields($dbFields, $maintenance)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect parameters for maintenance.')); } $update[$mnum] = ['values' => $maintenance, 'where' => ['maintenanceid' => $maintenance['maintenanceid']]]; // update time periods $this->replaceTimePeriods($updMaintenances[$maintenance['maintenanceid']], $maintenance); } DB::update('maintenances', $update); // some of the hosts and groups bound to maintenance must be deleted, other inserted and others left alone $insertHosts = []; $insertGroups = []; foreach ($maintenances as $maintenance) { // putting apart those host<->maintenance connections that should be inserted, deleted and not changed // $hostDiff['first'] - new hosts, that should be inserted // $hostDiff['second'] - hosts, that should be deleted // $hostDiff['both'] - hosts, that should not be touched $hostDiff = zbx_array_diff(zbx_toObject($maintenance['hostids'], 'hostid'), $updMaintenances[$maintenance['maintenanceid']]['hosts'], 'hostid'); foreach ($hostDiff['first'] as $host) { $insertHosts[] = ['hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']]; } foreach ($hostDiff['second'] as $host) { $deleteHosts = ['hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']]; DB::delete('maintenances_hosts', $deleteHosts); } // now the same with the groups $groupDiff = zbx_array_diff(zbx_toObject($maintenance['groupids'], 'groupid'), $updMaintenances[$maintenance['maintenanceid']]['groups'], 'groupid'); foreach ($groupDiff['first'] as $group) { $insertGroups[] = ['groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']]; } foreach ($groupDiff['second'] as $group) { $deleteGroups = ['groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']]; DB::delete('maintenances_groups', $deleteGroups); } add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_MAINTENANCE, $maintenance['maintenanceid'], array_key_exists('name', $maintenance) ? $maintenance['name'] : $updMaintenances[$maintenance['maintenanceid']]['name'], 'maintenances', $updMaintenances[$maintenance['maintenanceid']], $maintenance); } DB::insert('maintenances_hosts', $insertHosts); DB::insert('maintenances_groups', $insertGroups); return ['maintenanceids' => $maintenanceids]; }
/** * Validates script name menu path. * * @throws APIException if the input is invalid * * @param array $scripts * @param string $method */ protected function validateMenuPath(array $scripts, $method) { $dbScripts = $this->get(array('output' => array('scriptid', 'name'), 'nopermissions' => true)); foreach ($scripts as $script) { if (!isset($script['name'])) { continue; } $folders = $path = splitPath($script['name']); $name = array_pop($folders); // menu1/menu2/{empty} if (zbx_empty($name)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Empty name for script "%1$s".', $script['name'])); } // menu1/{empty}/name foreach ($folders as $folder) { if (zbx_empty($folder)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect menu path for script "%1$s".', $script['name'])); } } // validate path foreach ($dbScripts as $dbScript) { if ($method == 'update' && $script['scriptid'] === $dbScript['scriptid']) { continue; } $dbScriptFolders = $dbScriptPath = splitPath($dbScript['name']); array_pop($dbScriptFolders); // script NAME cannot be a FOLDER for other scripts $dbScriptFolderItems = array(); foreach ($dbScriptFolders as $dbScriptFolder) { $dbScriptFolderItems[] = $dbScriptFolder; if ($path === $dbScriptFolderItems) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Script name "%1$s" already used in menu path for script "%2$s".', $script['name'], $dbScript['name'])); } } // script FOLDER cannot be a NAME for other scripts $folderItems = array(); foreach ($folders as $folder) { $folderItems[] = $folder; if ($dbScriptPath === $folderItems) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Script menu path "%1$s" already used in script name "%2$s".', $script['name'], $dbScript['name'])); } } // check duplicate script names in same menu path if ($path == $dbScriptPath) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Script "%1$s" already exists.', $script['name'])); } } } }
public function setGraphOrientation($value, $axisside) { if ($value < 0) { $this->graphOrientation[$axisside] = '-'; } else { if (zbx_empty($this->graphOrientation[$axisside]) && $value > 0) { $this->graphOrientation[$axisside] = '+'; } } return $this->graphOrientation[$axisside]; }
/** * Get Host data * * {@source} * @access public * @static * @since 1.8 * @version 1 * * @param _array $options * @param array $options['nodeids'] Node IDs * @param array $options['groupids'] HostGroup IDs * @param array $options['hostids'] Host IDs * @param boolean $options['monitored_hosts'] only monitored Hosts * @param boolean $options['templated_hosts'] include templates in result * @param boolean $options['with_items'] only with items * @param boolean $options['with_monitored_items'] only with monitored items * @param boolean $options['with_historical_items'] only with historical items * @param boolean $options['with_triggers'] only with triggers * @param boolean $options['with_monitored_triggers'] only with monitored triggers * @param boolean $options['with_httptests'] only with http tests * @param boolean $options['with_monitored_httptests'] only with monitored http tests * @param boolean $options['with_graphs'] only with graphs * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins * @param int $options['extendoutput'] return all fields for Hosts * @param boolean $options['select_groups'] select HostGroups * @param boolean $options['select_templates'] select Templates * @param boolean $options['select_items'] select Items * @param boolean $options['select_triggers'] select Triggers * @param boolean $options['select_graphs'] select Graphs * @param boolean $options['select_applications'] select Applications * @param boolean $options['select_macros'] select Macros * @param boolean $options['select_profile'] select Profile * @param int $options['count'] count Hosts, returned column name is rowscount * @param string $options['pattern'] search hosts by pattern in Host name * @param string $options['extendPattern'] search hosts by pattern in Host name, ip and DNS * @param int $options['limit'] limit selection * @param string $options['sortfield'] field to sort by * @param string $options['sortorder'] sort order * @return array|boolean Host data as array or false if error */ public static function get($options = array()) { global $USER_DETAILS; $result = array(); $nodeCheck = false; $user_type = $USER_DETAILS['type']; $userid = $USER_DETAILS['userid']; $sort_columns = array('hostid', 'host', 'status', 'dns', 'ip'); // allowed columns for sorting $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM); // allowed output options for [ select_* ] params $sql_parts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null); $def_options = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'proxyids' => null, 'templateids' => null, 'itemids' => null, 'triggerids' => null, 'maintenanceids' => null, 'graphids' => null, 'dhostids' => null, 'dserviceids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'proxy_hosts' => null, 'with_items' => null, 'with_monitored_items' => null, 'with_historical_items' => null, 'with_triggers' => null, 'with_monitored_triggers' => null, 'with_httptests' => null, 'with_monitored_httptests' => null, 'with_graphs' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_groups' => null, 'selectParentTemplates' => null, 'select_items' => null, 'select_triggers' => null, 'select_graphs' => null, 'select_dhosts' => null, 'select_dservices' => null, 'select_applications' => null, 'select_macros' => null, 'select_profile' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null); $options = zbx_array_merge($def_options, $options); if (!is_null($options['extendoutput'])) { $options['output'] = API_OUTPUT_EXTEND; if (!is_null($options['select_groups'])) { $options['select_groups'] = API_OUTPUT_EXTEND; } if (!is_null($options['selectParentTemplates'])) { $options['selectParentTemplates'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_items'])) { $options['select_items'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_triggers'])) { $options['select_triggers'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_graphs'])) { $options['select_graphs'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_applications'])) { $options['select_applications'] = API_OUTPUT_EXTEND; } if (!is_null($options['select_macros'])) { $options['select_macros'] = API_OUTPUT_EXTEND; } } if (is_array($options['output'])) { unset($sql_parts['select']['hosts']); $sql_parts['select']['hostid'] = ' h.hostid'; foreach ($options['output'] as $key => $field) { $sql_parts['select'][$field] = ' h.' . $field; } $options['output'] = API_OUTPUT_CUSTOM; } // editable + PERMISSION CHECK if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) { } else { $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY; $sql_parts['where'][] = 'EXISTS (' . ' SELECT hh.hostid ' . ' FROM hosts hh, hosts_groups hgg, rights r, users_groups ug ' . ' WHERE hh.hostid=h.hostid ' . ' AND hh.hostid=hgg.hostid ' . ' AND r.id=hgg.groupid ' . ' AND r.groupid=ug.usrgrpid ' . ' AND ug.userid=' . $userid . ' AND r.permission>=' . $permission . ' AND NOT EXISTS( ' . ' SELECT hggg.groupid ' . ' FROM hosts_groups hggg, rights rr, users_groups gg ' . ' WHERE hggg.hostid=hgg.hostid ' . ' AND rr.id=hggg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . ' )) '; } // nodeids $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid(); // hostids if (!is_null($options['hostids'])) { zbx_value2array($options['hostids']); $sql_parts['where']['hostid'] = DBcondition('h.hostid', $options['hostids']); if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.hostid', $nodeids); } } // groupids if (!is_null($options['groupids'])) { zbx_value2array($options['groupids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['groupid'] = 'hg.groupid'; } $sql_parts['from']['hosts_groups'] = 'hosts_groups hg'; $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']); $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid'; if (!is_null($options['groupCount'])) { $sql_parts['group']['groupid'] = 'hg.groupid'; } if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('hg.groupid', $nodeids); } } // proxyids if (!is_null($options['proxyids'])) { zbx_value2array($options['proxyids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['proxy_hostid'] = 'h.proxy_hostid'; } $sql_parts['where'][] = DBcondition('h.proxy_hostid', $options['proxyids']); } // templateids if (!is_null($options['templateids'])) { zbx_value2array($options['templateids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['templateid'] = 'ht.templateid'; } $sql_parts['from']['hosts_templates'] = 'hosts_templates ht'; $sql_parts['where'][] = DBcondition('ht.templateid', $options['templateids']); $sql_parts['where']['hht'] = 'h.hostid=ht.hostid'; if (!is_null($options['groupCount'])) { $sql_parts['group']['templateid'] = 'ht.templateid'; } if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('ht.templateid', $nodeids); } } // itemids if (!is_null($options['itemids'])) { zbx_value2array($options['itemids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['itemid'] = 'i.itemid'; } $sql_parts['from']['items'] = 'items i'; $sql_parts['where'][] = DBcondition('i.itemid', $options['itemids']); $sql_parts['where']['hi'] = 'h.hostid=i.hostid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('i.itemid', $nodeids); } } // triggerids if (!is_null($options['triggerids'])) { zbx_value2array($options['triggerids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['triggerid'] = 'f.triggerid'; } $sql_parts['from']['functions'] = 'functions f'; $sql_parts['from']['items'] = 'items i'; $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']); $sql_parts['where']['hi'] = 'h.hostid=i.hostid'; $sql_parts['where']['fi'] = 'f.itemid=i.itemid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('f.triggerid', $nodeids); } } // graphids if (!is_null($options['graphids'])) { zbx_value2array($options['graphids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['graphid'] = 'gi.graphid'; } $sql_parts['from']['graphs_items'] = 'graphs_items gi'; $sql_parts['from']['items'] = 'items i'; $sql_parts['where'][] = DBcondition('gi.graphid', $options['graphids']); $sql_parts['where']['igi'] = 'i.itemid=gi.itemid'; $sql_parts['where']['hi'] = 'h.hostid=i.hostid'; if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('gi.graphid', $nodeids); } } // dhostids if (!is_null($options['dhostids'])) { zbx_value2array($options['dhostids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['dhostid'] = 'ds.dhostid'; } $sql_parts['from']['dservices'] = 'dservices ds'; $sql_parts['where'][] = DBcondition('ds.dhostid', $options['dhostids']); $sql_parts['where']['dsh'] = 'ds.ip=h.ip'; if (!is_null($options['groupCount'])) { $sql_parts['group']['dhostid'] = 'ds.dhostid'; } } // dserviceids if (!is_null($options['dserviceids'])) { zbx_value2array($options['dserviceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['dserviceid'] = 'ds.dserviceid'; } $sql_parts['from']['dservices'] = 'dservices ds'; $sql_parts['where'][] = DBcondition('ds.dserviceid', $options['dserviceids']); $sql_parts['where']['dsh'] = 'ds.ip=h.ip'; if (!is_null($options['groupCount'])) { $sql_parts['group']['dserviceid'] = 'ds.dserviceid'; } } // maintenanceids if (!is_null($options['maintenanceids'])) { zbx_value2array($options['maintenanceids']); if ($options['output'] != API_OUTPUT_SHORTEN) { $sql_parts['select']['maintenanceid'] = 'mh.maintenanceid'; } $sql_parts['from']['maintenances_hosts'] = 'maintenances_hosts mh'; $sql_parts['where'][] = DBcondition('mh.maintenanceid', $options['maintenanceids']); $sql_parts['where']['hmh'] = 'h.hostid=mh.hostid'; if (!is_null($options['groupCount'])) { $sql_parts['group']['maintenanceid'] = 'mh.maintenanceid'; } } // node check !!!!! // should last, after all ****IDS checks if (!$nodeCheck) { $nodeCheck = true; $sql_parts['where'][] = DBin_node('h.hostid', $nodeids); } // monitored_hosts, templated_hosts if (!is_null($options['monitored_hosts'])) { $sql_parts['where']['status'] = 'h.status=' . HOST_STATUS_MONITORED; } else { if (!is_null($options['templated_hosts'])) { $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')'; } else { if (!is_null($options['proxy_hosts'])) { $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')'; } else { $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')'; } } } // with_items, with_monitored_items, with_historical_items if (!is_null($options['with_items'])) { $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid )'; } else { if (!is_null($options['with_monitored_items'])) { $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND i.status=' . ITEM_STATUS_ACTIVE . ')'; } else { if (!is_null($options['with_historical_items'])) { $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND (i.status=' . ITEM_STATUS_ACTIVE . ' OR i.status=' . ITEM_STATUS_NOTSUPPORTED . ') AND i.lastvalue IS NOT NULL)'; } } } // with_triggers, with_monitored_triggers if (!is_null($options['with_triggers'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid)'; } else { if (!is_null($options['with_monitored_triggers'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid ' . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')'; } } // with_httptests, with_monitored_httptests if (!is_null($options['with_httptests'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid)'; } else { if (!is_null($options['with_monitored_httptests'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid ' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')'; } } // with_graphs if (!is_null($options['with_graphs'])) { $sql_parts['where'][] = 'EXISTS( ' . ' SELECT DISTINCT i.itemid ' . ' FROM items i, graphs_items gi ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=gi.itemid)'; } // output if ($options['output'] == API_OUTPUT_EXTEND) { $sql_parts['select']['hosts'] = 'h.*'; } // countOutput if (!is_null($options['countOutput'])) { $options['sortfield'] = ''; $sql_parts['select'] = array('count(DISTINCT h.hostid) as rowscount'); //groupCount if (!is_null($options['groupCount'])) { foreach ($sql_parts['group'] as $key => $fields) { $sql_parts['select'][$key] = $fields; } } } // search if (is_array($options['search'])) { zbx_db_search('hosts h', $options, $sql_parts); } // filter if (is_array($options['filter'])) { zbx_db_filter('hosts h', $options, $sql_parts); } // order // restrict not allowed columns for sorting $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : ''; if (!zbx_empty($options['sortfield'])) { $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP; $sql_parts['order'][$options['sortfield']] = 'h.' . $options['sortfield'] . ' ' . $sortorder; if (!str_in_array('h.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('h.*', $sql_parts['select'])) { $sql_parts['select'][$options['sortfield']] = 'h.' . $options['sortfield']; } } // limit if (zbx_ctype_digit($options['limit']) && $options['limit']) { $sql_parts['limit'] = $options['limit']; } //------- $hostids = array(); $sql_parts['select'] = array_unique($sql_parts['select']); $sql_parts['from'] = array_unique($sql_parts['from']); $sql_parts['where'] = array_unique($sql_parts['where']); $sql_parts['group'] = array_unique($sql_parts['group']); $sql_parts['order'] = array_unique($sql_parts['order']); $sql_select = ''; $sql_from = ''; $sql_where = ''; $sql_group = ''; $sql_order = ''; if (!empty($sql_parts['select'])) { $sql_select .= implode(',', $sql_parts['select']); } if (!empty($sql_parts['from'])) { $sql_from .= implode(',', $sql_parts['from']); } if (!empty($sql_parts['where'])) { $sql_where .= implode(' AND ', $sql_parts['where']); } if (!empty($sql_parts['group'])) { $sql_where .= ' GROUP BY ' . implode(',', $sql_parts['group']); } if (!empty($sql_parts['order'])) { $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']); } $sql_limit = $sql_parts['limit']; $sql = 'SELECT ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_group . $sql_order; //SDI($sql); $res = DBselect($sql, $sql_limit); while ($host = DBfetch($res)) { if (!is_null($options['countOutput'])) { if (!is_null($options['groupCount'])) { $result[] = $host; } else { $result = $host['rowscount']; } } else { $hostids[$host['hostid']] = $host['hostid']; if ($options['output'] == API_OUTPUT_SHORTEN) { $result[$host['hostid']] = array('hostid' => $host['hostid']); } else { if (!isset($result[$host['hostid']])) { $result[$host['hostid']] = array(); } if (!is_null($options['select_groups']) && !isset($result[$host['hostid']]['groups'])) { $result[$host['hostid']]['groups'] = array(); } if (!is_null($options['selectParentTemplates']) && !isset($result[$host['hostid']]['parentTemplates'])) { $result[$host['hostid']]['parentTemplates'] = array(); } if (!is_null($options['select_items']) && !isset($result[$host['hostid']]['items'])) { $result[$host['hostid']]['items'] = array(); } if (!is_null($options['select_profile']) && !isset($result[$host['hostid']]['profile'])) { $result[$host['hostid']]['profile'] = array(); $result[$host['hostid']]['profile_ext'] = array(); } if (!is_null($options['select_triggers']) && !isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } if (!is_null($options['select_graphs']) && !isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } if (!is_null($options['select_dhosts']) && !isset($result[$host['hostid']]['dhosts'])) { $result[$host['hostid']]['dhosts'] = array(); } if (!is_null($options['select_dservices']) && !isset($result[$host['hostid']]['dservices'])) { $result[$host['hostid']]['dservices'] = array(); } if (!is_null($options['select_applications']) && !isset($result[$host['hostid']]['applications'])) { $result[$host['hostid']]['applications'] = array(); } if (!is_null($options['select_macros']) && !isset($result[$host['hostid']]['macros'])) { $result[$host['hostid']]['macros'] = array(); } // if(!is_null($options['select_maintenances']) && !isset($result[$host['hostid']]['maintenances'])){ // $result[$host['hostid']]['maintenances'] = array(); // } // groupids if (isset($host['groupid']) && is_null($options['select_groups'])) { if (!isset($result[$host['hostid']]['groups'])) { $result[$host['hostid']]['groups'] = array(); } $result[$host['hostid']]['groups'][] = array('groupid' => $host['groupid']); unset($host['groupid']); } // templateids if (isset($host['templateid'])) { if (!isset($result[$host['hostid']]['templates'])) { $result[$host['hostid']]['templates'] = array(); } $result[$host['hostid']]['templates'][] = array('templateid' => $host['templateid']); unset($host['templateid']); } // triggerids if (isset($host['triggerid']) && is_null($options['select_triggers'])) { if (!isset($result[$host['hostid']]['triggers'])) { $result[$host['hostid']]['triggers'] = array(); } $result[$host['hostid']]['triggers'][] = array('triggerid' => $host['triggerid']); unset($host['triggerid']); } // itemids if (isset($host['itemid']) && is_null($options['select_items'])) { if (!isset($result[$host['hostid']]['items'])) { $result[$host['hostid']]['items'] = array(); } $result[$host['hostid']]['items'][] = array('itemid' => $host['itemid']); unset($host['itemid']); } // graphids if (isset($host['graphid']) && is_null($options['select_graphs'])) { if (!isset($result[$host['hostid']]['graphs'])) { $result[$host['hostid']]['graphs'] = array(); } $result[$host['hostid']]['graphs'][] = array('graphid' => $host['graphid']); unset($host['graphid']); } // dhostids if (isset($host['dhostid']) && is_null($options['select_dhosts'])) { if (!isset($result[$host['hostid']]['dhosts'])) { $result[$host['hostid']]['dhosts'] = array(); } $result[$host['hostid']]['dhosts'][] = array('dhostid' => $host['dhostid']); unset($host['dhostid']); } // dserviceids if (isset($host['dserviceid']) && is_null($options['select_dservices'])) { if (!isset($result[$host['hostid']]['dservices'])) { $result[$host['hostid']]['dservices'] = array(); } $result[$host['hostid']]['dservices'][] = array('dserviceid' => $host['dserviceid']); unset($host['dserviceid']); } // maintenanceids if (isset($host['maintenanceid'])) { if (!isset($result[$host['hostid']]['maintenanceid'])) { $result[$host['hostid']]['maintenances'] = array(); } $result[$host['hostid']]['maintenances'][] = array('maintenanceid' => $host['maintenanceid']); // unset($host['maintenanceid']); } //--- $result[$host['hostid']] += $host; } } } Copt::memoryPick(); if (!is_null($options['countOutput'])) { if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; } // Adding Objects // Adding Groups if (!is_null($options['select_groups']) && str_in_array($options['select_groups'], $subselects_allowed_outputs)) { $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_groups'], 'hostids' => $hostids, 'preservekeys' => 1); $groups = CHostgroup::get($obj_params); foreach ($groups as $groupid => $group) { $ghosts = $group['hosts']; unset($group['hosts']); foreach ($ghosts as $num => $host) { $result[$host['hostid']]['groups'][] = $group; } } } // Adding Profiles if (!is_null($options['select_profile'])) { $sql = 'SELECT hp.* ' . ' FROM hosts_profiles hp ' . ' WHERE ' . DBcondition('hp.hostid', $hostids); $db_profile = DBselect($sql); while ($profile = DBfetch($db_profile)) { $result[$profile['hostid']]['profile'] = $profile; } $sql = 'SELECT hpe.* ' . ' FROM hosts_profiles_ext hpe ' . ' WHERE ' . DBcondition('hpe.hostid', $hostids); $db_profile_ext = DBselect($sql); while ($profile_ext = DBfetch($db_profile_ext)) { $result[$profile_ext['hostid']]['profile_ext'] = $profile_ext; } } // Adding Templates if (!is_null($options['selectParentTemplates'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'preservekeys' => 1); if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['selectParentTemplates']; $templates = CTemplate::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($templates, 'host'); } foreach ($templates as $templateid => $template) { unset($templates[$templateid]['hosts']); $count = array(); foreach ($template['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['parentTemplates'][] =& $templates[$templateid]; } } } else { if (API_OUTPUT_COUNT == $options['selectParentTemplates']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $templates = CTemplate::get($obj_params); $templates = zbx_toHash($templates, 'hostid'); foreach ($result as $hostid => $host) { if (isset($templates[$hostid])) { $result[$hostid]['templates'] = $templates[$hostid]['rowscount']; } else { $result[$hostid]['templates'] = 0; } } } } } // Adding Items if (!is_null($options['select_items'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_items']) || str_in_array($options['select_items'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_items']; $items = CItem::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($items, 'description'); } foreach ($items as $itemid => $item) { unset($items[$itemid]['hosts']); foreach ($item['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['items'][] =& $items[$itemid]; } } } else { if (API_OUTPUT_COUNT == $options['select_items']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $items = CItem::get($obj_params); $items = zbx_toHash($items, 'hostid'); foreach ($result as $hostid => $host) { if (isset($items[$hostid])) { $result[$hostid]['items'] = $items[$hostid]['rowscount']; } else { $result[$hostid]['items'] = 0; } } } } } // Adding triggers if (!is_null($options['select_triggers'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_triggers']) || str_in_array($options['select_triggers'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_triggers']; $triggers = CTrigger::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($triggers, 'description'); } foreach ($triggers as $triggerid => $trigger) { unset($triggers[$triggerid]['hosts']); foreach ($trigger['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['triggers'][] =& $triggers[$triggerid]; } } } else { if (API_OUTPUT_COUNT == $options['select_triggers']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $triggers = CTrigger::get($obj_params); $triggers = zbx_toHash($triggers, 'hostid'); foreach ($result as $hostid => $host) { if (isset($triggers[$hostid])) { $result[$hostid]['triggers'] = $triggers[$hostid]['rowscount']; } else { $result[$hostid]['triggers'] = 0; } } } } } // Adding graphs if (!is_null($options['select_graphs'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_graphs']) || str_in_array($options['select_graphs'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_graphs']; $graphs = CGraph::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($graphs, 'name'); } foreach ($graphs as $graphid => $graph) { unset($graphs[$graphid]['hosts']); foreach ($graph['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['graphs'][] =& $graphs[$graphid]; } } } else { if (API_OUTPUT_COUNT == $options['select_graphs']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $graphs = CGraph::get($obj_params); $graphs = zbx_toHash($graphs, 'hostid'); foreach ($result as $hostid => $host) { if (isset($graphs[$hostid])) { $result[$hostid]['graphs'] = $graphs[$hostid]['rowscount']; } else { $result[$hostid]['graphs'] = 0; } } } } } // Adding discovery hosts if (!is_null($options['select_dhosts'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_dhosts']) || str_in_array($options['select_dhosts'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_dhosts']; $dhosts = CDHost::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($dhosts, 'dhostid'); } foreach ($dhosts as $dhostid => $dhost) { unset($dhosts[$dhostid]['hosts']); foreach ($dhost['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['dhosts'][] =& $dhosts[$dhostid]; } } } else { if (API_OUTPUT_COUNT == $options['select_dhosts']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $dhosts = CDHost::get($obj_params); $dhosts = zbx_toHash($dhosts, 'hostid'); foreach ($result as $hostid => $host) { if (isset($dhosts[$hostid])) { $result[$hostid]['dhosts'] = $dhosts[$hostid]['rowscount']; } else { $result[$hostid]['dhosts'] = 0; } } } } } // Adding applications if (!is_null($options['select_applications'])) { $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1); if (is_array($options['select_applications']) || str_in_array($options['select_applications'], $subselects_allowed_outputs)) { $obj_params['output'] = $options['select_applications']; $applications = CApplication::get($obj_params); if (!is_null($options['limitSelects'])) { order_result($applications, 'name'); } foreach ($applications as $applicationid => $application) { unset($applications[$applicationid]['hosts']); foreach ($application['hosts'] as $hnum => $host) { if (!is_null($options['limitSelects'])) { if (!isset($count[$host['hostid']])) { $count[$host['hostid']] = 0; } $count[$host['hostid']]++; if ($count[$host['hostid']] > $options['limitSelects']) { continue; } } $result[$host['hostid']]['applications'][] =& $applications[$applicationid]; } } } else { if (API_OUTPUT_COUNT == $options['select_applications']) { $obj_params['countOutput'] = 1; $obj_params['groupCount'] = 1; $applications = CApplication::get($obj_params); $applications = zbx_toHash($applications, 'hostid'); foreach ($result as $hostid => $host) { if (isset($applications[$hostid])) { $result[$hostid]['applications'] = $applications[$hostid]['rowscount']; } else { $result[$hostid]['applications'] = 0; } } } } } // Adding macros if (!is_null($options['select_macros']) && str_in_array($options['select_macros'], $subselects_allowed_outputs)) { $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_macros'], 'hostids' => $hostids, 'preservekeys' => 1); $macros = CUserMacro::get($obj_params); foreach ($macros as $macroid => $macro) { $mhosts = $macro['hosts']; unset($macro['hosts']); foreach ($mhosts as $num => $host) { $result[$host['hostid']]['macros'][] = $macro; } } } Copt::memoryPick(); // removing keys (hash -> array) if (is_null($options['preservekeys'])) { $result = zbx_cleanHashes($result); } return $result; }
/** * Check, if items that are about to be inserted or updated violate the rule: * only one item can be linked to a inventory filed. * If everything is ok, function return true or throws Exception otherwise * * @static * * @param array $items * @param bool $update whether this is update operation * * @return bool */ public static function validateInventoryLinks(array $items, $update = false) { // inventory link field is not being updated, or being updated to 0, no need to validate anything then foreach ($items as $i => $item) { if (!isset($item['inventory_link']) || $item['inventory_link'] == 0) { unset($items[$i]); } } if (zbx_empty($items)) { return true; } $possibleHostInventories = getHostInventories(); if ($update) { // for successful validation we need three fields for each item: inventory_link, hostid and key_ // problem is, that when we are updating an item, we might not have them, because they are not changed // so, we need to find out what is missing and use API to get the lacking info $itemsWithNoHostId = array(); $itemsWithNoInventoryLink = array(); $itemsWithNoKeys = array(); foreach ($items as $item) { if (!isset($item['inventory_link'])) { $itemsWithNoInventoryLink[$item['itemid']] = $item['itemid']; } if (!isset($item['hostid'])) { $itemsWithNoHostId[$item['itemid']] = $item['itemid']; } if (!isset($item['key_'])) { $itemsWithNoKeys[$item['itemid']] = $item['itemid']; } } $itemsToFind = array_merge($itemsWithNoHostId, $itemsWithNoInventoryLink, $itemsWithNoKeys); // are there any items with lacking info? if (!zbx_empty($itemsToFind)) { $missingInfo = API::Item()->get(array('output' => array('hostid', 'inventory_link', 'key_'), 'filter' => array('itemid' => $itemsToFind), 'nopermissions' => true)); $missingInfo = zbx_toHash($missingInfo, 'itemid'); // appending host ids, inventory_links and keys where they are needed foreach ($items as $i => $item) { if (isset($missingInfo[$item['itemid']])) { if (!isset($items[$i]['hostid'])) { $items[$i]['hostid'] = $missingInfo[$item['itemid']]['hostid']; } if (!isset($items[$i]['inventory_link'])) { $items[$i]['inventory_link'] = $missingInfo[$item['itemid']]['inventory_link']; } if (!isset($items[$i]['key_'])) { $items[$i]['key_'] = $missingInfo[$item['itemid']]['key_']; } } } } } $hostids = zbx_objectValues($items, 'hostid'); // getting all inventory links on every affected host $itemsOnHostsInfo = API::Item()->get(array('output' => array('key_', 'inventory_link', 'hostid'), 'filter' => array('hostid' => $hostids), 'nopermissions' => true)); // now, changing array to: 'hostid' => array('key_'=>'inventory_link') $linksOnHostsCurr = array(); foreach ($itemsOnHostsInfo as $info) { // 0 means no link - we are not interested in those ones if ($info['inventory_link'] != 0) { if (!isset($linksOnHostsCurr[$info['hostid']])) { $linksOnHostsCurr[$info['hostid']] = array($info['key_'] => $info['inventory_link']); } else { $linksOnHostsCurr[$info['hostid']][$info['key_']] = $info['inventory_link']; } } } $linksOnHostsFuture = array(); foreach ($items as $item) { // checking if inventory_link value is a valid number if ($update || $item['value_type'] != ITEM_VALUE_TYPE_LOG) { // does inventory field with provided number exists? if (!isset($possibleHostInventories[$item['inventory_link']])) { $maxVar = max(array_keys($possibleHostInventories)); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item "%1$s" cannot populate a missing host inventory field number "%2$d". Choices are: from 0 (do not populate) to %3$d.', $item['name'], $item['inventory_link'], $maxVar)); } } if (!isset($linksOnHostsFuture[$item['hostid']])) { $linksOnHostsFuture[$item['hostid']] = array($item['key_'] => $item['inventory_link']); } else { $linksOnHostsFuture[$item['hostid']][$item['key_']] = $item['inventory_link']; } } foreach ($linksOnHostsFuture as $hostId => $linkFuture) { if (isset($linksOnHostsCurr[$hostId])) { $futureSituation = array_merge($linksOnHostsCurr[$hostId], $linksOnHostsFuture[$hostId]); } else { $futureSituation = $linksOnHostsFuture[$hostId]; } $valuesCount = array_count_values($futureSituation); // if we have a duplicate inventory links after merging - we are in trouble if (max($valuesCount) > 1) { // what inventory field caused this conflict? $conflictedLink = array_keys($valuesCount, 2); $conflictedLink = reset($conflictedLink); // which of updated items populates this link? $beingSavedItemName = ''; foreach ($items as $item) { if ($item['inventory_link'] == $conflictedLink) { if (isset($item['name'])) { $beingSavedItemName = $item['name']; } else { $thisItem = API::Item()->get(array('output' => array('name'), 'filter' => array('itemid' => $item['itemid']), 'nopermissions' => true)); $beingSavedItemName = $thisItem[0]['name']; } break; } } // name of the original item that already populates the field $originalItem = API::Item()->get(array('output' => array('name'), 'filter' => array('hostid' => $hostId, 'inventory_link' => $conflictedLink), 'nopermissions' => true)); $originalItemName = $originalItem[0]['name']; self::exception(ZBX_API_ERROR_PARAMETERS, _s('Two items ("%1$s" and "%2$s") cannot populate one host inventory field "%3$s", this would lead to a conflict.', $beingSavedItemName, $originalItemName, $possibleHostInventories[$conflictedLink]['title'])); } } return true; }
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; } } }
uncheckTableRows(getRequest('parent_discoveryid')); } show_messages($result, _('Item prototype deleted'), _('Cannot delete item prototype')); unset($_REQUEST['itemid'], $_REQUEST['form']); } elseif (isset($_REQUEST['clone']) && isset($_REQUEST['itemid'])) { unset($_REQUEST['itemid']); $_REQUEST['form'] = 'clone'; } elseif (hasRequest('add') || hasRequest('update')) { $applications = getRequest('applications', []); $application = reset($applications); if ($application == 0) { array_shift($applications); } $result = true; DBstart(); if (!zbx_empty($_REQUEST['new_application'])) { $new_appid = API::Application()->create(['name' => $_REQUEST['new_application'], 'hostid' => $discoveryRule['hostid']]); if ($new_appid) { $new_appid = reset($new_appid['applicationids']); $applications[$new_appid] = $new_appid; } else { $result = false; } } /* * Intially validate "delay_flex" field one by one to make sure it does not have interval separator ";". * Skip empty fields and convert "delay_flex" array to string glued with ";" which is later validated through API. */ $delay_flex = ''; $intervals = []; if (getRequest('delay_flex')) {
/** * Create DIV with latest problem triggers. * * If no sortfield and sortorder are defined, the sort indicater in the column name will not be displayed. * * @param array $filter['screenid'] * @param array $filter['groupids'] * @param array $filter['hostids'] * @param array $filter['maintenance'] * @param int $filter['extAck'] * @param int $filter['severity'] * @param int $filter['limit'] * @param string $filter['sortfield'] * @param string $filter['sortorder'] * @param string $filter['backUrl'] * * @return CDiv */ function make_latest_issues(array $filter = array()) { // hide the sort indicator if no sortfield and sortorder are given $showSortIndicator = isset($filter['sortfield']) || isset($filter['sortorder']); if (!isset($filter['sortfield'])) { $filter['sortfield'] = 'lastchange'; } if (!isset($filter['sortorder'])) { $filter['sortorder'] = ZBX_SORT_DOWN; } $options = array('groupids' => $filter['groupids'], 'hostids' => isset($filter['hostids']) ? $filter['hostids'] : null, 'monitored' => true, 'maintenance' => $filter['maintenance'], 'filter' => array('priority' => $filter['severity'], 'value' => TRIGGER_VALUE_TRUE)); $triggers = API::Trigger()->get(array_merge($options, array('withLastEventUnacknowledged' => isset($filter['extAck']) && $filter['extAck'] == EXTACK_OPTION_UNACK ? true : null, 'skipDependent' => true, 'output' => array('triggerid', 'state', 'error', 'url', 'expression', 'description', 'priority', 'lastchange'), 'selectHosts' => array('hostid', 'name'), 'selectLastEvent' => array('eventid', 'acknowledged', 'objectid', 'clock', 'ns'), 'sortfield' => $filter['sortfield'], 'sortorder' => $filter['sortorder'], 'limit' => isset($filter['limit']) ? $filter['limit'] : DEFAULT_LATEST_ISSUES_CNT))); // don't use withLastEventUnacknowledged and skipDependent because of performance issues $triggersTotalCount = API::Trigger()->get(array_merge($options, array('countOutput' => true))); // get acknowledges $eventIds = array(); foreach ($triggers as $trigger) { if ($trigger['lastEvent']) { $eventIds[] = $trigger['lastEvent']['eventid']; } } if ($eventIds) { $eventAcknowledges = API::Event()->get(array('eventids' => $eventIds, 'select_acknowledges' => API_OUTPUT_EXTEND, 'preservekeys' => true)); } foreach ($triggers as $tnum => $trigger) { // if trigger is lost (broken expression) we skip it if (empty($trigger['hosts'])) { unset($triggers[$tnum]); continue; } $host = reset($trigger['hosts']); $trigger['hostid'] = $host['hostid']; $trigger['hostname'] = $host['name']; if ($trigger['lastEvent']) { $trigger['lastEvent']['acknowledges'] = isset($eventAcknowledges[$trigger['lastEvent']['eventid']]) ? $eventAcknowledges[$trigger['lastEvent']['eventid']]['acknowledges'] : null; } $triggers[$tnum] = $trigger; } $hostIds = zbx_objectValues($triggers, 'hostid'); // get hosts $hosts = API::Host()->get(array('hostids' => $hostIds, 'output' => array('hostid', 'name', 'status', 'maintenance_status', 'maintenance_type', 'maintenanceid'), 'selectScreens' => API_OUTPUT_COUNT, 'preservekeys' => true)); // actions $actions = getEventActionsStatHints($eventIds); // ack params $ackParams = isset($filter['screenid']) ? array('screenid' => $filter['screenid']) : array(); $config = select_config(); // indicator of sort field if ($showSortIndicator) { $sortDiv = new CDiv(SPACE, $filter['sortorder'] === ZBX_SORT_DOWN ? 'icon_sortdown default_cursor' : 'icon_sortup default_cursor'); $sortDiv->addStyle('float: left'); $hostHeaderDiv = new CDiv(array(_('Host'), SPACE)); $hostHeaderDiv->addStyle('float: left'); $issueHeaderDiv = new CDiv(array(_('Issue'), SPACE)); $issueHeaderDiv->addStyle('float: left'); $lastChangeHeaderDiv = new CDiv(array(_('Time'), SPACE)); $lastChangeHeaderDiv->addStyle('float: left'); } $table = new CTableInfo(_('No events found.')); $table->setHeader(array(is_show_all_nodes() ? _('Node') : null, $showSortIndicator && $filter['sortfield'] === 'hostname' ? array($hostHeaderDiv, $sortDiv) : _('Host'), $showSortIndicator && $filter['sortfield'] === 'priority' ? array($issueHeaderDiv, $sortDiv) : _('Issue'), $showSortIndicator && $filter['sortfield'] === 'lastchange' ? array($lastChangeHeaderDiv, $sortDiv) : _('Last change'), _('Age'), _('Info'), $config['event_ack_enable'] ? _('Ack') : null, _('Actions'))); $scripts = API::Script()->getScriptsByHosts($hostIds); // triggers foreach ($triggers as $trigger) { $host = $hosts[$trigger['hostid']]; $hostName = new CSpan($host['name'], 'link_menu'); $hostName->setMenuPopup(getMenuPopupHost($host, $scripts[$host['hostid']])); // add maintenance icon with hint if host is in maintenance $maintenanceIcon = null; if ($host['maintenance_status']) { $maintenanceIcon = new CDiv(null, 'icon-maintenance-abs'); // get maintenance $maintenances = API::Maintenance()->get(array('maintenanceids' => $host['maintenanceid'], 'output' => API_OUTPUT_EXTEND, 'limit' => 1)); if ($maintenance = reset($maintenances)) { $hint = $maintenance['name'] . ' [' . ($host['maintenance_type'] ? _('Maintenance without data collection') : _('Maintenance with data collection')) . ']'; if (isset($maintenance['description'])) { // double quotes mandatory $hint .= "\n" . $maintenance['description']; } $maintenanceIcon->setHint($hint); $maintenanceIcon->addClass('pointer'); } $hostName->addClass('left-to-icon-maintenance-abs'); } $hostDiv = new CDiv(array($hostName, $maintenanceIcon), 'maintenance-abs-cont'); // unknown triggers $unknown = SPACE; if ($trigger['state'] == TRIGGER_STATE_UNKNOWN) { $unknown = new CDiv(SPACE, 'status_icon iconunknown'); $unknown->setHint($trigger['error'], '', 'on'); } // trigger has events if ($trigger['lastEvent']) { // description $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['lastEvent']['clock'], 'ns' => $trigger['lastEvent']['ns']))); // ack $ack = getEventAckState($trigger['lastEvent'], empty($filter['backUrl']) ? true : $filter['backUrl'], true, $ackParams); } else { // description $description = CMacrosResolverHelper::resolveEventDescription(zbx_array_merge($trigger, array('clock' => $trigger['lastchange'], 'ns' => '999999999'))); // ack $ack = new CSpan(_('No events'), 'unknown'); } // description if (!zbx_empty($trigger['url'])) { $description = new CLink($description, resolveTriggerUrl($trigger), null, null, true); } else { $description = new CSpan($description, 'pointer'); } $description = new CCol($description, getSeverityStyle($trigger['priority'])); if ($trigger['lastEvent']) { $description->setHint(make_popup_eventlist($trigger['triggerid'], $trigger['lastEvent']['eventid']), '', '', false); } // clock $clock = new CLink(zbx_date2str(_('d M Y H:i:s'), $trigger['lastchange']), 'events.php?triggerid=' . $trigger['triggerid'] . '&source=0&show_unknown=1&nav_time=' . $trigger['lastchange']); // actions $actionHint = $trigger['lastEvent'] && isset($actions[$trigger['lastEvent']['eventid']]) ? $actions[$trigger['lastEvent']['eventid']] : SPACE; $table->addRow(array(get_node_name_by_elid($trigger['triggerid']), $hostDiv, $description, $clock, zbx_date2age($trigger['lastchange']), $unknown, $ack, $actionHint)); } // initialize blinking zbx_add_post_js('jqBlink.blink();'); $script = new CJSScript(get_js("jQuery('#hat_lastiss_footer').html('" . _s('Updated: %s', zbx_date2str(_('H:i:s'))) . "')")); $infoDiv = new CDiv(_n('%1$d of %2$d issue is shown', '%1$d of %2$d issues are shown', count($triggers), $triggersTotalCount)); $infoDiv->addStyle('text-align: right; padding-right: 3px;'); return new CDiv(array($table, $infoDiv, $script)); }
protected function validateRequiredFields($dRules, $on) { if ($on == 'update') { foreach ($dRules as $dRule) { if (!isset($dRule['druleid']) || zbx_empty($dRule['druleid'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Field "druleid" is required.')); } } } else { foreach ($dRules as $dRule) { if (!isset($dRule['name']) || zbx_empty($dRule['name'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Field "name" is required.')); } } } }
public function checkInput(&$maps, $method) { $create = $method == 'create'; $update = $method == 'update'; $delete = $method == 'delete'; // permissions if ($update || $delete) { $mapDbFields = array('sysmapid' => null); $dbMaps = $this->get(array('sysmapids' => zbx_objectValues($maps, 'sysmapid'), 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'preservekeys' => true, 'selectLinks' => API_OUTPUT_EXTEND, 'selectSelements' => API_OUTPUT_EXTEND, 'selectUrls' => API_OUTPUT_EXTEND)); } else { $mapDbFields = array('name' => null, 'width' => null, 'height' => null, 'urls' => array(), 'selements' => array(), 'links' => array()); } $mapNames = array(); foreach ($maps as &$map) { if (!check_db_fields($mapDbFields, $map)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect fields for sysmap.')); } if ($update || $delete) { if (!isset($dbMaps[$map['sysmapid']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } $dbMap = array_merge($dbMaps[$map['sysmapid']], $map); } else { $dbMap = $map; } if (isset($map['name'])) { if (isset($mapNames[$map['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Duplicate map name for map "%s".', $dbMap['name'])); } else { $mapNames[$map['name']] = $update ? $map['sysmapid'] : 1; } } if (isset($map['width']) && ($map['width'] > 65535 || $map['width'] < 1)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect map width value for map "%s".', $dbMap['name'])); } if (isset($map['height']) && ($map['height'] > 65535 || $map['height'] < 1)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect map height value for map "%s".', $dbMap['name'])); } // labels $mapLabels = array('label_type' => array('typeName' => _('icon'))); if ($dbMap['label_format'] == SYSMAP_LABEL_ADVANCED_ON) { $mapLabels['label_type_hostgroup'] = array('string' => 'label_string_hostgroup', 'typeName' => _('host group')); $mapLabels['label_type_host'] = array('string' => 'label_string_host', 'typeName' => _('host')); $mapLabels['label_type_trigger'] = array('string' => 'label_string_trigger', 'typeName' => _('trigger')); $mapLabels['label_type_map'] = array('string' => 'label_string_map', 'typeName' => _('map')); $mapLabels['label_type_image'] = array('string' => 'label_string_image', 'typeName' => _('image')); } foreach ($mapLabels as $labelName => $labelData) { if (!isset($map[$labelName])) { continue; } if (sysmapElementLabel($map[$labelName]) === false) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } if ($map[$labelName] == MAP_LABEL_TYPE_CUSTOM) { if (!isset($labelData['string'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } if (!isset($map[$labelData['string']]) || zbx_empty($map[$labelData['string']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Custom label for map "%2$s" elements of type "%1$s" may not be empty.', $labelData['typeName'], $dbMap['name'])); } } if ($labelName == 'label_type_image' && $map[$labelName] == MAP_LABEL_TYPE_STATUS) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } if ($labelName == 'label_type' || $labelName == 'label_type_host') { continue; } if ($map[$labelName] == MAP_LABEL_TYPE_IP) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect %1$s label type value for map "%2$s".', $labelData['typeName'], $dbMap['name'])); } } // validating grid options $possibleGridSizes = array(20, 40, 50, 75, 100); if ($update || $create) { // grid size if (isset($map['grid_size']) && !in_array($map['grid_size'], $possibleGridSizes)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Value "%1$s" is invalid for parameter "grid_show". Choices are: "%2$s".', $map['grid_size'], implode('", "', $possibleGridSizes))); } // grid auto align if (isset($map['grid_align']) && $map['grid_align'] != SYSMAP_GRID_ALIGN_ON && $map['grid_align'] != SYSMAP_GRID_ALIGN_OFF) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Value "%1$s" is invalid for parameter "grid_align". Choices are: "%2$s" and "%3$s"', $map['grid_align'], SYSMAP_GRID_ALIGN_ON, SYSMAP_GRID_ALIGN_OFF)); } // grid show if (isset($map['grid_show']) && $map['grid_show'] != SYSMAP_GRID_SHOW_ON && $map['grid_show'] != SYSMAP_GRID_SHOW_OFF) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Value "%1$s" is invalid for parameter "grid_show". Choices are: "%2$s" and "%3$s".', $map['grid_show'], SYSMAP_GRID_SHOW_ON, SYSMAP_GRID_SHOW_OFF)); } } // urls if (isset($map['urls']) && !empty($map['urls'])) { $urlNames = zbx_toHash($map['urls'], 'name'); foreach ($map['urls'] as $url) { if ($url['name'] === '' || $url['url'] === '') { self::exception(ZBX_API_ERROR_PARAMETERS, _s('URL should have both "name" and "url" fields for map "%s".', $dbMap['name'])); } if (!isset($urlNames[$url['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('URL name should be unique for map "%s".', $dbMap['name'])); } unset($urlNames[$url['name']]); } } // map selement links if (!empty($map['links'])) { $selementIds = zbx_objectValues($dbMap['selements'], 'selementid'); foreach ($map['links'] as $link) { if (!in_array($link['selementid1'], $selementIds)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Link selementid1 field is pointing to a nonexistent map selement ID "%1$s" for map "%2$s".', $link['selementid1'], $dbMap['name'])); } if (!in_array($link['selementid2'], $selementIds)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Link selementid2 field is pointing to a nonexistent map selement ID "%1$s" for map "%2$s".', $link['selementid2'], $dbMap['name'])); } } } } unset($map); // exists if (($create || $update) && $mapNames) { $existDbMaps = $this->get(array('filter' => array('name' => array_keys($mapNames)), 'output' => array('sysmapid', 'name'), 'nopermissions' => true)); foreach ($existDbMaps as $dbMap) { if ($create || bccomp($mapNames[$dbMap['name']], $dbMap['sysmapid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Map with name "%s" already exists.', $dbMap['name'])); } } } return $update || $delete ? $dbMaps : true; }
require_once dirname(__FILE__) . '/include/page_header.php'; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array('macros_rem' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null), 'macros' => array(T_ZBX_STR, O_OPT, P_SYS, null, null), 'macro_new' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, 'isset({macro_add})'), 'value_new' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, 'isset({macro_add})'), 'macro_add' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null), 'save' => array(T_ZBX_STR, O_OPT, P_SYS | P_ACT, null, null), 'form_refresh' => array(T_ZBX_INT, O_OPT, null, null, null)); check_fields($fields); /* * Actions */ $result = true; if (isset($_REQUEST['save'])) { try { DBstart(); $globalMacros = API::UserMacro()->get(array('globalmacro' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true)); $newMacros = get_request('macros', array()); // remove empty new macro lines foreach ($newMacros as $number => $newMacro) { if (!isset($newMacro['globalmacroid']) && zbx_empty($newMacro['macro']) && zbx_empty($newMacro['value'])) { unset($newMacros[$number]); } } $duplicatedMacros = array(); foreach ($newMacros as $number => $newMacro) { // transform macros to uppercase {$aaa} => {$AAA} $newMacros[$number]['macro'] = zbx_strtoupper($newMacro['macro']); } // update $macrosToUpdate = array(); foreach ($newMacros as $number => $newMacro) { if (isset($newMacro['globalmacroid']) && isset($globalMacros[$newMacro['globalmacroid']])) { $dbGlobalMacro = $globalMacros[$newMacro['globalmacroid']]; // remove item from new macros array unset($newMacros[$number]);