Beispiel #1
0
function itemIdents($itemids)
{
    $idents = array();
    $options = array('itemids' => $itemids, 'output' => API_OUTPUT_EXTEND, 'select_hosts' => array('hostid', 'host'), 'nodeids' => get_current_nodeid(true), 'webitems' => 1);
    $items = CItem::get($options);
    foreach ($items as $inum => $item) {
        $host = reset($item['hosts']);
        $idents[$item['itemid']] = array('node' => get_node_name_by_elid($item['itemid'], true), 'host' => $host['host'], 'key_' => $item['key_']);
    }
    return $idents;
}
function make_graph_submenu()
{
    $graphids = array();
    $itemids = array();
    $fav_graphs = get_favorites('web.favorite.graphids');
    foreach ($fav_graphs as $key => $favorite) {
        if ('itemid' == $favorite['source']) {
            $itemids[$favorite['value']] = $favorite['value'];
        } else {
            $graphids[$favorite['value']] = $favorite['value'];
        }
    }
    $options = array('graphids' => $graphids, 'select_hosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND);
    $graphs = CGraph::get($options);
    $graphs = zbx_toHash($graphs, 'graphid');
    $options = array('itemids' => $itemids, 'select_hosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND, 'webitems' => 1);
    $items = CItem::get($options);
    $items = zbx_toHash($items, 'itemid');
    $favGraphs = array();
    foreach ($fav_graphs as $key => $favorite) {
        $source = $favorite['source'];
        $sourceid = $favorite['value'];
        if ('itemid' == $source) {
            if (!isset($items[$sourceid])) {
                continue;
            }
            $item_added = true;
            $item = $items[$sourceid];
            $host = reset($item['hosts']);
            $item['description'] = item_description($item);
            $favGraphs[] = array('name' => $host['host'] . ':' . $item['description'], 'favobj' => 'itemid', 'favid' => $sourceid, 'action' => 'remove');
        } else {
            if (!isset($graphs[$sourceid])) {
                continue;
            }
            $graph_added = true;
            $graph = $graphs[$sourceid];
            $ghost = reset($graph['hosts']);
            $favGraphs[] = array('name' => $ghost['host'] . ':' . $graph['name'], 'favobj' => 'graphid', 'favid' => $sourceid, 'action' => 'remove');
        }
    }
    if (isset($graph_added)) {
        $favGraphs[] = array('name' => S_REMOVE . SPACE . S_ALL_S . SPACE . S_GRAPHS, 'favobj' => 'graphid', 'favid' => 0, 'action' => 'remove');
    }
    if (isset($item_added)) {
        $favGraphs[] = array('name' => S_REMOVE . SPACE . S_ALL_S . SPACE . S_SIMPLE_GRAPHS, 'favobj' => 'itemid', 'favid' => 0, 'action' => 'remove');
    }
    return $favGraphs;
}
Beispiel #3
0
 // FORM ITEM : linked Template table
 $tpl_table = new CTable();
 $tpl_table->setCellPadding(0);
 $tpl_table->setCellSpacing(0);
 foreach ($templates as $tid => $tname) {
     $frmHost->addVar('templates[' . $tid . ']', $tname);
     $tpl_table->addRow(array($tname, new CButton('unlink[' . $tid . ']', S_UNLINK), isset($original_templates[$tid]) ? new CButton('unlink_and_clear[' . $tid . ']', S_UNLINK_AND_CLEAR) : SPACE));
 }
 $template_tbl->addRow(array(S_LINK_WITH_TEMPLATE, array($tpl_table, new CButton('add_template', S_ADD, 'return PopUp("popup.php?dstfrm=' . $frmHost->GetName() . '&dstfld1=new_template&srctbl=templates&srcfld1=hostid&srcfld2=host&excludeids[' . $templateid . ']=' . $templateid . url_param($templates, false, "existed_templates") . '",450,450)', 'T'))));
 // FULL CLONE {
 if ($_REQUEST['form'] == 'full_clone') {
     // FORM ITEM : Template items
     $items_lbx = new CListBox('items', null, 8);
     $items_lbx->setAttribute('disabled', 'disabled');
     $options = array('editable' => 1, 'hostids' => $templateid, 'output' => API_OUTPUT_EXTEND);
     $template_items = CItem::get($options);
     if (empty($template_items)) {
         $items_lbx->setAttribute('style', 'width: 200px;');
     } else {
         foreach ($template_items as $inum => $titem) {
             $item_description = item_description($titem);
             $items_lbx->addItem($titem['itemid'], $item_description);
         }
     }
     $template_tbl->addRow(array(S_ITEMS, $items_lbx));
     // FORM ITEM : Template triggers
     $trig_lbx = new CListBox('triggers', null, 8);
     $trig_lbx->setAttribute('disabled', 'disabled');
     $options = array('editable' => 1, 'hostids' => $templateid, 'extendoutput' => 1);
     $template_triggers = CTrigger::get($options);
     if (empty($template_triggers)) {
 /**
  * Get history data
  *
  * {@source}
  * @access public
  * @static
  * @since 1.8.3
  * @version 1.3
  *
  * @param array $options
  * @param array $options['itemids']
  * @param boolean $options['editable']
  * @param string $options['pattern']
  * @param int $options['limit']
  * @param string $options['order']
  * @return array|int item data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $nodeCheck = false;
     $result = array();
     $sort_columns = array('itemid', 'clock');
     // allowed columns for sorting
     $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     // allowed output options for [ select_* ] params
     $sql_parts = array('select' => array('history' => 'h.itemid'), 'from' => array(), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('history' => ITEM_VALUE_TYPE_UINT64, 'nodeids' => null, 'hostids' => null, 'itemids' => null, 'triggerids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'time_from' => null, 'time_till' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'groupCount' => null, 'groupOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($def_options, $options);
     switch ($options['history']) {
         case ITEM_VALUE_TYPE_LOG:
             $sql_parts['from']['history'] = 'history_log h';
             $sort_columns[] = 'id';
             break;
         case ITEM_VALUE_TYPE_TEXT:
             $sql_parts['from']['history'] = 'history_text h';
             $sort_columns[] = 'id';
             break;
         case ITEM_VALUE_TYPE_STR:
             $sql_parts['from']['history'] = 'history_str h';
             break;
         case ITEM_VALUE_TYPE_UINT64:
             $sql_parts['from']['history'] = 'history_uint h';
             break;
         case ITEM_VALUE_TYPE_FLOAT:
         default:
             $sql_parts['from']['history'] = 'history h';
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $USER_DETAILS['type'] || $options['nopermissions']) {
     } else {
         $itemOptions = array('editable' => $options['editable'], 'preservekeys' => 1);
         if (!is_null($options['itemids'])) {
             $itemOptions['itemids'] = $options['itemids'];
         }
         $items = CItem::get($itemOptions);
         $options['itemids'] = array_keys($items);
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sql_parts['where']['itemid'] = DBcondition('h.itemid', $options['itemids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('h.itemid', $nodeids);
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['hostid'] = 'i.hostid';
         }
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where']['i'] = DBcondition('i.hostid', $options['hostids']);
         $sql_parts['where']['hi'] = 'h.itemid=i.itemid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('i.hostid', $nodeids);
         }
     }
     // node check !!!!!
     // should be last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sql_parts['where'][] = DBin_node('h.itemid', $nodeids);
     }
     // time_from
     if (!is_null($options['time_from'])) {
         $sql_parts['select']['clock'] = 'h.clock';
         $sql_parts['where']['clock_from'] = 'h.clock>=' . $options['time_from'];
     }
     // time_till
     if (!is_null($options['time_till'])) {
         $sql_parts['select']['clock'] = 'h.clock';
         $sql_parts['where']['clock_till'] = 'h.clock<=' . $options['time_till'];
     }
     // filter
     if (is_array($options['filter'])) {
         zbx_db_filter($sql_parts['from']['history'], $options, $sql_parts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search($sql_parts['from']['history'], $options, $sql_parts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         unset($sql_parts['select']['clock']);
         $sql_parts['select']['history'] = 'h.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sql_parts['select'] = array('count(DISTINCT h.hostid) as rowscount');
         //groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sql_parts['group'] as $key => $fields) {
                 $sql_parts['select'][$key] = $fields;
             }
         }
     }
     // groupOutput
     $groupOutput = false;
     if (!is_null($options['groupOutput'])) {
         if (str_in_array('h.' . $options['groupOutput'], $sql_parts['select']) || str_in_array('h.*', $sql_parts['select'])) {
             $groupOutput = true;
         }
     }
     // order
     // restrict not allowed columns for sorting
     $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : '';
     if (!zbx_empty($options['sortfield'])) {
         $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP;
         if ($options['sortfield'] == 'clock') {
             $sql_parts['order']['itemid'] = 'h.itemid ' . $sortorder;
         }
         $sql_parts['order'][$options['sortfield']] = 'h.' . $options['sortfield'] . ' ' . $sortorder;
         if (!str_in_array('h.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('h.*', $sql_parts['select'])) {
             $sql_parts['select'][$options['sortfield']] = 'h.' . $options['sortfield'];
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //---------------
     $itemids = array();
     $triggerids = array();
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_order;
     $db_res = DBselect($sql, $sql_limit);
     //SDI($sql);
     $count = 0;
     $group = array();
     while ($data = DBfetch($db_res)) {
         if ($options['countOutput']) {
             $result = $data;
         } else {
             $itemids[$data['itemid']] = $data['itemid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$count] = array('itemid' => $data['itemid']);
             } else {
                 $result[$count] = array();
                 // hostids
                 if (isset($data['hostid'])) {
                     if (!isset($result[$count]['hosts'])) {
                         $result[$count]['hosts'] = array();
                     }
                     $result[$count]['hosts'][] = array('hostid' => $data['hostid']);
                     unset($data['hostid']);
                 }
                 // triggerids
                 if (isset($data['triggerid'])) {
                     if (!isset($result[$count]['triggers'])) {
                         $result[$count]['triggers'] = array();
                     }
                     $result[$count]['triggers'][] = array('triggerid' => $data['triggerid']);
                     unset($data['triggerid']);
                 }
                 // itemids
                 //					if(isset($data['itemid']) && !is_null($options['itemids'])){
                 //						if(!isset($result[$count]['items'])) $result[$count]['items'] = array();
                 //						$result[$count]['items'][] = array('itemid' => $data['itemid']);
                 //					}
                 $result[$count] += $data;
                 // grouping
                 if ($groupOutput) {
                     $dataid = $data[$options['groupOutput']];
                     if (!isset($group[$dataid])) {
                         $group[$dataid] = array();
                     }
                     $group[$dataid][] = $result[$count];
                 }
                 $count++;
             }
         }
     }
     COpt::memoryPick();
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Beispiel #5
0
 /**
  * Delete items
  *
  * {@source}
  * @access public
  * @static
  * @since 1.8
  * @version 1
  *
  * @static
  * @param array $itemids
  * @return array|boolean
  */
 public static function delete($itemids)
 {
     $result = delete_item($itemids);
     if ($result) {
         return $itemids;
     } else {
         self::$error = array('error' => ZBX_API_ERROR_INTERNAL, 'data' => 'Internal zabbix error');
         return false;
     }
 }
Beispiel #6
0
function copyItems($srcHostId, $dstHostId)
{
    $srcItems = API::Item()->get(array('hostids' => $srcHostId, 'output' => array('type', 'snmp_community', 'snmp_oid', 'name', 'key_', 'delay', 'history', 'trends', 'status', 'value_type', 'trapper_hosts', 'units', 'multiplier', 'delta', 'snmpv3_contextname', 'snmpv3_securityname', 'snmpv3_securitylevel', 'snmpv3_authprotocol', 'snmpv3_authpassphrase', 'snmpv3_privprotocol', 'snmpv3_privpassphrase', 'formula', 'logtimefmt', 'valuemapid', 'delay_flex', 'params', 'ipmi_sensor', 'data_type', 'authtype', 'username', 'password', 'publickey', 'privatekey', 'flags', 'filter', 'port', 'description', 'inventory_link'), 'inherited' => false, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL), 'selectApplications' => API_OUTPUT_REFER));
    $dstHosts = API::Host()->get(array('output' => array('hostid', 'host', 'status'), 'selectInterfaces' => array('interfaceid', 'type', 'main'), 'hostids' => $dstHostId, 'preservekeys' => true, 'nopermissions' => true, 'templated_hosts' => true));
    $dstHost = reset($dstHosts);
    foreach ($srcItems as &$srcItem) {
        if ($dstHost['status'] != HOST_STATUS_TEMPLATE) {
            // find a matching interface
            $interface = CItem::findInterfaceForItem($srcItem, $dstHost['interfaces']);
            if ($interface) {
                $srcItem['interfaceid'] = $interface['interfaceid'];
            } elseif ($interface !== false) {
                error(_s('Cannot find host interface on "%1$s" for item key "%2$s".', $dstHost['host'], $srcItem['key_']));
            }
        }
        unset($srcItem['itemid']);
        unset($srcItem['templateid']);
        $srcItem['hostid'] = $dstHostId;
        $srcItem['applications'] = get_same_applications_for_host(zbx_objectValues($srcItem['applications'], 'applicationid'), $dstHostId);
    }
    return API::Item()->create($srcItems);
}
 private static function item($action, $params)
 {
     CItem::$error = array();
     switch ($action) {
         default:
             $result = call_user_func(array('CItem', $action), $params);
     }
     self::$result = $result;
 }
Beispiel #8
0
 $proxies = zbx_toHash($proxies, 'proxyid');
 // ordering && paging
 order_result($proxies, $sortfield, $sortorder);
 $paging = getPagingLine($proxies);
 // --
 // CALCULATE PERFORMANCE {{{
 $proxyids = array_keys($proxies);
 $sql = 'SELECT h.proxy_hostid, sum(1.0/i.delay) as qps ' . ' FROM items i,hosts h ' . ' WHERE i.status=' . ITEM_STATUS_ACTIVE . ' AND i.hostid=h.hostid ' . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND i.delay<>0' . ' AND ' . DBcondition('h.proxy_hostid', $proxyids) . ' GROUP BY h.proxy_hostid';
 $db_perf = DBselect($sql);
 while ($perf = DBfetch($db_perf)) {
     $proxies[$perf['proxy_hostid']]['perf'] = round($perf['qps'], 2);
 }
 // }}} CALCULATE PERFORMANCE
 // CALCULATE ITEMS {{{
 $options = array('groupCount' => 1, 'countOutput' => 1, 'proxyids' => $proxyids, 'webitems' => 1, 'monitored' => 1);
 $proxy_items = CItem::get($options);
 foreach ($proxy_items as $pitems) {
     if (!isset($proxies[$pitems['proxy_hostid']]['item_count'])) {
         $proxies[$pitems['proxy_hostid']]['item_count'] = 0;
     }
     $proxies[$pitems['proxy_hostid']]['item_count'] += $pitems['rowscount'];
 }
 // }}} CALCULATE ITEMS
 foreach ($proxies as $pnum => $proxy) {
     $hosts = array();
     foreach ($proxy['hosts'] as $host) {
         $style = $host['status'] == HOST_STATUS_MONITORED ? 'off' : ($host['status'] == HOST_STATUS_TEMPLATE ? 'unknown' : 'on');
         $hosts[] = new CLink($host['host'], 'hosts.php?form=update&hostid=' . $host['hostid'], $style);
         $hosts[] = ', ';
     }
     array_pop($hosts);
Beispiel #9
0
function insert_host_form()
{
    global $USER_DETAILS;
    $host_groups = get_request('groups', array());
    if (isset($_REQUEST['groupid']) && $_REQUEST['groupid'] > 0 && empty($host_groups)) {
        array_push($host_groups, $_REQUEST['groupid']);
    }
    $newgroup = get_request('newgroup', '');
    $host = get_request('host', '');
    $port = get_request('port', CProfile::get('HOST_PORT', 10050));
    $status = get_request('status', HOST_STATUS_MONITORED);
    $useip = get_request('useip', 1);
    $dns = get_request('dns', '');
    $ip = get_request('ip', '0.0.0.0');
    $proxy_hostid = get_request('proxy_hostid', '');
    $useipmi = get_request('useipmi', 'no');
    $ipmi_ip = get_request('ipmi_ip', '');
    $ipmi_port = get_request('ipmi_port', 623);
    $ipmi_authtype = get_request('ipmi_authtype', -1);
    $ipmi_privilege = get_request('ipmi_privilege', 2);
    $ipmi_username = get_request('ipmi_username', '');
    $ipmi_password = get_request('ipmi_password', '');
    $useprofile = get_request('useprofile', 'no');
    $devicetype = get_request('devicetype', '');
    $name = get_request('name', '');
    $os = get_request('os', '');
    $serialno = get_request('serialno', '');
    $tag = get_request('tag', '');
    $macaddress = get_request('macaddress', '');
    $hardware = get_request('hardware', '');
    $software = get_request('software', '');
    $contact = get_request('contact', '');
    $location = get_request('location', '');
    $notes = get_request('notes', '');
    $_REQUEST['hostid'] = get_request('hostid', 0);
    // BEGIN: HOSTS PROFILE EXTENDED Section
    $useprofile_ext = get_request('useprofile_ext', 'no');
    $ext_host_profiles = get_request('ext_host_profiles', array());
    // END:   HOSTS PROFILE EXTENDED Section
    $templates = get_request('templates', array());
    $clear_templates = get_request('clear_templates', array());
    $frm_title = S_HOST;
    if ($_REQUEST['hostid'] > 0) {
        $db_host = get_host_by_hostid($_REQUEST['hostid']);
        $frm_title .= SPACE . ' [' . $db_host['host'] . ']';
        $original_templates = get_templates_by_hostid($_REQUEST['hostid']);
    } else {
        $original_templates = array();
    }
    if ($_REQUEST['hostid'] > 0 && !isset($_REQUEST['form_refresh'])) {
        $proxy_hostid = $db_host['proxy_hostid'];
        $host = $db_host['host'];
        $port = $db_host['port'];
        $status = $db_host['status'];
        $useip = $db_host['useip'];
        $useipmi = $db_host['useipmi'] ? 'yes' : 'no';
        $ip = $db_host['ip'];
        $dns = $db_host['dns'];
        $ipmi_ip = $db_host['ipmi_ip'];
        $ipmi_port = $db_host['ipmi_port'];
        $ipmi_authtype = $db_host['ipmi_authtype'];
        $ipmi_privilege = $db_host['ipmi_privilege'];
        $ipmi_username = $db_host['ipmi_username'];
        $ipmi_password = $db_host['ipmi_password'];
        // add groups
        $options = array('hostids' => $_REQUEST['hostid']);
        $host_groups = CHostGroup::get($options);
        $host_groups = zbx_objectValues($host_groups, 'groupid');
        // read profile
        $db_profiles = DBselect('SELECT * FROM hosts_profiles WHERE hostid=' . $_REQUEST['hostid']);
        $useprofile = 'no';
        $db_profile = DBfetch($db_profiles);
        if ($db_profile) {
            $useprofile = 'yes';
            $devicetype = $db_profile['devicetype'];
            $name = $db_profile['name'];
            $os = $db_profile['os'];
            $serialno = $db_profile['serialno'];
            $tag = $db_profile['tag'];
            $macaddress = $db_profile['macaddress'];
            $hardware = $db_profile['hardware'];
            $software = $db_profile['software'];
            $contact = $db_profile['contact'];
            $location = $db_profile['location'];
            $notes = $db_profile['notes'];
        }
        // BEGIN: HOSTS PROFILE EXTENDED Section
        $useprofile_ext = 'no';
        $db_profiles_alt = DBselect('SELECT * FROM hosts_profiles_ext WHERE hostid=' . $_REQUEST['hostid']);
        if ($ext_host_profiles = DBfetch($db_profiles_alt)) {
            $useprofile_ext = 'yes';
        } else {
            $ext_host_profiles = array();
        }
        // END:   HOSTS PROFILE EXTENDED Section
        $templates = $original_templates;
    }
    $ext_profiles_fields = array('device_alias' => S_DEVICE_ALIAS, 'device_type' => S_DEVICE_TYPE, 'device_chassis' => S_DEVICE_CHASSIS, 'device_os' => S_DEVICE_OS, 'device_os_short' => S_DEVICE_OS_SHORT, 'device_hw_arch' => S_DEVICE_HW_ARCH, 'device_serial' => S_DEVICE_SERIAL, 'device_model' => S_DEVICE_MODEL, 'device_tag' => S_DEVICE_TAG, 'device_vendor' => S_DEVICE_VENDOR, 'device_contract' => S_DEVICE_CONTRACT, 'device_who' => S_DEVICE_WHO, 'device_status' => S_DEVICE_STATUS, 'device_app_01' => S_DEVICE_APP_01, 'device_app_02' => S_DEVICE_APP_02, 'device_app_03' => S_DEVICE_APP_03, 'device_app_04' => S_DEVICE_APP_04, 'device_app_05' => S_DEVICE_APP_05, 'device_url_1' => S_DEVICE_URL_1, 'device_url_2' => S_DEVICE_URL_2, 'device_url_3' => S_DEVICE_URL_3, 'device_networks' => S_DEVICE_NETWORKS, 'device_notes' => S_DEVICE_NOTES, 'device_hardware' => S_DEVICE_HARDWARE, 'device_software' => S_DEVICE_SOFTWARE, 'ip_subnet_mask' => S_IP_SUBNET_MASK, 'ip_router' => S_IP_ROUTER, 'ip_macaddress' => S_IP_MACADDRESS, 'oob_ip' => S_OOB_IP, 'oob_subnet_mask' => S_OOB_SUBNET_MASK, 'oob_router' => S_OOB_ROUTER, 'date_hw_buy' => S_DATE_HW_BUY, 'date_hw_install' => S_DATE_HW_INSTALL, 'date_hw_expiry' => S_DATE_HW_EXPIRY, 'date_hw_decomm' => S_DATE_HW_DECOMM, 'site_street_1' => S_SITE_STREET_1, 'site_street_2' => S_SITE_STREET_2, 'site_street_3' => S_SITE_STREET_3, 'site_city' => S_SITE_CITY, 'site_state' => S_SITE_STATE, 'site_country' => S_SITE_COUNTRY, 'site_zip' => S_SITE_ZIP, 'site_rack' => S_SITE_RACK, 'site_notes' => S_SITE_NOTES, 'poc_1_name' => S_POC_1_NAME, 'poc_1_email' => S_POC_1_EMAIL, 'poc_1_phone_1' => S_POC_1_PHONE_1, 'poc_1_phone_2' => S_POC_1_PHONE_2, 'poc_1_cell' => S_POC_1_CELL, 'poc_1_screen' => S_POC_1_SCREEN, 'poc_1_notes' => S_POC_1_NOTES, 'poc_2_name' => S_POC_2_NAME, 'poc_2_email' => S_POC_2_EMAIL, 'poc_2_phone_1' => S_POC_2_PHONE_1, 'poc_2_phone_2' => S_POC_2_PHONE_2, 'poc_2_cell' => S_POC_2_CELL, 'poc_2_screen' => S_POC_2_SCREEN, 'poc_2_notes' => S_POC_2_NOTES);
    foreach ($ext_profiles_fields as $field => $caption) {
        if (!isset($ext_host_profiles[$field])) {
            $ext_host_profiles[$field] = '';
        }
    }
    $clear_templates = array_intersect($clear_templates, array_keys($original_templates));
    $clear_templates = array_diff($clear_templates, array_keys($templates));
    natcasesort($templates);
    $frmHost = new CForm('hosts.php', 'post');
    $frmHost->setName('web.hosts.host.php.');
    //		$frmHost->setHelp('web.hosts.host.php');
    //		$frmHost->addVar('config',get_request('config',0));
    $frmHost->addVar('form', get_request('form', 1));
    $from_rfr = get_request('form_refresh', 0);
    $frmHost->addVar('form_refresh', $from_rfr + 1);
    $frmHost->addVar('clear_templates', $clear_templates);
    // HOST WIDGET {
    $host_tbl = new CTable('', 'tablestripped');
    $host_tbl->setOddRowClass('form_odd_row');
    $host_tbl->setEvenRowClass('form_even_row');
    if ($_REQUEST['hostid'] > 0) {
        $frmHost->addVar('hostid', $_REQUEST['hostid']);
    }
    if ($_REQUEST['groupid'] > 0) {
        $frmHost->addVar('groupid', $_REQUEST['groupid']);
    }
    $host_tbl->addRow(array(S_NAME, new CTextBox('host', $host, 54)));
    $grp_tb = new CTweenBox($frmHost, 'groups', $host_groups, 10);
    $all_groups = CHostGroup::get(array('editable' => 1, 'extendoutput' => 1));
    order_result($all_groups, 'name');
    foreach ($all_groups as $group) {
        $grp_tb->addItem($group['groupid'], $group['name']);
    }
    $host_tbl->addRow(array(S_GROUPS, $grp_tb->get(S_IN_GROUPS, S_OTHER_GROUPS)));
    $host_tbl->addRow(array(S_NEW_GROUP, new CTextBox('newgroup', $newgroup)));
    // onchange does not work on some browsers: MacOS, KDE browser
    $host_tbl->addRow(array(S_DNS_NAME, new CTextBox('dns', $dns, '40')));
    if (defined('ZBX_HAVE_IPV6')) {
        $host_tbl->addRow(array(S_IP_ADDRESS, new CTextBox('ip', $ip, '39')));
    } else {
        $host_tbl->addRow(array(S_IP_ADDRESS, new CTextBox('ip', $ip, '15')));
    }
    $cmbConnectBy = new CComboBox('useip', $useip);
    $cmbConnectBy->addItem(0, S_DNS_NAME);
    $cmbConnectBy->addItem(1, S_IP_ADDRESS);
    $host_tbl->addRow(array(S_CONNECT_TO, $cmbConnectBy));
    $host_tbl->addRow(array(S_AGENT_PORT, new CNumericBox('port', $port, 5)));
    //Proxy
    $cmbProxy = new CComboBox('proxy_hostid', $proxy_hostid);
    $cmbProxy->addItem(0, S_NO_PROXY);
    $options = array('extendoutput' => 1);
    $db_proxies = CProxy::get($options);
    order_result($db_proxies, 'host');
    foreach ($db_proxies as $proxy) {
        $cmbProxy->addItem($proxy['proxyid'], $proxy['host']);
    }
    $host_tbl->addRow(array(S_MONITORED_BY_PROXY, $cmbProxy));
    //----------
    $cmbStatus = new CComboBox('status', $status);
    $cmbStatus->addItem(HOST_STATUS_MONITORED, S_MONITORED);
    $cmbStatus->addItem(HOST_STATUS_NOT_MONITORED, S_NOT_MONITORED);
    $host_tbl->addRow(array(S_STATUS, $cmbStatus));
    $host_tbl->addRow(array(S_USEIPMI, new CCheckBox('useipmi', $useipmi, 'submit()')));
    if ($useipmi == 'yes') {
        $host_tbl->addRow(array(S_IPMI_IP_ADDRESS, new CTextBox('ipmi_ip', $ipmi_ip, defined('ZBX_HAVE_IPV6') ? 39 : 15)));
        $host_tbl->addRow(array(S_IPMI_PORT, new CNumericBox('ipmi_port', $ipmi_port, 5)));
        $cmbIPMIAuthtype = new CComboBox('ipmi_authtype', $ipmi_authtype);
        $cmbIPMIAuthtype->addItem(IPMI_AUTHTYPE_DEFAULT, S_AUTHTYPE_DEFAULT);
        $cmbIPMIAuthtype->addItem(IPMI_AUTHTYPE_NONE, S_AUTHTYPE_NONE);
        $cmbIPMIAuthtype->addItem(IPMI_AUTHTYPE_MD2, S_AUTHTYPE_MD2);
        $cmbIPMIAuthtype->addItem(IPMI_AUTHTYPE_MD5, S_AUTHTYPE_MD5);
        $cmbIPMIAuthtype->addItem(IPMI_AUTHTYPE_STRAIGHT, S_AUTHTYPE_STRAIGHT);
        $cmbIPMIAuthtype->addItem(IPMI_AUTHTYPE_OEM, S_AUTHTYPE_OEM);
        $cmbIPMIAuthtype->addItem(IPMI_AUTHTYPE_RMCP_PLUS, S_AUTHTYPE_RMCP_PLUS);
        $host_tbl->addRow(array(S_IPMI_AUTHTYPE, $cmbIPMIAuthtype));
        $cmbIPMIPrivilege = new CComboBox('ipmi_privilege', $ipmi_privilege);
        $cmbIPMIPrivilege->addItem(IPMI_PRIVILEGE_CALLBACK, S_PRIVILEGE_CALLBACK);
        $cmbIPMIPrivilege->addItem(IPMI_PRIVILEGE_USER, S_PRIVILEGE_USER);
        $cmbIPMIPrivilege->addItem(IPMI_PRIVILEGE_OPERATOR, S_PRIVILEGE_OPERATOR);
        $cmbIPMIPrivilege->addItem(IPMI_PRIVILEGE_ADMIN, S_PRIVILEGE_ADMIN);
        $cmbIPMIPrivilege->addItem(IPMI_PRIVILEGE_OEM, S_PRIVILEGE_OEM);
        $host_tbl->addRow(array(S_IPMI_PRIVILEGE, $cmbIPMIPrivilege));
        $host_tbl->addRow(array(S_IPMI_USERNAME, new CTextBox('ipmi_username', $ipmi_username, 16)));
        $host_tbl->addRow(array(S_IPMI_PASSWORD, new CTextBox('ipmi_password', $ipmi_password, 20)));
    } else {
        $frmHost->addVar('ipmi_ip', $ipmi_ip);
        $frmHost->addVar('ipmi_port', $ipmi_port);
        $frmHost->addVar('ipmi_authtype', $ipmi_authtype);
        $frmHost->addVar('ipmi_privilege', $ipmi_privilege);
        $frmHost->addVar('ipmi_username', $ipmi_username);
        $frmHost->addVar('ipmi_password', $ipmi_password);
    }
    if ($_REQUEST['form'] == 'full_clone') {
        // Host items
        $options = array('inherited' => 0, 'hostids' => $_REQUEST['hostid'], 'output' => API_OUTPUT_EXTEND, 'webitems' => 1);
        $host_items = CItem::get($options);
        if (!empty($host_items)) {
            $items_lbx = new CListBox('items', null, 8);
            $items_lbx->setAttribute('disabled', 'disabled');
            order_result($host_items, 'description');
            foreach ($host_items as $hitem) {
                $items_lbx->addItem($hitem['itemid'], item_description($hitem));
            }
            $host_tbl->addRow(array(S_ITEMS, $items_lbx));
        }
        // Host triggers
        $options = array('inherited' => 0, 'hostids' => $_REQUEST['hostid'], 'output' => API_OUTPUT_EXTEND, 'expandDescription' => true);
        $host_triggers = CTrigger::get($options);
        if (!empty($host_triggers)) {
            $trig_lbx = new CListBox('triggers', null, 8);
            $trig_lbx->setAttribute('disabled', 'disabled');
            order_result($host_triggers, 'description');
            foreach ($host_triggers as $htrigger) {
                $trig_lbx->addItem($htrigger['triggerid'], $htrigger['description']);
            }
            $host_tbl->addRow(array(S_TRIGGERS, $trig_lbx));
        }
        // Host graphs
        $options = array('inherited' => 0, 'hostids' => $_REQUEST['hostid'], 'select_hosts' => API_OUTPUT_REFER, 'output' => API_OUTPUT_EXTEND);
        $host_graphs = CGraph::get($options);
        if (!empty($host_graphs)) {
            $graphs_lbx = new CListBox('graphs', null, 8);
            $graphs_lbx->setAttribute('disabled', 'disabled');
            order_result($host_graphs, 'name');
            foreach ($host_graphs as $hgraph) {
                if (count($hgraph['hosts']) > 1) {
                    continue;
                }
                $graphs_lbx->addItem($hgraph['graphid'], $hgraph['name']);
            }
            if ($graphs_lbx->ItemsCount() > 1) {
                $host_tbl->addRow(array(S_GRAPHS, $graphs_lbx));
            }
        }
    }
    $host_footer = array();
    $host_footer[] = new CButton('save', S_SAVE);
    if ($_REQUEST['hostid'] > 0 && $_REQUEST['form'] != 'full_clone') {
        array_push($host_footer, SPACE, new CButton('clone', S_CLONE), SPACE, new CButton('full_clone', S_FULL_CLONE), SPACE, new CButtonDelete(S_DELETE_SELECTED_HOST_Q, url_param('form') . url_param('hostid') . url_param('groupid')));
    }
    array_push($host_footer, SPACE, new CButtonCancel(url_param('groupid')));
    $host_footer = new CCol($host_footer);
    $host_footer->setColSpan(2);
    $host_tbl->setFooter($host_footer);
    $host_wdgt = new CWidget();
    $host_wdgt->setClass('header');
    $host_wdgt->addHeader($frm_title);
    $host_wdgt->addItem($host_tbl);
    // } HOST WIDGET
    // TEMPLATES{
    $template_tbl = new CTableInfo(S_NO_TEMPLATES_LINKED, 'tablestripped');
    $template_tbl->setOddRowClass('form_odd_row');
    $template_tbl->setEvenRowClass('form_even_row');
    foreach ($templates as $id => $temp_name) {
        $frmHost->addVar('templates[' . $id . ']', $temp_name);
        $template_tbl->addRow(new CCol(array(new CCheckBox('templates_rem[' . $id . ']', 'no', null, $id), $temp_name)));
    }
    $footer = new CCol(array(new CButton('add_template', S_ADD, "return PopUp('popup.php?dstfrm=" . $frmHost->getName() . "&dstfld1=new_template&srctbl=templates&srcfld1=hostid&srcfld2=host" . url_param($templates, false, 'existed_templates') . "',450,450)", 'T'), SPACE, new CButton('unlink', S_UNLINK), SPACE, new CButton('unlink_and_clear', S_UNLINK_AND_CLEAR)));
    //$footer->setColSpan(2);
    $template_tbl->setFooter($footer);
    $template_wdgt = new CWidget();
    $template_wdgt->setClass('header');
    $template_wdgt->addHeader(S_LINKED_TEMPLATES);
    $template_wdgt->addItem($template_tbl);
    // } TEMPLATES
    // MACROS WIDGET {
    $macros_wdgt = get_macros_widget($_REQUEST['hostid']);
    // } MACROS WIDGET
    // PROFILE WIDGET {
    $profile_tbl = new CTable('', 'tablestripped');
    $profile_tbl->setOddRowClass('form_odd_row');
    $profile_tbl->setEvenRowClass('form_even_row');
    $profile_tbl->addRow(array(S_USE_PROFILE, new CCheckBox('useprofile', $useprofile, 'submit()')));
    if ($useprofile == 'yes') {
        $profile_tbl->addRow(array(S_DEVICE_TYPE, new CTextBox('devicetype', $devicetype, 61)));
        $profile_tbl->addRow(array(S_NAME, new CTextBox('name', $name, 61)));
        $profile_tbl->addRow(array(S_OS, new CTextBox('os', $os, 61)));
        $profile_tbl->addRow(array(S_SERIALNO, new CTextBox('serialno', $serialno, 61)));
        $profile_tbl->addRow(array(S_TAG, new CTextBox('tag', $tag, 61)));
        $profile_tbl->addRow(array(S_MACADDRESS, new CTextBox('macaddress', $macaddress, 61)));
        $profile_tbl->addRow(array(S_HARDWARE, new CTextArea('hardware', $hardware, 60, 4)));
        $profile_tbl->addRow(array(S_SOFTWARE, new CTextArea('software', $software, 60, 4)));
        $profile_tbl->addRow(array(S_CONTACT, new CTextArea('contact', $contact, 60, 4)));
        $profile_tbl->addRow(array(S_LOCATION, new CTextArea('location', $location, 60, 4)));
        $profile_tbl->addRow(array(S_NOTES, new CTextArea('notes', $notes, 60, 4)));
    } else {
        $frmHost->addVar('devicetype', $devicetype);
        $frmHost->addVar('name', $name);
        $frmHost->addVar('os', $os);
        $frmHost->addVar('serialno', $serialno);
        $frmHost->addVar('tag', $tag);
        $frmHost->addVar('macaddress', $macaddress);
        $frmHost->addVar('hardware', $hardware);
        $frmHost->addVar('software', $software);
        $frmHost->addVar('contact', $contact);
        $frmHost->addVar('location', $location);
        $frmHost->addVar('notes', $notes);
    }
    $profile_wdgt = new CWidget();
    $profile_wdgt->setClass('header');
    $profile_wdgt->addHeader(S_PROFILE);
    $profile_wdgt->addItem($profile_tbl);
    // } PROFILE WIDGET
    // EXT PROFILE WIDGET {
    $ext_profile_tbl = new CTable('', 'tablestripped');
    $ext_profile_tbl->setOddRowClass('form_odd_row');
    $ext_profile_tbl->setEvenRowClass('form_even_row');
    $ext_profile_tbl->addRow(array(S_USE_EXTENDED_PROFILE, new CCheckBox('useprofile_ext', $useprofile_ext, 'submit()', 'yes')));
    foreach ($ext_profiles_fields as $prof_field => $caption) {
        if ($useprofile_ext == 'yes') {
            $ext_profile_tbl->addRow(array($caption, new CTextBox('ext_host_profiles[' . $prof_field . ']', $ext_host_profiles[$prof_field], 40)));
        } else {
            $frmHost->addVar('ext_host_profiles[' . $prof_field . ']', $ext_host_profiles[$prof_field]);
        }
    }
    $ext_profile_wdgt = new CWidget();
    $ext_profile_wdgt->setClass('header');
    $ext_profile_wdgt->addHeader(S_EXTENDED_HOST_PROFILE);
    $ext_profile_wdgt->addItem($ext_profile_tbl);
    // } EXT PROFILE WIDGET
    $left_table = new CTable();
    $left_table->setCellPadding(4);
    $left_table->setCellSpacing(4);
    $left_table->addRow($host_wdgt);
    $right_table = new CTable();
    $right_table->setCellPadding(4);
    $right_table->setCellSpacing(4);
    $right_table->addRow($template_wdgt);
    $right_table->addRow($macros_wdgt);
    $right_table->addRow($profile_wdgt);
    $right_table->addRow($ext_profile_wdgt);
    $td_l = new CCol($left_table);
    $td_l->setAttribute('valign', 'top');
    $td_r = new CCol($right_table);
    $td_r->setAttribute('valign', 'top');
    $outer_table = new CTable();
    $outer_table->addRow(array($td_l, $td_r));
    $frmHost->addItem($outer_table);
    return $frmHost;
}
<?php 
}
echo SBR;
$form = new CFormTable(S_CONDITION);
$form->SetName('expression');
$form->addVar('dstfrm', $dstfrm);
$form->addVar('dstfld1', $dstfld1);
$form->addVar('itemid', $itemid);
$form->addRow(S_ITEM, array(new CTextBox('description', $description, 50, 'yes'), new CButton('select', S_SELECT, "return PopUp('popup.php?dstfrm=" . $form->GetName() . "&dstfld1=itemid&dstfld2=description&submitParent=1&" . "srctbl=items&srcfld1=itemid&srcfld2=description',0,0,'zbx_popup_item');")));
$cmbFnc = new CComboBox('expr_type', $expr_type, 'submit()');
$cmbFnc->addStyle('width: auto;');
//If user has already selected an item
if (isset($_REQUEST['itemid'])) {
    //getting type of return value for the item user selected
    $options = array('itemids' => array($_REQUEST['itemid']), 'output' => API_OUTPUT_EXTEND);
    $selectedItems = CItem::get($options);
    if ($selectedItem = reset($selectedItems)) {
        $itemValueType = $selectedItem['value_type'];
    }
}
foreach ($functions as $id => $f) {
    foreach ($f['operators'] as $op => $txt_op) {
        //if user has selected an item, we are filtering out the triggers that can't work with it
        if (!isset($itemValueType) || isset($f['allowed_types'][$itemValueType])) {
            $cmbFnc->addItem($id . '[' . $op . ']', str_replace('{OP}', $txt_op, $f['description']));
        }
    }
}
$form->addRow(S_FUNCTION, $cmbFnc);
if (isset($functions[$function]['params'])) {
    foreach ($functions[$function]['params'] as $pid => $pf) {
Beispiel #11
0
 // SELECT GRAPH ITEMS
 $graphids = zbx_objectValues($graphs, 'graphid');
 $params = array('graphids' => $graphids, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1, 'expandData' => 1);
 $gitems = CGraphItem::get($params);
 foreach ($gitems as $gnum => $gitem) {
     $gitems[$gitem['gitemid']]['host_key_'] = $gitem['host'] . ':' . $gitem['key_'];
 }
 // SELECT TEMPLATES
 $params = array('hostids' => $hostids, 'preservekeys' => 1, 'output' => API_OUTPUT_EXTEND);
 $templates = CTemplate::get($params);
 // SELECT MACROS
 $params = array('hostids' => $hostids, 'preservekeys' => 1, 'output' => API_OUTPUT_EXTEND);
 $macros = CUserMacro::get($params);
 // SELECT ITEMS
 $params = array('hostids' => $hostids, 'preservekeys' => 1, 'output' => API_OUTPUT_EXTEND);
 $items = CItem::get($params);
 // SELECT APPLICATIONS
 $itemids = zbx_objectValues($items, 'itemid');
 //sdii($itemids);
 $params = array('itemids' => $itemids, 'preservekeys' => 1, 'output' => API_OUTPUT_EXTEND);
 $applications = Capplication::get($params);
 //sdii($applications);
 // SELECT TRIGGERS
 $params = array('hostids' => $hostids, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1, 'select_dependencies' => API_OUTPUT_EXTEND, 'expandData' => 1);
 $triggers = CTrigger::get($params);
 foreach ($triggers as $tnum => $trigger) {
     $triggers[$trigger['triggerid']]['expression'] = explode_exp($trigger['expression'], false);
 }
 // SELECT TRIGGER DEPENDENCIES
 $dependencies = array();
 foreach ($triggers as $tnum => $trigger) {
 /**
  * Get Triggers data
  *
  * @param _array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['triggerids']
  * @param array $options['applicationids']
  * @param array $options['status']
  * @param array $options['editable']
  * @param array $options['extendoutput']
  * @param array $options['count']
  * @param array $options['pattern']
  * @param array $options['limit']
  * @param array $options['order']
  * @return array|int item data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $result = array();
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $sort_columns = array('triggerid', 'description', 'status', 'priority', 'lastchange');
     // allowed columns for sorting
     $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     // allowed output options for [ select_* ] params
     $sql_parts = array('select' => array('triggers' => 't.triggerid'), 'from' => array('t' => 'triggers t'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'triggerids' => null, 'itemids' => null, 'applicationids' => null, 'functions' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'active' => null, 'maintenance' => null, 'withUnacknowledgedEvents' => null, 'withAcknowledgedEvents' => null, 'withLastEventUnacknowledged' => null, 'skipDependent' => null, 'nopermissions' => null, 'editable' => null, 'lastChangeSince' => null, 'lastChangeTill' => null, 'group' => null, 'host' => null, 'only_true' => null, 'min_severity' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'expandData' => null, 'expandDescription' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_groups' => null, 'select_hosts' => null, 'select_items' => null, 'select_functions' => null, 'select_dependencies' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($def_options, $options);
     if (!is_null($options['extendoutput'])) {
         $options['output'] = API_OUTPUT_EXTEND;
         if (!is_null($options['select_hosts'])) {
             $options['select_hosts'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_items'])) {
             $options['select_items'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_dependencies'])) {
             $options['select_dependencies'] = API_OUTPUT_EXTEND;
         }
     }
     if (is_array($options['output'])) {
         unset($sql_parts['select']['triggers']);
         foreach ($options['output'] as $key => $field) {
             $sql_parts['select'][$field] = ' t.' . $field;
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         /*/
         			$sql_parts['where'][] = ' EXISTS(  '.
         						' SELECT tt.triggerid  '.
         						' FROM triggers tt,functions ff,items ii,hosts_groups hgg,rights rr,users_groups ugg '.
         						' WHERE t.triggerid=tt.triggerid  '.
         							' AND ff.triggerid=tt.triggerid  '.
         							' AND ff.itemid=ii.itemid  '.
         							' AND hgg.hostid=ii.hostid  '.
         							' AND rr.id=hgg.groupid  '.
         							' AND rr.groupid=ugg.usrgrpid  '.
         							' AND ugg.userid='.$userid.
         							' AND rr.permission>='.$permission.
         							' AND NOT EXISTS(  '.
         								' SELECT fff.triggerid  '.
         								' FROM functions fff, items iii  '.
         								' WHERE fff.triggerid=tt.triggerid '.
         									' AND fff.itemid=iii.itemid '.		'    '.
         									' AND EXISTS( '.
         										' SELECT hggg.groupid '.
         										' FROM hosts_groups hggg, rights rrr, users_groups uggg '.
         										' WHERE hggg.hostid=iii.hostid '.
         											' AND rrr.id=hggg.groupid '.
         											' AND rrr.groupid=uggg.usrgrpid '.
         											' AND uggg.userid='.$userid.
         											' AND rrr.permission<'.$permission.
         										' ) '.
         								' ) '.
         						' ) ';
         //*/
         //*/
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['from']['rights'] = 'rights r';
         $sql_parts['from']['users_groups'] = 'users_groups ug';
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where'][] = 'r.id=hg.groupid ';
         $sql_parts['where'][] = 'r.groupid=ug.usrgrpid';
         $sql_parts['where'][] = 'ug.userid=' . $userid;
         $sql_parts['where'][] = 'r.permission>=' . $permission;
         $sql_parts['where'][] = 'NOT EXISTS( ' . ' SELECT ff.triggerid ' . ' FROM functions ff, items ii ' . ' WHERE ff.triggerid=t.triggerid ' . ' AND ff.itemid=ii.itemid ' . ' AND EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups gg ' . ' WHERE hgg.hostid=ii.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . '))';
         //*/
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['groupid'] = 'hg.groupid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         $sql_parts['where']['groupid'] = DBcondition('hg.groupid', $options['groupids']);
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['hg'] = 'hg.groupid';
         }
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if (!is_null($options['hostids'])) {
             zbx_value2array($options['hostids']);
             $options['hostids'] = array_merge($options['hostids'], $options['templateids']);
         } else {
             $options['hostids'] = $options['templateids'];
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['hostid'] = 'i.hostid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where']['hostid'] = DBcondition('i.hostid', $options['hostids']);
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['i'] = 'i.hostid';
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         $sql_parts['where']['triggerid'] = DBcondition('t.triggerid', $options['triggerids']);
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['itemid'] = 'f.itemid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['where']['itemid'] = DBcondition('f.itemid', $options['itemids']);
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['applicationid'] = 'a.applicationid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['applications'] = 'applications a';
         $sql_parts['where']['a'] = DBcondition('a.applicationid', $options['applicationids']);
         $sql_parts['where']['ia'] = 'i.hostid=a.hostid';
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // functions
     if (!is_null($options['functions'])) {
         zbx_value2array($options['functions']);
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where'][] = DBcondition('f.function', $options['functions'], false, true);
     }
     // monitored
     if (!is_null($options['monitored'])) {
         $sql_parts['where']['monitored'] = '' . ' NOT EXISTS (' . ' SELECT ff.functionid' . ' FROM functions ff' . ' WHERE ff.triggerid=t.triggerid' . ' AND EXISTS (' . ' SELECT ii.itemid' . ' FROM items ii, hosts hh' . ' WHERE ff.itemid=ii.itemid' . ' AND hh.hostid=ii.hostid' . ' AND (' . ' ii.status<>' . ITEM_STATUS_ACTIVE . ' OR hh.status<>' . HOST_STATUS_MONITORED . ' )' . ' )' . ' )';
         $sql_parts['where']['status'] = 't.status=' . TRIGGER_STATUS_ENABLED;
     }
     // active
     if (!is_null($options['active'])) {
         $sql_parts['where']['active'] = '' . ' NOT EXISTS (' . ' SELECT ff.functionid' . ' FROM functions ff' . ' WHERE ff.triggerid=t.triggerid' . ' AND EXISTS (' . ' SELECT ii.itemid' . ' FROM items ii, hosts hh' . ' WHERE ff.itemid=ii.itemid' . ' AND hh.hostid=ii.hostid' . ' AND  hh.status<>' . HOST_STATUS_MONITORED . ' )' . ' )';
         $sql_parts['where']['status'] = 't.status=' . TRIGGER_STATUS_ENABLED;
     }
     // maintenance
     if (!is_null($options['maintenance'])) {
         $sql_parts['where'][] = ($options['maintenance'] == 0 ? ' NOT ' : '') . ' EXISTS (' . ' SELECT ff.functionid' . ' FROM functions ff' . ' WHERE ff.triggerid=t.triggerid' . ' AND EXISTS (' . ' SELECT ii.itemid' . ' FROM items ii, hosts hh' . ' WHERE ff.itemid=ii.itemid' . ' AND hh.hostid=ii.hostid' . ' AND hh.maintenance_status=1' . ' )' . ' )';
         $sql_parts['where'][] = 't.status=' . TRIGGER_STATUS_ENABLED;
     }
     // lastChangeSince
     if (!is_null($options['lastChangeSince'])) {
         $sql_parts['where']['lastchangesince'] = 't.lastchange>' . $options['lastChangeSince'];
     }
     // lastChangeTill
     if (!is_null($options['lastChangeTill'])) {
         $sql_parts['where']['lastchangetill'] = 't.lastchange<' . $options['lastChangeTill'];
     }
     // withUnacknowledgedEvents
     if (!is_null($options['withUnacknowledgedEvents'])) {
         $sql_parts['where']['unack'] = ' EXISTS(' . ' SELECT e.eventid' . ' FROM events e' . ' WHERE e.objectid=t.triggerid' . ' AND e.object=0' . ' AND e.value=' . TRIGGER_VALUE_TRUE . ' AND e.acknowledged=0)';
     }
     // withAcknowledgedEvents
     if (!is_null($options['withAcknowledgedEvents'])) {
         $sql_parts['where']['ack'] = 'NOT EXISTS(' . ' SELECT e.eventid' . ' FROM events e' . ' WHERE e.objectid=t.triggerid' . ' AND e.object=0' . ' AND e.value=' . TRIGGER_VALUE_TRUE . ' AND e.acknowledged=0)';
     }
     // templated
     if (!is_null($options['templated'])) {
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['templated']) {
             $sql_parts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sql_parts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sql_parts['where'][] = 't.templateid<>0';
         } else {
             $sql_parts['where'][] = 't.templateid=0';
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('triggers t', $options, $sql_parts);
     }
     // --- FILTER ---
     if (is_array($options['filter'])) {
         zbx_db_filter('triggers t', $options, $sql_parts);
         if (isset($options['filter']['host']) && !is_null($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sql_parts['from']['functions'] = 'functions f';
             $sql_parts['from']['items'] = 'items i';
             $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
             $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
             $sql_parts['from']['hosts'] = 'hosts h';
             $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
             $sql_parts['where']['host'] = DBcondition('h.host', $options['filter']['host'], false, true);
         }
         if (isset($options['filter']['hostid']) && !is_null($options['filter']['hostid'])) {
             zbx_value2array($options['filter']['hostid']);
             $sql_parts['from']['functions'] = 'functions f';
             $sql_parts['from']['items'] = 'items i';
             $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
             $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
             $sql_parts['where']['hostid'] = DBcondition('i.hostid', $options['filter']['hostid']);
         }
     }
     // group
     if (!is_null($options['group'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['name'] = 'g.name';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['from']['groups'] = 'groups g';
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where']['ghg'] = 'g.groupid = hg.groupid';
         $sql_parts['where']['group'] = ' UPPER(g.name)=' . zbx_dbstr(zbx_strtoupper($options['group']));
     }
     // host
     if (!is_null($options['host'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['host'] = 'h.host';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where']['i'] = DBcondition('i.hostid', $options['hostids']);
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         $sql_parts['where']['host'] = ' UPPER(h.host)=' . zbx_dbstr(zbx_strtoupper($options['host']));
     }
     // only_true
     if (!is_null($options['only_true'])) {
         $sql_parts['where']['ot'] = '((t.value=' . TRIGGER_VALUE_TRUE . ')' . ' OR ' . '((t.value=' . TRIGGER_VALUE_FALSE . ') AND (t.lastchange>' . (time() - TRIGGER_FALSE_PERIOD) . ')))';
     }
     // min_severity
     if (!is_null($options['min_severity'])) {
         $sql_parts['where'][] = 't.priority>=' . $options['min_severity'];
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sql_parts['select']['triggers'] = 't.*';
     }
     // expandData
     if (!is_null($options['expandData'])) {
         $sql_parts['select']['host'] = 'h.host';
         $sql_parts['select']['hostid'] = 'h.hostid';
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sql_parts['select'] = array('COUNT(DISTINCT t.triggerid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sql_parts['group'] as $key => $fields) {
                 $sql_parts['select'][$key] = $fields;
             }
         }
     }
     // order
     // restrict not allowed columns for sorting
     $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : '';
     if (!zbx_empty($options['sortfield'])) {
         $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP;
         $sql_parts['order'][] = 't.' . $options['sortfield'] . ' ' . $sortorder;
         if (!str_in_array('t.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('t.*', $sql_parts['select'])) {
             $sql_parts['select'][] = 't.' . $options['sortfield'];
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //---------------
     $triggerids = array();
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['group'] = array_unique($sql_parts['group']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_group = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= ' AND ' . implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['group'])) {
         $sql_where .= ' GROUP BY ' . implode(',', $sql_parts['group']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . DBin_node('t.triggerid', $nodeids) . $sql_where . $sql_group . $sql_order;
     //SDI($sql);
     $db_res = DBselect($sql, $sql_limit);
     while ($trigger = DBfetch($db_res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $trigger;
             } else {
                 $result = $trigger['rowscount'];
             }
         } else {
             $triggerids[$trigger['triggerid']] = $trigger['triggerid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$trigger['triggerid']] = array('triggerid' => $trigger['triggerid']);
             } else {
                 if (!isset($result[$trigger['triggerid']])) {
                     $result[$trigger['triggerid']] = array();
                 }
                 if (!is_null($options['select_hosts']) && !isset($result[$trigger['triggerid']]['hosts'])) {
                     $result[$trigger['triggerid']]['hosts'] = array();
                 }
                 if (!is_null($options['select_items']) && !isset($result[$trigger['triggerid']]['items'])) {
                     $result[$trigger['triggerid']]['items'] = array();
                 }
                 if (!is_null($options['select_functions']) && !isset($result[$trigger['triggerid']]['functions'])) {
                     $result[$trigger['triggerid']]['functions'] = array();
                 }
                 if (!is_null($options['select_dependencies']) && !isset($result[$trigger['triggerid']]['dependencies'])) {
                     $result[$trigger['triggerid']]['dependencies'] = array();
                 }
                 // groups
                 if (isset($trigger['groupid']) && is_null($options['select_groups'])) {
                     if (!isset($result[$trigger['triggerid']]['groups'])) {
                         $result[$trigger['triggerid']]['groups'] = array();
                     }
                     $result[$trigger['triggerid']]['groups'][] = array('groupid' => $trigger['groupid']);
                     unset($trigger['groupid']);
                 }
                 // hostids
                 if (isset($trigger['hostid']) && is_null($options['select_hosts'])) {
                     if (!isset($result[$trigger['triggerid']]['hosts'])) {
                         $result[$trigger['triggerid']]['hosts'] = array();
                     }
                     $result[$trigger['triggerid']]['hosts'][] = array('hostid' => $trigger['hostid']);
                     if (is_null($options['expandData'])) {
                         unset($trigger['hostid']);
                     }
                 }
                 // itemids
                 if (isset($trigger['itemid']) && is_null($options['select_items'])) {
                     if (!isset($result[$trigger['triggerid']]['items'])) {
                         $result[$trigger['triggerid']]['items'] = array();
                     }
                     $result[$trigger['triggerid']]['items'][] = array('itemid' => $trigger['itemid']);
                     unset($trigger['itemid']);
                 }
                 $result[$trigger['triggerid']] += $trigger;
             }
         }
     }
     Copt::memoryPick();
     if (!is_null($options['countOutput'])) {
         if (is_null($options['preservekeys'])) {
             $result = zbx_cleanHashes($result);
         }
         return $result;
     }
     // skipDependent
     if (!is_null($options['skipDependent'])) {
         $tids = $triggerids;
         $map = array();
         do {
             $sql = 'SELECT d.triggerid_down, d.triggerid_up, t.value ' . ' FROM trigger_depends d, triggers t ' . ' WHERE ' . DBcondition('d.triggerid_down', $tids) . ' AND d.triggerid_up=t.triggerid';
             $db_result = DBselect($sql);
             $tids = array();
             while ($row = DBfetch($db_result)) {
                 if (TRIGGER_VALUE_TRUE == $row['value']) {
                     if (isset($map[$row['triggerid_down']])) {
                         foreach ($map[$row['triggerid_down']] as $triggerid => $state) {
                             unset($result[$triggerid]);
                             unset($triggerids[$triggerid]);
                         }
                     } else {
                         unset($result[$row['triggerid_down']]);
                         unset($triggerids[$row['triggerid_down']]);
                     }
                 } else {
                     if (isset($map[$row['triggerid_down']])) {
                         if (!isset($map[$row['triggerid_up']])) {
                             $map[$row['triggerid_up']] = array();
                         }
                         $map[$row['triggerid_up']] += $map[$row['triggerid_down']];
                     } else {
                         if (!isset($map[$row['triggerid_up']])) {
                             $map[$row['triggerid_up']] = array();
                         }
                         $map[$row['triggerid_up']][$row['triggerid_down']] = 1;
                     }
                     $tids[] = $row['triggerid_up'];
                 }
             }
         } while (!empty($tids));
     }
     // withLastEventUnacknowledged
     if (!is_null($options['withLastEventUnacknowledged'])) {
         $eventids = array();
         $sql = 'SELECT max(e.eventid) as eventid, e.objectid' . ' FROM events e ' . ' WHERE e.object=' . EVENT_OBJECT_TRIGGER . ' AND ' . DBcondition('e.objectid', $triggerids) . ' AND ' . DBcondition('e.value', array(TRIGGER_VALUE_TRUE)) . ' GROUP BY e.objectid';
         $events_db = DBselect($sql);
         while ($event = DBfetch($events_db)) {
             $eventids[] = $event['eventid'];
         }
         $correct_triggerids = array();
         $sql = 'SELECT e.objectid' . ' FROM events e ' . ' WHERE ' . DBcondition('e.eventid', $eventids) . ' AND e.acknowledged=0';
         $triggers_db = DBselect($sql);
         while ($trigger = DBfetch($triggers_db)) {
             $correct_triggerids[$trigger['objectid']] = $trigger['objectid'];
         }
         foreach ($result as $triggerid => $trigger) {
             if (!isset($correct_triggerids[$triggerid])) {
                 unset($result[$triggerid]);
                 unset($triggerids[$triggerid]);
             }
         }
     }
     // Adding Objects
     // Adding trigger dependencies
     if (!is_null($options['select_dependencies']) && str_in_array($options['select_dependencies'], $subselects_allowed_outputs)) {
         $deps = array();
         $depids = array();
         $sql = 'SELECT triggerid_up, triggerid_down ' . ' FROM trigger_depends ' . ' WHERE ' . DBcondition('triggerid_down', $triggerids);
         $db_deps = DBselect($sql);
         while ($db_dep = DBfetch($db_deps)) {
             if (!isset($deps[$db_dep['triggerid_down']])) {
                 $deps[$db_dep['triggerid_down']] = array();
             }
             $deps[$db_dep['triggerid_down']][$db_dep['triggerid_up']] = $db_dep['triggerid_up'];
             $depids[] = $db_dep['triggerid_up'];
         }
         $obj_params = array('triggerids' => $depids, 'output' => $options['select_dependencies'], 'expandData' => 1, 'preservekeys' => 1);
         $allowed = self::get($obj_params);
         //allowed triggerids
         foreach ($deps as $triggerid => $deptriggers) {
             foreach ($deptriggers as $num => $deptriggerid) {
                 if (isset($allowed[$deptriggerid])) {
                     $result[$triggerid]['dependencies'][] = $allowed[$deptriggerid];
                 }
             }
         }
     }
     // Adding groups
     if (!is_null($options['select_groups']) && str_in_array($options['select_groups'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_groups'], 'triggerids' => $triggerids, 'preservekeys' => 1);
         $groups = CHostgroup::get($obj_params);
         foreach ($groups as $groupid => $group) {
             $gtriggers = $group['triggers'];
             unset($group['triggers']);
             foreach ($gtriggers as $num => $trigger) {
                 $result[$trigger['triggerid']]['groups'][] = $group;
             }
         }
     }
     // Adding hosts
     if (!is_null($options['select_hosts'])) {
         $obj_params = array('nodeids' => $nodeids, 'triggerids' => $triggerids, 'templated_hosts' => 1, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_hosts']) || str_in_array($options['select_hosts'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_hosts'];
             $hosts = CHost::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($hosts, 'host');
             }
             foreach ($hosts as $hostid => $host) {
                 unset($hosts[$hostid]['triggers']);
                 $count = array();
                 foreach ($host['triggers'] as $tnum => $trigger) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$trigger['triggerid']])) {
                             $count[$trigger['triggerid']] = 0;
                         }
                         $count[$trigger['triggerid']]++;
                         if ($count[$trigger['triggerid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$trigger['triggerid']]['hosts'][] =& $hosts[$hostid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_hosts']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $hosts = CHost::get($obj_params);
                 $hosts = zbx_toHash($hosts, 'hostid');
                 foreach ($result as $triggerid => $trigger) {
                     if (isset($hosts[$triggerid])) {
                         $result[$triggerid]['hosts'] = $hosts[$triggerid]['rowscount'];
                     } else {
                         $result[$triggerid]['hosts'] = 0;
                     }
                 }
             }
         }
     }
     // Adding Functions
     if (!is_null($options['select_functions']) && str_in_array($options['select_functions'], $subselects_allowed_outputs)) {
         if ($options['select_functions'] == API_OUTPUT_EXTEND) {
             $sql_select = 'f.*';
         } else {
             $sql_select = 'f.functionid, f.triggerid';
         }
         $sql = 'SELECT ' . $sql_select . ' FROM functions f ' . ' WHERE ' . DBcondition('f.triggerid', $triggerids);
         $res = DBselect($sql);
         while ($function = DBfetch($res)) {
             $triggerid = $function['triggerid'];
             unset($function['triggerid']);
             $result[$triggerid]['functions'][] = $function;
         }
     }
     // Adding Items
     if (!is_null($options['select_items']) && str_in_array($options['select_items'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_items'], 'triggerids' => $triggerids, 'webitems' => 1, 'nopermissions' => 1, 'preservekeys' => 1);
         $items = CItem::get($obj_params);
         foreach ($items as $itemid => $item) {
             $itriggers = $item['triggers'];
             unset($item['triggers']);
             foreach ($itriggers as $num => $trigger) {
                 $result[$trigger['triggerid']]['items'][] = $item;
             }
         }
     }
     // expandDescription
     if (!is_null($options['expandDescription'])) {
         // Function compare values {{{
         foreach ($result as $tnum => $trigger) {
             preg_match_all('/\\$([1-9])/u', $trigger['description'], $numbers);
             preg_match_all('~{[0-9]+}[+\\-\\*/<>=#]?[\\(]*(?P<val>[+\\-0-9]+)[\\)]*~u', $trigger['expression'], $matches);
             foreach ($numbers[1] as $i) {
                 $rep = isset($matches['val'][$i - 1]) ? $matches['val'][$i - 1] : '';
                 $result[$tnum]['description'] = str_replace('$' . $i, $rep, $result[$tnum]['description']);
             }
         }
         // }}}
         $functionids = array();
         $triggers_to_expand_hosts = array();
         $triggers_to_expand_items = array();
         $triggers_to_expand_items2 = array();
         foreach ($result as $tnum => $trigger) {
             preg_match_all('/{HOSTNAME([1-9]?)}/u', $trigger['description'], $hnums);
             if (!empty($hnums[1])) {
                 preg_match_all('/{([0-9]+)}/u', $trigger['expression'], $funcs);
                 $funcs = $funcs[1];
                 foreach ($hnums[1] as $fnum) {
                     $fnum = $fnum ? $fnum : 1;
                     if (isset($funcs[$fnum - 1])) {
                         $functionid = $funcs[$fnum - 1];
                         $functionids[$functionid] = $functionid;
                         $triggers_to_expand_hosts[$trigger['triggerid']][$functionid] = $fnum;
                     }
                 }
             }
             preg_match_all('/{ITEM.LASTVALUE([1-9]?)}/u', $trigger['description'], $inums);
             if (!empty($inums[1])) {
                 preg_match_all('/{([0-9]+)}/u', $trigger['expression'], $funcs);
                 $funcs = $funcs[1];
                 foreach ($inums[1] as $fnum) {
                     $fnum = $fnum ? $fnum : 1;
                     if (isset($funcs[$fnum - 1])) {
                         $functionid = $funcs[$fnum - 1];
                         $functionids[$functionid] = $functionid;
                         $triggers_to_expand_items[$trigger['triggerid']][$functionid] = $fnum;
                     }
                 }
             }
             preg_match_all('/{ITEM.VALUE([1-9]?)}/u', $trigger['description'], $inums);
             if (!empty($inums[1])) {
                 preg_match_all('/{([0-9]+)}/u', $trigger['expression'], $funcs);
                 $funcs = $funcs[1];
                 foreach ($inums[1] as $fnum) {
                     $fnum = $fnum ? $fnum : 1;
                     if (isset($funcs[$fnum - 1])) {
                         $functionid = $funcs[$fnum - 1];
                         $functionids[$functionid] = $functionid;
                         $triggers_to_expand_items2[$trigger['triggerid']][$functionid] = $fnum;
                     }
                 }
             }
         }
         if (!empty($functionids)) {
             $sql = 'SELECT DISTINCT f.triggerid, f.functionid, h.host, i.lastvalue' . ' FROM functions f,items i,hosts h' . ' WHERE f.itemid=i.itemid' . ' AND i.hostid=h.hostid' . ' AND h.status<>' . HOST_STATUS_TEMPLATE . ' AND ' . DBcondition('f.functionid', $functionids);
             $db_funcs = DBselect($sql);
             while ($func = DBfetch($db_funcs)) {
                 if (isset($triggers_to_expand_hosts[$func['triggerid']][$func['functionid']])) {
                     $fnum = $triggers_to_expand_hosts[$func['triggerid']][$func['functionid']];
                     if ($fnum == 1) {
                         $result[$func['triggerid']]['description'] = str_replace('{HOSTNAME}', $func['host'], $result[$func['triggerid']]['description']);
                     }
                     $result[$func['triggerid']]['description'] = str_replace('{HOSTNAME' . $fnum . '}', $func['host'], $result[$func['triggerid']]['description']);
                 }
                 if (isset($triggers_to_expand_items[$func['triggerid']][$func['functionid']])) {
                     $fnum = $triggers_to_expand_items[$func['triggerid']][$func['functionid']];
                     if ($fnum == 1) {
                         $result[$func['triggerid']]['description'] = str_replace('{ITEM.LASTVALUE}', $func['lastvalue'], $result[$func['triggerid']]['description']);
                     }
                     $result[$func['triggerid']]['description'] = str_replace('{ITEM.LASTVALUE' . $fnum . '}', $func['lastvalue'], $result[$func['triggerid']]['description']);
                 }
                 if (isset($triggers_to_expand_items2[$func['triggerid']][$func['functionid']])) {
                     $fnum = $triggers_to_expand_items2[$func['triggerid']][$func['functionid']];
                     if ($fnum == 1) {
                         $result[$func['triggerid']]['description'] = str_replace('{ITEM.VALUE}', $func['lastvalue'], $result[$func['triggerid']]['description']);
                     }
                     $result[$func['triggerid']]['description'] = str_replace('{ITEM.VALUE' . $fnum . '}', $func['lastvalue'], $result[$func['triggerid']]['description']);
                 }
             }
         }
         foreach ($result as $tnum => $trigger) {
             if ($res = preg_match_all('/' . ZBX_PREG_EXPRESSION_USER_MACROS . '/', $trigger['description'], $arr)) {
                 $macros = CUserMacro::getMacros($arr[1], array('triggerid' => $trigger['triggerid']));
                 $search = array_keys($macros);
                 $values = array_values($macros);
                 $result[$tnum]['description'] = str_replace($search, $values, $trigger['description']);
             }
         }
     }
     COpt::memoryPick();
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Beispiel #13
0
 public static function export($data)
 {
     $root = self::createDOMDocument();
     $hosts_node = $root->appendChild(new DOMElement(XML_TAG_HOSTS));
     foreach ($data['hosts'] as $host) {
         // HOST
         $host_node = self::addChildData($hosts_node, XML_TAG_HOST, $host);
         // HOST PROFILE
         if (!empty($host['profile'])) {
             self::addChildData($host_node, XML_TAG_HOSTPROFILE, $host['profile']);
         }
         if (!empty($host['profile_ext'])) {
             self::addChildData($host_node, XML_TAG_HOSTPROFILE_EXT, $host['profile_ext']);
         }
         // GROUPS
         if (isset($data['hosts_groups'])) {
             $groups_node = $host_node->appendChild(new DOMElement(XML_TAG_GROUPS));
             foreach ($data['hosts_groups'] as $gnum => $group) {
                 $group['hosts'] = zbx_toHash($group['hosts'], 'hostid');
                 if (isset($group['hosts'][$host['hostid']])) {
                     $n = $groups_node->appendChild(new DOMElement(XML_TAG_GROUP));
                     $n->appendChild(new DOMText($group['name']));
                 }
             }
         }
         // TRIGGERS
         if (isset($data['triggers'])) {
             $triggers_node = $host_node->appendChild(new DOMElement(XML_TAG_TRIGGERS));
             foreach ($data['triggers'] as $tnum => $trigger) {
                 $trigger['hosts'] = zbx_toHash($trigger['hosts'], 'hostid');
                 if (isset($trigger['hosts'][$host['hostid']])) {
                     self::addChildData($triggers_node, XML_TAG_TRIGGER, $trigger);
                 }
             }
         }
         // ITEMS
         if (isset($data['items'])) {
             $items_node = $host_node->appendChild(new DOMElement(XML_TAG_ITEMS));
             foreach ($data['items'] as $item) {
                 $item['hosts'] = zbx_toHash($item['hosts'], 'hostid');
                 if (isset($item['hosts'][$host['hostid']])) {
                     $item_node = self::addChildData($items_node, XML_TAG_ITEM, $item);
                     if (isset($data['items_applications'])) {
                         $applications_node = $item_node->appendChild(new DOMElement(XML_TAG_APPLICATIONS));
                         foreach ($data['items_applications'] as $application) {
                             $application['items'] = zbx_toHash($application['items'], 'itemid');
                             if (isset($application['items'][$item['itemid']])) {
                                 $n = $applications_node->appendChild(new DOMElement(XML_TAG_APPLICATION));
                                 $n->appendChild(new DOMText($application['name']));
                             }
                         }
                     }
                 }
             }
         }
         // TEMPLATES
         if (isset($data['templates'])) {
             $templates_node = $host_node->appendChild(new DOMElement(XML_TAG_TEMPLATES));
             foreach ($data['templates'] as $template) {
                 $template['hosts'] = zbx_toHash($template['hosts'], 'hostid');
                 if (isset($template['hosts'][$host['hostid']])) {
                     $n = $templates_node->appendChild(new DOMElement(XML_TAG_TEMPLATE));
                     $n->appendChild(new DOMText($template['host']));
                 }
             }
         }
         // GRAPHS
         if (isset($data['graphs'])) {
             $graphs_node = $host_node->appendChild(new DOMElement(XML_TAG_GRAPHS));
             $itemminmaxids = array();
             foreach ($data['graphs'] as $num => $graph) {
                 if ($graph['ymin_itemid'] && $graph['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                     $itemminmaxids[$graph['ymin_itemid']] = $graph['ymin_itemid'];
                 }
                 if ($graph['ymax_itemid'] && $graph['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                     $itemminmaxids[$graph['ymax_itemid']] = $graph['ymax_itemid'];
                 }
             }
             $options = array('itemids' => $itemminmaxids, 'output' => API_OUTPUT_EXTEND, 'templated_hosts' => 1, 'nopermissions' => 1);
             $itemminmaxs = CItem::get($options);
             $itemminmaxs = zbx_toHash($itemminmaxs, 'itemid');
             $hostminmaxs = CHost::get($options);
             $hostminmaxs = zbx_toHash($hostminmaxs, 'hostid');
             foreach ($data['graphs'] as $num => $graph) {
                 $graph['hosts'] = zbx_toHash($graph['hosts'], 'hostid');
                 if (isset($graph['hosts'][$host['hostid']])) {
                     if ($graph['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                         $graph['ymin_item_key'] = $hostminmaxs[$itemminmaxs[$graph['ymin_itemid']]['hostid']]['host'] . ':' . $itemminmaxs[$graph['ymin_itemid']]['key_'];
                     } else {
                         $graph['ymin_item_key'] = '';
                     }
                     if ($graph['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                         $graph['ymax_item_key'] = $hostminmaxs[$itemminmaxs[$graph['ymax_itemid']]['hostid']]['host'] . ':' . $itemminmaxs[$graph['ymax_itemid']]['key_'];
                     } else {
                         $graph['ymax_item_key'] = '';
                     }
                     $graph_node = self::addChildData($graphs_node, XML_TAG_GRAPH, $graph);
                     if (isset($data['graphs_items'])) {
                         $graph_elements_node = $graph_node->appendChild(new DOMElement(XML_TAG_GRAPH_ELEMENTS));
                         foreach ($data['graphs_items'] as $ginum => $gitem) {
                             $tmp_item = get_item_by_itemid($gitem['itemid']);
                             $gitem['graphs'] = zbx_toHash($gitem['graphs'], 'graphid');
                             if (isset($gitem['graphs'][$graph['graphid']])) {
                                 self::addChildData($graph_elements_node, XML_TAG_GRAPH_ELEMENT, $gitem);
                             }
                         }
                     }
                 }
             }
         }
         // MACROS
         if (isset($data['macros'])) {
             $macros_node = $host_node->appendChild(new DOMElement(XML_TAG_MACROS));
             foreach ($data['macros'] as $mnum => $macro) {
                 $macro['hosts'] = zbx_toHash($macro['hosts'], 'hostid');
                 if (isset($macro['hosts'][$host['hostid']])) {
                     self::addChildData($macros_node, XML_TAG_MACRO, $macro);
                 }
             }
         }
     }
     // DEPENDENCIES
     if (isset($data['dependencies'])) {
         $dependencies_node = $root->appendChild(new DOMElement(XML_TAG_DEPENDENCIES));
         foreach ($data['dependencies'] as $ddnum => $dep_data) {
             $dependeny_node = $dependencies_node->appendChild(new DOMElement(XML_TAG_DEPENDENCY));
             $dependeny_node->setAttributeNode(new DOMAttr('description', $dep_data['trigger']['host_description']));
             foreach ($dep_data['depends_on'] as $dtnum => $dep_trigger) {
                 $n = $dependeny_node->appendChild(new DOMElement('depends'));
                 $n->appendChild(new DOMText($dep_trigger['host_description']));
             }
         }
     }
     return self::outputXML($root);
 }
 /**
  * Add Items to applications
  *
  * @param array $data
  * @param array $data['applications']
  * @param array $data['items']
  * @return boolean
  */
 public static function massAdd($data)
 {
     if (empty($data['applications'])) {
         return true;
     }
     $applications = zbx_toArray($data['applications']);
     $items = zbx_toArray($data['items']);
     $applicationids = zbx_objectValues($applications, 'applicationid');
     $itemids = zbx_objectValues($items, 'itemid');
     try {
         self::BeginTransaction(__METHOD__);
         // PERMISSIONS {{{
         $app_options = array('applicationids' => $applicationids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1);
         $allowed_applications = self::get($app_options);
         foreach ($applications as $anum => $application) {
             if (!isset($allowed_applications[$application['applicationid']])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSIONS);
             }
         }
         $item_options = array('itemids' => $itemids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1);
         $allowed_items = CItem::get($item_options);
         foreach ($items as $num => $item) {
             if (!isset($allowed_items[$item['itemid']])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSIONS);
             }
         }
         // }}} PERMISSIONS
         $sql = 'SELECT itemid, applicationid ' . ' FROM items_applications ' . ' WHERE ' . DBcondition('itemid', $itemids) . ' AND ' . DBcondition('applicationid', $applicationids);
         $linked_db = DBselect($sql);
         while ($pair = DBfetch($linked_db)) {
             $linked[$pair['applicationid']] = array($pair['itemid'] => $pair['itemid']);
         }
         $apps_insert = array();
         foreach ($applicationids as $anum => $applicationid) {
             foreach ($itemids as $inum => $itemid) {
                 if (isset($linked[$applicationid]) && isset($linked[$applicationid][$itemid])) {
                     continue;
                 }
                 $apps_insert[] = array('itemid' => $itemid, 'applicationid' => $applicationid);
             }
         }
         DB::insert('items_applications', $apps_insert);
         foreach ($itemids as $inum => $itemid) {
             $db_childs = DBselect('SELECT itemid, hostid FROM items WHERE templateid=' . $itemid);
             while ($child = DBfetch($db_childs)) {
                 $sql = 'SELECT a1.applicationid ' . ' FROM applications a1, applications a2 ' . ' WHERE a1.name=a2.name ' . ' AND a1.hostid=' . $child['hostid'] . ' AND ' . DBcondition('a2.applicationid', $applicationids);
                 $db_apps = DBselect($sql);
                 $child_applications = array();
                 while ($app = DBfetch($db_apps)) {
                     $child_applications[] = $app;
                 }
                 $result = self::massAdd(array('items' => $child, 'applications' => $child_applications));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot add items');
                 }
             }
         }
         self::EndTransaction(true, __METHOD__);
         return true;
     } catch (APIException $e) {
         self::EndTransaction(false, __METHOD__);
         $error = $e->getErrors();
         $error = reset($error);
         self::setError(__METHOD__, $e->getCode(), $error);
         return false;
     }
 }
Beispiel #15
0
function resolveMapLabelMacros($label, $replaceHost = null)
{
    if (null === $replaceHost) {
        $pattern = "/{" . ZBX_PREG_HOST_FORMAT . ":.+\\.(last|max|min|avg)\\([0-9]+\\)}/Uu";
    } else {
        $pattern = "/{(" . ZBX_PREG_HOST_FORMAT . "|{HOSTNAME}):.+\\.(last|max|min|avg)\\([0-9]+\\)}/Uu";
    }
    preg_match_all($pattern, $label, $matches);
    foreach ($matches[0] as $expr) {
        $macro = $expr;
        if ($replaceHost !== null && zbx_strpos($macro, '{HOSTNAME}') == 1) {
            $macro = substr_replace($macro, $replaceHost, 1, 10);
        }
        $trigExpr = new CTriggerExpression(array('expression' => $macro));
        if (!empty($trigExpr->errors)) {
            continue;
        }
        $itemHost = reset($trigExpr->data['hosts']);
        $key = reset($trigExpr->data['items']);
        $function = reset($trigExpr->data['functions']);
        $parameter = reset($trigExpr->data['functionParams']);
        $item = CItem::get(array('filter' => array('host' => $itemHost, 'key_' => $key), 'output' => API_OUTPUT_EXTEND));
        $item = reset($item);
        if (!$item) {
            $label = str_replace($expr, '???', $label);
            continue;
        }
        switch ($item['value_type']) {
            case ITEM_VALUE_TYPE_FLOAT:
                $history_table = 'history';
                break;
            case ITEM_VALUE_TYPE_UINT64:
                $history_table = 'history_uint';
                break;
            case ITEM_VALUE_TYPE_TEXT:
                $history_table = 'history_text';
                break;
            case ITEM_VALUE_TYPE_LOG:
                $history_table = 'history_log';
                break;
            case ITEM_VALUE_TYPE_STR:
                $history_table = 'history_str';
                break;
            default:
                $history_table = 'history_str';
        }
        if (0 == strcmp($function, 'last')) {
            if (null === $item['lastvalue']) {
                $label = str_replace($expr, '(' . S_NO_DATA_SMALL . ')', $label);
            } else {
                switch ($item['value_type']) {
                    case ITEM_VALUE_TYPE_FLOAT:
                    case ITEM_VALUE_TYPE_UINT64:
                        $value = convert_units($item['lastvalue'], $item['units']);
                        break;
                    default:
                        $value = $item['lastvalue'];
                }
                $label = str_replace($expr, $value, $label);
            }
        } else {
            if (0 == strcmp($function, 'min') || 0 == strcmp($function, 'max') || 0 == strcmp($function, 'avg')) {
                if ($item['value_type'] != ITEM_VALUE_TYPE_FLOAT && $item['value_type'] != ITEM_VALUE_TYPE_UINT64) {
                    $label = str_replace($expr, '???', $label);
                    continue;
                }
                $sql = 'SELECT ' . $function . '(value) as value ' . ' FROM ' . $history_table . ' WHERE clock>' . (time() - $parameter) . ' AND itemid=' . $item['itemid'];
                $result = DBselect($sql);
                if (null === ($row = DBfetch($result)) || null === $row['value']) {
                    $label = str_replace($expr, '(' . S_NO_DATA_SMALL . ')', $label);
                } else {
                    $label = str_replace($expr, convert_units($row['value'], $item['units']), $label);
                }
            }
        }
    }
    return $label;
}
function get_screen_item_form()
{
    global $USER_DETAILS;
    $form = new CFormTable(S_SCREEN_CELL_CONFIGURATION, 'screenedit.php?screenid=' . $_REQUEST['screenid']);
    $form->SetHelp('web.screenedit.cell.php');
    if (isset($_REQUEST['screenitemid'])) {
        $sql = 'SELECT * ' . ' FROM screens_items' . ' WHERE screenid=' . $_REQUEST['screenid'] . ' AND screenitemid=' . $_REQUEST['screenitemid'];
        $iresult = DBSelect($sql);
        $form->addVar('screenitemid', $_REQUEST['screenitemid']);
    } else {
        $form->addVar('x', $_REQUEST['x']);
        $form->addVar('y', $_REQUEST['y']);
    }
    if (isset($_REQUEST['screenitemid']) && !isset($_REQUEST['form_refresh'])) {
        $irow = DBfetch($iresult);
        $resourcetype = $irow['resourcetype'];
        $resourceid = $irow['resourceid'];
        $width = $irow['width'];
        $height = $irow['height'];
        $colspan = $irow['colspan'];
        $rowspan = $irow['rowspan'];
        $elements = $irow['elements'];
        $valign = $irow['valign'];
        $halign = $irow['halign'];
        $style = $irow['style'];
        $url = $irow['url'];
        $dynamic = $irow['dynamic'];
    } else {
        $resourcetype = get_request('resourcetype', 0);
        $resourceid = get_request('resourceid', 0);
        $width = get_request('width', 500);
        $height = get_request('height', 100);
        $colspan = get_request('colspan', 0);
        $rowspan = get_request('rowspan', 0);
        $elements = get_request('elements', 25);
        $valign = get_request('valign', VALIGN_DEFAULT);
        $halign = get_request('halign', HALIGN_DEFAULT);
        $style = get_request('style', 0);
        $url = get_request('url', '');
        $dynamic = get_request('dynamic', SCREEN_SIMPLE_ITEM);
    }
    $form->addVar('screenid', $_REQUEST['screenid']);
    // a-z order!!!
    $cmbRes = new CCombobox('resourcetype', $resourcetype, 'submit()');
    $cmbRes->addItem(SCREEN_RESOURCE_CLOCK, S_CLOCK);
    $cmbRes->addItem(SCREEN_RESOURCE_DATA_OVERVIEW, S_DATA_OVERVIEW);
    $cmbRes->addItem(SCREEN_RESOURCE_GRAPH, S_GRAPH);
    $cmbRes->addItem(SCREEN_RESOURCE_ACTIONS, S_HISTORY_OF_ACTIONS);
    $cmbRes->addItem(SCREEN_RESOURCE_EVENTS, S_HISTORY_OF_EVENTS);
    $cmbRes->addItem(SCREEN_RESOURCE_HOSTS_INFO, S_HOSTS_INFO);
    $cmbRes->addItem(SCREEN_RESOURCE_MAP, S_MAP);
    $cmbRes->addItem(SCREEN_RESOURCE_PLAIN_TEXT, S_PLAIN_TEXT);
    $cmbRes->addItem(SCREEN_RESOURCE_SCREEN, S_SCREEN);
    $cmbRes->addItem(SCREEN_RESOURCE_SERVER_INFO, S_SERVER_INFO);
    $cmbRes->addItem(SCREEN_RESOURCE_SIMPLE_GRAPH, S_SIMPLE_GRAPH);
    $cmbRes->addItem(SCREEN_RESOURCE_HOSTGROUP_TRIGGERS, S_STATUS_OF_HOSTGROUP_TRIGGERS);
    $cmbRes->addItem(SCREEN_RESOURCE_HOST_TRIGGERS, S_STATUS_OF_HOST_TRIGGERS);
    $cmbRes->addItem(SCREEN_RESOURCE_SYSTEM_STATUS, S_SYSTEM_STATUS);
    $cmbRes->addItem(SCREEN_RESOURCE_TRIGGERS_INFO, S_TRIGGERS_INFO);
    $cmbRes->addItem(SCREEN_RESOURCE_TRIGGERS_OVERVIEW, S_TRIGGERS_OVERVIEW);
    $cmbRes->addItem(SCREEN_RESOURCE_URL, S_URL);
    $form->addRow(S_RESOURCE, $cmbRes);
    if ($resourcetype == SCREEN_RESOURCE_GRAPH) {
        // User-defined graph
        $options = array('graphids' => $resourceid, 'select_hosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND);
        $graphs = CGraph::get($options);
        $caption = '';
        $id = 0;
        if (!empty($graphs)) {
            $id = $resourceid;
            $graph = reset($graphs);
            order_result($graph['hosts'], 'host');
            $graph['host'] = reset($graph['hosts']);
            $caption = $graph['host']['host'] . ':' . $graph['name'];
            $nodeName = get_node_name_by_elid($graph['host']['hostid']);
            if (!zbx_empty($nodeName)) {
                $caption = '(' . $nodeName . ') ' . $caption;
            }
        }
        $form->addVar('resourceid', $id);
        $textfield = new CTextbox('caption', $caption, 75, 'yes');
        $selectbtn = new CButton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&real_hosts=1&dstfld1=resourceid&dstfld2=caption&srctbl=graphs&srcfld1=graphid&srcfld2=name',800,450);");
        $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
        $form->addRow(S_GRAPH_NAME, array($textfield, SPACE, $selectbtn));
    } else {
        if ($resourcetype == SCREEN_RESOURCE_SIMPLE_GRAPH) {
            // Simple graph
            $options = array('itemids' => $resourceid, 'select_hosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND);
            $items = CItem::get($options);
            $caption = '';
            $id = 0;
            if (!empty($items)) {
                $id = $resourceid;
                $item = reset($items);
                $item['host'] = reset($item['hosts']);
                $caption = item_description($item);
                $nodeName = get_node_name_by_elid($item['itemid']);
                if (!zbx_empty($nodeName)) {
                    $caption = '(' . $nodeName . ') ' . $caption;
                }
            }
            $form->addVar('resourceid', $id);
            $textfield = new Ctextbox('caption', $caption, 75, 'yes');
            $selectbtn = new Cbutton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&real_hosts=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=simple_graph&srcfld1=itemid&srcfld2=description',800,450);");
            $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
            $form->addRow(S_PARAMETER, array($textfield, SPACE, $selectbtn));
        } else {
            if ($resourcetype == SCREEN_RESOURCE_MAP) {
                // Map
                $options = array('sysmapids' => $resourceid, 'output' => API_OUTPUT_EXTEND);
                $maps = CMap::get($options);
                $caption = '';
                $id = 0;
                if (!empty($maps)) {
                    $id = $resourceid;
                    $map = reset($maps);
                    $caption = $map['name'];
                    $nodeName = get_node_name_by_elid($map['sysmapid']);
                    if (!zbx_empty($nodeName)) {
                        $caption = '(' . $nodeName . ') ' . $caption;
                    }
                }
                $form->addVar('resourceid', $id);
                $textfield = new Ctextbox('caption', $caption, 60, 'yes');
                $selectbtn = new Cbutton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=sysmaps&srcfld1=sysmapid&srcfld2=name',400,450);");
                $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
                $form->addRow(S_PARAMETER, array($textfield, SPACE, $selectbtn));
            } else {
                if ($resourcetype == SCREEN_RESOURCE_PLAIN_TEXT) {
                    // Plain text
                    $options = array('itemids' => $resourceid, 'select_hosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND);
                    $items = CItem::get($options);
                    $caption = '';
                    $id = 0;
                    if (!empty($items)) {
                        $id = $resourceid;
                        $item = reset($items);
                        $item['host'] = reset($item['hosts']);
                        $caption = item_description($item);
                        $nodeName = get_node_name_by_elid($item['itemid']);
                        if (!zbx_empty($nodeName)) {
                            $caption = '(' . $nodeName . ') ' . $caption;
                        }
                    }
                    $form->addVar('resourceid', $id);
                    $textfield = new CTextbox('caption', $caption, 75, 'yes');
                    $selectbtn = new CButton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=plain_text&srcfld1=itemid&srcfld2=description',800,450);");
                    $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
                    $form->addRow(S_PARAMETER, array($textfield, SPACE, $selectbtn));
                    $form->addRow(S_SHOW_LINES, new CNumericBox('elements', $elements, 2));
                    $form->addRow(S_SHOW_TEXT_AS_HTML, new CCheckBox('style', $style, null, 1));
                } else {
                    if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_HOSTGROUP_TRIGGERS, SCREEN_RESOURCE_HOST_TRIGGERS))) {
                        // Status of triggers
                        $caption = '';
                        $id = 0;
                        if (SCREEN_RESOURCE_HOSTGROUP_TRIGGERS == $resourcetype) {
                            if ($resourceid > 0) {
                                $options = array('groupids' => $resourceid, 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                                $groups = CHostgroup::get($options);
                                foreach ($groups as $gnum => $group) {
                                    $caption = get_node_name_by_elid($group['groupid'], true, ':') . $group['name'];
                                    $id = $resourceid;
                                }
                            }
                            $form->addVar('resourceid', $id);
                            $textfield = new CTextbox('caption', $caption, 60, 'yes');
                            $selectbtn = new CButton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=host_group&srcfld1=groupid&srcfld2=name',800,450);");
                            $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
                            $form->addRow(S_GROUP, array($textfield, SPACE, $selectbtn));
                        } else {
                            if ($resourceid > 0) {
                                $options = array('hostids' => $resourceid, 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                                $hosts = CHost::get($options);
                                foreach ($hosts as $hnum => $host) {
                                    $caption = get_node_name_by_elid($host['hostid'], true, ':') . $host['host'];
                                    $id = $resourceid;
                                }
                            }
                            $form->addVar('resourceid', $id);
                            $textfield = new CTextbox('caption', $caption, 60, 'yes');
                            $selectbtn = new CButton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=hosts&srcfld1=hostid&srcfld2=host',800,450);");
                            $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
                            $form->addRow(S_HOST, array($textfield, SPACE, $selectbtn));
                        }
                        $form->addRow(S_SHOW_LINES, new CNumericBox('elements', $elements, 2));
                    } else {
                        if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_EVENTS, SCREEN_RESOURCE_ACTIONS))) {
                            // History of actions
                            // History of events
                            $form->addRow(S_SHOW_LINES, new CNumericBox('elements', $elements, 2));
                            $form->addVar('resourceid', 0);
                        } else {
                            if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW))) {
                                // Overviews
                                $caption = '';
                                $id = 0;
                                if ($resourceid > 0) {
                                    $options = array('groupids' => $resourceid, 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                                    $groups = CHostgroup::get($options);
                                    foreach ($groups as $gnum => $group) {
                                        $caption = get_node_name_by_elid($group['groupid'], true, ':') . $group['name'];
                                        $id = $resourceid;
                                    }
                                }
                                $form->addVar('resourceid', $id);
                                $textfield = new CTextbox('caption', $caption, 75, 'yes');
                                $selectbtn = new CButton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=overview&srcfld1=groupid&srcfld2=name',800,450);");
                                $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
                                $form->addRow(S_GROUP, array($textfield, SPACE, $selectbtn));
                            } else {
                                if ($resourcetype == SCREEN_RESOURCE_SCREEN) {
                                    // Screens
                                    $caption = '';
                                    $id = 0;
                                    if ($resourceid > 0) {
                                        $result = DBselect('SELECT DISTINCT n.name as node_name,s.screenid,s.name ' . ' FROM screens s ' . ' LEFT JOIN nodes n ON n.nodeid=' . DBid2nodeid('s.screenid') . ' WHERE s.screenid=' . $resourceid);
                                        while ($row = DBfetch($result)) {
                                            $r = CScreen::get(array('screenids' => $row['screenid'], 'output' => API_OUTPUT_SHORTEN));
                                            if (empty($r)) {
                                                continue;
                                            }
                                            if (check_screen_recursion($_REQUEST['screenid'], $row['screenid'])) {
                                                continue;
                                            }
                                            $row['node_name'] = isset($row['node_name']) ? '(' . $row['node_name'] . ') ' : '';
                                            $caption = $row['node_name'] . $row['name'];
                                            $id = $resourceid;
                                        }
                                    }
                                    $form->addVar('resourceid', $id);
                                    $textfield = new Ctextbox('caption', $caption, 60, 'yes');
                                    $selectbtn = new Cbutton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=screens2&srcfld1=screenid&srcfld2=name&screenid=" . $_REQUEST['screenid'] . "',800,450);");
                                    $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
                                    $form->addRow(S_PARAMETER, array($textfield, SPACE, $selectbtn));
                                } else {
                                    if ($resourcetype == SCREEN_RESOURCE_HOSTS_INFO || $resourcetype == SCREEN_RESOURCE_TRIGGERS_INFO) {
                                        // HOSTS info
                                        $caption = '';
                                        $id = 0;
                                        $available_groups = get_accessible_groups_by_user($USER_DETAILS, PERM_READ_ONLY);
                                        if (remove_nodes_from_id($resourceid) > 0) {
                                            $result = DBselect('SELECT DISTINCT n.name as node_name,g.groupid,g.name ' . ' FROM hosts_groups hg, groups g ' . ' LEFT JOIN nodes n ON n.nodeid=' . DBid2nodeid('g.groupid') . ' WHERE ' . DBcondition('g.groupid', $available_groups) . ' AND g.groupid=' . $resourceid);
                                            while ($row = DBfetch($result)) {
                                                $row['node_name'] = isset($row['node_name']) ? '(' . $row['node_name'] . ') ' : '';
                                                $caption = $row['node_name'] . $row['name'];
                                                $id = $resourceid;
                                            }
                                        } else {
                                            if (remove_nodes_from_id($resourceid) == 0) {
                                                $result = DBselect('SELECT DISTINCT n.name as node_name ' . ' FROM nodes n ' . ' WHERE n.nodeid=' . id2nodeid($resourceid));
                                                while ($row = DBfetch($result)) {
                                                    $row['node_name'] = isset($row['node_name']) ? '(' . $row['node_name'] . ') ' : '';
                                                    $caption = $row['node_name'] . S_MINUS_ALL_GROUPS_MINUS;
                                                    $id = $resourceid;
                                                }
                                            }
                                        }
                                        $form->addVar('resourceid', $id);
                                        $textfield = new CTextbox('caption', $caption, 60, 'yes');
                                        $selectbtn = new Cbutton('select', S_SELECT, "javascript: return PopUp('popup.php?writeonly=1&dstfrm=" . $form->getName() . "&dstfld1=resourceid&dstfld2=caption&srctbl=host_group_scr&srcfld1=groupid&srcfld2=name',480,450);");
                                        $selectbtn->setAttribute('onmouseover', "javascript: this.style.cursor = 'pointer';");
                                        $form->addRow(S_GROUP, array($textfield, SPACE, $selectbtn));
                                    } else {
                                        // SCREEN_RESOURCE_CLOCK
                                        $form->addVar('resourceid', 0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_HOSTS_INFO, SCREEN_RESOURCE_TRIGGERS_INFO))) {
        $cmbStyle = new CComboBox("style", $style);
        $cmbStyle->addItem(STYLE_HORISONTAL, S_HORIZONTAL);
        $cmbStyle->addItem(STYLE_VERTICAL, S_VERTICAL);
        $form->addRow(S_STYLE, $cmbStyle);
    } else {
        if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW))) {
            $cmbStyle = new CComboBox('style', $style);
            $cmbStyle->addItem(STYLE_LEFT, S_LEFT);
            $cmbStyle->addItem(STYLE_TOP, S_TOP);
            $form->addRow(S_HOSTS_LOCATION, $cmbStyle);
        } else {
            if ($resourcetype == SCREEN_RESOURCE_CLOCK) {
                $cmbStyle = new CComboBox('style', $style);
                $cmbStyle->addItem(TIME_TYPE_LOCAL, S_LOCAL_TIME);
                $cmbStyle->addItem(TIME_TYPE_SERVER, S_SERVER_TIME);
                $form->addRow(S_TIME_TYPE, $cmbStyle);
            } else {
                $form->addVar('style', 0);
            }
        }
    }
    if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_URL))) {
        $form->addRow(S_URL, new CTextBox('url', $url, 60));
    } else {
        $form->addVar('url', '');
    }
    if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_GRAPH, SCREEN_RESOURCE_SIMPLE_GRAPH, SCREEN_RESOURCE_CLOCK, SCREEN_RESOURCE_URL))) {
        $form->addRow(S_WIDTH, new CNumericBox('width', $width, 5));
        $form->addRow(S_HEIGHT, new CNumericBox('height', $height, 5));
    } else {
        $form->addVar('width', 500);
        $form->addVar('height', 100);
    }
    if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_GRAPH, SCREEN_RESOURCE_SIMPLE_GRAPH, SCREEN_RESOURCE_MAP, SCREEN_RESOURCE_CLOCK, SCREEN_RESOURCE_URL))) {
        $cmbHalign = new CComboBox('halign', $halign);
        $cmbHalign->addItem(HALIGN_CENTER, S_CENTRE);
        $cmbHalign->addItem(HALIGN_LEFT, S_LEFT);
        $cmbHalign->addItem(HALIGN_RIGHT, S_RIGHT);
        $form->addRow(S_HORIZONTAL_ALIGN, $cmbHalign);
    } else {
        $form->addVar('halign', 0);
    }
    $cmbValign = new CComboBox('valign', $valign);
    $cmbValign->addItem(VALIGN_MIDDLE, S_MIDDLE);
    $cmbValign->addItem(VALIGN_TOP, S_TOP);
    $cmbValign->addItem(VALIGN_BOTTOM, S_BOTTOM);
    $form->addRow(S_VERTICAL_ALIGN, $cmbValign);
    $form->addRow(S_COLUMN_SPAN, new CNumericBox('colspan', $colspan, 2));
    $form->addRow(S_ROW_SPAN, new CNumericBox('rowspan', $rowspan, 2));
    // dynamic AddOn
    if (uint_in_array($resourcetype, array(SCREEN_RESOURCE_GRAPH, SCREEN_RESOURCE_SIMPLE_GRAPH, SCREEN_RESOURCE_PLAIN_TEXT))) {
        $form->addRow(S_DYNAMIC_ITEM, new CCheckBox('dynamic', $dynamic, null, 1));
    }
    $form->addItemToBottomRow(new CButton('save', S_SAVE));
    if (isset($_REQUEST['screenitemid'])) {
        $form->addItemToBottomRow(SPACE);
        $form->addItemToBottomRow(new CButtonDelete(null, url_param('form') . url_param('screenid') . url_param('screenitemid')));
    }
    $form->addItemToBottomRow(SPACE);
    $form->addItemToBottomRow(new CButtonCancel(url_param('screenid')));
    return $form;
}
 protected static function checkAxisItems($graph, $tpl = false)
 {
     $axis_items = array();
     if (isset($graph['ymin_type']) && $graph['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
         $axis_items[$graph['ymin_itemid']] = $graph['ymin_itemid'];
     }
     if (isset($graph['ymax_type']) && $graph['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
         $axis_items[$graph['ymax_itemid']] = $graph['ymax_itemid'];
     }
     if (!empty($axis_items)) {
         $cnt = count($axis_items);
         $options = array('itemids' => $axis_items, 'output' => API_OUTPUT_SHORTEN, 'countOutput' => 1);
         if ($tpl) {
             $options['hostids'] = $tpl;
         } else {
             $options['templated'] = false;
         }
         $cnt_exist = CItem::get($options);
         if ($cnt != $cnt_exist) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect item for axis value item');
         }
     }
     return true;
 }
 /**
  * Get events data
  *
  * {@source}
  * @access public
  * @static
  * @since 1.8
  * @version 1
  *
  * @param _array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['eventids']
  * @param array $options['applicationids']
  * @param array $options['status']
  * @param array $options['editable']
  * @param array $options['extendoutput']
  * @param array $options['count']
  * @param array $options['pattern']
  * @param array $options['limit']
  * @param array $options['order']
  * @return array|int item data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $result = array();
     $nodeCheck = array();
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $sort_columns = array('eventid', 'clock');
     // allowed columns for sorting
     $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     // allowed output options for [ select_* ] params
     $sql_parts = array('select' => array('events' => array('e.eventid')), 'from' => array('events' => 'events e'), 'where' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'triggerids' => null, 'eventids' => null, 'editable' => null, 'object' => null, 'source' => null, 'acknowledged' => null, 'nopermissions' => null, 'hide_unknown' => null, 'value' => null, 'time_from' => null, 'time_till' => null, 'eventid_from' => null, 'eventid_till' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_hosts' => null, 'select_items' => null, 'select_triggers' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($def_options, $options);
     if (!is_null($options['extendoutput'])) {
         $options['output'] = API_OUTPUT_EXTEND;
         if (!is_null($options['select_hosts'])) {
             $options['select_hosts'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_triggers'])) {
             $options['select_triggers'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_items'])) {
             $options['select_items'] = API_OUTPUT_EXTEND;
         }
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         if (is_null($options['source']) && is_null($options['object'])) {
             $options['object'] = EVENT_OBJECT_TRIGGER;
         }
         if ($options['object'] == EVENT_OBJECT_TRIGGER || $options['source'] == EVENT_SOURCE_TRIGGER) {
             if (!is_null($options['triggerids'])) {
                 $triggerOptions = array('triggerids' => $options['triggerids'], 'editable' => $options['editable']);
                 $triggers = CTrigger::get($triggerOptions);
                 $options['triggerids'] = zbx_objectValues($triggers, 'triggerid');
             } else {
                 $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
                 $sql_parts['from']['functions'] = 'functions f';
                 $sql_parts['from']['items'] = 'items i';
                 $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
                 $sql_parts['from']['rights'] = 'rights r';
                 $sql_parts['from']['users_groups'] = 'users_groups ug';
                 $sql_parts['where']['e'] = 'e.object=' . EVENT_OBJECT_TRIGGER;
                 $sql_parts['where']['fe'] = 'f.triggerid=e.objectid';
                 $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
                 $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
                 $sql_parts['where'][] = 'r.id=hg.groupid ';
                 $sql_parts['where'][] = 'r.groupid=ug.usrgrpid';
                 $sql_parts['where'][] = 'ug.userid=' . $userid;
                 $sql_parts['where'][] = 'r.permission>=' . $permission;
                 $sql_parts['where'][] = 'NOT EXISTS( ' . ' SELECT ff.triggerid ' . ' FROM functions ff, items ii ' . ' WHERE ff.triggerid=e.objectid ' . ' AND ff.itemid=ii.itemid ' . ' AND EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups gg ' . ' WHERE hgg.hostid=ii.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . '))';
             }
         }
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // eventids
     if (!is_null($options['eventids'])) {
         zbx_value2array($options['eventids']);
         $sql_parts['where'][] = DBcondition('e.eventid', $options['eventids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('e.objectid', $nodeids);
         }
     }
     // triggerids
     if (!is_null($options['triggerids']) && $options['object'] == EVENT_OBJECT_TRIGGER) {
         zbx_value2array($options['triggerids']);
         $sql_parts['where'][] = DBcondition('e.objectid', $options['triggerids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('e.objectid', $nodeids);
         }
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['groupid'] = 'hg.groupid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where']['hg'] = DBcondition('hg.groupid', $options['groupids']);
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where']['fe'] = 'f.triggerid=e.objectid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['hostid'] = 'i.hostid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where']['i'] = DBcondition('i.hostid', $options['hostids']);
         $sql_parts['where']['ft'] = 'f.triggerid=e.objectid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // node check !!!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sql_parts['where'][] = DBin_node('e.eventid', $nodeids);
     }
     // object
     if (!is_null($options['object'])) {
         $sql_parts['where']['o'] = 'e.object=' . $options['object'];
     }
     // source
     if (!is_null($options['source'])) {
         $sql_parts['where'][] = 'e.source=' . $options['source'];
     }
     // acknowledged
     if (!is_null($options['acknowledged'])) {
         $sql_parts['where'][] = 'e.acknowledged=' . ($options['acknowledged'] ? 1 : 0);
     }
     // hide_unknown
     if (!is_null($options['hide_unknown'])) {
         $sql_parts['where'][] = 'e.value<>' . TRIGGER_VALUE_UNKNOWN;
     }
     // time_from
     if (!is_null($options['time_from'])) {
         $sql_parts['where'][] = 'e.clock>=' . $options['time_from'];
     }
     // time_till
     if (!is_null($options['time_till'])) {
         $sql_parts['where'][] = 'e.clock<=' . $options['time_till'];
     }
     // eventid_from
     if (!is_null($options['eventid_from'])) {
         $sql_parts['where'][] = 'e.eventid>=' . $options['eventid_from'];
     }
     // eventid_till
     if (!is_null($options['eventid_till'])) {
         $sql_parts['where'][] = 'e.eventid<=' . $options['eventid_till'];
     }
     // value
     if (!is_null($options['value'])) {
         zbx_value2array($options['value']);
         $sql_parts['where'][] = DBcondition('e.value', $options['value']);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sql_parts['select']['events'] = array('e.*');
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sql_parts['select'] = array('events' => array('COUNT(DISTINCT e.eventid) as rowscount'));
     }
     // order
     // restrict not allowed columns for sorting
     $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : '';
     if (!zbx_empty($options['sortfield'])) {
         $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP;
         $sql_parts['order'][] = 'e.' . $options['sortfield'] . ' ' . $sortorder;
         if (!is_null($options['triggerids']) && $options['sortfield'] == 'clock') {
             $sql_parts['where']['o'] = '(e.object-0)=' . EVENT_OBJECT_TRIGGER;
         }
         $eventFields = $sql_parts['select']['events'];
         if (!str_in_array('e.' . $options['sortfield'], $eventFields) && !str_in_array('e.*', $eventFields)) {
             $sql_parts['select']['events'][] = 'e.' . $options['sortfield'];
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     // select_********
     if ($options['output'] != API_OUTPUT_EXTEND && (!is_null($options['select_hosts']) || !is_null($options['select_triggers']) || !is_null($options['select_items']))) {
         $sql_parts['select']['events'][] = 'e.object';
         $sql_parts['select']['events'][] = 'e.objectid';
     }
     //---------------
     $eventids = array();
     $triggerids = array();
     // Event fields
     $sql_parts['select']['events'] = implode(',', array_unique($sql_parts['select']['events']));
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_order;
     $db_res = DBselect($sql, $sql_limit);
     //SDI($sql);
     while ($event = DBfetch($db_res)) {
         if ($options['countOutput']) {
             $result = $event['rowscount'];
         } else {
             $eventids[$event['eventid']] = $event['eventid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$event['eventid']] = array('eventid' => $event['eventid']);
             } else {
                 if (isset($event['object']) && $event['object'] == EVENT_OBJECT_TRIGGER) {
                     $triggerids[$event['objectid']] = $event['objectid'];
                 }
                 if (!isset($result[$event['eventid']])) {
                     $result[$event['eventid']] = array();
                 }
                 if (!is_null($options['select_hosts']) && !isset($result[$event['eventid']]['hosts'])) {
                     $result[$event['eventid']]['hosts'] = array();
                 }
                 if (!is_null($options['select_triggers']) && !isset($result[$event['eventid']]['triggers'])) {
                     $result[$event['eventid']]['triggers'] = array();
                 }
                 if (!is_null($options['select_items']) && !isset($result[$event['eventid']]['items'])) {
                     $result[$event['eventid']]['items'] = array();
                 }
                 // hostids
                 if (isset($event['hostid']) && is_null($options['select_hosts'])) {
                     if (!isset($result[$event['eventid']]['hosts'])) {
                         $result[$event['eventid']]['hosts'] = array();
                     }
                     $result[$event['eventid']]['hosts'][] = array('hostid' => $event['hostid']);
                     unset($event['hostid']);
                 }
                 // triggerids
                 if (isset($event['triggerid']) && is_null($options['select_triggers'])) {
                     if (!isset($result[$event['eventid']]['triggers'])) {
                         $result[$event['eventid']]['triggers'] = array();
                     }
                     $result[$event['eventid']]['triggers'][] = array('triggerid' => $event['triggerid']);
                     unset($event['triggerid']);
                 }
                 // itemids
                 if (isset($event['itemid']) && is_null($options['select_items'])) {
                     if (!isset($result[$event['eventid']]['items'])) {
                         $result[$event['eventid']]['items'] = array();
                     }
                     $result[$event['eventid']]['items'][] = array('itemid' => $event['itemid']);
                     unset($event['itemid']);
                 }
                 $result[$event['eventid']] += $event;
             }
         }
     }
     Copt::memoryPick();
     if (!is_null($options['countOutput'])) {
         if (is_null($options['preservekeys'])) {
             $result = zbx_cleanHashes($result);
         }
         return $result;
     }
     // Adding Objects
     // Adding hosts
     if (!is_null($options['select_hosts']) && str_in_array($options['select_hosts'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_hosts'], 'triggerids' => $triggerids, 'nopermissions' => 1, 'preservekeys' => 1);
         $hosts = CHost::get($obj_params);
         $triggers = array();
         foreach ($hosts as $hostid => $host) {
             $htriggers = $host['triggers'];
             unset($host['triggers']);
             foreach ($htriggers as $tnum => $trigger) {
                 $triggerid = $trigger['triggerid'];
                 if (!isset($triggers[$triggerid])) {
                     $triggers[$triggerid] = array('hosts' => array());
                 }
                 $triggers[$triggerid]['hosts'][] = $host;
             }
         }
         foreach ($result as $eventid => $event) {
             if (isset($triggers[$event['objectid']])) {
                 $result[$eventid]['hosts'] = $triggers[$event['objectid']]['hosts'];
             } else {
                 $result[$eventid]['hosts'] = array();
             }
         }
     }
     // Adding triggers
     if (!is_null($options['select_triggers']) && str_in_array($options['select_triggers'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_triggers'], 'triggerids' => $triggerids, 'nopermissions' => 1, 'preservekeys' => 1);
         $triggers = CTrigger::get($obj_params);
         foreach ($result as $eventid => $event) {
             if (isset($triggers[$event['objectid']])) {
                 $result[$eventid]['triggers'][] = $triggers[$event['objectid']];
             } else {
                 $result[$eventid]['triggers'] = array();
             }
         }
     }
     // Adding items
     if (!is_null($options['select_items']) && str_in_array($options['select_items'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_items'], 'triggerids' => $triggerids, 'webitems' => 1, 'nopermissions' => 1, 'preservekeys' => 1);
         $db_items = CItem::get($obj_params);
         $items = array();
         foreach ($db_items as $itemid => $item) {
             $itriggers = $item['triggers'];
             unset($item['triggers']);
             foreach ($itriggers as $trigger) {
                 if (!isset($items[$trigger['triggerid']])) {
                     $items[$trigger['triggerid']] = array();
                 }
                 $items[$trigger['triggerid']][] = $item;
             }
         }
         foreach ($result as $eventid => $event) {
             if (isset($items[$event['objectid']])) {
                 $result[$eventid]['items'] = $items[$event['objectid']];
             } else {
                 $result[$eventid]['items'] = array();
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Beispiel #19
0
    /**
     * Get Host data
     *
     * {@source}
     * @access public
     * @static
     * @since 1.8
     * @version 1
     *
     * @param _array $options
     * @param array $options['nodeids'] Node IDs
     * @param array $options['groupids'] HostGroup IDs
     * @param array $options['hostids'] Host IDs
     * @param boolean $options['monitored_hosts'] only monitored Hosts
     * @param boolean $options['templated_hosts'] include templates in result
     * @param boolean $options['with_items'] only with items
     * @param boolean $options['with_monitored_items'] only with monitored items
     * @param boolean $options['with_historical_items'] only with historical items
     * @param boolean $options['with_triggers'] only with triggers
     * @param boolean $options['with_monitored_triggers'] only with monitores triggers
     * @param boolean $options['with_httptests'] only with http tests
     * @param boolean $options['with_monitored_httptests'] only with monitores http tests
     * @param boolean $options['with_graphs'] only with graphs
     * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
     * @param int $options['extendoutput'] return all fields for Hosts
     * @param int $options['count'] count Hosts, returned column name is rowscount
     * @param string $options['pattern'] search hosts by pattern in host names
     * @param int $options['limit'] limit selection
     * @param string $options['order'] depricated parametr (for now)
     * @return array|boolean Host data as array or false if error
     */
    public static function get($options = array())
    {
        global $USER_DETAILS;
        $result = array();
        $user_type = $USER_DETAILS['type'];
        $userid = $USER_DETAILS['userid'];
        $sort_columns = array('hostid', 'host');
        // allowed columns for sorting
        $sql_parts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts h'), 'where' => array(), 'order' => array(), 'limit' => null);
        $def_options = array('nodeids' => 0, 'groupids' => 0, 'hostids' => 0, 'templateids' => 0, 'triggerids' => 0, 'graphids' => 0, 'monitored_hosts' => 0, 'templated_hosts' => 0, 'with_items' => 0, 'with_monitored_items' => 0, 'with_historical_items' => 0, 'with_triggers' => 0, 'with_monitored_triggers' => 0, 'with_httptests' => 0, 'with_monitored_httptests' => 0, 'with_graphs' => 0, 'editable' => 0, 'nopermissions' => 0, 'extendoutput' => 0, 'select_templates' => 0, 'select_items' => 0, 'select_triggers' => 0, 'select_graphs' => 0, 'count' => 0, 'pattern' => '', 'extend_pattern' => 0, 'order' => '', 'limit' => 0);
        $options = array_merge($def_options, $options);
        // editable + PERMISSION CHECK
        if (defined('ZBX_API_REQUEST')) {
            $options['nopermissions'] = false;
        }
        if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
        } else {
            $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
            $sql_parts['from']['hg'] = 'hosts_groups hg';
            $sql_parts['from']['r'] = 'rights r';
            $sql_parts['from']['ug'] = 'users_groups ug';
            $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid';
            $sql_parts['where'][] = 'r.id=hg.groupid ';
            $sql_parts['where'][] = 'r.groupid=ug.usrgrpid';
            $sql_parts['where'][] = 'ug.userid=' . $userid;
            $sql_parts['where'][] = 'r.permission>=' . $permission;
            $sql_parts['where'][] = 'NOT EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups gg ' . ' WHERE hgg.hostid=hg.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . ')';
        }
        // nodeids
        $nodeids = $options['nodeids'] ? $options['nodeids'] : get_current_nodeid(false);
        // groupids
        if ($options['groupids'] != 0) {
            zbx_value2array($options['groupids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['groupid'] = 'hg.groupid';
            }
            $sql_parts['from']['hg'] = 'hosts_groups hg';
            $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
            $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid';
        }
        // hostids
        if ($options['hostids'] != 0) {
            zbx_value2array($options['hostids']);
            $sql_parts['where'][] = DBcondition('h.hostid', $options['hostids']);
        }
        // templateids
        if ($options['templateids'] != 0) {
            zbx_value2array($options['templateids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['templateid'] = 'ht.templateid';
            }
            $sql_parts['from']['ht'] = 'hosts_templates ht';
            $sql_parts['where'][] = DBcondition('ht.templateid', $options['templateids']);
            $sql_parts['where']['hht'] = 'h.hostid=ht.hostid';
        }
        // triggerids
        if ($options['triggerids'] != 0) {
            zbx_value2array($options['triggerids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['triggerid'] = 'f.triggerid';
            }
            $sql_parts['from']['f'] = 'functions f';
            $sql_parts['from']['i'] = 'items i';
            $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']);
            $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
            $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
        }
        // graphids
        if ($options['graphids'] != 0) {
            zbx_value2array($options['graphids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['graphid'] = 'gi.graphid';
            }
            $sql_parts['from']['gi'] = 'graphs_items gi';
            $sql_parts['from']['i'] = 'items i';
            $sql_parts['where'][] = DBcondition('gi.graphid', $options['graphids']);
            $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
            $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
        }
        // monitored_hosts, templated_hosts
        if ($options['monitored_hosts'] != 0) {
            $sql_parts['where'][] = 'h.status=' . HOST_STATUS_MONITORED;
        } else {
            if ($options['templated_hosts'] != 0) {
                $sql_parts['where'][] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')';
            } else {
                $sql_parts['where'][] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')';
            }
        }
        // with_items, with_monitored_items, with_historical_items
        if ($options['with_items'] != 0) {
            $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid )';
        } else {
            if ($options['with_monitored_items'] != 0) {
                $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND i.status=' . ITEM_STATUS_ACTIVE . ')';
            } else {
                if ($options['with_historical_items']) {
                    $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND (i.status=' . ITEM_STATUS_ACTIVE . ' OR i.status=' . ITEM_STATUS_NOTSUPPORTED . ') AND i.lastvalue IS NOT NULL)';
                }
            }
        }
        // with_triggers, with_monitored_triggers
        if ($options['with_triggers'] != 0) {
            $sql_parts['where'][] = 'EXISTS( 
					SELECT i.itemid
					FROM items i, functions f, triggers t
					WHERE i.hostid=h.hostid 
						AND i.itemid=f.itemid 
						AND f.triggerid=t.triggerid)';
        } else {
            if ($options['with_monitored_triggers'] != 0) {
                $sql_parts['where'][] = 'EXISTS( 
					SELECT i.itemid 
					FROM items i, functions f, triggers t
					WHERE i.hostid=h.hostid 
						AND i.status=' . ITEM_STATUS_ACTIVE . '
						AND i.itemid=f.itemid 
						AND f.triggerid=t.triggerid 
						AND t.status=' . TRIGGER_STATUS_ENABLED . ')';
            }
        }
        // with_httptests, with_monitored_httptests
        if ($options['with_httptests'] != 0) {
            $sql_parts['where'][] = 'EXISTS( 
					SELECT a.applicationid 
					FROM applications a, httptest ht 
					WHERE a.hostid=h.hostid 
						AND ht.applicationid=a.applicationid)';
        } else {
            if ($options['with_monitored_httptests'] != 0) {
                $sql_parts['where'][] = 'EXISTS( 
					SELECT a.applicationid 	
					FROM applications a, httptest ht 	
					WHERE a.hostid=h.hostid	
						AND ht.applicationid=a.applicationid 	
						AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')';
            }
        }
        // with_graphs
        if ($options['with_graphs'] != 0) {
            $sql_parts['where'][] = 'EXISTS( 
					SELECT DISTINCT i.itemid 
					FROM items i, graphs_items gi 
					WHERE i.hostid=h.hostid 
						AND i.itemid=gi.itemid)';
        }
        // extendoutput
        if ($options['extendoutput'] != 0) {
            $sql_parts['select']['hosts'] = 'h.*';
        }
        // count
        if ($options['count'] != 0) {
            $options['select_templates'] = 0;
            $options['select_items'] = 0;
            $options['select_triggers'] = 0;
            $options['select_graphs'] = 0;
            $sql_parts['select'] = array('count(h.hostid) as rowscount');
        }
        // pattern
        if (!zbx_empty($options['pattern'])) {
            if ($options['extend_pattern']) {
                $sql_parts['where'][] = ' ( ' . 'UPPER(h.host) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%') . ' OR ' . 'h.ip LIKE ' . zbx_dbstr('%' . $options['pattern'] . '%') . ' OR ' . 'UPPER(h.dns) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%') . ' ) ';
            } else {
                $sql_parts['where'][] = ' UPPER(h.host) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%');
            }
        }
        // order
        // restrict not allowed columns for sorting
        $options['order'] = str_in_array($options['order'], $sort_columns) ? $options['order'] : '';
        if (!zbx_empty($options['order'])) {
            $sql_parts['order'][] = 'h.' . $options['order'];
            if (!str_in_array('h.' . $options['order'], $sql_parts['select'])) {
                $sql_parts['select'][] = 'h.' . $options['order'];
            }
        }
        // limit
        if (zbx_ctype_digit($options['limit']) && $options['limit']) {
            $sql_parts['limit'] = $options['limit'];
        }
        //-------
        $hostids = array();
        $sql_parts['select'] = array_unique($sql_parts['select']);
        $sql_parts['from'] = array_unique($sql_parts['from']);
        $sql_parts['where'] = array_unique($sql_parts['where']);
        $sql_parts['order'] = array_unique($sql_parts['order']);
        $sql_select = '';
        $sql_from = '';
        $sql_where = '';
        $sql_order = '';
        if (!empty($sql_parts['select'])) {
            $sql_select .= implode(',', $sql_parts['select']);
        }
        if (!empty($sql_parts['from'])) {
            $sql_from .= implode(',', $sql_parts['from']);
        }
        if (!empty($sql_parts['where'])) {
            $sql_where .= ' AND ' . implode(' AND ', $sql_parts['where']);
        }
        if (!empty($sql_parts['order'])) {
            $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
        }
        $sql_limit = $sql_parts['limit'];
        $sql = 'SELECT ' . $sql_select . '
				FROM ' . $sql_from . '
				WHERE ' . DBin_node('h.hostid', $nodeids) . $sql_where . $sql_order;
        $res = DBselect($sql, $sql_limit);
        while ($host = DBfetch($res)) {
            if ($options['count']) {
                $result = $host;
            } else {
                $hostids[$host['hostid']] = $host['hostid'];
                if ($options['extendoutput'] == 0) {
                    $result[$host['hostid']] = $host['hostid'];
                } else {
                    if (!isset($result[$host['hostid']])) {
                        $result[$host['hostid']] = array();
                    }
                    if ($options['select_templates'] && !isset($result[$host['hostid']]['templateids'])) {
                        $result[$host['hostid']]['templateids'] = array();
                        $result[$host['hostid']]['templates'] = array();
                    }
                    if ($options['select_items'] && !isset($result[$host['hostid']]['itemids'])) {
                        $result[$host['hostid']]['itemids'] = array();
                        $result[$host['hostid']]['items'] = array();
                    }
                    if ($options['select_triggers'] && !isset($result[$host['hostid']]['triggerids'])) {
                        $result[$host['hostid']]['triggerids'] = array();
                        $result[$host['hostid']]['triggers'] = array();
                    }
                    if ($options['select_graphs'] && !isset($result[$host['hostid']]['graphids'])) {
                        $result[$host['hostid']]['graphids'] = array();
                        $result[$host['hostid']]['graphs'] = array();
                    }
                    // groupids
                    if (isset($host['groupid'])) {
                        if (!isset($result[$host['hostid']]['groupids'])) {
                            $result[$host['hostid']]['groupids'] = array();
                        }
                        $result[$host['hostid']]['groupids'][$host['groupid']] = $host['groupid'];
                        unset($host['groupid']);
                    }
                    // templateids
                    if (isset($host['templateid'])) {
                        if (!isset($result[$host['hostid']]['templateids'])) {
                            $result[$host['hostid']]['templateids'] = array();
                        }
                        $result[$host['hostid']]['templateids'][$host['templateid']] = $host['templateid'];
                        unset($host['templateid']);
                    }
                    // triggerids
                    if (isset($host['triggerid'])) {
                        if (!isset($result[$host['hostid']]['triggerids'])) {
                            $result[$host['hostid']]['triggerids'] = array();
                        }
                        $result[$host['hostid']]['triggerids'][$host['triggerid']] = $host['triggerid'];
                        unset($host['triggerid']);
                    }
                    // itemids
                    if (isset($host['itemid'])) {
                        if (!isset($result[$host['hostid']]['itemids'])) {
                            $result[$host['hostid']]['itemids'] = array();
                        }
                        $result[$host['hostid']]['itemids'][$host['itemid']] = $host['itemid'];
                        unset($host['itemid']);
                    }
                    // graphids
                    if (isset($host['graphid'])) {
                        if (!isset($result[$host['hostid']]['graphids'])) {
                            $result[$host['hostid']]['graphids'] = array();
                        }
                        $result[$host['hostid']]['graphids'][$host['graphid']] = $host['graphid'];
                        unset($host['graphid']);
                    }
                    $result[$host['hostid']] += $host;
                }
            }
        }
        // Adding Objects
        // Adding Templates
        if ($options['select_templates']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids);
            $templates = CTemplate::get($obj_params);
            foreach ($templates as $templateid => $template) {
                foreach ($template['hostids'] as $num => $hostid) {
                    $result[$hostid]['templateids'][$templateid] = $templateid;
                    $result[$hostid]['templates'][$templateid] = $template;
                }
            }
        }
        // Adding Items
        if ($options['select_items']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids, 'nopermissions' => 1);
            $items = CItem::get($obj_params);
            foreach ($items as $itemid => $item) {
                foreach ($item['hostids'] as $num => $hostid) {
                    $result[$hostid]['itemids'][$itemid] = $itemid;
                    $result[$hostid]['items'][$itemid] = $item;
                }
            }
        }
        // Adding triggers
        if ($options['select_triggers']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids);
            $triggers = CTrigger::get($obj_params);
            foreach ($triggers as $triggerid => $trigger) {
                foreach ($trigger['hostids'] as $num => $hostid) {
                    $result[$hostid]['triggerids'][$triggerid] = $triggerid;
                    $result[$hostid]['triggers'][$triggerid] = $trigger;
                }
            }
        }
        // Adding graphs
        if ($options['select_graphs']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids);
            $graphs = CGraph::get($obj_params);
            foreach ($graphs as $graphid => $graph) {
                foreach ($graph['hostids'] as $num => $hostid) {
                    $result[$hostid]['graphids'][$graphid] = $graphid;
                    $result[$hostid]['graphs'][$graphid] = $graph;
                }
            }
        }
        return $result;
    }
