/**
  * Check if trigger prototype has a correct trigger expression and has at least one item prototype and belongs to
  * one discovery rule, does not belong to a host and a template simultaneously and has permissions to all hosts and
  * templates in the expression.
  *
  * @param array  $triggerPrototype
  * @param string $triggerPrototype['description']
  * @param string $triggerPrototype['expression']
  *
  * @throws APIException
  *
  * @return void
  */
 protected function checkExpression(array $triggerPrototype)
 {
     $triggerExpression = new CTriggerExpression();
     if (!$triggerExpression->parse($triggerPrototype['expression'])) {
         self::exception(ZBX_API_ERROR_PARAMETERS, $triggerExpression->error);
     }
     $lld_rules = [];
     if ($triggerExpression->expressions) {
         $expressions = [];
         $hosts = [];
         $has_host = false;
         $has_template = false;
         foreach ($triggerExpression->expressions as $expression) {
             if (!array_key_exists($expression['host'], $expressions)) {
                 $expressions[$expression['host']] = ['hostid' => null, 'items' => []];
             }
             $expressions[$expression['host']]['items'][$expression['item']] = true;
             $hosts[$expression['host']] = true;
         }
         $db_hosts = API::Host()->get(['output' => ['hostid', 'host'], 'filter' => ['host' => array_keys($hosts)]]);
         foreach ($db_hosts as $db_host) {
             $expressions[$db_host['host']]['hostid'] = $db_host['hostid'];
             $has_host = true;
             unset($hosts[$db_host['host']]);
         }
         if ($hosts) {
             $db_templates = API::Template()->get(['output' => ['templateid', 'host'], 'filter' => ['host' => array_keys($hosts)]]);
             foreach ($db_templates as $db_template) {
                 $expressions[$db_template['host']]['hostid'] = $db_template['templateid'];
                 $has_template = true;
             }
         }
         if ($has_host && $has_template) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect trigger prototype expression.' . ' Trigger prototype expression elements should not belong to a template and a host simultaneously.'));
         }
         foreach ($expressions as $host => $expression) {
             if ($expression['hostid'] === null) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect trigger prototype expression.' . ' Host "%1$s" does not exist or you have no access to this host.', $host));
             }
             $db_item_prototypes = API::ItemPrototype()->get(['output' => [], 'selectDiscoveryRule' => ['itemid'], 'hostids' => [$expression['hostid']], 'filter' => ['key_' => array_keys($expression['items'])], 'nopermissions' => true]);
             foreach ($db_item_prototypes as $db_item_prototype) {
                 $lld_rules[$db_item_prototype['discoveryRule']['itemid']] = true;
             }
         }
         if (count($lld_rules) > 1) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger prototype "%1$s" contains item prototypes from multiple discovery rules.', $triggerPrototype['description']));
         }
     }
     if (!$lld_rules) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Trigger prototype "%1$s" must contain at least one item prototype.', $triggerPrototype['description']));
     }
 }
 // discovery rules
 $hostDiscoveryRules = API::DiscoveryRule()->get(array('inherited' => false, 'hostids' => $templateid, 'output' => API_OUTPUT_EXTEND));
 if ($hostDiscoveryRules) {
     $hostDiscoveryRules = CMacrosResolverHelper::resolveItemNames($hostDiscoveryRules);
     $discoveryRuleList = array();
     foreach ($hostDiscoveryRules as $discoveryRule) {
         $discoveryRuleList[$discoveryRule['itemid']] = $discoveryRule['name_expanded'];
     }
     order_result($discoveryRuleList);
     $hostDiscoveryRuleids = array_keys($discoveryRuleList);
     $listBox = new CListBox('discoveryRules', null, 8);
     $listBox->setAttribute('disabled', 'disabled');
     $listBox->addItems($discoveryRuleList);
     $templateList->addRow(_('Discovery rules'), $listBox);
     // item prototypes
     $hostItemPrototypes = API::ItemPrototype()->get(array('hostids' => $templateid, 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND));
     if ($hostItemPrototypes) {
         $hostItemPrototypes = CMacrosResolverHelper::resolveItemNames($hostItemPrototypes);
         $prototypeList = array();
         foreach ($hostItemPrototypes as $itemPrototype) {
             $prototypeList[$itemPrototype['itemid']] = $itemPrototype['name_expanded'];
         }
         order_result($prototypeList);
         $listBox = new CListBox('itemsPrototypes', null, 8);
         $listBox->setAttribute('disabled', 'disabled');
         $listBox->addItems($prototypeList);
         $templateList->addRow(_('Item prototypes'), $listBox);
     }
     // Trigger prototypes
     $hostTriggerPrototypes = API::TriggerPrototype()->get(array('hostids' => $templateid, 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND));
     if (!empty($hostTriggerPrototypes)) {
 /**
  * Get discovery rules related objects from database.
  *
  * @param array $items
  *
  * @return array
  */
 protected function prepareDiscoveryRules(array $items)
 {
     foreach ($items as &$item) {
         $item['itemPrototypes'] = array();
         $item['graphPrototypes'] = array();
         $item['triggerPrototypes'] = array();
     }
     unset($item);
     // gather item prototypes
     $prototypes = API::ItemPrototype()->get(array('discoveryids' => zbx_objectValues($items, 'itemid'), 'output' => array('hostid', 'multiplier', 'type', 'snmp_community', 'snmp_oid', 'name', 'key_', 'delay', 'history', 'trends', 'status', 'value_type', 'trapper_hosts', 'units', 'delta', 'snmpv3_securityname', 'snmpv3_securitylevel', 'snmpv3_authpassphrase', 'snmpv3_privpassphrase', 'formula', 'valuemapid', 'delay_flex', 'params', 'ipmi_sensor', 'data_type', 'authtype', 'username', 'password', 'publickey', 'privatekey', 'interfaceid', 'port', 'description', 'inventory_link', 'flags'), 'selectApplications' => API_OUTPUT_EXTEND, 'inherited' => false, 'preservekeys' => true));
     // gather value maps
     $valueMapIds = zbx_objectValues($prototypes, 'valuemapid');
     $DbValueMaps = DBselect('SELECT vm.valuemapid, vm.name FROM valuemaps vm WHERE ' . dbConditionInt('vm.valuemapid', $valueMapIds));
     $valueMaps = array();
     while ($valueMap = DBfetch($DbValueMaps)) {
         $valueMaps[$valueMap['valuemapid']] = $valueMap['name'];
     }
     foreach ($prototypes as $prototype) {
         $prototype['valuemap'] = array();
         if ($prototype['valuemapid']) {
             $prototype['valuemap']['name'] = $valueMaps[$prototype['valuemapid']];
         }
         $items[$prototype['parent_itemid']]['itemPrototypes'][] = $prototype;
     }
     // gather graph prototypes
     $graphs = API::GraphPrototype()->get(array('discoveryids' => zbx_objectValues($items, 'itemid'), 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND, 'inherited' => false, 'preservekeys' => true));
     $graphs = $this->prepareGraphs($graphs);
     foreach ($graphs as $graph) {
         $items[$graph['discoveryRule']['itemid']]['graphPrototypes'][] = $graph;
     }
     // gather trigger prototypes
     $triggers = API::TriggerPrototype()->get(array('discoveryids' => zbx_objectValues($items, 'itemid'), 'output' => API_OUTPUT_EXTEND, 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectItems' => array('flags', 'type'), 'inherited' => false, 'preservekeys' => true, 'expandData' => true));
     foreach ($triggers as $trigger) {
         foreach ($trigger['items'] as $item) {
             if ($item['flags'] == ZBX_FLAG_DISCOVERY_CREATED || $item['type'] == ITEM_TYPE_HTTPTEST) {
                 continue 2;
             }
         }
         $trigger['expression'] = explode_exp($trigger['expression']);
         $items[$trigger['discoveryRule']['itemid']]['triggerPrototypes'][] = $trigger;
     }
     return $items;
 }
 /**
  * Get discovery rules related objects from database.
  *
  * @param array $items
  *
  * @return array
  */
 protected function prepareDiscoveryRules(array $items)
 {
     foreach ($items as &$item) {
         $item['itemPrototypes'] = array();
         $item['graphPrototypes'] = array();
         $item['triggerPrototypes'] = array();
         $item['hostPrototypes'] = array();
     }
     unset($item);
     // gather item prototypes
     $prototypes = API::ItemPrototype()->get(array('discoveryids' => zbx_objectValues($items, 'itemid'), 'output' => $this->dataFields['discoveryrule'], 'selectApplications' => API_OUTPUT_EXTEND, 'selectDiscoveryRule' => array('itemid'), 'inherited' => false, 'preservekeys' => true));
     // gather value maps
     $valueMapIds = zbx_objectValues($prototypes, 'valuemapid');
     $DbValueMaps = DBselect('SELECT vm.valuemapid, vm.name FROM valuemaps vm WHERE ' . dbConditionInt('vm.valuemapid', $valueMapIds));
     $valueMaps = array();
     while ($valueMap = DBfetch($DbValueMaps)) {
         $valueMaps[$valueMap['valuemapid']] = $valueMap['name'];
     }
     foreach ($prototypes as $prototype) {
         $prototype['valuemap'] = array();
         if ($prototype['valuemapid']) {
             $prototype['valuemap']['name'] = $valueMaps[$prototype['valuemapid']];
         }
         $items[$prototype['discoveryRule']['itemid']]['itemPrototypes'][] = $prototype;
     }
     // gather graph prototypes
     $graphs = API::GraphPrototype()->get(array('discoveryids' => zbx_objectValues($items, 'itemid'), 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND, 'inherited' => false, 'preservekeys' => true));
     $graphs = $this->prepareGraphs($graphs);
     foreach ($graphs as $graph) {
         $items[$graph['discoveryRule']['itemid']]['graphPrototypes'][] = $graph;
     }
     // gather trigger prototypes
     $triggers = API::TriggerPrototype()->get(array('discoveryids' => zbx_objectValues($items, 'itemid'), 'output' => API_OUTPUT_EXTEND, 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectItems' => array('flags', 'type'), 'inherited' => false, 'preservekeys' => true, 'expandData' => true));
     foreach ($triggers as $trigger) {
         foreach ($trigger['items'] as $item) {
             if ($item['flags'] == ZBX_FLAG_DISCOVERY_CREATED || $item['type'] == ITEM_TYPE_HTTPTEST) {
                 continue 2;
             }
         }
         $trigger['expression'] = explode_exp($trigger['expression']);
         $items[$trigger['discoveryRule']['itemid']]['triggerPrototypes'][] = $trigger;
     }
     // gather host prototypes
     $hostPrototypes = API::HostPrototype()->get(array('discoveryids' => zbx_objectValues($items, 'itemid'), 'output' => API_OUTPUT_EXTEND, 'selectGroupLinks' => API_OUTPUT_EXTEND, 'selectGroupPrototypes' => API_OUTPUT_EXTEND, 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectTemplates' => API_OUTPUT_EXTEND, 'inherited' => false, 'preservekeys' => true));
     // replace group prototype group IDs with references
     $groupIds = array();
     foreach ($hostPrototypes as $hostPrototype) {
         foreach ($hostPrototype['groupLinks'] as $groupLink) {
             $groupIds[$groupLink['groupid']] = $groupLink['groupid'];
         }
     }
     $groups = $this->getGroupsReferences($groupIds);
     // export the groups used in group prototypes
     $this->data['groups'] += $groups;
     foreach ($hostPrototypes as $hostPrototype) {
         foreach ($hostPrototype['groupLinks'] as &$groupLink) {
             $groupLink['groupid'] = $groups[$groupLink['groupid']];
         }
         unset($groupLink);
         $items[$hostPrototype['discoveryRule']['itemid']]['hostPrototypes'][] = $hostPrototype;
     }
     return $items;
 }
 /**
  * Resolves and retrieves effective item prototype used in this screen item.
  *
  * @return array|bool
  */
 protected function getItemPrototype()
 {
     if ($this->itemPrototype === null) {
         $defaultOptions = array('output' => array('itemid', 'name'), 'selectHosts' => array('name'), 'selectDiscoveryRule' => array('hostid'));
         $options = array();
         /*
          * If screen item is dynamic or is templated screen, real item prototype is looked up by "key"
          * used as resource ID for this screen item and by current host.
          */
         if (($this->screenitem['dynamic'] == SCREEN_DYNAMIC_ITEM || $this->isTemplatedScreen) && $this->hostid) {
             $currentItemPrototype = API::ItemPrototype()->get(array('output' => array('key_'), 'itemids' => array($this->screenitem['resourceid'])));
             $currentItemPrototype = reset($currentItemPrototype);
             $options['hostids'] = array($this->hostid);
             $options['filter'] = array('key_' => $currentItemPrototype['key_']);
         } else {
             $options['itemids'] = array($this->screenitem['resourceid']);
         }
         $options = zbx_array_merge($defaultOptions, $options);
         $selectedItemPrototype = API::ItemPrototype()->get($options);
         $this->itemPrototype = reset($selectedItemPrototype);
     }
     return $this->itemPrototype;
 }
示例#6
0
        $itemPrototype = reset($itemPrototype);
    }
    $data = getItemFormData($itemPrototype);
    $data['config'] = select_config();
    // render view
    $itemView = new CView('configuration.item.prototype.edit', $data);
    $itemView->render();
    $itemView->show();
} else {
    $sortField = getRequest('sort', CProfile::get('web.' . $page['file'] . '.sort', 'name'));
    $sortOrder = getRequest('sortorder', CProfile::get('web.' . $page['file'] . '.sortorder', ZBX_SORT_UP));
    CProfile::update('web.' . $page['file'] . '.sort', $sortField, PROFILE_TYPE_STR);
    CProfile::update('web.' . $page['file'] . '.sortorder', $sortOrder, PROFILE_TYPE_STR);
    $config = select_config();
    $data = ['form' => getRequest('form'), 'parent_discoveryid' => getRequest('parent_discoveryid'), 'hostid' => $discoveryRule['hostid'], 'sort' => $sortField, 'sortorder' => $sortOrder];
    $data['items'] = API::ItemPrototype()->get(['discoveryids' => $data['parent_discoveryid'], 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'selectApplications' => API_OUTPUT_EXTEND, 'sortfield' => $sortField, 'limit' => $config['search_limit'] + 1]);
    foreach ($data['items'] as &$item) {
        if ($item['value_type'] == ITEM_VALUE_TYPE_STR || $item['value_type'] == ITEM_VALUE_TYPE_LOG || $item['value_type'] == ITEM_VALUE_TYPE_TEXT) {
            $item['trends'] = '';
        }
        if ($item['type'] == ITEM_TYPE_TRAPPER || $item['type'] == ITEM_TYPE_SNMPTRAP) {
            $item['delay'] = '';
        }
    }
    unset($item);
    $data['items'] = CMacrosResolverHelper::resolveItemNames($data['items']);
    order_result($data['items'], $sortField, $sortOrder);
    $url = (new CUrl('disc_prototypes.php'))->setArgument('parent_discoveryid', $data['parent_discoveryid']);
    $data['paging'] = getPagingLine($data['items'], $sortOrder, $url);
    // render view
    $itemView = new CView('configuration.item.prototype.list', $data);
 /**
  * Get discovery rules related objects from database.
  *
  * @param array $items
  *
  * @return array
  */
 protected function prepareDiscoveryRules(array $items)
 {
     foreach ($items as &$item) {
         $item['itemPrototypes'] = [];
         $item['graphPrototypes'] = [];
         $item['triggerPrototypes'] = [];
         $item['hostPrototypes'] = [];
         // unset unnecessary condition fields
         foreach ($item['filter']['conditions'] as &$condition) {
             unset($condition['item_conditionid'], $condition['itemid']);
         }
         unset($condition);
     }
     unset($item);
     // gather item prototypes
     $prototypes = API::ItemPrototype()->get(['output' => $this->dataFields['item_prototype'], 'selectApplications' => ['name'], 'selectApplicationPrototypes' => ['name'], 'selectDiscoveryRule' => ['itemid'], 'discoveryids' => zbx_objectValues($items, 'itemid'), 'inherited' => false, 'preservekeys' => true]);
     $valuemapids = [];
     foreach ($prototypes as $prototype) {
         $valuemapids[$prototype['valuemapid']] = true;
     }
     // Value map IDs that are zeroes, should be skipped.
     unset($valuemapids[0]);
     if ($this->data['valueMaps']) {
         /*
          * If there is an option "valueMaps", some value maps may already been selected. Copy the result and remove
          * value map IDs that should not be selected again.
          */
         foreach ($this->data['valueMaps'] as $valuemapid => $valuemap) {
             if (array_key_exists($valuemapid, $valuemapids)) {
                 unset($valuemapids[$valuemapid]);
             }
         }
     }
     if ($valuemapids) {
         $this->data['valueMaps'] += API::ValueMap()->get(['output' => ['valuemapid', 'name'], 'selectMappings' => ['value', 'newvalue'], 'valuemapids' => array_keys($valuemapids), 'preservekeys' => true]);
     }
     foreach ($prototypes as $prototype) {
         $prototype['valuemap'] = [];
         if ($prototype['valuemapid'] != 0) {
             $prototype['valuemap']['name'] = $this->data['valueMaps'][$prototype['valuemapid']]['name'];
         }
         $items[$prototype['discoveryRule']['itemid']]['itemPrototypes'][] = $prototype;
     }
     // gather graph prototypes
     $graphs = API::GraphPrototype()->get(['discoveryids' => zbx_objectValues($items, 'itemid'), 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND, 'inherited' => false, 'preservekeys' => true]);
     $graphs = $this->prepareGraphs($graphs);
     foreach ($graphs as $graph) {
         $items[$graph['discoveryRule']['itemid']]['graphPrototypes'][] = $graph;
     }
     // gather trigger prototypes
     $triggers = API::TriggerPrototype()->get(['discoveryids' => zbx_objectValues($items, 'itemid'), 'output' => ['expression', 'description', 'url', 'status', 'priority', 'comments', 'type'], 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectDependencies' => ['description', 'expression'], 'selectItems' => ['itemid', 'flags', 'type'], 'inherited' => false, 'preservekeys' => true]);
     $triggers = $this->prepareTriggers($triggers);
     foreach ($triggers as $trigger) {
         $items[$trigger['discoveryRule']['itemid']]['triggerPrototypes'][] = $trigger;
     }
     // gather host prototypes
     $hostPrototypes = API::HostPrototype()->get(['discoveryids' => zbx_objectValues($items, 'itemid'), 'output' => API_OUTPUT_EXTEND, 'selectGroupLinks' => API_OUTPUT_EXTEND, 'selectGroupPrototypes' => API_OUTPUT_EXTEND, 'selectDiscoveryRule' => API_OUTPUT_EXTEND, 'selectTemplates' => API_OUTPUT_EXTEND, 'inherited' => false, 'preservekeys' => true]);
     // replace group prototype group IDs with references
     $groupIds = [];
     foreach ($hostPrototypes as $hostPrototype) {
         foreach ($hostPrototype['groupLinks'] as $groupLink) {
             $groupIds[$groupLink['groupid']] = true;
         }
     }
     $groups = $this->getGroupsReferences(array_keys($groupIds));
     // export the groups used in group prototypes
     $this->data['groups'] += $groups;
     foreach ($hostPrototypes as $hostPrototype) {
         foreach ($hostPrototype['groupLinks'] as &$groupLink) {
             $groupLink['groupid'] = $groups[$groupLink['groupid']];
         }
         unset($groupLink);
         $items[$hostPrototype['discoveryRule']['itemid']]['hostPrototypes'][] = $hostPrototype;
     }
     return $items;
 }
 $hostDiscoveryRuleids = array();
 $hostDiscoveryRules = API::DiscoveryRule()->get(array('inherited' => false, 'hostids' => $_REQUEST['hostid'], 'output' => array('itemid', 'key_', 'name')));
 if (!empty($hostDiscoveryRules)) {
     $discoveryRuleList = array();
     foreach ($hostDiscoveryRules as $discoveryRule) {
         $discoveryRuleList[$discoveryRule['itemid']] = itemName($discoveryRule);
     }
     order_result($discoveryRuleList);
     $hostDiscoveryRuleids = array_keys($discoveryRuleList);
     $listBox = new CListBox('discoveryRules', null, 8);
     $listBox->setAttribute('disabled', 'disabled');
     $listBox->addItems($discoveryRuleList);
     $hostList->addRow(_('Discovery rules'), $listBox);
 }
 // item prototypes
 $hostItemPrototypes = API::ItemPrototype()->get(array('hostids' => $_REQUEST['hostid'], 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => array('itemid', 'key_', 'name')));
 if (!empty($hostItemPrototypes)) {
     $prototypeList = array();
     foreach ($hostItemPrototypes as $itemPrototype) {
         $prototypeList[$itemPrototype['itemid']] = itemName($itemPrototype);
     }
     order_result($prototypeList);
     $listBox = new CListBox('itemsPrototypes', null, 8);
     $listBox->setAttribute('disabled', 'disabled');
     $listBox->addItems($prototypeList);
     $hostList->addRow(_('Item prototypes'), $listBox);
 }
 // Trigger prototypes
 $hostTriggerPrototypes = API::TriggerPrototype()->get(array('hostids' => $_REQUEST['hostid'], 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => array('triggerid', 'description'), 'selectItems' => array('type')));
 if (!empty($hostTriggerPrototypes)) {
     $prototypeList = array();
示例#9
0
 /**
  * Validates screen items.
  *
  * If the $dbScreenItems parameter is given, the screen items will be matched
  * against the ones given in $dbScreenItems. If a screen item is not present in
  * $dbScreenItems, a ZBX_API_ERROR_PERMISSIONS exception will be thrown.
  *
  * @throws APIException if a validation error occurred.
  *
  * @param array $screenItems
  * @param array $dbScreenItems
  */
 protected function checkInput(array $screenItems, array $dbScreenItems = array())
 {
     $hostGroupsIds = array();
     $hostIds = array();
     $graphIds = array();
     $itemIds = array();
     $mapIds = array();
     $screenIds = array();
     $itemPrototypeIds = array();
     $graphPrototypeIds = array();
     $screenItems = $this->extendFromObjects($screenItems, $dbScreenItems, array('resourcetype'));
     $validStyles = array(SCREEN_RESOURCE_CLOCK => array(TIME_TYPE_LOCAL, TIME_TYPE_SERVER, TIME_TYPE_HOST), SCREEN_RESOURCE_DATA_OVERVIEW => array(STYLE_TOP, STYLE_LEFT), SCREEN_RESOURCE_TRIGGERS_OVERVIEW => array(STYLE_TOP, STYLE_LEFT), SCREEN_RESOURCE_HOSTS_INFO => array(STYLE_VERTICAL, STYLE_HORIZONTAL), SCREEN_RESOURCE_TRIGGERS_INFO => array(STYLE_VERTICAL, STYLE_HORIZONTAL));
     foreach ($screenItems as $screenItem) {
         // check permissions
         if (isset($screenItem['screenitemid']) && !isset($dbScreenItems[$screenItem['screenitemid']])) {
             self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!'));
         }
         if (!$this->isValidResourceType($screenItem['resourcetype'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect resource type provided for screen item.'));
         }
         if (!isset($screenItem['resourceid'])) {
             $screenItem['resourceid'] = null;
         }
         // check resource id
         switch ($screenItem['resourcetype']) {
             case SCREEN_RESOURCE_HOSTS_INFO:
             case SCREEN_RESOURCE_TRIGGERS_INFO:
             case SCREEN_RESOURCE_TRIGGERS_OVERVIEW:
             case SCREEN_RESOURCE_HOSTGROUP_TRIGGERS:
             case SCREEN_RESOURCE_DATA_OVERVIEW:
                 $overviewResources = array(SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW);
                 if (in_array($screenItem['resourcetype'], $overviewResources)) {
                     if (!$screenItem['resourceid']) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _('No host group ID provided for screen element.'));
                     }
                 }
                 if ($screenItem['resourceid']) {
                     $hostGroupsIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 }
                 break;
             case SCREEN_RESOURCE_HOST_TRIGGERS:
                 if ($screenItem['resourceid']) {
                     $hostIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 }
                 break;
             case SCREEN_RESOURCE_GRAPH:
                 if (!$screenItem['resourceid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No graph ID provided for screen element.'));
                 }
                 $graphIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 break;
             case SCREEN_RESOURCE_LLD_GRAPH:
                 if (!$screenItem['resourceid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No graph prototype ID provided for screen element.'));
                 }
                 $graphPrototypeIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 break;
             case SCREEN_RESOURCE_LLD_SIMPLE_GRAPH:
                 if (!$screenItem['resourceid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No item prototype ID provided for screen element.'));
                 }
                 $itemPrototypeIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 break;
             case SCREEN_RESOURCE_SIMPLE_GRAPH:
             case SCREEN_RESOURCE_PLAIN_TEXT:
                 if (!$screenItem['resourceid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No item ID provided for screen element.'));
                 }
                 $itemIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 break;
             case SCREEN_RESOURCE_CLOCK:
                 if (isset($screenItem['style'])) {
                     if ($screenItem['style'] == TIME_TYPE_HOST) {
                         if (!$screenItem['resourceid']) {
                             self::exception(ZBX_API_ERROR_PARAMETERS, _('No item ID provided for screen element.'));
                         }
                         $itemIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                     } elseif ($screenItem['resourceid']) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set resource ID for screen element.'));
                     }
                 }
                 break;
             case SCREEN_RESOURCE_MAP:
                 if (!$screenItem['resourceid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No map ID provided for screen element.'));
                 }
                 $mapIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 break;
             case SCREEN_RESOURCE_SCREEN:
                 if (!$screenItem['resourceid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('No screen ID provided for screen element.'));
                 }
                 $screenIds[$screenItem['resourceid']] = $screenItem['resourceid'];
                 break;
             case SCREEN_RESOURCE_ACTIONS:
             case SCREEN_RESOURCE_SERVER_INFO:
             case SCREEN_RESOURCE_SYSTEM_STATUS:
             case SCREEN_RESOURCE_URL:
                 if ($screenItem['resourceid']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set resource ID for screen element.'));
                 }
                 break;
         }
         // check url
         if ($screenItem['resourcetype'] == SCREEN_RESOURCE_URL) {
             if (!isset($screenItem['url']) || zbx_empty($screenItem['url'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No URL provided for screen element.'));
             }
         }
         // check "Show lines"
         if (isset($screenItem['elements'])) {
             switch ($screenItem['resourcetype']) {
                 case SCREEN_RESOURCE_ACTIONS:
                 case SCREEN_RESOURCE_EVENTS:
                 case SCREEN_RESOURCE_HOSTGROUP_TRIGGERS:
                 case SCREEN_RESOURCE_HOST_TRIGGERS:
                 case SCREEN_RESOURCE_PLAIN_TEXT:
                     if ($screenItem['elements'] < 1 || $screenItem['elements'] > 100) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect value "%1$s" for "%2$s" field: must be between %3$s and %4$s.', $screenItem['elements'], 'elements', 1, 100));
                     }
                     break;
             }
         }
         // check 'max_columns' parameter for LLD screen resources:
         // is set and valid for create method, and is valid for update method, if set
         $dbScreenItem = isset($screenItem['screenitemid']) ? $dbScreenItems[$screenItem['screenitemid']] : null;
         $lldResources = array(SCREEN_RESOURCE_LLD_GRAPH, SCREEN_RESOURCE_LLD_SIMPLE_GRAPH);
         if (in_array($screenItem['resourcetype'], $lldResources)) {
             $set = isset($screenItem['max_columns']);
             $valid = $set && $this->isValidMaxColumns($screenItem['max_columns']);
             $error = $dbScreenItem ? $set && !$valid : !$set || !$valid;
             if ($error) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect max columns provided for screen element.'));
             }
         }
         if (isset($validStyles[$screenItem['resourcetype']]) && !in_array($screenItem['style'], $validStyles[$screenItem['resourcetype']])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect style provided for screen element.'));
         }
     }
     // check host groups
     if ($hostGroupsIds) {
         $dbHostGroups = API::HostGroup()->get(array('output' => array('groupid'), 'groupids' => $hostGroupsIds, 'editable' => true, 'preservekeys' => true));
         foreach ($hostGroupsIds as $hostGroupsId) {
             if (!isset($dbHostGroups[$hostGroupsId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect host group ID "%1$s" provided for screen element.', $hostGroupsId));
             }
         }
     }
     // check hosts
     if ($hostIds) {
         $dbHosts = API::Host()->get(array('output' => array('hostid'), 'hostids' => $hostIds, 'editable' => true, 'preservekeys' => true));
         foreach ($hostIds as $hostId) {
             if (!isset($dbHosts[$hostId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect host ID "%1$s" provided for screen element.', $hostId));
             }
         }
     }
     // check graphs
     if ($graphIds) {
         $dbGraphs = API::Graph()->get(array('output' => array('graphid'), 'graphids' => $graphIds, 'editable' => true, 'preservekeys' => true));
         foreach ($graphIds as $graphId) {
             if (!isset($dbGraphs[$graphId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect graph ID "%1$s" provided for screen element.', $graphId));
             }
         }
     }
     // check graph prototypes
     if ($graphPrototypeIds) {
         $dbGraphPrototypes = API::GraphPrototype()->get(array('output' => array('graphid'), 'graphids' => $graphPrototypeIds, 'editable' => true, 'preservekeys' => true));
         foreach ($graphPrototypeIds as $graphPrototypeId) {
             if (!isset($dbGraphPrototypes[$graphPrototypeId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect graph prototype ID "%1$s" provided for screen element.', $graphPrototypeId));
             }
         }
     }
     // check items
     if ($itemIds) {
         $dbItems = API::Item()->get(array('output' => array('itemid'), 'itemids' => $itemIds, 'editable' => true, 'preservekeys' => true, 'webitems' => true));
         foreach ($itemIds as $itemId) {
             if (!isset($dbItems[$itemId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect item ID "%1$s" provided for screen element.', $itemId));
             }
         }
     }
     // check item prototypes
     if ($itemPrototypeIds) {
         $dbItemPrototypes = API::ItemPrototype()->get(array('output' => array('itemid'), 'itemids' => $itemPrototypeIds, 'editable' => true, 'preservekeys' => true));
         foreach ($itemPrototypeIds as $itemPrototypeId) {
             if (!isset($dbItemPrototypes[$itemPrototypeId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect item prototype ID "%1$s" provided for screen element.', $itemPrototypeId));
             }
         }
     }
     // check maps
     if ($mapIds) {
         $dbMaps = API::Map()->get(array('output' => array('sysmapid'), 'sysmapids' => $mapIds, 'editable' => true, 'preservekeys' => true));
         foreach ($mapIds as $mapId) {
             if (!isset($dbMaps[$mapId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect map ID "%1$s" provided for screen element.', $mapId));
             }
         }
     }
     // check screens
     if ($screenIds) {
         $dbScreens = API::Screen()->get(array('output' => array('screenid'), 'screenids' => $screenIds, 'editable' => true, 'preservekeys' => true));
         if (count($dbScreens) < count($screenIds)) {
             $dbTemplateScreens = API::TemplateScreen()->get(array('output' => array('screenid'), 'screenids' => $screenIds, 'editable' => true, 'preservekeys' => true));
             if ($dbTemplateScreens) {
                 $dbScreens = zbx_array_merge($dbScreens, $dbTemplateScreens);
             }
         }
         foreach ($screenIds as $screenId) {
             if (!isset($dbScreens[$screenId])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _s('Incorrect screen ID "%1$s" provided for screen element.', $screenId));
             }
         }
     }
 }
        $id = $resourceId;
        $item = reset($items);
        $item['host'] = reset($item['hosts']);
        $caption = $item['host']['name'] . NAME_DELIMITER . $item['name_expanded'];
    }
    if ($this->data['screen']['templateid']) {
        $selectButton = (new CButton('select', _('Select')))->addClass(ZBX_STYLE_BTN_GREY)->onClick('javascript: return PopUp("popup.php?srctbl=items&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $form->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&templated_hosts=1&only_hostid=' . $this->data['screen']['templateid'] . '&numeric=1");');
    } else {
        $selectButton = (new CButton('select', _('Select')))->addClass(ZBX_STYLE_BTN_GREY)->onClick('javascript: return PopUp("popup.php?srctbl=items&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $form->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&real_hosts=1&with_simple_graph_items=1&numeric=1");');
    }
    $form->addVar('resourceid', $id);
    $screenFormList->addRow(_('Item'), [(new CTextBox('caption', $caption, true))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH), (new CDiv())->addClass(ZBX_STYLE_FORM_INPUT_MARGIN), $selectButton]);
} elseif ($resourceType == SCREEN_RESOURCE_LLD_SIMPLE_GRAPH) {
    $caption = '';
    $id = 0;
    $items = API::ItemPrototype()->get(['output' => ['hostid', 'key_', 'name'], 'itemids' => $resourceId, 'selectHosts' => ['name']]);
    if ($items) {
        $items = CMacrosResolverHelper::resolveItemNames($items);
        $id = $resourceId;
        $item = reset($items);
        $item['host'] = reset($item['hosts']);
        $caption = $item['host']['name'] . NAME_DELIMITER . $item['name_expanded'];
    }
    if ($this->data['screen']['templateid']) {
        $selectButton = (new CButton('select', _('Select')))->addClass(ZBX_STYLE_BTN_GREY)->onClick('javascript: return PopUp("popup.php?srctbl=item_prototypes&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $form->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&templated_hosts=1&only_hostid=' . $this->data['screen']['templateid'] . '&numeric=1");');
    } else {
        $selectButton = (new CButton('select', _('Select')))->addClass(ZBX_STYLE_BTN_GREY)->onClick('javascript: return PopUp("popup.php?srctbl=item_prototypes&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $form->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&real_hosts=1&with_discovery_rule=1&items=1&numeric=1");');
    }
    $form->addVar('resourceid', $id);
    $screenFormList->addRow(_('Item prototype'), [(new CTextBox('caption', $caption, true))->setWidth(ZBX_TEXTAREA_STANDARD_WIDTH), (new CDiv())->addClass(ZBX_STYLE_FORM_INPUT_MARGIN), $selectButton]);
    $screenFormList->addRow(_('Max columns'), (new CNumericBox('max_columns', $maxColumns, 3, false, false, false))->setWidth(ZBX_TEXTAREA_NUMERIC_STANDARD_WIDTH));
示例#11
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     $itemIds = array_keys($result);
     // adding items
     if (!is_null($options['selectItems'])) {
         if ($options['selectItems'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'parent_itemid', 'itemid', 'item_discovery');
             $items = API::ItemPrototype()->get(array('output' => $options['selectItems'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $items, 'items', $options['limitSelects']);
         } else {
             $items = API::ItemPrototype()->get(array('discoveryids' => $itemIds, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true));
             $items = zbx_toHash($items, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['items'] = isset($items[$itemid]) ? $items[$itemid]['rowscount'] : 0;
             }
         }
     }
     // adding triggers
     if (!is_null($options['selectTriggers'])) {
         if ($options['selectTriggers'] != API_OUTPUT_COUNT) {
             $relationMap = new CRelationMap();
             $res = DBselect('SELECT id.parent_itemid,f.triggerid' . ' FROM item_discovery id,items i,functions f' . ' WHERE ' . dbConditionInt('id.parent_itemid', $itemIds) . ' AND id.itemid=i.itemid' . ' AND i.itemid=f.itemid');
             while ($relation = DBfetch($res)) {
                 $relationMap->addRelation($relation['parent_itemid'], $relation['triggerid']);
             }
             $triggers = API::TriggerPrototype()->get(array('output' => $options['selectTriggers'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']);
         } else {
             $triggers = API::TriggerPrototype()->get(array('discoveryids' => $itemIds, 'countOutput' => true, 'groupCount' => true));
             $triggers = zbx_toHash($triggers, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['triggers'] = isset($triggers[$itemid]) ? $triggers[$itemid]['rowscount'] : 0;
             }
         }
     }
     // adding graphs
     if (!is_null($options['selectGraphs'])) {
         if ($options['selectGraphs'] != API_OUTPUT_COUNT) {
             $relationMap = new CRelationMap();
             $res = DBselect('SELECT id.parent_itemid,gi.graphid' . ' FROM item_discovery id,items i,graphs_items gi' . ' WHERE ' . dbConditionInt('id.parent_itemid', $itemIds) . ' AND id.itemid=i.itemid' . ' AND i.itemid=gi.itemid');
             while ($relation = DBfetch($res)) {
                 $relationMap->addRelation($relation['parent_itemid'], $relation['graphid']);
             }
             $graphs = API::GraphPrototype()->get(array('output' => $options['selectGraphs'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']);
         } else {
             $graphs = API::GraphPrototype()->get(array('discoveryids' => $itemIds, 'countOutput' => true, 'groupCount' => true));
             $graphs = zbx_toHash($graphs, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['graphs'] = isset($graphs[$itemid]) ? $graphs[$itemid]['rowscount'] : 0;
             }
         }
     }
     // adding hosts
     if ($options['selectHostPrototypes'] !== null) {
         if ($options['selectHostPrototypes'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'parent_itemid', 'hostid', 'host_discovery');
             $hostPrototypes = API::HostPrototype()->get(array('output' => $options['selectHostPrototypes'], 'hostids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $hostPrototypes, 'hostPrototypes', $options['limitSelects']);
         } else {
             $hostPrototypes = API::HostPrototype()->get(array('discoveryids' => $itemIds, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true));
             $hostPrototypes = zbx_toHash($hostPrototypes, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['hostPrototypes'] = isset($hostPrototypes[$itemid]) ? $hostPrototypes[$itemid]['rowscount'] : 0;
             }
         }
     }
     if ($options['selectFilter'] !== null) {
         $formulaRequested = $this->outputIsRequested('formula', $options['selectFilter']);
         $evalFormulaRequested = $this->outputIsRequested('eval_formula', $options['selectFilter']);
         $conditionsRequested = $this->outputIsRequested('conditions', $options['selectFilter']);
         $filters = array();
         foreach ($result as $rule) {
             $filters[$rule['itemid']] = array('evaltype' => $rule['evaltype'], 'formula' => isset($rule['formula']) ? $rule['formula'] : '');
         }
         // adding conditions
         if ($formulaRequested || $evalFormulaRequested || $conditionsRequested) {
             $conditions = API::getApiService()->select('item_condition', array('output' => array('item_conditionid', 'macro', 'value', 'itemid', 'operator'), 'filter' => array('itemid' => $itemIds), 'preservekeys' => true, 'sortfield' => 'item_conditionid'));
             $relationMap = $this->createRelationMap($conditions, 'itemid', 'item_conditionid');
             $filters = $relationMap->mapMany($filters, $conditions, 'conditions');
             foreach ($filters as &$filter) {
                 // in case of a custom expression - use the given formula
                 if ($filter['evaltype'] == CONDITION_EVAL_TYPE_EXPRESSION) {
                     $formula = $filter['formula'];
                 } else {
                     // sort the conditions by macro before generating the formula
                     $conditions = zbx_toHash($filter['conditions'], 'item_conditionid');
                     $conditions = order_macros($conditions, 'macro');
                     $formulaConditions = array();
                     foreach ($conditions as $condition) {
                         $formulaConditions[$condition['item_conditionid']] = $condition['macro'];
                     }
                     $formula = CConditionHelper::getFormula($formulaConditions, $filter['evaltype']);
                 }
                 // generate formulaids from the effective formula
                 $formulaIds = CConditionHelper::getFormulaIds($formula);
                 foreach ($filter['conditions'] as &$condition) {
                     $condition['formulaid'] = $formulaIds[$condition['item_conditionid']];
                 }
                 unset($condition);
                 // generated a letter based formula only for rules with custom expressions
                 if ($formulaRequested && $filter['evaltype'] == CONDITION_EVAL_TYPE_EXPRESSION) {
                     $filter['formula'] = CConditionHelper::replaceNumericIds($formula, $formulaIds);
                 }
                 if ($evalFormulaRequested) {
                     $filter['eval_formula'] = CConditionHelper::replaceNumericIds($formula, $formulaIds);
                 }
             }
             unset($filter);
         }
         // add filters to the result
         foreach ($result as &$rule) {
             $rule['filter'] = $filters[$rule['itemid']];
         }
         unset($rule);
     }
     return $result;
 }
示例#12
0
    }
    zbx_add_post_js('chkbxRange.pageGoName = "items";');
    $form->addItem($table);
    $form->show();
} elseif ($srctbl == 'prototypes') {
    $form = new CForm();
    $form->setName('itemform');
    $form->setAttribute('id', 'items');
    $table = new CTableInfo(_('No item prototypes defined.'));
    if ($multiselect) {
        $header = array(array(new CCheckBox('all_items', null, "javascript: checkAll('" . $form->getName() . "', 'all_items', 'items');"), _('Name')), _('Key'), _('Type'), _('Type of information'), _('Status'));
    } else {
        $header = array(_('Name'), _('Key'), _('Type'), _('Type of information'), _('Status'));
    }
    $table->setHeader($header);
    $items = API::ItemPrototype()->get(array('nodeids' => $nodeid, 'selectHosts' => array('name'), 'discoveryids' => get_request('parent_discoveryid'), 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true));
    order_result($items, 'name');
    foreach ($items as &$item) {
        $host = reset($item['hosts']);
        $description = new CSpan(itemName($item), 'link');
        $item['name'] = $host['name'] . ': ' . $item['name'];
        if ($multiselect) {
            $js_action = 'javascript: addValue(' . zbx_jsvalue($reference) . ', ' . zbx_jsvalue($item['itemid']) . ');';
        } else {
            $values = array();
            for ($i = 1; $i <= $dstfldCount; $i++) {
                $dstfld = get_request('dstfld' . $i);
                $srcfld = get_request('srcfld' . $i);
                if (!empty($dstfld) && !empty($item[$srcfld])) {
                    $values[$dstfld] = $item[$srcfld];
                }
     $templateList->addRow(_('Graphs'), $listBox);
 }
 // discovery rules
 $hostDiscoveryRules = API::DiscoveryRule()->get(['inherited' => false, 'hostids' => $data['templateId'], 'output' => API_OUTPUT_EXTEND]);
 if ($hostDiscoveryRules) {
     $hostDiscoveryRules = CMacrosResolverHelper::resolveItemNames($hostDiscoveryRules);
     $discoveryRuleList = [];
     foreach ($hostDiscoveryRules as $discoveryRule) {
         $discoveryRuleList[$discoveryRule['itemid']] = $discoveryRule['name_expanded'];
     }
     order_result($discoveryRuleList);
     $hostDiscoveryRuleids = array_keys($discoveryRuleList);
     $listBox = (new CListBox('discoveryRules', null, 8))->setAttribute('disabled', 'disabled')->addItems($discoveryRuleList);
     $templateList->addRow(_('Discovery rules'), $listBox);
     // item prototypes
     $hostItemPrototypes = API::ItemPrototype()->get(['hostids' => $data['templateId'], 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND]);
     if ($hostItemPrototypes) {
         $hostItemPrototypes = CMacrosResolverHelper::resolveItemNames($hostItemPrototypes);
         $prototypeList = [];
         foreach ($hostItemPrototypes as $itemPrototype) {
             $prototypeList[$itemPrototype['itemid']] = $itemPrototype['name_expanded'];
         }
         order_result($prototypeList);
         $listBox = (new CListBox('itemsPrototypes', null, 8))->setAttribute('disabled', 'disabled')->addItems($prototypeList);
         $templateList->addRow(_('Item prototypes'), $listBox);
     }
     // Trigger prototypes
     $hostTriggerPrototypes = API::TriggerPrototype()->get(['hostids' => $data['templateId'], 'discoveryids' => $hostDiscoveryRuleids, 'inherited' => false, 'output' => API_OUTPUT_EXTEND]);
     if (!empty($hostTriggerPrototypes)) {
         $prototypeList = [];
         foreach ($hostTriggerPrototypes as $triggerPrototype) {
 /**
  * Copies all of the item prototypes from the source discovery to the target
  * discovery rule.
  *
  * @throws APIException if prototype saving fails
  *
  * @param array $srcDiscovery   The source discovery rule to copy from
  * @param array $dstDiscovery   The target discovery rule to copy to
  * @param array $dstHost        The target host to copy the deiscovery rule to
  *
  * @return array
  */
 protected function copyItemPrototypes(array $srcDiscovery, array $dstDiscovery, array $dstHost)
 {
     $prototypes = API::ItemPrototype()->get(array('discoveryids' => $srcDiscovery['itemid'], 'selectApplications' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true));
     $rs = array();
     if ($prototypes) {
         foreach ($prototypes as $key => $prototype) {
             $prototype['ruleid'] = $dstDiscovery['itemid'];
             $prototype['hostid'] = $dstDiscovery['hostid'];
             unset($prototype['templateid']);
             // map prototype interfaces
             if ($dstHost['status'] != HOST_STATUS_TEMPLATE) {
                 // find a matching interface
                 $interface = self::findInterfaceForItem($prototype, $dstHost['interfaces']);
                 if ($interface) {
                     $prototype['interfaceid'] = $interface['interfaceid'];
                 } elseif ($interface !== false) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot find host interface on "%1$s" for item key "%2$s".', $dstHost['name'], $prototype['key_']));
                 }
             }
             // add new applications
             $prototype['applications'] = get_same_applications_for_host(zbx_objectValues($prototype['applications'], 'applicationid'), $dstHost['hostid']);
             $prototypes[$key] = $prototype;
         }
         $rs = API::ItemPrototype()->create($prototypes);
         if (!$rs) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot clone item prototypes.'));
         }
     }
     return $rs;
 }
 $hostDiscoveryRules = API::DiscoveryRule()->get(['output' => ['itemid', 'hostid', 'key_', 'name'], 'hostids' => [$data['clone_hostid']], 'inherited' => false]);
 if ($hostDiscoveryRules) {
     $hostDiscoveryRules = CMacrosResolverHelper::resolveItemNames($hostDiscoveryRules);
     $discoveryRuleList = [];
     foreach ($hostDiscoveryRules as $discoveryRule) {
         $discoveryRuleList[$discoveryRule['itemid']] = $discoveryRule['name_expanded'];
     }
     order_result($discoveryRuleList);
     $hostDiscoveryRuleIds = array_keys($discoveryRuleList);
     $listBox = new CListBox('discoveryRules', null, 8);
     $listBox->setAttribute('disabled', 'disabled');
     $listBox->addItems($discoveryRuleList);
     $hostList->addRow(_('Discovery rules'), $listBox);
 }
 // item prototypes
 $hostItemPrototypes = API::ItemPrototype()->get(['output' => ['itemid', 'hostid', 'key_', 'name'], 'hostids' => [$data['clone_hostid']], 'discoveryids' => $hostDiscoveryRuleIds, 'inherited' => false]);
 if ($hostItemPrototypes) {
     $hostItemPrototypes = CMacrosResolverHelper::resolveItemNames($hostItemPrototypes);
     $prototypeList = [];
     foreach ($hostItemPrototypes as $itemPrototype) {
         $prototypeList[$itemPrototype['itemid']] = $itemPrototype['name_expanded'];
     }
     order_result($prototypeList);
     $listBox = new CListBox('itemsPrototypes', null, 8);
     $listBox->setAttribute('disabled', 'disabled');
     $listBox->addItems($prototypeList);
     $hostList->addRow(_('Item prototypes'), $listBox);
 }
 // Trigger prototypes
 $hostTriggerPrototypes = API::TriggerPrototype()->get(['output' => ['triggerid', 'description'], 'selectItems' => ['type'], 'hostids' => [$data['clone_hostid']], 'discoveryids' => $hostDiscoveryRuleIds, 'inherited' => false]);
 if ($hostTriggerPrototypes) {
 /**
  * Deletes discovery rules and prototypes from DB that are missing in XML.
  *
  * @return null
  */
 protected function deleteMissingDiscoveryRules()
 {
     if (!$this->options['discoveryRules']['deleteMissing']) {
         return;
     }
     $processedHostIds = $this->importedObjectContainer->getHostIds();
     $processedTemplateIds = $this->importedObjectContainer->getTemplateIds();
     $processedHostIds = array_merge($processedHostIds, $processedTemplateIds);
     // no hosts or templates have been processed
     if (!$processedHostIds) {
         return;
     }
     $discoveryRuleIdsXML = array();
     $allDiscoveryRules = $this->getFormattedDiscoveryRules();
     if ($allDiscoveryRules) {
         foreach ($allDiscoveryRules as $host => $discoveryRules) {
             $hostId = $this->referencer->resolveHostOrTemplate($host);
             foreach ($discoveryRules as $discoveryRule) {
                 $discoveryRuleId = $this->referencer->resolveItem($hostId, $discoveryRule['key_']);
                 if ($discoveryRuleId) {
                     $discoveryRuleIdsXML[$discoveryRuleId] = $discoveryRuleId;
                 }
             }
         }
     }
     $dbDiscoveryRuleIds = API::DiscoveryRule()->get(array('output' => array('itemid'), 'hostids' => $processedHostIds, 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false));
     $discoveryRulesToDelete = array_diff_key($dbDiscoveryRuleIds, $discoveryRuleIdsXML);
     if ($discoveryRulesToDelete) {
         API::DiscoveryRule()->delete(array_keys($discoveryRulesToDelete));
     }
     // refresh discovery rules because templated ones can be inherited to host and used for prototypes
     $this->referencer->refreshItems();
     $hostPrototypeIdsXML = array();
     $triggerPrototypeIdsXML = array();
     $itemPrototypeIdsXML = array();
     $graphPrototypeIdsXML = array();
     foreach ($allDiscoveryRules as $host => $discoveryRules) {
         $hostId = $this->referencer->resolveHostOrTemplate($host);
         foreach ($discoveryRules as $discoveryRule) {
             $discoveryRuleId = $this->referencer->resolveItem($hostId, $discoveryRule['key_']);
             if ($discoveryRuleId) {
                 // gather host prototype IDs to delete
                 foreach ($discoveryRule['host_prototypes'] as $hostPrototype) {
                     $hostPrototypeId = $this->referencer->resolveHostPrototype($hostId, $discoveryRuleId, $hostPrototype['host']);
                     if ($hostPrototypeId) {
                         $hostPrototypeIdsXML[$hostPrototypeId] = $hostPrototypeId;
                     }
                 }
                 // gather trigger prototype IDs to delete
                 foreach ($discoveryRule['trigger_prototypes'] as $triggerPrototype) {
                     $triggerPrototypeId = $this->referencer->resolveTrigger($triggerPrototype['description'], $triggerPrototype['expression']);
                     if ($triggerPrototypeId) {
                         $triggerPrototypeIdsXML[$triggerPrototypeId] = $triggerPrototypeId;
                     }
                 }
                 // gather graph prototype IDs to delete
                 foreach ($discoveryRule['graph_prototypes'] as $graphPrototype) {
                     $graphPrototypeId = $this->referencer->resolveGraph($hostId, $graphPrototype['name']);
                     if ($graphPrototypeId) {
                         $graphPrototypeIdsXML[$graphPrototypeId] = $graphPrototypeId;
                     }
                 }
                 // gather item prototype IDs to delete
                 foreach ($discoveryRule['item_prototypes'] as $itemPrototype) {
                     $itemPrototypeId = $this->referencer->resolveItem($hostId, $itemPrototype['key_']);
                     if ($itemPrototypeId) {
                         $itemPrototypeIdsXML[$itemPrototypeId] = $itemPrototypeId;
                     }
                 }
             }
         }
     }
     // delete missing host prototypes
     $dbHostPrototypeIds = API::HostPrototype()->get(array('output' => array('hostid'), 'discoveryids' => $discoveryRuleIdsXML, 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false));
     $hostPrototypesToDelete = array_diff_key($dbHostPrototypeIds, $hostPrototypeIdsXML);
     if ($hostPrototypesToDelete) {
         API::HostPrototype()->delete(array_keys($hostPrototypesToDelete));
     }
     // delete missing trigger prototypes
     $dbTriggerPrototypeIds = API::TriggerPrototype()->get(array('output' => array('triggerid'), 'hostids' => $processedHostIds, 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false));
     $triggerPrototypesToDelete = array_diff_key($dbTriggerPrototypeIds, $triggerPrototypeIdsXML);
     // unlike triggers that belong to multiple hosts, trigger prototypes do not, so we just delete them
     if ($triggerPrototypesToDelete) {
         API::TriggerPrototype()->delete(array_keys($triggerPrototypesToDelete));
     }
     // delete missing graph prototypes
     $dbGraphPrototypeIds = API::GraphPrototype()->get(array('output' => array('graphid'), 'hostids' => $processedHostIds, 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false));
     $graphPrototypesToDelete = array_diff_key($dbGraphPrototypeIds, $graphPrototypeIdsXML);
     // unlike graphs that belong to multiple hosts, graph prototypes do not, so we just delete them
     if ($graphPrototypesToDelete) {
         API::GraphPrototype()->delete(array_keys($graphPrototypesToDelete));
     }
     // delete missing item prototypes
     $dbItemPrototypeIds = API::ItemPrototype()->get(array('output' => array('itemid'), 'hostids' => $processedHostIds, 'preservekeys' => true, 'nopermissions' => true, 'inherited' => false));
     $itemPrototypesToDelete = array_diff_key($dbItemPrototypeIds, $itemPrototypeIdsXML);
     if ($itemPrototypesToDelete) {
         API::ItemPrototype()->delete(array_keys($itemPrototypesToDelete));
     }
 }
示例#17
0
 protected function addRelatedObjects(array $options, array $result)
 {
     $result = parent::addRelatedObjects($options, $result);
     $itemIds = array_keys($result);
     // adding items
     if (!is_null($options['selectItems'])) {
         if ($options['selectItems'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'parent_itemid', 'itemid', 'item_discovery');
             $items = API::ItemPrototype()->get(array('output' => $options['selectItems'], 'nodeids' => $options['nodeids'], 'itemids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $items, 'items', $options['limitSelects']);
         } else {
             $items = API::ItemPrototype()->get(array('nodeids' => $options['nodeids'], 'discoveryids' => $itemIds, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true));
             $items = zbx_toHash($items, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['items'] = isset($items[$itemid]) ? $items[$itemid]['rowscount'] : 0;
             }
         }
     }
     // adding triggers
     if (!is_null($options['selectTriggers'])) {
         if ($options['selectTriggers'] != API_OUTPUT_COUNT) {
             $relationMap = new CRelationMap();
             $res = DBselect('SELECT id.parent_itemid,f.triggerid' . ' FROM item_discovery id,items i,functions f' . ' WHERE ' . dbConditionInt('id.parent_itemid', $itemIds) . ' AND id.itemid=i.itemid' . ' AND i.itemid=f.itemid');
             while ($relation = DBfetch($res)) {
                 $relationMap->addRelation($relation['parent_itemid'], $relation['triggerid']);
             }
             $triggers = API::TriggerPrototype()->get(array('output' => $options['selectTriggers'], 'nodeids' => $options['nodeids'], 'triggerids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $triggers, 'triggers', $options['limitSelects']);
         } else {
             $triggers = API::TriggerPrototype()->get(array('nodeids' => $options['nodeids'], 'discoveryids' => $itemIds, 'countOutput' => true, 'groupCount' => true));
             $triggers = zbx_toHash($triggers, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['triggers'] = isset($triggers[$itemid]) ? $triggers[$itemid]['rowscount'] : 0;
             }
         }
     }
     // adding graphs
     if (!is_null($options['selectGraphs'])) {
         if ($options['selectGraphs'] != API_OUTPUT_COUNT) {
             $relationMap = new CRelationMap();
             $res = DBselect('SELECT id.parent_itemid,gi.graphid' . ' FROM item_discovery id,items i,graphs_items gi' . ' WHERE ' . dbConditionInt('id.parent_itemid', $itemIds) . ' AND id.itemid=i.itemid' . ' AND i.itemid=gi.itemid');
             while ($relation = DBfetch($res)) {
                 $relationMap->addRelation($relation['parent_itemid'], $relation['graphid']);
             }
             $graphs = API::GraphPrototype()->get(array('output' => $options['selectGraphs'], 'nodeids' => $options['nodeids'], 'graphids' => $relationMap->getRelatedIds(), 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $graphs, 'graphs', $options['limitSelects']);
         } else {
             $graphs = API::GraphPrototype()->get(array('nodeids' => $options['nodeids'], 'discoveryids' => $itemIds, 'countOutput' => true, 'groupCount' => true));
             $graphs = zbx_toHash($graphs, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['graphs'] = isset($graphs[$itemid]) ? $graphs[$itemid]['rowscount'] : 0;
             }
         }
     }
     // adding hosts
     if ($options['selectHostPrototypes'] !== null) {
         if ($options['selectHostPrototypes'] != API_OUTPUT_COUNT) {
             $relationMap = $this->createRelationMap($result, 'parent_itemid', 'hostid', 'host_discovery');
             $hostPrototypes = API::HostPrototype()->get(array('output' => $options['selectHostPrototypes'], 'nodeids' => $options['nodeids'], 'hostids' => $relationMap->getRelatedIds(), 'nopermissions' => true, 'preservekeys' => true));
             $result = $relationMap->mapMany($result, $hostPrototypes, 'hostPrototypes', $options['limitSelects']);
         } else {
             $hostPrototypes = API::HostPrototype()->get(array('nodeids' => $options['nodeids'], 'discoveryids' => $itemIds, 'nopermissions' => true, 'countOutput' => true, 'groupCount' => true));
             $hostPrototypes = zbx_toHash($hostPrototypes, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 $result[$itemid]['hostPrototypes'] = isset($hostPrototypes[$itemid]) ? $hostPrototypes[$itemid]['rowscount'] : 0;
             }
         }
     }
     return $result;
 }
示例#18
0
 /**
  * Import discovery rules.
  *
  * @throws Exception
  */
 protected function processDiscoveryRules()
 {
     $allDiscoveryRules = $this->getFormattedDiscoveryRules();
     if (empty($allDiscoveryRules)) {
         return;
     }
     // unset rules that are related to hosts we did not process
     foreach ($allDiscoveryRules as $host => $discoveryRules) {
         if (!$this->referencer->isProcessedHost($host)) {
             unset($allDiscoveryRules[$host]);
         }
     }
     $itemsToCreate = array();
     $itemsToUpdate = array();
     foreach ($allDiscoveryRules as $host => $discoveryRules) {
         $hostid = $this->referencer->resolveHostOrTemplate($host);
         foreach ($discoveryRules as $item) {
             $item['hostid'] = $hostid;
             if (isset($item['interface_ref'])) {
                 $item['interfaceid'] = $this->referencer->interfacesCache[$hostid][$item['interface_ref']];
             }
             unset($item['item_prototypes']);
             unset($item['trigger_prototypes']);
             unset($item['graph_prototypes']);
             unset($item['host_prototypes']);
             $itemId = $this->referencer->resolveItem($hostid, $item['key_']);
             if ($itemId) {
                 $item['itemid'] = $itemId;
                 $itemsToUpdate[] = $item;
             } else {
                 $itemsToCreate[] = $item;
             }
         }
     }
     // create/update discovery rules and add processed rules to array $processedRules
     $processedRules = array();
     if ($this->options['discoveryRules']['createMissing'] && $itemsToCreate) {
         $newItemsIds = API::DiscoveryRule()->create($itemsToCreate);
         foreach ($newItemsIds['itemids'] as $inum => $itemid) {
             $item = $itemsToCreate[$inum];
             $this->referencer->addItemRef($item['hostid'], $item['key_'], $itemid);
         }
         foreach ($itemsToCreate as $item) {
             $processedRules[$item['hostid']][$item['key_']] = 1;
         }
     }
     if ($this->options['discoveryRules']['updateExisting'] && $itemsToUpdate) {
         API::DiscoveryRule()->update($itemsToUpdate);
         foreach ($itemsToUpdate as $item) {
             $processedRules[$item['hostid']][$item['key_']] = 1;
         }
     }
     // refresh discovery rules because templated ones can be inherited to host and used for prototypes
     $this->referencer->refreshItems();
     // process prototypes
     $prototypesToUpdate = array();
     $prototypesToCreate = array();
     $hostPrototypesToUpdate = array();
     $hostPrototypesToCreate = array();
     foreach ($allDiscoveryRules as $host => $discoveryRules) {
         $hostid = $this->referencer->resolveHostOrTemplate($host);
         foreach ($discoveryRules as $item) {
             // if rule was not processed we should not create/update any of its prototypes
             if (!isset($processedRules[$hostid][$item['key_']])) {
                 continue;
             }
             $item['hostid'] = $hostid;
             $itemId = $this->referencer->resolveItem($hostid, $item['key_']);
             // prototypes
             foreach ($item['item_prototypes'] as $prototype) {
                 $prototype['hostid'] = $hostid;
                 $applicationsIds = array();
                 foreach ($prototype['applications'] as $application) {
                     $applicationsIds[] = $this->referencer->resolveApplication($hostid, $application['name']);
                 }
                 $prototype['applications'] = $applicationsIds;
                 if (isset($prototype['interface_ref'])) {
                     $prototype['interfaceid'] = $this->referencer->interfacesCache[$hostid][$prototype['interface_ref']];
                 }
                 if ($prototype['valuemap']) {
                     $valueMapId = $this->referencer->resolveValueMap($prototype['valuemap']['name']);
                     if (!$valueMapId) {
                         throw new Exception(_s('Cannot find value map "%1$s" used for item prototype "%2$s" of discovery rule "%3$s" on "%4$s".', $prototype['valuemap']['name'], $prototype['name'], $item['name'], $host));
                     }
                     $prototype['valuemapid'] = $valueMapId;
                 }
                 $prototypeId = $this->referencer->resolveItem($hostid, $prototype['key_']);
                 $prototype['rule'] = array('hostid' => $hostid, 'key' => $item['key_']);
                 if ($prototypeId) {
                     $prototype['itemid'] = $prototypeId;
                     $prototypesToUpdate[] = $prototype;
                 } else {
                     $prototypesToCreate[] = $prototype;
                 }
             }
             // host prototype
             foreach ($item['host_prototypes'] as $hostPrototype) {
                 // resolve group prototypes
                 $groupLinks = array();
                 foreach ($hostPrototype['group_links'] as $groupLink) {
                     $groupId = $this->referencer->resolveGroup($groupLink['group']['name']);
                     if (!$groupId) {
                         throw new Exception(_s('Cannot find host group "%1$s" for host prototype "%2$s" of discovery rule "%3$s" on "%4$s".', $groupLink['group']['name'], $hostPrototype['name'], $item['name'], $host));
                     }
                     $groupLinks[] = array('groupid' => $groupId);
                 }
                 $hostPrototype['groupLinks'] = $groupLinks;
                 $hostPrototype['groupPrototypes'] = $hostPrototype['group_prototypes'];
                 unset($hostPrototype['group_links'], $hostPrototype['group_prototypes']);
                 // resolve templates
                 $templates = array();
                 foreach ($hostPrototype['templates'] as $template) {
                     $templateId = $this->referencer->resolveTemplate($template['name']);
                     if (!$templateId) {
                         throw new Exception(_s('Cannot find template "%1$s" for host prototype "%2$s" of discovery rule "%3$s" on "%4$s".', $template['name'], $hostPrototype['name'], $item['name'], $host));
                     }
                     $templates[] = array('templateid' => $templateId);
                 }
                 $hostPrototype['templates'] = $templates;
                 $hostPrototypeId = $this->referencer->resolveHostPrototype($hostid, $itemId, $hostPrototype['host']);
                 if ($hostPrototypeId) {
                     $hostPrototype['hostid'] = $hostPrototypeId;
                     $hostPrototypesToUpdate[] = $hostPrototype;
                 } else {
                     $hostPrototype['ruleid'] = $itemId;
                     $hostPrototypesToCreate[] = $hostPrototype;
                 }
             }
             if (isset($item['interface_ref'])) {
                 $item['interfaceid'] = $this->referencer->interfacesCache[$hostid][$item['interface_ref']];
             }
             unset($item['item_prototypes']);
             unset($item['trigger_prototypes']);
             unset($item['graph_prototypes']);
             unset($item['host_prototypes']);
             $itemsId = $this->referencer->resolveItem($hostid, $item['key_']);
             if ($itemsId) {
                 $item['itemid'] = $itemsId;
                 $itemsToUpdate[] = $item;
             } else {
                 $itemsToCreate[] = $item;
             }
         }
     }
     if ($prototypesToCreate) {
         foreach ($prototypesToCreate as &$prototype) {
             $prototype['ruleid'] = $this->referencer->resolveItem($prototype['rule']['hostid'], $prototype['rule']['key']);
         }
         unset($prototype);
         $newPrototypeIds = API::ItemPrototype()->create($prototypesToCreate);
         foreach ($newPrototypeIds['itemids'] as $inum => $itemid) {
             $item = $prototypesToCreate[$inum];
             $this->referencer->addItemRef($item['hostid'], $item['key_'], $itemid);
         }
     }
     if ($prototypesToUpdate) {
         foreach ($prototypesToCreate as &$prototype) {
             $prototype['ruleid'] = $this->referencer->resolveItem($prototype['rule']['hostid'], $prototype['rule']['key']);
         }
         unset($prototype);
         API::ItemPrototype()->update($prototypesToUpdate);
     }
     if ($hostPrototypesToCreate) {
         API::HostPrototype()->create($hostPrototypesToCreate);
     }
     if ($hostPrototypesToUpdate) {
         API::HostPrototype()->update($hostPrototypesToUpdate);
     }
     // refresh prototypes because templated ones can be inherited to host and used in triggers prototypes or graph prototypes
     $this->referencer->refreshItems();
     // first we need to create item prototypes and only then graph prototypes
     $triggersToCreate = array();
     $triggersToUpdate = array();
     $graphsToCreate = array();
     $graphsToUpdate = array();
     foreach ($allDiscoveryRules as $host => $discoveryRules) {
         $hostid = $this->referencer->resolveHostOrTemplate($host);
         foreach ($discoveryRules as $item) {
             // if rule was not processed we should not create/update any of its prototypes
             if (!isset($processedRules[$hostid][$item['key_']])) {
                 continue;
             }
             // trigger prototypes
             foreach ($item['trigger_prototypes'] as $trigger) {
                 $triggerId = $this->referencer->resolveTrigger($trigger['description'], $trigger['expression']);
                 if ($triggerId) {
                     $trigger['triggerid'] = $triggerId;
                     $triggersToUpdate[] = $trigger;
                 } else {
                     $triggersToCreate[] = $trigger;
                 }
             }
             // graph prototypes
             foreach ($item['graph_prototypes'] as $graph) {
                 $graphHostIds = array();
                 if ($graph['ymin_item_1']) {
                     $hostId = $this->referencer->resolveHostOrTemplate($graph['ymin_item_1']['host']);
                     $itemId = $hostId ? $this->referencer->resolveItem($hostId, $graph['ymin_item_1']['key']) : false;
                     if (!$itemId) {
                         throw new Exception(_s('Cannot find item "%1$s" on "%2$s" used as the Y axis MIN value for graph prototype "%3$s" of discovery rule "%4$s" on "%5$s".', $graph['ymin_item_1']['key'], $graph['ymin_item_1']['host'], $graph['name'], $item['name'], $host));
                     }
                     $graph['ymin_itemid'] = $itemId;
                 }
                 if ($graph['ymax_item_1']) {
                     $hostId = $this->referencer->resolveHostOrTemplate($graph['ymax_item_1']['host']);
                     $itemId = $hostId ? $this->referencer->resolveItem($hostId, $graph['ymax_item_1']['key']) : false;
                     if (!$itemId) {
                         throw new Exception(_s('Cannot find item "%1$s" on "%2$s" used as the Y axis MAX value for graph prototype "%3$s" of discovery rule "%4$s" on "%5$s".', $graph['ymax_item_1']['key'], $graph['ymax_item_1']['host'], $graph['name'], $item['name'], $host));
                     }
                     $graph['ymax_itemid'] = $itemId;
                 }
                 foreach ($graph['gitems'] as &$gitem) {
                     if (!($gitemHostId = $this->referencer->resolveHostOrTemplate($gitem['item']['host']))) {
                         throw new Exception(_s('Cannot find host or template "%1$s" used in graph "%2$s".', $gitem['item']['host'], $graph['name']));
                     }
                     $gitem['itemid'] = $this->referencer->resolveItem($gitemHostId, $gitem['item']['key']);
                     $graphHostIds[$gitemHostId] = $gitemHostId;
                 }
                 unset($gitem);
                 // TODO: do this for all graphs at once
                 $sql = 'SELECT g.graphid' . ' FROM graphs g,graphs_items gi,items i' . ' WHERE g.graphid=gi.graphid' . ' AND gi.itemid=i.itemid' . ' AND g.name=' . zbx_dbstr($graph['name']) . ' AND ' . dbConditionInt('i.hostid', $graphHostIds);
                 $graphExists = DBfetch(DBselect($sql));
                 if ($graphExists) {
                     $dbGraph = API::GraphPrototype()->get(array('graphids' => $graphExists['graphid'], 'output' => array('graphid'), 'editable' => true));
                     if (empty($dbGraph)) {
                         throw new Exception(_s('No permission for graph "%1$s".', $graph['name']));
                     }
                     $graph['graphid'] = $graphExists['graphid'];
                     $graphsToUpdate[] = $graph;
                 } else {
                     $graphsToCreate[] = $graph;
                 }
             }
         }
     }
     if ($triggersToCreate) {
         API::TriggerPrototype()->create($triggersToCreate);
     }
     if ($triggersToUpdate) {
         API::TriggerPrototype()->update($triggersToUpdate);
     }
     if ($graphsToCreate) {
         API::GraphPrototype()->create($graphsToCreate);
     }
     if ($graphsToUpdate) {
         API::GraphPrototype()->update($graphsToUpdate);
     }
 }
示例#19
0
} elseif ($srctbl == 'prototypes') {
    $form = new CForm();
    $form->setName('itemform');
    $form->setAttribute('id', 'items');
    $table = new CTableInfo(_('No item prototypes found.'));
    if ($multiselect) {
        $header = array(array(new CCheckBox('all_items', null, "javascript: checkAll('" . $form->getName() . "', 'all_items', 'items');"), _('Name')), _('Key'), _('Type'), _('Type of information'), _('Status'));
    } else {
        $header = array(_('Name'), _('Key'), _('Type'), _('Type of information'), _('Status'));
    }
    $table->setHeader($header);
    $options = array('nodeids' => $nodeId, 'selectHosts' => array('name'), 'discoveryids' => get_request('parent_discoveryid'), 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true);
    if (!is_null($value_types)) {
        $options['filter']['value_type'] = $value_types;
    }
    $items = API::ItemPrototype()->get($options);
    $items = CMacrosResolverHelper::resolveItemNames($items);
    order_result($items, 'name_expanded');
    foreach ($items as &$item) {
        $host = reset($item['hosts']);
        $description = new CSpan($item['name_expanded'], 'link');
        $item['name'] = $host['name'] . NAME_DELIMITER . $item['name_expanded'];
        if ($multiselect) {
            $js_action = 'javascript: addValue(' . zbx_jsvalue($reference) . ', ' . zbx_jsvalue($item['itemid']) . ');';
        } else {
            $values = array();
            for ($i = 1; $i <= $dstfldCount; $i++) {
                $dstfld = get_request('dstfld' . $i);
                $srcfld = get_request('srcfld' . $i);
                if (!empty($dstfld) && !empty($item[$srcfld])) {
                    $values[$dstfld] = $item[$srcfld];
示例#20
0
function get_item_function_info($expr)
{
    $value_type = array(ITEM_VALUE_TYPE_UINT64 => _('Numeric (integer 64bit)'), ITEM_VALUE_TYPE_FLOAT => _('Numeric (float)'), ITEM_VALUE_TYPE_STR => _('Character'), ITEM_VALUE_TYPE_LOG => _('Log'), ITEM_VALUE_TYPE_TEXT => _('Text'));
    $type_of_value_type = array(ITEM_VALUE_TYPE_UINT64 => T_ZBX_INT, ITEM_VALUE_TYPE_FLOAT => T_ZBX_DBL, ITEM_VALUE_TYPE_STR => T_ZBX_STR, ITEM_VALUE_TYPE_LOG => T_ZBX_STR, ITEM_VALUE_TYPE_TEXT => T_ZBX_STR);
    $function_info = array('band' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'abschange' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'avg' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'change' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'count' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'date' => array('value_type' => 'YYYYMMDD', 'type' => T_ZBX_INT, 'validation' => '{}>=19700101&&{}<=99991231'), 'dayofmonth' => array('value_type' => '1-31', 'type' => T_ZBX_INT, 'validation' => '{}>=1&&{}<=31'), 'dayofweek' => array('value_type' => '1-7', 'type' => T_ZBX_INT, 'validation' => IN('1,2,3,4,5,6,7')), 'delta' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'diff' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'fuzzytime' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'iregexp' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'last' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'logeventid' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'logseverity' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'logsource' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'max' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'min' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'nodata' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'now' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'prev' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'regexp' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'str' => array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'strlen' => array('value_type' => _('Numeric (integer 64bit)'), 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'sum' => array('value_type' => $value_type, 'type' => $type_of_value_type, 'validation' => NOT_EMPTY), 'time' => array('value_type' => 'HHMMSS', 'type' => T_ZBX_INT, 'validation' => 'zbx_strlen({})==6'));
    $expressionData = new CTriggerExpression();
    if ($expressionData->parse($expr)) {
        if (isset($expressionData->macros[0])) {
            $result = array('value_type' => _('0 or 1'), 'type' => T_ZBX_INT, 'validation' => IN('0,1'));
        } elseif (isset($expressionData->usermacros[0]) || isset($expressionData->lldmacros[0])) {
            $result = array('value_type' => $value_type[ITEM_VALUE_TYPE_FLOAT], 'type' => T_ZBX_STR, 'validation' => 'preg_match("/^' . ZBX_PREG_NUMBER . '$/u", {})');
        } elseif (isset($expressionData->expressions[0])) {
            $exprPart = reset($expressionData->expressions);
            if (!isset($function_info[$exprPart['functionName']])) {
                return EXPRESSION_FUNCTION_UNKNOWN;
            }
            $hostFound = API::Host()->get(array('filter' => array('host' => array($exprPart['host'])), 'templated_hosts' => true));
            if (!$hostFound) {
                return EXPRESSION_HOST_UNKNOWN;
            }
            $itemFound = API::Item()->get(array('output' => array('value_type'), 'hostids' => zbx_objectValues($hostFound, 'hostid'), 'filter' => array('key_' => array($exprPart['item'])), 'webitems' => true));
            if (!$itemFound) {
                $itemFound = API::ItemPrototype()->get(array('output' => array('value_type'), 'hostids' => zbx_objectValues($hostFound, 'hostid'), 'filter' => array('key_' => array($exprPart['item']))));
                if (!$itemFound) {
                    return EXPRESSION_HOST_ITEM_UNKNOWN;
                }
            }
            $itemFound = reset($itemFound);
            $result = $function_info[$exprPart['functionName']];
            if (is_array($result['value_type'])) {
                $result['value_type'] = $result['value_type'][$itemFound['value_type']];
                $result['type'] = $result['type'][$itemFound['value_type']];
                if ($result['type'] == T_ZBX_INT || $result['type'] == T_ZBX_DBL) {
                    $result['type'] = T_ZBX_STR;
                    $result['validation'] = 'preg_match("/^' . ZBX_PREG_NUMBER . '$/u",{})';
                }
            }
        } else {
            return EXPRESSION_NOT_A_MACRO_ERROR;
        }
    }
    return $result;
}
        $id = $resourceId;
        $item = reset($items);
        $item['host'] = reset($item['hosts']);
        $caption = $item['host']['name'] . NAME_DELIMITER . $item['name_expanded'];
    }
    if ($this->data['screen']['templateid']) {
        $selectButton = new CButton('select', _('Select'), 'javascript: return PopUp("popup.php?srctbl=items&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $screenForm->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&templated_hosts=1&only_hostid=' . $this->data['screen']['templateid'] . '&writeonly=1&numeric=1", 800, 450);', 'formlist');
    } else {
        $selectButton = new CButton('select', _('Select'), 'javascript: return PopUp("popup.php?srctbl=items&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $screenForm->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&real_hosts=1&with_simple_graph_items=1&writeonly=1&numeric=1", 800, 450);', 'formlist');
    }
    $screenFormList->addVar('resourceid', $id);
    $screenFormList->addRow(_('Parameter'), array(new CTextBox('caption', $caption, ZBX_TEXTBOX_STANDARD_SIZE, true), $selectButton), false, null, 'nowrap');
} elseif ($resourceType == SCREEN_RESOURCE_LLD_SIMPLE_GRAPH) {
    $caption = '';
    $id = 0;
    $items = API::ItemPrototype()->get(array('output' => array('hostid', 'key_', 'name'), 'itemids' => $resourceId, 'selectHosts' => array('name')));
    if ($items) {
        $items = CMacrosResolverHelper::resolveItemNames($items);
        $id = $resourceId;
        $item = reset($items);
        $item['host'] = reset($item['hosts']);
        $caption = $item['host']['name'] . NAME_DELIMITER . $item['name_expanded'];
    }
    if ($this->data['screen']['templateid']) {
        $selectButton = new CButton('select', _('Select'), 'javascript: return PopUp("popup.php?srctbl=item_prototypes&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $screenForm->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&templated_hosts=1&only_hostid=' . $this->data['screen']['templateid'] . '&writeonly=1&numeric=1", 800, 450);', 'formlist');
    } else {
        $selectButton = new CButton('select', _('Select'), 'javascript: return PopUp("popup.php?srctbl=item_prototypes&srcfld1=itemid&srcfld2=name' . '&dstfrm=' . $screenForm->getName() . '&dstfld1=resourceid&dstfld2=caption' . '&real_hosts=1&with_discovery_rule=1&items=1&writeonly=1&numeric=1", 800, 450);', 'formlist');
    }
    $screenFormList->addVar('resourceid', $id);
    $screenFormList->addRow(_('Parameter'), array(new CTextBox('caption', $caption, ZBX_TEXTBOX_STANDARD_SIZE, true), $selectButton), false, null, 'nowrap');
    $screenFormList->addRow(_('Max columns'), new CNumericBox('max_columns', $maxColumns, 3, false, false, false));
示例#22
0
 protected function inherit($graph, $hostids = null)
 {
     $graphTemplates = API::Template()->get(array('itemids' => zbx_objectValues($graph['gitems'], 'itemid'), 'output' => array('templateid'), 'nopermissions' => true));
     if (empty($graphTemplates)) {
         return true;
     }
     $graphTemplate = reset($graphTemplates);
     $chdHosts = API::Host()->get(array('templateids' => $graphTemplate['templateid'], 'output' => array('hostid', 'host'), 'preservekeys' => true, 'hostids' => $hostids, 'nopermissions' => true, 'templated_hosts' => true));
     $graph = $this->get(array('graphids' => $graph['graphid'], 'nopermissions' => true, 'filter' => array('flags' => null), 'selectGraphItems' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND));
     $graph = reset($graph);
     foreach ($chdHosts as $chdHost) {
         $tmpGraph = $graph;
         $tmpGraph['templateid'] = $graph['graphid'];
         $tmpGraph['gitems'] = getSameGraphItemsForHost($tmpGraph['gitems'], $chdHost['hostid']);
         if (!$tmpGraph['gitems']) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" cannot inherit. No required items on "%2$s".', $tmpGraph['name'], $chdHost['host']));
         }
         if ($tmpGraph['ymax_itemid'] > 0) {
             $ymaxItemid = getSameGraphItemsForHost(array(array('itemid' => $tmpGraph['ymax_itemid'])), $chdHost['hostid']);
             if (!$ymaxItemid) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" cannot inherit. No required items on "%2$s" (Ymax value item).', $tmpGraph['name'], $chdHost['host']));
             }
             $ymaxItemid = reset($ymaxItemid);
             $tmpGraph['ymax_itemid'] = $ymaxItemid['itemid'];
         }
         if ($tmpGraph['ymin_itemid'] > 0) {
             $yminItemid = getSameGraphItemsForHost(array(array('itemid' => $tmpGraph['ymin_itemid'])), $chdHost['hostid']);
             if (!$yminItemid) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" cannot inherit. No required items on "%2$s" (Ymin value item).', $tmpGraph['name'], $chdHost['host']));
             }
             $yminItemid = reset($yminItemid);
             $tmpGraph['ymin_itemid'] = $yminItemid['itemid'];
         }
         // check if templated graph exists
         $chdGraphs = $this->get(array('filter' => array('templateid' => $tmpGraph['graphid'], 'flags' => array(ZBX_FLAG_DISCOVERY_PROTOTYPE, ZBX_FLAG_DISCOVERY_NORMAL)), 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'hostids' => $chdHost['hostid']));
         if ($chdGraph = reset($chdGraphs)) {
             if ($tmpGraph['name'] !== $chdGraph['name']) {
                 $graphExists = $this->get(array('output' => array('graphid'), 'hostids' => $chdHost['hostid'], 'filter' => array('name' => $tmpGraph['name'], 'flags' => null), 'nopermissions' => true, 'limit' => 1));
                 if ($graphExists) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s".', $tmpGraph['name'], $chdHost['host']));
                 }
             } elseif ($chdGraph['flags'] != $tmpGraph['flags']) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Graph with same name but other type exist.'));
             }
             $tmpGraph['graphid'] = $chdGraph['graphid'];
             $this->updateReal($tmpGraph, $chdGraph);
         } else {
             $chdGraph = $this->get(array('filter' => array('name' => $tmpGraph['name'], 'flags' => null), 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'nopermissions' => true, 'hostids' => $chdHost['hostid']));
             if ($chdGraph = reset($chdGraph)) {
                 if ($chdGraph['templateid'] != 0) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s" (inherited from another template).', $tmpGraph['name'], $chdHost['host']));
                 } elseif ($chdGraph['flags'] != $tmpGraph['flags']) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _('Graph with same name but other type exist.'));
                 }
                 $chdGraphItemItems = array();
                 foreach (array(API::Item(), API::ItemPrototype()) as $api) {
                     $chdGraphItemItems += $api->get(array('output' => array('key_', 'hostid', 'itemid'), 'itemids' => zbx_objectValues($chdGraph['gitems'], 'itemid'), 'preservekeys' => true));
                 }
                 if (count($chdGraph['gitems']) == count($tmpGraph['gitems'])) {
                     foreach ($tmpGraph['gitems'] as $gitem) {
                         foreach ($chdGraph['gitems'] as $chdGraphItem) {
                             $chdGraphItemItem = $chdGraphItemItems[$chdGraphItem['itemid']];
                             if ($gitem['key_'] == $chdGraphItemItem['key_'] && bccomp($chdHost['hostid'], $chdGraphItemItem['hostid']) == 0) {
                                 continue 2;
                             }
                         }
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s" (items are not identical).', $tmpGraph['name'], $chdHost['host']));
                     }
                     $tmpGraph['graphid'] = $chdGraph['graphid'];
                     $this->updateReal($tmpGraph, $chdGraph);
                 } else {
                     self::exception(ZBX_API_ERROR_PARAMETERS, _s('Graph "%1$s" already exists on "%2$s" (items are not identical).', $tmpGraph['name'], $chdHost['host']));
                 }
             } else {
                 $graphid = $this->createReal($tmpGraph);
                 $tmpGraph['graphid'] = $graphid;
             }
         }
         $this->inherit($tmpGraph);
     }
 }
示例#23
0
    } else {
        $data['name'] = getRequest('name', '');
        $data['mappings'] = getRequest('mappings', []);
    }
    if ($data['valuemapid'] != 0) {
        $data['valuemap_count'] += API::Item()->get(['countOutput' => true, 'webitems' => true, 'filter' => ['valuemapid' => $data['valuemapid']]]);
        $data['valuemap_count'] += API::ItemPrototype()->get(['countOutput' => true, 'filter' => ['valuemapid' => $data['valuemapid']]]);
    }
    if (!$data['mappings']) {
        $data['mappings'][] = ['value' => '', 'newvalue' => ''];
    }
    $view = new CView('administration.general.valuemapping.edit', $data);
} else {
    $sortfield = getRequest('sort', CProfile::get('web.' . $page['file'] . '.sort', 'name'));
    $sortorder = getRequest('sortorder', CProfile::get('web.' . $page['file'] . '.sortorder', ZBX_SORT_UP));
    CProfile::update('web.' . $page['file'] . '.sort', $sortfield, PROFILE_TYPE_STR);
    CProfile::update('web.' . $page['file'] . '.sortorder', $sortorder, PROFILE_TYPE_STR);
    $data = ['sort' => $sortfield, 'sortorder' => $sortorder];
    $data['valuemaps'] = API::ValueMap()->get(['output' => ['valuemapid', 'name'], 'selectMappings' => ['value', 'newvalue'], 'sortfield' => $sortfield, 'limit' => $config['search_limit'] + 1]);
    order_result($data['valuemaps'], $sortfield, $sortorder);
    $data['paging'] = getPagingLine($data['valuemaps'], $sortorder, new CUrl('adm.valuemapping.php'));
    foreach ($data['valuemaps'] as &$valuemap) {
        order_result($valuemap['mappings'], 'value');
        $valuemap['used_in_items'] = (bool) API::Item()->get(['output' => [], 'webitems' => true, 'filter' => ['valuemapid' => $valuemap['valuemapid']], 'limit' => 1]) || (bool) API::ItemPrototype()->get(['output' => [], 'filter' => ['valuemapid' => $valuemap['valuemapid']], 'limit' => 1]);
    }
    unset($valuemap);
    $view = new CView('administration.general.valuemapping.list', $data);
}
$view->render();
$view->show();
require_once dirname(__FILE__) . '/include/page_footer.php';