Пример #1
0
 public function addItem($itemid, $axis = GRAPH_YAXIS_SIDE_DEFAULT, $calc_fnc = CALC_FNC_AVG, $color = null, $drawtype = null, $type = null)
 {
     if ($this->type == GRAPH_TYPE_STACKED) {
         $drawtype = GRAPH_ITEM_DRAWTYPE_FILLED_REGION;
     }
     // TODO: graphs shouldn't retrieve items and resolve macros themselves
     // all of the data must be passed as parameters
     $items = CMacrosResolverHelper::resolveItemNames([get_item_by_itemid($itemid)]);
     $item = reset($items);
     $item['name'] = $item['name_expanded'];
     $this->items[$this->num] = $item;
     $parser = new CItemDelayFlexParser($item['delay_flex']);
     $this->items[$this->num]['delay'] = getItemDelay($item['delay'], $parser->getFlexibleIntervals());
     $this->items[$this->num]['intervals'] = $parser->getIntervals();
     if (strpos($item['units'], ',') === false) {
         $this->items[$this->num]['unitsLong'] = '';
     } else {
         list($this->items[$this->num]['units'], $this->items[$this->num]['unitsLong']) = explode(',', $item['units']);
     }
     $host = get_host_by_hostid($item['hostid']);
     $this->items[$this->num]['host'] = $host['host'];
     $this->items[$this->num]['hostname'] = $host['name'];
     $this->items[$this->num]['color'] = is_null($color) ? 'Dark Green' : $color;
     $this->items[$this->num]['drawtype'] = is_null($drawtype) ? GRAPH_ITEM_DRAWTYPE_LINE : $drawtype;
     $this->items[$this->num]['axisside'] = is_null($axis) ? GRAPH_YAXIS_SIDE_DEFAULT : $axis;
     $this->items[$this->num]['calc_fnc'] = is_null($calc_fnc) ? CALC_FNC_AVG : $calc_fnc;
     $this->items[$this->num]['calc_type'] = is_null($type) ? GRAPH_ITEM_SIMPLE : $type;
     if ($this->items[$this->num]['axisside'] == GRAPH_YAXIS_SIDE_LEFT) {
         $this->yaxisleft = 1;
     }
     if ($this->items[$this->num]['axisside'] == GRAPH_YAXIS_SIDE_RIGHT) {
         $this->yaxisright = 1;
     }
     $this->num++;
 }