Beispiel #20
0
 private static function item($action, $params)
 {
     CItem::$error = array();
     switch ($action) {
         case 'add':
             $result = CItem::add($params);
             break;
         case 'get':
             $result = CItem::get($params);
             break;
         case 'getById':
             $result = CItem::getById($params);
             break;
         case 'getId':
             $result = CItem::getId($params);
             break;
         case 'update':
             $result = CItem::update($params);
             break;
         case 'delete':
             $result = CItem::delete($params);
             break;
         default:
             self::$result = array('error' => ZBX_API_ERROR_NO_METHOD, 'data' => 'Method: "' . $action . '" doesn\'t exist.');
             return;
             //exit function
     }
     if ($result !== false) {
         self::$result = array('result' => $result);
     } else {
         self::$result = CItem::$error;
     }
 }
 protected static function checkItems($screenitems)
 {
     $hostgroups = array();
     $hosts = array();
     $graphs = array();
     $items = array();
     $maps = array();
     $screens = array();
     $resources = array(SCREEN_RESOURCE_GRAPH, SCREEN_RESOURCE_SIMPLE_GRAPH, SCREEN_RESOURCE_PLAIN_TEXT, SCREEN_RESOURCE_MAP, SCREEN_RESOURCE_SCREEN, SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW);
     foreach ($screenitems as $item) {
         if (isset($item['resourcetype']) && !isset($item['resourceid']) || !isset($item['resourcetype']) && isset($item['resourceid'])) {
             self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
         }
         if (isset($item['resourceid']) && $item['resourceid'] == 0) {
             if (uint_in_array($item['resourcetype'], $resources)) {
                 throw new Exception(S_INCORRECT_RESOURCE_PROVIDED_FOR_SCREEN_ITEM);
             } else {
                 continue;
             }
         }
         switch ($item['resourcetype']) {
             case SCREEN_RESOURCE_HOSTS_INFO:
             case SCREEN_RESOURCE_TRIGGERS_INFO:
             case SCREEN_RESOURCE_TRIGGERS_OVERVIEW:
             case SCREEN_RESOURCE_DATA_OVERVIEW:
             case SCREEN_RESOURCE_HOSTGROUP_TRIGGERS:
                 $hostgroups[] = $item['resourceid'];
                 break;
             case SCREEN_RESOURCE_HOST_TRIGGERS:
                 $hosts[] = $item['resourceid'];
                 break;
             case SCREEN_RESOURCE_GRAPH:
                 $graphs[] = $item['resourceid'];
                 break;
             case SCREEN_RESOURCE_SIMPLE_GRAPH:
             case SCREEN_RESOURCE_PLAIN_TEXT:
                 $items[] = $item['resourceid'];
                 break;
             case SCREEN_RESOURCE_MAP:
                 $maps[] = $item['resourceid'];
                 break;
             case SCREEN_RESOURCE_SCREEN:
                 $screens[] = $item['resourceid'];
                 break;
         }
     }
     if (!empty($hostgroups)) {
         $result = CHostGroup::get(array('groupids' => $hostgroups, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1));
         foreach ($hostgroups as $id) {
             if (!isset($result[$id])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, 'Incorrect Host group identity "' . $id . '" provided for Screens item resource');
             }
         }
     }
     if (!empty($hosts)) {
         $result = CHost::get(array('hostids' => $hosts, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1));
         foreach ($hosts as $id) {
             if (!isset($result[$id])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, 'Incorrect Host identity "' . $id . '" provided for Screens item resource');
             }
         }
     }
     if (!empty($graphs)) {
         $result = CGraph::get(array('graphids' => $graphs, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1));
         foreach ($graphs as $id) {
             if (!isset($result[$id])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, 'Incorrect Graph identity "' . $id . '" provided for Screens item resource');
             }
         }
     }
     if (!empty($items)) {
         $result = CItem::get(array('itemids' => $items, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1, 'webitems' => 1));
         foreach ($items as $id) {
             if (!isset($result[$id])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, 'Incorrect Item identity "' . $id . '" provided for Screens item resource');
             }
         }
     }
     if (!empty($maps)) {
         $result = CMap::get(array('sysmapids' => $maps, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1));
         foreach ($maps as $id) {
             if (!isset($result[$id])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, 'Incorrect Map identity "' . $id . '" provided for Screens item resource');
             }
         }
     }
     if (!empty($screens)) {
         $result = self::get(array('screenids' => $screens, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1));
         foreach ($screens as $id) {
             if (!isset($result[$id])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, 'Incorrect Screen identity "' . $id . '" provided for Screens item resource');
             }
         }
     }
 }
Beispiel #22
0
 /**
  * Get graph data
  *
  * <code>
  * $options = array(
  *	array 'graphids'				=> array(graphid1, graphid2, ...),
  *	array 'itemids'					=> array(itemid1, itemid2, ...),
  *	array 'hostids'					=> array(hostid1, hostid2, ...),
  *	int 'type'					=> 'graph type, chart/pie'
  *	boolean 'templated_graphs'			=> 'only templated graphs',
  *	int 'count'					=> 'count',
  *	string 'pattern'				=> 'search hosts by pattern in graph names',
  *	integer 'limit'					=> 'limit selection',
  *	string 'order'					=> 'depricated parameter (for now)'
  * );
  * </code>
  *
  * @static
  * @param array $options
  * @return array|boolean host data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $result = array();
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $result = array();
     $sort_columns = array('graphid');
     // allowed columns for sorting
     $sql_parts = array('select' => array('graphs' => 'g.graphid'), 'from' => array('graphs g'), 'where' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => 0, 'groupids' => 0, 'hostids' => 0, 'graphids' => 0, 'itemids' => 0, 'type' => 0, 'templated_graphs' => 0, 'editable' => 0, 'nopermission' => 0, 'select_hosts' => 0, 'select_templates' => 0, 'select_items' => 0, 'extendoutput' => 0, 'count' => 0, 'pattern' => '', 'limit' => 0, 'order' => '');
     $options = array_merge($def_options, $options);
     // editable + PERMISSION CHECK
     if (defined('ZBX_API_REQUEST')) {
         $options['nopermissions'] = false;
     }
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['from']['i'] = 'items i';
         $sql_parts['from']['hg'] = 'hosts_groups hg';
         $sql_parts['from']['r'] = 'rights r';
         $sql_parts['from']['ug'] = 'users_groups ug';
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where'][] = 'r.id=hg.groupid ';
         $sql_parts['where'][] = 'r.groupid=ug.usrgrpid';
         $sql_parts['where'][] = 'ug.userid=' . $userid;
         $sql_parts['where'][] = 'r.permission>=' . $permission;
         $sql_parts['where'][] = 'NOT EXISTS( ' . ' SELECT gii.graphid ' . ' FROM graphs_items gii, items ii ' . ' WHERE gii.graphid=g.graphid ' . ' AND gii.itemid=ii.itemid ' . ' AND EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups ugg ' . ' WHERE ii.hostid=hgg.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=ugg.usrgrpid ' . ' AND ugg.userid=' . $userid . ' AND rr.permission<' . $permission . '))';
     }
     // nodeids
     $nodeids = $options['nodeids'] ? $options['nodeids'] : get_current_nodeid(false);
     // groupids
     if ($options['groupids'] != 0) {
         zbx_value2array($options['groupids']);
         if ($options['extendoutput'] != 0) {
             $sql_parts['select']['groupid'] = 'hg.groupid';
         }
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['from']['i'] = 'items i';
         $sql_parts['from']['hg'] = 'hosts_groups hg';
         $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
         $sql_parts['where'][] = 'hg.hostid=i.hostid';
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
     }
     // hostids
     if ($options['hostids'] != 0) {
         zbx_value2array($options['hostids']);
         if ($options['extendoutput'] != 0) {
             $sql_parts['select']['hostid'] = 'i.hostid';
         }
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['from']['i'] = 'items i';
         $sql_parts['where'][] = DBcondition('i.hostid', $options['hostids']);
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
     }
     // graphids
     if ($options['graphids'] != 0) {
         $sql_parts['where'][] = DBcondition('g.graphid', $options['graphids']);
     }
     // itemids
     if ($options['itemids'] != 0) {
         zbx_value2array($options['itemids']);
         if ($options['extendoutput'] != 0) {
             $sql_parts['select']['itemid'] = 'gi.itemid';
         }
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where'][] = DBcondition('gi.itemid', $options['itemids']);
     }
     // type
     if ($options['type'] != 0) {
         $sql_parts['where'][] = 'g.type=' . $options['type'];
     }
     // templated_graphs
     if ($options['templated_graphs'] != 0) {
         $sql_parts['where'][] = 'g.templateid<>0';
     }
     // extendoutput
     if ($options['extendoutput'] != 0) {
         $sql_parts['select']['graphs'] = 'g.*';
     }
     // count
     if ($options['count'] != 0) {
         $sql_parts['select']['graphs'] = 'count(g.graphid) as count';
     }
     // pattern
     if (!zbx_empty($options['pattern'])) {
         $sql_parts['where'][] = ' UPPER(g.name) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%');
     }
     // order
     // restrict not allowed columns for sorting
     $options['order'] = in_array($options['order'], $sort_columns) ? $options['order'] : '';
     if (!zbx_empty($options['order'])) {
         $sql_parts['order'][] = 'g.' . $options['order'];
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //------------
     $graphids = array();
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= ' AND ' . implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . DBin_node('g.graphid', $nodeids) . $sql_where . $sql_order;
     $db_res = DBselect($sql, $sql_limit);
     while ($graph = DBfetch($db_res)) {
         if ($options['count']) {
             $result = $graph;
         } else {
             if (!$options['extendoutput']) {
                 $result[$graph['graphid']] = $graph['graphid'];
             } else {
                 $graphids[$graph['graphid']] = $graph['graphid'];
                 if (!isset($result[$graph['graphid']])) {
                     $result[$graph['graphid']] = array();
                 }
                 if ($options['select_hosts'] && !isset($result[$graph['graphid']]['hostids'])) {
                     $result[$graph['graphid']]['hostids'] = array();
                     $result[$graph['graphid']]['hosts'] = array();
                 }
                 if ($options['select_templates'] && !isset($result[$graph['graphid']]['templateids'])) {
                     $result[$graph['graphid']]['templateids'] = array();
                     $result[$graph['graphid']]['templates'] = array();
                 }
                 if ($options['select_items'] && !isset($result[$graph['graphid']]['itemids'])) {
                     $result[$graph['graphid']]['itemids'] = array();
                     $result[$graph['graphid']]['items'] = array();
                 }
                 // hostids
                 if (isset($graph['hostid'])) {
                     if (!isset($result[$graph['graphid']]['hostids'])) {
                         $result[$graph['graphid']]['hostids'] = array();
                     }
                     $result[$graph['graphid']]['hostids'][$graph['hostid']] = $graph['hostid'];
                     unset($graph['hostid']);
                 }
                 // itemids
                 if (isset($graph['itemid'])) {
                     if (!isset($result[$graph['graphid']]['itemid'])) {
                         $result[$graph['graphid']]['itemid'] = array();
                     }
                     $result[$graph['graphid']]['itemids'][$graph['itemid']] = $graph['itemid'];
                     unset($graph['itemid']);
                 }
                 $result[$graph['graphid']] += $graph;
             }
         }
     }
     // Adding Hosts
     if ($options['select_hosts']) {
         $obj_params = array('extendoutput' => 1, 'graphids' => $graphids, 'nopermissions' => 1);
         $hosts = CHost::get($obj_params);
         foreach ($hosts as $hostid => $host) {
             foreach ($host['graphids'] as $num => $graphid) {
                 $result[$graphid]['hostids'][$hostid] = $hostid;
                 $result[$graphid]['hosts'][$hostid] = $host;
             }
         }
     }
     // Adding Templates
     if ($options['select_templates']) {
         $obj_params = array('extendoutput' => 1, 'graphids' => $graphids, 'nopermissions' => 1);
         $templates = CTemplate::get($obj_params);
         foreach ($templates as $templateid => $template) {
             foreach ($template['graphids'] as $num => $graphid) {
                 $result[$graphid]['templateids'][$templateid] = $templateid;
                 $result[$graphid]['templates'][$templateid] = $template;
             }
         }
     }
     // Adding Items
     if ($options['select_items']) {
         $obj_params = array('extendoutput' => 1, 'graphids' => $graphids, 'nopermissions' => 1);
         $items = CItem::get($obj_params);
         foreach ($items as $itemid => $item) {
             foreach ($item['graphids'] as $num => $graphid) {
                 $result[$graphid]['itemids'][$itemid] = $itemid;
                 $result[$graphid]['items'][$itemid] = $item;
             }
         }
     }
     return $result;
 }
            $slink .= "{$target_id}/";
        }
        if ($subtarget_id) {
            $slink .= "{$subtarget_id}";
        }
        print "<li " . ($id_category == $current_category ? 'class="active" >' : ">") . l(t($category_name), "poker/shop/shop/{$slink}") . "</li>";
    }
}
?>
			</ul>
			</div>
		</div>
		<div class="right">
			<div id="items">
				<?php 
$fitem = new CItem();
if (!$error) {
    if ($items) {
        print theme('os_poker_item_list', $items);
    }
} else {
    print $error;
}
?>
			</div>
		</div>
	</div>
	<div class="footer">
		<div class="left">
			<?php 
print t("Info:") . "<br/>" . t("Purchase taken from Off-Table Chips.");
Beispiel #24
0
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**/
require_once 'include/config.inc.php';
require_once 'include/graphs.inc.php';
$page['file'] = 'chart7.php';
// $page['title']	= "S_CHART";
$page['type'] = PAGE_TYPE_IMAGE;
include_once 'include/page_header.php';
//		VAR			TYPE	OPTIONAL FLAGS	VALIDATION	EXCEPTION
$fields = array('period' => array(T_ZBX_INT, O_OPT, P_NZERO, BETWEEN(ZBX_MIN_PERIOD, ZBX_MAX_PERIOD), null), 'from' => array(T_ZBX_INT, O_OPT, P_NZERO, null, null), 'stime' => array(T_ZBX_INT, O_OPT, P_NZERO, null, null), 'border' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'name' => array(T_ZBX_STR, O_OPT, NULL, null, null), 'width' => array(T_ZBX_INT, O_OPT, NULL, BETWEEN(0, 65535), null), 'height' => array(T_ZBX_INT, O_OPT, NULL, BETWEEN(0, 65535), null), 'graphtype' => array(T_ZBX_INT, O_OPT, NULL, IN('2,3'), null), 'graph3d' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'legend' => array(T_ZBX_INT, O_OPT, P_NZERO, IN('0,1'), null), 'items' => array(T_ZBX_STR, O_OPT, NULL, null, null));
check_fields($fields);
$items = get_request('items', array());
asort_by_key($items, 'sortorder');
$options = array('webitems' => 1, 'itemids' => zbx_objectValues($items, 'itemid'), 'nodeids' => get_current_nodeid(true));
$db_data = CItem::get($options);
$db_data = zbx_toHash($db_data, 'itemid');
foreach ($items as $id => $gitem) {
    if (!isset($db_data[$gitem['itemid']])) {
        access_deny();
    }
}
$effectiveperiod = navigation_bar_calc();
$graph = new CPie(get_request('graphtype', GRAPH_TYPE_NORMAL));
$graph->setHeader(get_request('name', ''));
$graph3d = get_request('graph3d', 0);
$legend = get_request('legend', 0);
if ($graph3d == 1) {
    $graph->switchPie3D();
}
$graph->showLegend($legend);
Beispiel #25
0
$_REQUEST['graph3d'] = get_request('graph3d', 0);
$_REQUEST['legend'] = get_request('legend', 0);
// ---- <ACTIONS> ----
if (isset($_REQUEST['clone']) && isset($_REQUEST['graphid'])) {
    unset($_REQUEST['graphid']);
    $_REQUEST['form'] = 'clone';
} else {
    if (isset($_REQUEST['save'])) {
        $items = get_request('items', array());
        $itemids = array();
        foreach ($items as $inum => $gitem) {
            $itemids[$gitem['itemid']] = $gitem['itemid'];
        }
        if (!empty($itemids)) {
            $options = array('nodeids' => get_current_nodeid(true), 'itemids' => $itemids, 'webitems' => 1, 'editable' => 1);
            $db_items = CItem::get($options);
            $db_items = zbx_toHash($db_items, 'itemid');
            foreach ($itemids as $inum => $itemid) {
                if (!isset($db_items[$itemid])) {
                    access_deny();
                }
            }
        }
        if (empty($items)) {
            info(S_REQUIRED_ITEMS_FOR_GRAPH);
            $result = false;
        } else {
            if (!isset($_REQUEST['ymin_type'])) {
                $_REQUEST['ymin_type'] = 0;
            }
            if (!isset($_REQUEST['ymax_type'])) {
 /**
  * Get Host data
  *
  * {@source}
  * @access public
  * @static
  * @since 1.8
  * @version 1
  *
  * @param _array $options
  * @param array $options['nodeids'] Node IDs
  * @param array $options['groupids'] HostGroup IDs
  * @param array $options['hostids'] Host IDs
  * @param boolean $options['monitored_hosts'] only monitored Hosts
  * @param boolean $options['templated_hosts'] include templates in result
  * @param boolean $options['with_items'] only with items
  * @param boolean $options['with_monitored_items'] only with monitored items
  * @param boolean $options['with_historical_items'] only with historical items
  * @param boolean $options['with_triggers'] only with triggers
  * @param boolean $options['with_monitored_triggers'] only with monitored triggers
  * @param boolean $options['with_httptests'] only with http tests
  * @param boolean $options['with_monitored_httptests'] only with monitored http tests
  * @param boolean $options['with_graphs'] only with graphs
  * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
  * @param int $options['extendoutput'] return all fields for Hosts
  * @param boolean $options['select_groups'] select HostGroups
  * @param boolean $options['select_templates'] select Templates
  * @param boolean $options['select_items'] select Items
  * @param boolean $options['select_triggers'] select Triggers
  * @param boolean $options['select_graphs'] select Graphs
  * @param boolean $options['select_applications'] select Applications
  * @param boolean $options['select_macros'] select Macros
  * @param boolean $options['select_profile'] select Profile
  * @param int $options['count'] count Hosts, returned column name is rowscount
  * @param string $options['pattern'] search hosts by pattern in Host name
  * @param string $options['extendPattern'] search hosts by pattern in Host name, ip and DNS
  * @param int $options['limit'] limit selection
  * @param string $options['sortfield'] field to sort by
  * @param string $options['sortorder'] sort order
  * @return array|boolean Host data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $result = array();
     $nodeCheck = false;
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $sort_columns = array('hostid', 'host', 'status', 'dns', 'ip');
     // allowed columns for sorting
     $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     // allowed output options for [ select_* ] params
     $sql_parts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'proxyids' => null, 'templateids' => null, 'itemids' => null, 'triggerids' => null, 'maintenanceids' => null, 'graphids' => null, 'dhostids' => null, 'dserviceids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'proxy_hosts' => null, 'with_items' => null, 'with_monitored_items' => null, 'with_historical_items' => null, 'with_triggers' => null, 'with_monitored_triggers' => null, 'with_httptests' => null, 'with_monitored_httptests' => null, 'with_graphs' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_groups' => null, 'selectParentTemplates' => null, 'select_items' => null, 'select_triggers' => null, 'select_graphs' => null, 'select_dhosts' => null, 'select_dservices' => null, 'select_applications' => null, 'select_macros' => null, 'select_profile' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($def_options, $options);
     if (!is_null($options['extendoutput'])) {
         $options['output'] = API_OUTPUT_EXTEND;
         if (!is_null($options['select_groups'])) {
             $options['select_groups'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['selectParentTemplates'])) {
             $options['selectParentTemplates'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_items'])) {
             $options['select_items'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_triggers'])) {
             $options['select_triggers'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_graphs'])) {
             $options['select_graphs'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_applications'])) {
             $options['select_applications'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_macros'])) {
             $options['select_macros'] = API_OUTPUT_EXTEND;
         }
     }
     if (is_array($options['output'])) {
         unset($sql_parts['select']['hosts']);
         $sql_parts['select']['hostid'] = ' h.hostid';
         foreach ($options['output'] as $key => $field) {
             $sql_parts['select'][$field] = ' h.' . $field;
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $sql_parts['where'][] = 'EXISTS (' . ' SELECT hh.hostid ' . ' FROM hosts hh, hosts_groups hgg, rights r, users_groups ug ' . ' WHERE hh.hostid=h.hostid ' . ' AND hh.hostid=hgg.hostid ' . ' AND r.id=hgg.groupid ' . ' AND r.groupid=ug.usrgrpid ' . ' AND ug.userid=' . $userid . ' AND r.permission>=' . $permission . ' AND NOT EXISTS( ' . ' SELECT hggg.groupid ' . ' FROM hosts_groups hggg, rights rr, users_groups gg ' . ' WHERE hggg.hostid=hgg.hostid ' . ' AND rr.id=hggg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . ' )) ';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         $sql_parts['where']['hostid'] = DBcondition('h.hostid', $options['hostids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('h.hostid', $nodeids);
         }
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['groupid'] = 'hg.groupid';
         }
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
         $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['groupid'] = 'hg.groupid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('hg.groupid', $nodeids);
         }
     }
     // proxyids
     if (!is_null($options['proxyids'])) {
         zbx_value2array($options['proxyids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['proxy_hostid'] = 'h.proxy_hostid';
         }
         $sql_parts['where'][] = DBcondition('h.proxy_hostid', $options['proxyids']);
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['templateid'] = 'ht.templateid';
         }
         $sql_parts['from']['hosts_templates'] = 'hosts_templates ht';
         $sql_parts['where'][] = DBcondition('ht.templateid', $options['templateids']);
         $sql_parts['where']['hht'] = 'h.hostid=ht.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['templateid'] = 'ht.templateid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('ht.templateid', $nodeids);
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['itemid'] = 'i.itemid';
         }
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where'][] = DBcondition('i.itemid', $options['itemids']);
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('i.itemid', $nodeids);
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['triggerid'] = 'f.triggerid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']);
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('f.triggerid', $nodeids);
         }
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['graphid'] = 'gi.graphid';
         }
         $sql_parts['from']['graphs_items'] = 'graphs_items gi';
         $sql_parts['from']['items'] = 'items i';
         $sql_parts['where'][] = DBcondition('gi.graphid', $options['graphids']);
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sql_parts['where'][] = DBin_node('gi.graphid', $nodeids);
         }
     }
     // dhostids
     if (!is_null($options['dhostids'])) {
         zbx_value2array($options['dhostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['dhostid'] = 'ds.dhostid';
         }
         $sql_parts['from']['dservices'] = 'dservices ds';
         $sql_parts['where'][] = DBcondition('ds.dhostid', $options['dhostids']);
         $sql_parts['where']['dsh'] = 'ds.ip=h.ip';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['dhostid'] = 'ds.dhostid';
         }
     }
     // dserviceids
     if (!is_null($options['dserviceids'])) {
         zbx_value2array($options['dserviceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['dserviceid'] = 'ds.dserviceid';
         }
         $sql_parts['from']['dservices'] = 'dservices ds';
         $sql_parts['where'][] = DBcondition('ds.dserviceid', $options['dserviceids']);
         $sql_parts['where']['dsh'] = 'ds.ip=h.ip';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['dserviceid'] = 'ds.dserviceid';
         }
     }
     // maintenanceids
     if (!is_null($options['maintenanceids'])) {
         zbx_value2array($options['maintenanceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['maintenanceid'] = 'mh.maintenanceid';
         }
         $sql_parts['from']['maintenances_hosts'] = 'maintenances_hosts mh';
         $sql_parts['where'][] = DBcondition('mh.maintenanceid', $options['maintenanceids']);
         $sql_parts['where']['hmh'] = 'h.hostid=mh.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['maintenanceid'] = 'mh.maintenanceid';
         }
     }
     // node check !!!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sql_parts['where'][] = DBin_node('h.hostid', $nodeids);
     }
     // monitored_hosts, templated_hosts
     if (!is_null($options['monitored_hosts'])) {
         $sql_parts['where']['status'] = 'h.status=' . HOST_STATUS_MONITORED;
     } else {
         if (!is_null($options['templated_hosts'])) {
             $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')';
         } else {
             if (!is_null($options['proxy_hosts'])) {
                 $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')';
             } else {
                 $sql_parts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')';
             }
         }
     }
     // with_items, with_monitored_items, with_historical_items
     if (!is_null($options['with_items'])) {
         $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid )';
     } else {
         if (!is_null($options['with_monitored_items'])) {
             $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND i.status=' . ITEM_STATUS_ACTIVE . ')';
         } else {
             if (!is_null($options['with_historical_items'])) {
                 $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND (i.status=' . ITEM_STATUS_ACTIVE . ' OR i.status=' . ITEM_STATUS_NOTSUPPORTED . ') AND i.lastvalue IS NOT NULL)';
             }
         }
     }
     // with_triggers, with_monitored_triggers
     if (!is_null($options['with_triggers'])) {
         $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid)';
     } else {
         if (!is_null($options['with_monitored_triggers'])) {
             $sql_parts['where'][] = 'EXISTS( ' . ' SELECT i.itemid ' . ' FROM items i, functions f, triggers t ' . ' WHERE i.hostid=h.hostid ' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.itemid=f.itemid ' . ' AND f.triggerid=t.triggerid ' . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')';
         }
     }
     // with_httptests, with_monitored_httptests
     if (!is_null($options['with_httptests'])) {
         $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid)';
     } else {
         if (!is_null($options['with_monitored_httptests'])) {
             $sql_parts['where'][] = 'EXISTS( ' . ' SELECT a.applicationid ' . ' FROM applications a, httptest ht ' . ' WHERE a.hostid=h.hostid ' . ' AND ht.applicationid=a.applicationid ' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')';
         }
     }
     // with_graphs
     if (!is_null($options['with_graphs'])) {
         $sql_parts['where'][] = 'EXISTS( ' . ' SELECT DISTINCT i.itemid ' . ' FROM items i, graphs_items gi ' . ' WHERE i.hostid=h.hostid ' . ' AND i.itemid=gi.itemid)';
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sql_parts['select']['hosts'] = 'h.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sql_parts['select'] = array('count(DISTINCT h.hostid) as rowscount');
         //groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sql_parts['group'] as $key => $fields) {
                 $sql_parts['select'][$key] = $fields;
             }
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('hosts h', $options, $sql_parts);
     }
     // filter
     if (is_array($options['filter'])) {
         zbx_db_filter('hosts h', $options, $sql_parts);
     }
     // order
     // restrict not allowed columns for sorting
     $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : '';
     if (!zbx_empty($options['sortfield'])) {
         $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP;
         $sql_parts['order'][$options['sortfield']] = 'h.' . $options['sortfield'] . ' ' . $sortorder;
         if (!str_in_array('h.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('h.*', $sql_parts['select'])) {
             $sql_parts['select'][$options['sortfield']] = 'h.' . $options['sortfield'];
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //-------
     $hostids = array();
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['group'] = array_unique($sql_parts['group']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_group = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['group'])) {
         $sql_where .= ' GROUP BY ' . implode(',', $sql_parts['group']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . $sql_where . $sql_group . $sql_order;
     //SDI($sql);
     $res = DBselect($sql, $sql_limit);
     while ($host = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $host;
             } else {
                 $result = $host['rowscount'];
             }
         } else {
             $hostids[$host['hostid']] = $host['hostid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$host['hostid']] = array('hostid' => $host['hostid']);
             } else {
                 if (!isset($result[$host['hostid']])) {
                     $result[$host['hostid']] = array();
                 }
                 if (!is_null($options['select_groups']) && !isset($result[$host['hostid']]['groups'])) {
                     $result[$host['hostid']]['groups'] = array();
                 }
                 if (!is_null($options['selectParentTemplates']) && !isset($result[$host['hostid']]['parentTemplates'])) {
                     $result[$host['hostid']]['parentTemplates'] = array();
                 }
                 if (!is_null($options['select_items']) && !isset($result[$host['hostid']]['items'])) {
                     $result[$host['hostid']]['items'] = array();
                 }
                 if (!is_null($options['select_profile']) && !isset($result[$host['hostid']]['profile'])) {
                     $result[$host['hostid']]['profile'] = array();
                     $result[$host['hostid']]['profile_ext'] = array();
                 }
                 if (!is_null($options['select_triggers']) && !isset($result[$host['hostid']]['triggers'])) {
                     $result[$host['hostid']]['triggers'] = array();
                 }
                 if (!is_null($options['select_graphs']) && !isset($result[$host['hostid']]['graphs'])) {
                     $result[$host['hostid']]['graphs'] = array();
                 }
                 if (!is_null($options['select_dhosts']) && !isset($result[$host['hostid']]['dhosts'])) {
                     $result[$host['hostid']]['dhosts'] = array();
                 }
                 if (!is_null($options['select_dservices']) && !isset($result[$host['hostid']]['dservices'])) {
                     $result[$host['hostid']]['dservices'] = array();
                 }
                 if (!is_null($options['select_applications']) && !isset($result[$host['hostid']]['applications'])) {
                     $result[$host['hostid']]['applications'] = array();
                 }
                 if (!is_null($options['select_macros']) && !isset($result[$host['hostid']]['macros'])) {
                     $result[$host['hostid']]['macros'] = array();
                 }
                 //					if(!is_null($options['select_maintenances']) && !isset($result[$host['hostid']]['maintenances'])){
                 //						$result[$host['hostid']]['maintenances'] = array();
                 //					}
                 // groupids
                 if (isset($host['groupid']) && is_null($options['select_groups'])) {
                     if (!isset($result[$host['hostid']]['groups'])) {
                         $result[$host['hostid']]['groups'] = array();
                     }
                     $result[$host['hostid']]['groups'][] = array('groupid' => $host['groupid']);
                     unset($host['groupid']);
                 }
                 // templateids
                 if (isset($host['templateid'])) {
                     if (!isset($result[$host['hostid']]['templates'])) {
                         $result[$host['hostid']]['templates'] = array();
                     }
                     $result[$host['hostid']]['templates'][] = array('templateid' => $host['templateid']);
                     unset($host['templateid']);
                 }
                 // triggerids
                 if (isset($host['triggerid']) && is_null($options['select_triggers'])) {
                     if (!isset($result[$host['hostid']]['triggers'])) {
                         $result[$host['hostid']]['triggers'] = array();
                     }
                     $result[$host['hostid']]['triggers'][] = array('triggerid' => $host['triggerid']);
                     unset($host['triggerid']);
                 }
                 // itemids
                 if (isset($host['itemid']) && is_null($options['select_items'])) {
                     if (!isset($result[$host['hostid']]['items'])) {
                         $result[$host['hostid']]['items'] = array();
                     }
                     $result[$host['hostid']]['items'][] = array('itemid' => $host['itemid']);
                     unset($host['itemid']);
                 }
                 // graphids
                 if (isset($host['graphid']) && is_null($options['select_graphs'])) {
                     if (!isset($result[$host['hostid']]['graphs'])) {
                         $result[$host['hostid']]['graphs'] = array();
                     }
                     $result[$host['hostid']]['graphs'][] = array('graphid' => $host['graphid']);
                     unset($host['graphid']);
                 }
                 // dhostids
                 if (isset($host['dhostid']) && is_null($options['select_dhosts'])) {
                     if (!isset($result[$host['hostid']]['dhosts'])) {
                         $result[$host['hostid']]['dhosts'] = array();
                     }
                     $result[$host['hostid']]['dhosts'][] = array('dhostid' => $host['dhostid']);
                     unset($host['dhostid']);
                 }
                 // dserviceids
                 if (isset($host['dserviceid']) && is_null($options['select_dservices'])) {
                     if (!isset($result[$host['hostid']]['dservices'])) {
                         $result[$host['hostid']]['dservices'] = array();
                     }
                     $result[$host['hostid']]['dservices'][] = array('dserviceid' => $host['dserviceid']);
                     unset($host['dserviceid']);
                 }
                 // maintenanceids
                 if (isset($host['maintenanceid'])) {
                     if (!isset($result[$host['hostid']]['maintenanceid'])) {
                         $result[$host['hostid']]['maintenances'] = array();
                     }
                     $result[$host['hostid']]['maintenances'][] = array('maintenanceid' => $host['maintenanceid']);
                     //						unset($host['maintenanceid']);
                 }
                 //---
                 $result[$host['hostid']] += $host;
             }
         }
     }
     Copt::memoryPick();
     if (!is_null($options['countOutput'])) {
         if (is_null($options['preservekeys'])) {
             $result = zbx_cleanHashes($result);
         }
         return $result;
     }
     // Adding Objects
     // Adding Groups
     if (!is_null($options['select_groups']) && str_in_array($options['select_groups'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_groups'], 'hostids' => $hostids, 'preservekeys' => 1);
         $groups = CHostgroup::get($obj_params);
         foreach ($groups as $groupid => $group) {
             $ghosts = $group['hosts'];
             unset($group['hosts']);
             foreach ($ghosts as $num => $host) {
                 $result[$host['hostid']]['groups'][] = $group;
             }
         }
     }
     // Adding Profiles
     if (!is_null($options['select_profile'])) {
         $sql = 'SELECT hp.* ' . ' FROM hosts_profiles hp ' . ' WHERE ' . DBcondition('hp.hostid', $hostids);
         $db_profile = DBselect($sql);
         while ($profile = DBfetch($db_profile)) {
             $result[$profile['hostid']]['profile'] = $profile;
         }
         $sql = 'SELECT hpe.* ' . ' FROM hosts_profiles_ext hpe ' . ' WHERE ' . DBcondition('hpe.hostid', $hostids);
         $db_profile_ext = DBselect($sql);
         while ($profile_ext = DBfetch($db_profile_ext)) {
             $result[$profile_ext['hostid']]['profile_ext'] = $profile_ext;
         }
     }
     // Adding Templates
     if (!is_null($options['selectParentTemplates'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'preservekeys' => 1);
         if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['selectParentTemplates'];
             $templates = CTemplate::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($templates, 'host');
             }
             foreach ($templates as $templateid => $template) {
                 unset($templates[$templateid]['hosts']);
                 $count = array();
                 foreach ($template['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['parentTemplates'][] =& $templates[$templateid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['selectParentTemplates']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $templates = CTemplate::get($obj_params);
                 $templates = zbx_toHash($templates, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($templates[$hostid])) {
                         $result[$hostid]['templates'] = $templates[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['templates'] = 0;
                     }
                 }
             }
         }
     }
     // Adding Items
     if (!is_null($options['select_items'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_items']) || str_in_array($options['select_items'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_items'];
             $items = CItem::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($items, 'description');
             }
             foreach ($items as $itemid => $item) {
                 unset($items[$itemid]['hosts']);
                 foreach ($item['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['items'][] =& $items[$itemid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_items']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $items = CItem::get($obj_params);
                 $items = zbx_toHash($items, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($items[$hostid])) {
                         $result[$hostid]['items'] = $items[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['items'] = 0;
                     }
                 }
             }
         }
     }
     // Adding triggers
     if (!is_null($options['select_triggers'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_triggers']) || str_in_array($options['select_triggers'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_triggers'];
             $triggers = CTrigger::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($triggers, 'description');
             }
             foreach ($triggers as $triggerid => $trigger) {
                 unset($triggers[$triggerid]['hosts']);
                 foreach ($trigger['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['triggers'][] =& $triggers[$triggerid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_triggers']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $triggers = CTrigger::get($obj_params);
                 $triggers = zbx_toHash($triggers, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($triggers[$hostid])) {
                         $result[$hostid]['triggers'] = $triggers[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['triggers'] = 0;
                     }
                 }
             }
         }
     }
     // Adding graphs
     if (!is_null($options['select_graphs'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_graphs']) || str_in_array($options['select_graphs'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_graphs'];
             $graphs = CGraph::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($graphs, 'name');
             }
             foreach ($graphs as $graphid => $graph) {
                 unset($graphs[$graphid]['hosts']);
                 foreach ($graph['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['graphs'][] =& $graphs[$graphid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_graphs']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $graphs = CGraph::get($obj_params);
                 $graphs = zbx_toHash($graphs, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($graphs[$hostid])) {
                         $result[$hostid]['graphs'] = $graphs[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['graphs'] = 0;
                     }
                 }
             }
         }
     }
     // Adding discovery hosts
     if (!is_null($options['select_dhosts'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_dhosts']) || str_in_array($options['select_dhosts'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_dhosts'];
             $dhosts = CDHost::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($dhosts, 'dhostid');
             }
             foreach ($dhosts as $dhostid => $dhost) {
                 unset($dhosts[$dhostid]['hosts']);
                 foreach ($dhost['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['dhosts'][] =& $dhosts[$dhostid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_dhosts']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $dhosts = CDHost::get($obj_params);
                 $dhosts = zbx_toHash($dhosts, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($dhosts[$hostid])) {
                         $result[$hostid]['dhosts'] = $dhosts[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['dhosts'] = 0;
                     }
                 }
             }
         }
     }
     // Adding applications
     if (!is_null($options['select_applications'])) {
         $obj_params = array('nodeids' => $nodeids, 'hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['select_applications']) || str_in_array($options['select_applications'], $subselects_allowed_outputs)) {
             $obj_params['output'] = $options['select_applications'];
             $applications = CApplication::get($obj_params);
             if (!is_null($options['limitSelects'])) {
                 order_result($applications, 'name');
             }
             foreach ($applications as $applicationid => $application) {
                 unset($applications[$applicationid]['hosts']);
                 foreach ($application['hosts'] as $hnum => $host) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$host['hostid']])) {
                             $count[$host['hostid']] = 0;
                         }
                         $count[$host['hostid']]++;
                         if ($count[$host['hostid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$host['hostid']]['applications'][] =& $applications[$applicationid];
                 }
             }
         } else {
             if (API_OUTPUT_COUNT == $options['select_applications']) {
                 $obj_params['countOutput'] = 1;
                 $obj_params['groupCount'] = 1;
                 $applications = CApplication::get($obj_params);
                 $applications = zbx_toHash($applications, 'hostid');
                 foreach ($result as $hostid => $host) {
                     if (isset($applications[$hostid])) {
                         $result[$hostid]['applications'] = $applications[$hostid]['rowscount'];
                     } else {
                         $result[$hostid]['applications'] = 0;
                     }
                 }
             }
         }
     }
     // Adding macros
     if (!is_null($options['select_macros']) && str_in_array($options['select_macros'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_macros'], 'hostids' => $hostids, 'preservekeys' => 1);
         $macros = CUserMacro::get($obj_params);
         foreach ($macros as $macroid => $macro) {
             $mhosts = $macro['hosts'];
             unset($macro['hosts']);
             foreach ($mhosts as $num => $host) {
                 $result[$host['hostid']]['macros'][] = $macro;
             }
         }
     }
     Copt::memoryPick();
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
function get_item_function_info($expr)
{
    global $ZBX_TR_EXPR_SIMPLE_MACROS;
    $value_type = array(ITEM_VALUE_TYPE_UINT64 => S_NUMERIC_UINT64, ITEM_VALUE_TYPE_FLOAT => S_NUMERIC_FLOAT, ITEM_VALUE_TYPE_STR => S_CHARACTER, ITEM_VALUE_TYPE_LOG => S_LOG, ITEM_VALUE_TYPE_TEXT => S_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('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' => S_NUMERIC_UINT64, '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' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'fuzzytime' => array('value_type' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'iregexp' => array('value_type' => S_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' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'logseverity' => array('value_type' => S_NUMERIC_UINT64, 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY), 'logsource' => array('value_type' => S_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' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'now' => array('value_type' => S_NUMERIC_UINT64, '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' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'str' => array('value_type' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => IN('0,1')), 'strlen' => array('value_type' => S_NUMERIC_UINT64, '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'));
    if (isset($ZBX_TR_EXPR_SIMPLE_MACROS[$expr])) {
        $result = array('value_type' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => IN('0,1'));
    } else {
        if (preg_match('/^' . ZBX_PREG_EXPRESSION_USER_MACROS . '$/', $expr)) {
            $result = array('value_type' => S_0_OR_1, 'type' => T_ZBX_INT, 'validation' => NOT_EMPTY);
        } else {
            $hostId = $itemId = $function = null;
            $triggerExpr = new CTriggerExpression(array('expression' => $expr));
            if (empty($triggerExpr->errors)) {
                if (count($triggerExpr->data['macros']) > 0) {
                    $result = array('value_type' => S_NUMERIC_FLOAT, 'type' => T_ZBX_DBL, 'validation' => NOT_EMPTY);
                } else {
                    if (count($triggerExpr->expressions) > 0) {
                        $function = reset($triggerExpr->data['functions']);
                        $hostFound = CHost::get(array('filter' => array('host' => $triggerExpr->data['hosts']), 'templated_hosts' => true));
                        if (empty($hostFound)) {
                            return EXPRESSION_HOST_UNKNOWN;
                        }
                        $itemFound = CItem::get(array('hostids' => zbx_objectValues($hostFound, 'hostid'), 'filter' => array('key_' => $triggerExpr->data['items']), 'webitems' => true));
                        if (empty($itemFound)) {
                            return EXPRESSION_HOST_ITEM_UNKNOWN;
                        }
                        unset($triggerExpr);
                        $result = $function_info[$function];
                        if (is_array($result['value_type'])) {
                            $value_type = null;
                            $item_data = CItem::get(array('itemids' => zbx_objectValues($itemFound, 'itemid'), 'output' => API_OUTPUT_EXTEND, 'webitems' => true));
                            if ($item_data = reset($item_data)) {
                                $value_type = $item_data['value_type'];
                            }
                            if ($value_type == null) {
                                return VALUE_TYPE_UNKNOWN;
                            }
                            $result['value_type'] = $result['value_type'][$value_type];
                            $result['type'] = $result['type'][$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;
}