Пример #2
0
 /**
  * Check items data.
  *
  * Any system field passed to the function will be unset.
  *
  * @throw APIException
  *
  * @param array $items passed by reference
  * @param bool  $update
  *
  * @return void
  */
 protected function checkInput(array &$items, $update = false)
 {
     if ($update) {
         $itemDbFields = ['itemid' => null];
         $dbItemsFields = ['itemid', 'templateid'];
         foreach ($this->fieldRules as $field => $rule) {
             if (!isset($rule['system'])) {
                 $dbItemsFields[] = $field;
             }
         }
         $dbItems = $this->get(['output' => $dbItemsFields, 'itemids' => zbx_objectValues($items, 'itemid'), 'editable' => true, 'preservekeys' => true]);
         $dbHosts = API::Host()->get(['output' => ['hostid', 'status', 'name'], 'hostids' => zbx_objectValues($dbItems, 'hostid'), 'templated_hosts' => true, 'editable' => true, 'selectApplications' => ['applicationid', 'flags'], 'preservekeys' => true]);
     } else {
         $itemDbFields = ['name' => null, 'key_' => null, 'hostid' => null, 'type' => null, 'value_type' => null, 'delay' => '0', 'delay_flex' => ''];
         $dbHosts = API::Host()->get(['output' => ['hostid', 'status', 'name'], 'hostids' => zbx_objectValues($items, 'hostid'), 'templated_hosts' => true, 'editable' => true, 'selectApplications' => ['applicationid', 'flags'], 'preservekeys' => true]);
     }
     // interfaces
     $interfaces = API::HostInterface()->get(['output' => ['interfaceid', 'hostid', 'type'], 'hostids' => zbx_objectValues($dbHosts, 'hostid'), 'nopermissions' => true, 'preservekeys' => true]);
     if ($update) {
         $updateDiscoveredValidator = new CUpdateDiscoveredValidator(['allowed' => ['itemid', 'status'], 'messageAllowedField' => _('Cannot update "%2$s" for a discovered item "%1$s".')]);
         foreach ($items as $item) {
             // check permissions
             if (!isset($dbItems[$item['itemid']])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
             }
             $dbItem = $dbItems[$item['itemid']];
             $itemName = isset($item['name']) ? $item['name'] : $dbItem['name'];
             // discovered fields, except status, cannot be updated
             $updateDiscoveredValidator->setObjectName($itemName);
             $this->checkPartialValidator($item, $updateDiscoveredValidator, $dbItem);
         }
         $items = $this->extendObjects($this->tableName(), $items, ['name', 'flags']);
     }
     $item_key_parser = new CItemKey();
     foreach ($items as $inum => &$item) {
         $item = $this->clearValues($item);
         $fullItem = $items[$inum];
         if (!check_db_fields($itemDbFields, $item)) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect arguments passed to function.'));
         }
         if ($update) {
             check_db_fields($dbItems[$item['itemid']], $fullItem);
             $this->checkNoParameters($item, ['templateid', 'state'], _('Cannot update "%1$s" for item "%2$s".'), $item['name']);
             // apply rules
             foreach ($this->fieldRules as $field => $rules) {
                 if (0 != $fullItem['templateid'] && isset($rules['template']) || isset($rules['system'])) {
                     unset($item[$field]);
                     // For templated item and fields that should not be modified, use the value from DB.
                     if (array_key_exists($field, $dbItems[$item['itemid']]) && array_key_exists($field, $fullItem)) {
                         $fullItem[$field] = $dbItems[$item['itemid']][$field];
                     }
                 }
             }
             if (!isset($item['key_'])) {
                 $item['key_'] = $fullItem['key_'];
             }
             if (!isset($item['hostid'])) {
                 $item['hostid'] = $fullItem['hostid'];
             }
             // if a templated item is being assigned to an interface with a different type, ignore it
             $itemInterfaceType = itemTypeInterface($dbItems[$item['itemid']]['type']);
             if ($fullItem['templateid'] && isset($item['interfaceid']) && isset($interfaces[$item['interfaceid']]) && $itemInterfaceType !== INTERFACE_TYPE_ANY && $interfaces[$item['interfaceid']]['type'] != $itemInterfaceType) {
                 unset($item['interfaceid']);
             }
         } else {
             if (!isset($dbHosts[$item['hostid']])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
             }
             check_db_fields($itemDbFields, $fullItem);
             $this->checkNoParameters($item, ['templateid', 'state'], _('Cannot set "%1$s" for item "%2$s".'), $item['name']);
         }
         $host = $dbHosts[$fullItem['hostid']];
         if ($fullItem['type'] == ITEM_TYPE_ZABBIX_ACTIVE) {
             $item['delay_flex'] = '';
         }
         if ($fullItem['value_type'] == ITEM_VALUE_TYPE_STR) {
             $item['delta'] = 0;
         }
         if ($fullItem['value_type'] != ITEM_VALUE_TYPE_UINT64) {
             $item['data_type'] = 0;
         }
         // For non-numeric types, whichever value was entered in trends field, is overwritten to zero.
         if ($fullItem['value_type'] == ITEM_VALUE_TYPE_STR || $fullItem['value_type'] == ITEM_VALUE_TYPE_LOG || $fullItem['value_type'] == ITEM_VALUE_TYPE_TEXT) {
             $item['trends'] = 0;
         }
         // check if the item requires an interface
         $itemInterfaceType = itemTypeInterface($fullItem['type']);
         if ($itemInterfaceType !== false && $host['status'] != HOST_STATUS_TEMPLATE) {
             if (!$fullItem['interfaceid']) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No interface found.'));
             } elseif (!isset($interfaces[$fullItem['interfaceid']]) || bccomp($interfaces[$fullItem['interfaceid']]['hostid'], $fullItem['hostid']) != 0) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Item uses host interface from non-parent host.'));
             } elseif ($itemInterfaceType !== INTERFACE_TYPE_ANY && $interfaces[$fullItem['interfaceid']]['type'] != $itemInterfaceType) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Item uses incorrect interface type.'));
             }
         } else {
             $item['interfaceid'] = 0;
         }
         // item key
         if ($fullItem['type'] == ITEM_TYPE_DB_MONITOR) {
             if (!isset($fullItem['flags']) || $fullItem['flags'] != ZBX_FLAG_DISCOVERY_RULE) {
                 if (strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_DB_MONITOR) == 0) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('Check the key, please. Default example was passed.'));
                 }
             } elseif ($fullItem['flags'] == ZBX_FLAG_DISCOVERY_RULE) {
                 if (strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_DB_MONITOR_DISCOVERY) == 0) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('Check the key, please. Default example was passed.'));
                 }
             }
         } elseif ($fullItem['type'] == ITEM_TYPE_SSH && strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_SSH) == 0 || $fullItem['type'] == ITEM_TYPE_TELNET && strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_TELNET) == 0 || $fullItem['type'] == ITEM_TYPE_JMX && strcmp($fullItem['key_'], ZBX_DEFAULT_KEY_JMX) == 0) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Check the key, please. Default example was passed.'));
         }
         // key
         if ($item_key_parser->parse($fullItem['key_']) != CParser::PARSE_SUCCESS) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _params($this->getErrorMsg(self::ERROR_INVALID_KEY), [$fullItem['key_'], $fullItem['name'], $host['name'], $item_key_parser->getError()]));
         }
         // parameters
         if ($fullItem['type'] == ITEM_TYPE_AGGREGATE) {
             $params_num = $item_key_parser->getParamsNum();
             if (!str_in_array($item_key_parser->getKey(), ['grpmax', 'grpmin', 'grpsum', 'grpavg']) || $params_num > 4 || $params_num < 3 || $params_num == 3 && $item_key_parser->getParam(2) !== 'last' || !str_in_array($item_key_parser->getParam(2), ['last', 'min', 'max', 'avg', 'sum', 'count'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Key "%1$s" does not match <grpmax|grpmin|grpsum|grpavg>["Host group(s)", "Item key",' . ' "<last|min|max|avg|sum|count>", "parameter"].', $item_key_parser->getKey()));
             }
         }
         // type of information
         if ($fullItem['type'] == ITEM_TYPE_AGGREGATE && $fullItem['value_type'] != ITEM_VALUE_TYPE_UINT64 && $fullItem['value_type'] != ITEM_VALUE_TYPE_FLOAT) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Type of information must be "Numeric (unsigned)" or "Numeric (float)" for aggregate items.'));
         }
         // update interval
         if ($fullItem['type'] != ITEM_TYPE_TRAPPER && $fullItem['type'] != ITEM_TYPE_SNMPTRAP) {
             // delay must be between 0 and 86400, if delay is 0, delay_flex interval must be set.
             if ($fullItem['delay'] < 0 || $fullItem['delay'] > SEC_PER_DAY || $fullItem['delay'] == 0 && $fullItem['delay_flex'] === '') {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Item will not be refreshed. Please enter a correct update interval.'));
             }
             // Don't parse empty strings, they will not be valid.
             if ($fullItem['delay_flex'] === '') {
                 continue;
             }
             // Validate item delay_flex string. First check syntax with parser, then validate time ranges.
             $item_delay_flex_parser = new CItemDelayFlexParser($fullItem['delay_flex']);
             if ($item_delay_flex_parser->isValid()) {
                 $delay_flex_validator = new CItemDelayFlexValidator();
                 if ($delay_flex_validator->validate($item_delay_flex_parser->getIntervals())) {
                     // Some valid intervals exist at this point.
                     $flexible_intervals = $item_delay_flex_parser->getFlexibleIntervals();
                     // If there are no flexible intervals, skip the next check calculation.
                     if (!$flexible_intervals) {
                         continue;
                     }
                     $nextCheck = calculateItemNextCheck(0, $fullItem['delay'], $item_delay_flex_parser->getFlexibleIntervals($flexible_intervals), time());
                     if ($nextCheck == ZBX_JAN_2038) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _('Item will not be refreshed. Please enter a correct update interval.'));
                     }
                 } else {
                     self::exception(ZBX_API_ERROR_PARAMETERS, $delay_flex_validator->getError());
                 }
             } else {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Invalid interval "%1$s": %2$s.', $fullItem['delay_flex'], $item_delay_flex_parser->getError()));
             }
         }
         // ssh, telnet
         if ($fullItem['type'] == ITEM_TYPE_SSH || $fullItem['type'] == ITEM_TYPE_TELNET) {
             if (zbx_empty($fullItem['username'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No authentication user name specified.'));
             }
             if ($fullItem['type'] == ITEM_TYPE_SSH && $fullItem['authtype'] == ITEM_AUTHTYPE_PUBLICKEY) {
                 if (zbx_empty($fullItem['publickey'])) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No public key file specified.'));
                 }
                 if (zbx_empty($fullItem['privatekey'])) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No private key file specified.'));
                 }
             }
         }
         // snmp trap
         if ($fullItem['type'] == ITEM_TYPE_SNMPTRAP && $fullItem['key_'] !== 'snmptrap.fallback' && $item_key_parser->getKey() !== 'snmptrap') {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('SNMP trap key is invalid.'));
         }
         // snmp oid
         if (in_array($fullItem['type'], [ITEM_TYPE_SNMPV1, ITEM_TYPE_SNMPV2C, ITEM_TYPE_SNMPV3]) && zbx_empty($fullItem['snmp_oid'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('No SNMP OID specified.'));
         }
         // snmp community
         if (in_array($fullItem['type'], [ITEM_TYPE_SNMPV1, ITEM_TYPE_SNMPV2C]) && zbx_empty($fullItem['snmp_community'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('No SNMP community specified.'));
         }
         // snmp port
         if (isset($fullItem['port']) && !zbx_empty($fullItem['port']) && !validatePortNumberOrMacro($fullItem['port'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Item "%1$s:%2$s" has invalid port: "%3$s".', $fullItem['name'], $fullItem['key_'], $fullItem['port']));
         }
         if (isset($fullItem['snmpv3_securitylevel']) && $fullItem['snmpv3_securitylevel'] != ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV) {
             // snmpv3 authprotocol
             if (str_in_array($fullItem['snmpv3_securitylevel'], [ITEM_SNMPV3_SECURITYLEVEL_AUTHNOPRIV, ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV])) {
                 if (isset($fullItem['snmpv3_authprotocol']) && (zbx_empty($fullItem['snmpv3_authprotocol']) || !str_in_array($fullItem['snmpv3_authprotocol'], [ITEM_AUTHPROTOCOL_MD5, ITEM_AUTHPROTOCOL_SHA]))) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect authentication protocol for item "%1$s".', $fullItem['name']));
                 }
             }
             // snmpv3 privprotocol
             if ($fullItem['snmpv3_securitylevel'] == ITEM_SNMPV3_SECURITYLEVEL_AUTHPRIV) {
                 if (isset($fullItem['snmpv3_privprotocol']) && (zbx_empty($fullItem['snmpv3_privprotocol']) || !str_in_array($fullItem['snmpv3_privprotocol'], [ITEM_PRIVPROTOCOL_DES, ITEM_PRIVPROTOCOL_AES]))) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect privacy protocol for item "%1$s".', $fullItem['name']));
                 }
             }
         }
         if (isset($item['applications']) && $item['applications']) {
             /*
              * 'flags' is available for update and item prototypes.
              * Don't allow discovered or any other application types for item prototypes in 'applications' option.
              */
             if (array_key_exists('flags', $fullItem) && $fullItem['flags'] == ZBX_FLAG_DISCOVERY_PROTOTYPE) {
                 foreach ($host['applications'] as $num => $application) {
                     if ($application['flags'] != ZBX_FLAG_DISCOVERY_NORMAL) {
                         unset($host['applications'][$num]);
                     }
                 }
             }
             // check that the given applications belong to the item's host
             $dbApplicationIds = zbx_objectValues($host['applications'], 'applicationid');
             foreach ($item['applications'] as $appId) {
                 if (!in_array($appId, $dbApplicationIds)) {
                     $error = _s('Application with ID "%1$s" is not available on "%2$s".', $appId, $host['name']);
                     self::exception(ZBX_API_ERROR_PARAMETERS, $error);
                 }
             }
         }
         $this->checkSpecificFields($fullItem);
     }
     unset($item);
     $this->checkExistingItems($items);
 }
Пример #3
0
/**
 * Get data for item edit page.
 *
 * @param array	$item							item, item prototype or LLD rule to take the data from
 * @param bool $options['is_discovery_rule']
 *
 * @return array
 */
function getItemFormData(array $item = [], array $options = [])
{
    $data = ['form' => getRequest('form'), 'form_refresh' => getRequest('form_refresh'), 'is_discovery_rule' => !empty($options['is_discovery_rule']), 'parent_discoveryid' => getRequest('parent_discoveryid', !empty($options['is_discovery_rule']) ? getRequest('itemid') : null), 'itemid' => getRequest('itemid'), 'limited' => false, 'interfaceid' => getRequest('interfaceid', 0), 'name' => getRequest('name', ''), 'description' => getRequest('description', ''), 'key' => getRequest('key', ''), 'hostname' => getRequest('hostname'), 'delay' => getRequest('delay', ZBX_ITEM_DELAY_DEFAULT), 'history' => getRequest('history', 90), 'status' => getRequest('status', isset($_REQUEST['form_refresh']) ? 1 : 0), 'type' => getRequest('type', 0), 'snmp_community' => getRequest('snmp_community', 'public'), 'snmp_oid' => getRequest('snmp_oid', 'interfaces.ifTable.ifEntry.ifInOctets.1'), 'port' => getRequest('port', ''), 'value_type' => getRequest('value_type', ITEM_VALUE_TYPE_UINT64), 'data_type' => getRequest('data_type', ITEM_DATA_TYPE_DECIMAL), 'trapper_hosts' => getRequest('trapper_hosts', ''), 'units' => getRequest('units', ''), 'valuemapid' => getRequest('valuemapid', 0), 'params' => getRequest('params', ''), 'multiplier' => getRequest('multiplier', 0), 'delta' => getRequest('delta', 0), 'trends' => getRequest('trends', DAY_IN_YEAR), 'new_application' => getRequest('new_application', ''), 'applications' => getRequest('applications', []), 'delay_flex' => getRequest('delay_flex', []), 'snmpv3_contextname' => getRequest('snmpv3_contextname', ''), 'snmpv3_securityname' => getRequest('snmpv3_securityname', ''), 'snmpv3_securitylevel' => getRequest('snmpv3_securitylevel', 0), 'snmpv3_authprotocol' => getRequest('snmpv3_authprotocol', ITEM_AUTHPROTOCOL_MD5), 'snmpv3_authpassphrase' => getRequest('snmpv3_authpassphrase', ''), 'snmpv3_privprotocol' => getRequest('snmpv3_privprotocol', ITEM_PRIVPROTOCOL_DES), 'snmpv3_privpassphrase' => getRequest('snmpv3_privpassphrase', ''), 'ipmi_sensor' => getRequest('ipmi_sensor', ''), 'authtype' => getRequest('authtype', 0), 'username' => getRequest('username', ''), 'password' => getRequest('password', ''), 'publickey' => getRequest('publickey', ''), 'privatekey' => getRequest('privatekey', ''), 'formula' => getRequest('formula', 1), 'logtimefmt' => getRequest('logtimefmt', ''), 'add_groupid' => getRequest('add_groupid', getRequest('groupid', 0)), 'valuemaps' => null, 'possibleHostInventories' => null, 'alreadyPopulated' => null, 'initial_item_type' => null, 'templates' => []];
    // hostid
    if (!empty($data['parent_discoveryid'])) {
        $discoveryRule = API::DiscoveryRule()->get(['itemids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true]);
        $discoveryRule = reset($discoveryRule);
        $data['hostid'] = $discoveryRule['hostid'];
        $data['new_application_prototype'] = getRequest('new_application_prototype', '');
        $data['application_prototypes'] = getRequest('application_prototypes', array());
    } else {
        $data['hostid'] = getRequest('hostid', 0);
    }
    // types, http items only for internal processes
    $data['types'] = item_type2str();
    unset($data['types'][ITEM_TYPE_HTTPTEST]);
    if (!empty($options['is_discovery_rule'])) {
        unset($data['types'][ITEM_TYPE_AGGREGATE], $data['types'][ITEM_TYPE_CALCULATED], $data['types'][ITEM_TYPE_SNMPTRAP]);
    }
    // item
    if ($item) {
        $data['item'] = $item;
        $data['hostid'] = !empty($data['hostid']) ? $data['hostid'] : $data['item']['hostid'];
        $data['limited'] = $data['item']['templateid'] != 0;
        // get templates
        $itemid = $item['itemid'];
        do {
            $params = ['itemids' => $itemid, 'output' => ['itemid', 'templateid'], 'selectHosts' => ['name']];
            if ($data['is_discovery_rule']) {
                $item = API::DiscoveryRule()->get($params);
            } else {
                $params['selectDiscoveryRule'] = ['itemid'];
                $params['filter'] = ['flags' => null];
                $item = API::Item()->get($params);
            }
            $item = reset($item);
            if (!empty($item)) {
                $host = reset($item['hosts']);
                if (!empty($item['hosts'])) {
                    $host['name'] = CHtml::encode($host['name']);
                    if (bccomp($data['itemid'], $itemid) == 0) {
                    } elseif ($data['is_discovery_rule']) {
                        $data['templates'][] = new CLink($host['name'], 'host_discovery.php?form=update&itemid=' . $item['itemid']);
                        $data['templates'][] = SPACE . '&rArr;' . SPACE;
                    } elseif ($item['discoveryRule']) {
                        $data['templates'][] = new CLink($host['name'], 'disc_prototypes.php?form=update' . '&itemid=' . $item['itemid'] . '&parent_discoveryid=' . $item['discoveryRule']['itemid']);
                        $data['templates'][] = SPACE . '&rArr;' . SPACE;
                    } else {
                        $data['templates'][] = new CLink($host['name'], 'items.php?form=update&itemid=' . $item['itemid']);
                        $data['templates'][] = SPACE . '&rArr;' . SPACE;
                    }
                }
                $itemid = $item['templateid'];
            } else {
                break;
            }
        } while ($itemid != 0);
        $data['templates'] = array_reverse($data['templates']);
        array_shift($data['templates']);
    }
    // caption
    if (!empty($data['is_discovery_rule'])) {
        $data['caption'] = _('Discovery rule');
    } else {
        $data['caption'] = !empty($data['parent_discoveryid']) ? _('Item prototype') : _('Item');
    }
    // hostname
    if (empty($data['is_discovery_rule']) && empty($data['hostname'])) {
        if (!empty($data['hostid'])) {
            $hostInfo = API::Host()->get(['hostids' => $data['hostid'], 'output' => ['name'], 'templated_hosts' => true]);
            $hostInfo = reset($hostInfo);
            $data['hostname'] = $hostInfo['name'];
        } else {
            $data['hostname'] = _('not selected');
        }
    }
    // fill data from item
    if (!hasRequest('form_refresh') && ($item || $data['limited'])) {
        $data['name'] = $data['item']['name'];
        $data['description'] = $data['item']['description'];
        $data['key'] = $data['item']['key_'];
        $data['interfaceid'] = $data['item']['interfaceid'];
        $data['type'] = $data['item']['type'];
        $data['snmp_community'] = $data['item']['snmp_community'];
        $data['snmp_oid'] = $data['item']['snmp_oid'];
        $data['port'] = $data['item']['port'];
        $data['value_type'] = $data['item']['value_type'];
        $data['data_type'] = $data['item']['data_type'];
        $data['trapper_hosts'] = $data['item']['trapper_hosts'];
        $data['units'] = $data['item']['units'];
        $data['valuemapid'] = $data['item']['valuemapid'];
        $data['multiplier'] = $data['item']['multiplier'];
        $data['hostid'] = $data['item']['hostid'];
        $data['params'] = $data['item']['params'];
        $data['snmpv3_contextname'] = $data['item']['snmpv3_contextname'];
        $data['snmpv3_securityname'] = $data['item']['snmpv3_securityname'];
        $data['snmpv3_securitylevel'] = $data['item']['snmpv3_securitylevel'];
        $data['snmpv3_authprotocol'] = $data['item']['snmpv3_authprotocol'];
        $data['snmpv3_authpassphrase'] = $data['item']['snmpv3_authpassphrase'];
        $data['snmpv3_privprotocol'] = $data['item']['snmpv3_privprotocol'];
        $data['snmpv3_privpassphrase'] = $data['item']['snmpv3_privpassphrase'];
        $data['ipmi_sensor'] = $data['item']['ipmi_sensor'];
        $data['authtype'] = $data['item']['authtype'];
        $data['username'] = $data['item']['username'];
        $data['password'] = $data['item']['password'];
        $data['publickey'] = $data['item']['publickey'];
        $data['privatekey'] = $data['item']['privatekey'];
        $data['logtimefmt'] = $data['item']['logtimefmt'];
        $data['new_application'] = getRequest('new_application', '');
        if ($data['parent_discoveryid'] != 0) {
            $data['new_application_prototype'] = getRequest('new_application_prototype', '');
        }
        if (!$data['is_discovery_rule']) {
            $data['formula'] = $data['item']['formula'];
        }
        if (!$data['limited'] || !isset($_REQUEST['form_refresh'])) {
            $data['delay'] = $data['item']['delay'];
            if (($data['type'] == ITEM_TYPE_TRAPPER || $data['type'] == ITEM_TYPE_SNMPTRAP) && $data['delay'] == 0) {
                $data['delay'] = ZBX_ITEM_DELAY_DEFAULT;
            }
            $data['history'] = $data['item']['history'];
            $data['status'] = $data['item']['status'];
            $data['delta'] = $data['item']['delta'];
            $data['trends'] = $data['item']['trends'];
            $parser = new CItemDelayFlexParser($data['item']['delay_flex']);
            if ($parser->isValid()) {
                foreach ($parser->getIntervals() as $interval) {
                    if ($interval['type'] == ITEM_DELAY_FLEX_TYPE_FLEXIBLE) {
                        $interval_parts = explode('/', $interval['interval']);
                        $data['delay_flex'][] = ['delay' => $interval_parts[0], 'period' => $interval_parts[1], 'type' => ITEM_DELAY_FLEX_TYPE_FLEXIBLE];
                    } else {
                        $data['delay_flex'][] = ['schedule' => $interval['interval'], 'type' => ITEM_DELAY_FLEX_TYPE_SCHEDULING];
                    }
                }
            }
            $data['applications'] = array_unique(zbx_array_merge($data['applications'], get_applications_by_itemid($data['itemid'])));
            if ($data['parent_discoveryid'] != 0) {
                /*
                 * Get a list of application prototypes assigned to item prototype. Don't select distinct names,
                 * since database can be accidentally created case insensitive.
                 */
                $application_prototypes = DBfetchArray(DBselect('SELECT ap.name' . ' FROM application_prototype ap,item_application_prototype iap' . ' WHERE ap.application_prototypeid=iap.application_prototypeid' . ' AND ap.itemid=' . zbx_dbstr($data['parent_discoveryid']) . ' AND iap.itemid=' . zbx_dbstr($data['itemid'])));
                // Merge form submitted data with data existing in DB to find diff and correctly display ListBox.
                $data['application_prototypes'] = array_unique(zbx_array_merge($data['application_prototypes'], zbx_objectValues($application_prototypes, 'name')));
            }
        }
    }
    if (!$data['delay_flex']) {
        $data['delay_flex'][] = ['delay' => '', 'period' => '', 'type' => ITEM_DELAY_FLEX_TYPE_FLEXIBLE];
    }
    // applications
    if (count($data['applications']) == 0) {
        array_push($data['applications'], 0);
    }
    $data['db_applications'] = DBfetchArray(DBselect('SELECT DISTINCT a.applicationid,a.name' . ' FROM applications a' . ' WHERE a.hostid=' . zbx_dbstr($data['hostid']) . ($data['parent_discoveryid'] ? ' AND a.flags=' . ZBX_FLAG_DISCOVERY_NORMAL : '')));
    order_result($data['db_applications'], 'name');
    if ($data['parent_discoveryid'] != 0) {
        // Make the application prototype list no appearing empty, but filling it with "-None-" as first element.
        if (count($data['application_prototypes']) == 0) {
            $data['application_prototypes'][] = 0;
        }
        // Get a list of application prototypes by discovery rule.
        $data['db_application_prototypes'] = DBfetchArray(DBselect('SELECT ap.application_prototypeid,ap.name' . ' FROM application_prototype ap' . ' WHERE ap.itemid=' . zbx_dbstr($data['parent_discoveryid'])));
        order_result($data['db_application_prototypes'], 'name');
    }
    // interfaces
    $data['interfaces'] = API::HostInterface()->get(['hostids' => $data['hostid'], 'output' => API_OUTPUT_EXTEND]);
    // valuemapid
    if ($data['limited']) {
        if ($data['valuemapid'] != 0) {
            $valuemaps = API::ValueMap()->get(['output' => ['name'], 'valuemapids' => [$data['valuemapid']]]);
            if ($valuemaps) {
                $data['valuemaps'] = $valuemaps[0]['name'];
            }
        }
    } else {
        $data['valuemaps'] = API::ValueMap()->get(['output' => ['valemapid', 'name']]);
        CArrayHelper::sort($data['valuemaps'], ['name']);
    }
    // possible host inventories
    if (empty($data['parent_discoveryid'])) {
        $data['possibleHostInventories'] = getHostInventories();
        // get already populated fields by other items
        $data['alreadyPopulated'] = API::item()->get(['output' => ['inventory_link'], 'filter' => ['hostid' => $data['hostid']], 'nopermissions' => true]);
        $data['alreadyPopulated'] = zbx_toHash($data['alreadyPopulated'], 'inventory_link');
    }
    // unset snmpv3 fields
    if ($data['type'] != ITEM_TYPE_SNMPV3) {
        $data['snmpv3_contextname'] = '';
        $data['snmpv3_securityname'] = '';
        $data['snmpv3_securitylevel'] = ITEM_SNMPV3_SECURITYLEVEL_NOAUTHNOPRIV;
        $data['snmpv3_authprotocol'] = ITEM_AUTHPROTOCOL_MD5;
        $data['snmpv3_authpassphrase'] = '';
        $data['snmpv3_privprotocol'] = ITEM_PRIVPROTOCOL_DES;
        $data['snmpv3_privpassphrase'] = '';
    }
    // unset ssh auth fields
    if ($data['type'] != ITEM_TYPE_SSH) {
        $data['authtype'] = ITEM_AUTHTYPE_PASSWORD;
        $data['publickey'] = '';
        $data['privatekey'] = '';
    }
    return $data;
}