function triggerIdents($triggerids)
{
    $idents = array();
    $options = array('triggerids' => $triggerids, 'select_hosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND, 'nodeids' => get_current_nodeid(true));
    $triggers = CTrigger::get($options);
    foreach ($triggers as $tnum => $trigger) {
        $host = reset($trigger['hosts']);
        $idents[$trigger['triggerid']] = array('node' => get_node_name_by_elid($host['hostid'], true), 'host' => $host['host'], 'description' => $trigger['description'], 'expression' => explode_exp($trigger['expression'], false));
    }
    return $idents;
}
function make_latest_issues($filter = array())
{
    global $page;
    $config = select_config();
    $limit = isset($filter['limit']) ? $filter['limit'] : 20;
    $options = array('groupids' => $filter['groupids'], 'monitored' => 1, 'maintenance' => $filter['maintenance'], 'skipDependent' => 1, 'filter' => array('priority' => $filter['severity'], 'value' => TRIGGER_VALUE_TRUE), 'select_groups' => API_OUTPUT_EXTEND, 'select_hosts' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND, 'sortfield' => 'lastchange', 'sortorder' => ZBX_SORT_DOWN, 'limit' => $limit);
    if (isset($filter['hostids'])) {
        $options['hostids'] = $filter['hostids'];
    }
    $triggers = CTrigger::get($options);
    // GATHER HOSTS FOR SELECTED TRIGGERS {{{
    $triggers_hosts = array();
    foreach ($triggers as $tnum => $trigger) {
        // if trigger is lost(broken expression) we skip it
        if (empty($trigger['hosts'])) {
            unset($triggers[$tnum]);
            continue;
        }
        $triggers_hosts = array_merge($triggers_hosts, $trigger['hosts']);
    }
    $triggers_hosts = zbx_toHash($triggers_hosts, 'hostid');
    $triggers_hostids = array_keys($triggers_hosts);
    // }}} GATHER HOSTS FOR SELECTED TRIGGERS
    $scripts_by_hosts = CScript::getScriptsByHosts($triggers_hostids);
    $table = new CTableInfo();
    $table->setHeader(array(is_show_all_nodes() ? S_NODE : null, S_HOST, S_ISSUE, S_LAST_CHANGE, S_AGE, $config['event_ack_enable'] ? S_ACK : NULL, S_ACTIONS));
    $thosts_cache = array();
    foreach ($triggers as $tnum => $trigger) {
        // Check for dependencies
        $group = reset($trigger['groups']);
        $host = reset($trigger['hosts']);
        $trigger['hostid'] = $host['hostid'];
        $trigger['host'] = $host['host'];
        $host = null;
        $menus = '';
        $host_nodeid = id2nodeid($trigger['hostid']);
        foreach ($scripts_by_hosts[$trigger['hostid']] as $id => $script) {
            $script_nodeid = id2nodeid($script['scriptid']);
            if (bccomp($host_nodeid, $script_nodeid) == 0) {
                $menus .= "[" . zbx_jsvalue($script['name']) . ",\"javascript: openWinCentered('scripts_exec.php?execute=1&hostid=" . $trigger['hostid'] . "&scriptid=" . $script['scriptid'] . "','" . S_TOOLS . "',760,540,'titlebar=no, resizable=yes, scrollbars=yes, dialog=no');\", null,{'outer' : ['pum_o_item'],'inner' : ['pum_i_item']}],";
            }
        }
        if (!empty($scripts_by_hosts)) {
            $menus = "['" . S_TOOLS . "',null,null,{'outer' : ['pum_oheader'],'inner' : ['pum_iheader']}]," . $menus;
        }
        if (isset($thosts_cache[$trigger['hostid']])) {
            $hprofile = $thosts_cache[$trigger['hostid']];
        } else {
            $hprofile = CHost::get(array('hostids' => $trigger['hostid'], 'output' => API_OUTPUT_SHORTEN, 'select_profile' => API_OUTPUT_EXTEND));
            $hprofile = reset($hprofile);
            $thosts_cache[$hprofile['hostid']] = $hprofile;
        }
        $menus .= "['" . S_LINKS . "',null,null,{'outer' : ['pum_oheader'],'inner' : ['pum_iheader']}],";
        $menus .= "['" . S_LATEST_DATA . "',\"javascript: redirect('latest.php?groupid=" . $group['groupid'] . '&hostid=' . $trigger['hostid'] . "')\", null,{'outer' : ['pum_o_item'],'inner' : ['pum_i_item']}],";
        if (!empty($hprofile['profile'])) {
            $menus .= "['" . S_PROFILE . "',\"javascript: redirect('hostprofiles.php?hostid=" . $trigger['hostid'] . "&prof_type=0')\", null,{'outer' : ['pum_o_item'],'inner' : ['pum_i_item']}],";
        }
        if (!empty($hprofile['profile_ext'])) {
            $menus .= "['" . S_EXTENDED_PROFILE . "',\"javascript: redirect('hostprofiles.php?hostid=" . $trigger['hostid'] . "&prof_type=1')\", null,{'outer' : ['pum_o_item'],'inner' : ['pum_i_item']}],";
        }
        $menus = rtrim($menus, ',');
        $menus = 'show_popup_menu(event,[' . $menus . '],180);';
        $host = new CSpan($trigger['host'], 'link_menu pointer');
        $host->setAttribute('onclick', 'javascript: ' . $menus);
        //$host = new CSpan($trigger['host'],'link_menu pointer');
        //$host->setAttribute('onclick','javascript: '.$menus);
        // Maintenance {{{
        $trigger_host = $triggers_hosts[$trigger['hostid']];
        $text = null;
        $style = 'link_menu';
        if ($trigger_host['maintenance_status']) {
            $style .= ' orange';
            $options = array('maintenanceids' => $trigger_host['maintenanceid'], 'output' => API_OUTPUT_EXTEND);
            $maintenances = CMaintenance::get($options);
            $maintenance = reset($maintenances);
            $text = $maintenance['name'];
            $text .= ' [' . ($trigger_host['maintenance_type'] ? S_NO_DATA_MAINTENANCE : S_NORMAL_MAINTENANCE) . ']';
        }
        $host = new CSpan($trigger['host'], $style . ' pointer');
        $host->setAttribute('onclick', 'javascript: ' . $menus);
        if (!is_null($text)) {
            $host->setHint($text, '', '', false);
        }
        // }}} Maintenance
        $event_sql = 'SELECT e.eventid, e.value, e.clock, e.objectid as triggerid, e.acknowledged' . ' FROM events e' . ' WHERE e.object=' . EVENT_OBJECT_TRIGGER . ' AND e.objectid=' . $trigger['triggerid'] . ' AND e.value=' . TRIGGER_VALUE_TRUE . ' ORDER by e.object DESC, e.objectid DESC, e.eventid DESC';
        $res_events = DBSelect($event_sql, 1);
        while ($row_event = DBfetch($res_events)) {
            $ack = NULL;
            if ($config['event_ack_enable']) {
                if ($row_event['acknowledged'] == 1) {
                    $ack_info = make_acktab_by_eventid($row_event['eventid']);
                    $ack_info->setAttribute('style', 'width: auto;');
                    $ack = new CLink(S_YES, 'acknow.php?eventid=' . $row_event['eventid'] . '&backurl=' . $page['file'], 'off');
                    $ack->setHint($ack_info, '', '', false);
                } else {
                    $ack = new CLink(S_NO, 'acknow.php?eventid=' . $row_event['eventid'] . '&backurl=' . $page['file'], 'on');
                }
            }
            //			$description = expand_trigger_description($row['triggerid']);
            $description = expand_trigger_description_by_data(zbx_array_merge($trigger, array('clock' => $row_event['clock'])), ZBX_FLAG_EVENT);
            //actions
            $actions = get_event_actions_stat_hints($row_event['eventid']);
            $clock = new CLink(zbx_date2str(S_BLOCKS_LATEST_ISSUES_DATE_FORMAT, $row_event['clock']), 'events.php?triggerid=' . $trigger['triggerid'] . '&source=0&show_unknown=1&nav_time=' . $row_event['clock']);
            if ($trigger['url']) {
                $description = new CLink($description, $trigger['url'], null, null, true);
            } else {
                $description = new CSpan($description, 'pointer');
            }
            $description = new CCol($description, get_severity_style($trigger['priority']));
            $description->setHint(make_popup_eventlist($row_event['eventid'], $trigger['type'], $trigger['triggerid']), '', '', false);
            $table->addRow(array(get_node_name_by_elid($trigger['triggerid']), $host, $description, $clock, zbx_date2age($row_event['clock']), $ack, $actions));
        }
        unset($trigger, $description, $actions);
    }
    $table->setFooter(new CCol(S_UPDATED . ': ' . zbx_date2str(S_BLOCKS_LATEST_ISSUES_TIME_FORMAT)));
    return $table;
}
 /**
  * Get items 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['triggerids']
  * @param array $options['applicationids']
  * @param boolean $options['status']
  * @param boolean $options['templated_items']
  * @param boolean $options['editable']
  * @param boolean $options['count']
  * @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;
     $result = array();
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $sort_columns = array('itemid', 'description', 'key_', 'delay', 'history', 'trends', 'type', 'status');
     // 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('items' => 'i.itemid'), 'from' => array('items' => 'items i'), 'where' => array('webtype' => 'i.type<>9'), 'group' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'proxyids' => null, 'itemids' => null, 'graphids' => null, 'triggerids' => null, 'applicationids' => null, 'webitems' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'group' => null, 'host' => null, 'application' => null, 'belongs' => null, 'with_triggers' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_hosts' => null, 'select_triggers' => null, 'select_graphs' => null, 'select_applications' => null, 'countOutput' => null, 'groupCount' => 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_graphs'])) {
             $options['select_graphs'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_applications'])) {
             $options['select_applications'] = API_OUTPUT_EXTEND;
         }
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $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'][] = '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 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 = !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']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
         $sql_parts['where'][] = 'hg.hostid=i.hostid';
         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_EXTEND) {
             $sql_parts['select']['hostid'] = 'i.hostid';
         }
         $sql_parts['where']['hostid'] = DBcondition('i.hostid', $options['hostids']);
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['i'] = 'i.hostid';
         }
     }
     // proxyids
     if (!is_null($options['proxyids'])) {
         zbx_value2array($options['proxyids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sql_parts['select']['proxyid'] = 'h.proxy_hostid';
         }
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where'][] = DBcondition('h.proxy_hostid', $options['proxyids']);
         $sql_parts['where'][] = 'h.hostid=i.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['h'] = 'h.proxy_hostid';
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sql_parts['where']['itemid'] = DBcondition('i.itemid', $options['itemids']);
     }
     // 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['where'][] = DBcondition('f.triggerid', $options['triggerids']);
         $sql_parts['where']['if'] = 'i.itemid=f.itemid';
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['applicationid'] = 'ia.applicationid';
         }
         $sql_parts['from']['items_applications'] = 'items_applications ia';
         $sql_parts['where'][] = DBcondition('ia.applicationid', $options['applicationids']);
         $sql_parts['where']['ia'] = 'ia.itemid=i.itemid';
     }
     // 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['where'][] = DBcondition('gi.graphid', $options['graphids']);
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
     }
     // webitems
     if (!is_null($options['webitems'])) {
         unset($sql_parts['where']['webtype']);
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sql_parts['where'][] = 'i.templateid>0';
         } else {
             $sql_parts['where'][] = 'i.templateid=0';
         }
     }
     // templated
     if (!is_null($options['templated'])) {
         $sql_parts['from']['hosts'] = 'hosts h';
         $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;
         }
     }
     // monitored
     if (!is_null($options['monitored'])) {
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['monitored']) {
             $sql_parts['where'][] = 'h.status=' . HOST_STATUS_MONITORED;
             $sql_parts['where'][] = 'i.status=' . ITEM_STATUS_ACTIVE;
         } else {
             $sql_parts['where'][] = '(h.status<>' . HOST_STATUS_MONITORED . ' OR i.status<>' . ITEM_STATUS_ACTIVE . ')';
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('items i', $options, $sql_parts);
     }
     // --- FILTER ---
     if (is_array($options['filter'])) {
         zbx_db_filter('items i', $options, $sql_parts);
         if (isset($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sql_parts['from']['hosts'] = 'hosts h';
             $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
             $sql_parts['where']['h'] = DBcondition('h.host', $options['filter']['host'], false, true);
         }
     }
     // group
     if (!is_null($options['group'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['name'] = 'g.name';
         }
         $sql_parts['from']['groups'] = 'groups g';
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where']['ghg'] = 'g.groupid = hg.groupid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where'][] = ' 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']['hosts'] = 'hosts h';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         $sql_parts['where'][] = ' UPPER(h.host)=' . zbx_dbstr(zbx_strtoupper($options['host']));
     }
     // application
     if (!is_null($options['application'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['application'] = 'a.name as application';
         }
         $sql_parts['from']['applications'] = 'applications a';
         $sql_parts['from']['items_applications'] = 'items_applications ia';
         $sql_parts['where']['aia'] = 'a.applicationid = ia.applicationid';
         $sql_parts['where']['iai'] = 'ia.itemid=i.itemid';
         $sql_parts['where'][] = ' UPPER(a.name)=' . zbx_dbstr(zbx_strtoupper($options['application']));
     }
     // with_triggers
     if (!is_null($options['with_triggers'])) {
         if ($options['with_triggers'] == 1) {
             $sql_parts['where'][] = ' EXISTS ( SELECT functionid FROM functions ff WHERE ff.itemid=i.itemid )';
         } else {
             $sql_parts['where'][] = 'NOT EXISTS ( SELECT functionid FROM functions ff WHERE ff.itemid=i.itemid )';
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sql_parts['select']['items'] = 'i.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sql_parts['select'] = array('count(DISTINCT i.itemid) 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'][] = 'i.' . $options['sortfield'] . ' ' . $sortorder;
         if (!str_in_array('i.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('i.*', $sql_parts['select'])) {
             $sql_parts['select'][] = 'i.' . $options['sortfield'];
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //----------
     $itemids = 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('i.itemid', $nodeids) . $sql_where . $sql_group . $sql_order;
     $res = DBselect($sql, $sql_limit);
     while ($item = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $item;
             } else {
                 $result = $item['rowscount'];
             }
         } else {
             $itemids[$item['itemid']] = $item['itemid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$item['itemid']] = array('itemid' => $item['itemid']);
             } else {
                 if (!isset($result[$item['itemid']])) {
                     $result[$item['itemid']] = array();
                 }
                 if (!is_null($options['select_hosts']) && !isset($result[$item['itemid']]['hosts'])) {
                     $result[$item['itemid']]['hosts'] = array();
                 }
                 if (!is_null($options['select_triggers']) && !isset($result[$item['itemid']]['triggers'])) {
                     $result[$item['itemid']]['triggers'] = array();
                 }
                 if (!is_null($options['select_graphs']) && !isset($result[$item['itemid']]['graphs'])) {
                     $result[$item['itemid']]['graphs'] = array();
                 }
                 if (!is_null($options['select_applications']) && !isset($result[$item['itemid']]['applications'])) {
                     $result[$item['itemid']]['applications'] = array();
                 }
                 // hostids
                 if (isset($item['hostid']) && is_null($options['select_hosts'])) {
                     if (!isset($result[$item['itemid']]['hosts'])) {
                         $result[$item['itemid']]['hosts'] = array();
                     }
                     $result[$item['itemid']]['hosts'][] = array('hostid' => $item['hostid']);
                     //						unset($item['hostid']);
                 }
                 // triggerids
                 if (isset($item['triggerid']) && is_null($options['select_triggers'])) {
                     if (!isset($result[$item['itemid']]['triggers'])) {
                         $result[$item['itemid']]['triggers'] = array();
                     }
                     $result[$item['itemid']]['triggers'][] = array('triggerid' => $item['triggerid']);
                     unset($item['triggerid']);
                 }
                 // graphids
                 if (isset($item['graphid']) && is_null($options['select_graphs'])) {
                     if (!isset($result[$item['itemid']]['graphs'])) {
                         $result[$item['itemid']]['graphs'] = array();
                     }
                     $result[$item['itemid']]['graphs'][] = array('graphid' => $item['graphid']);
                     unset($item['graphid']);
                 }
                 // applicationids
                 if (isset($item['applicationid']) && is_null($options['select_applications'])) {
                     if (!isset($result[$item['itemid']]['applications'])) {
                         $result[$item['itemid']]['applications'] = array();
                     }
                     $result[$item['itemid']]['applications'][] = array('applicationid' => $item['applicationid']);
                     unset($item['applicationid']);
                 }
                 $result[$item['itemid']] += $item;
             }
         }
     }
     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'])) {
         if (is_array($options['select_hosts']) || str_in_array($options['select_hosts'], $subselects_allowed_outputs)) {
             $obj_params = array('nodeids' => $nodeids, 'itemids' => $itemids, 'templated_hosts' => 1, 'output' => $options['select_hosts'], 'nopermissions' => 1, 'preservekeys' => 1);
             $hosts = CHost::get($obj_params);
             foreach ($hosts as $hostid => $host) {
                 $hitems = $host['items'];
                 unset($host['items']);
                 foreach ($hitems as $inum => $item) {
                     $result[$item['itemid']]['hosts'][] = $host;
                 }
             }
             $templates = CTemplate::get($obj_params);
             foreach ($templates as $templateid => $template) {
                 $titems = $template['items'];
                 unset($template['items']);
                 foreach ($titems as $inum => $item) {
                     $result[$item['itemid']]['hosts'][] = $template;
                 }
             }
         }
     }
     // 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'], 'itemids' => $itemids, 'preservekeys' => 1);
         $triggers = CTrigger::get($obj_params);
         foreach ($triggers as $triggerid => $trigger) {
             $titems = $trigger['items'];
             unset($trigger['items']);
             foreach ($titems as $inum => $item) {
                 $result[$item['itemid']]['triggers'][] = $trigger;
             }
         }
     }
     // Adding graphs
     if (!is_null($options['select_graphs']) && str_in_array($options['select_graphs'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_graphs'], 'itemids' => $itemids, 'preservekeys' => 1);
         $graphs = CGraph::get($obj_params);
         foreach ($graphs as $graphid => $graph) {
             $gitems = $graph['items'];
             unset($graph['items']);
             foreach ($gitems as $inum => $item) {
                 $result[$item['itemid']]['graphs'][] = $graph;
             }
         }
     }
     // Adding applications
     if (!is_null($options['select_applications']) && str_in_array($options['select_applications'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_applications'], 'itemids' => $itemids, 'preservekeys' => 1);
         $applications = CApplication::get($obj_params);
         foreach ($applications as $applicationid => $application) {
             $aitems = $application['items'];
             unset($application['items']);
             foreach ($aitems as $inum => $item) {
                 $result[$item['itemid']]['applications'][] = $application;
             }
         }
     }
     COpt::memoryPick();
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
function available_triggers($triggerids, $editable = null)
{
    $options = array('triggerids' => $triggerids, 'editable' => $editable, 'nodes' => get_current_nodeid(true));
    $triggers = CTrigger::get($options);
    return zbx_objectValues($triggers, 'triggerid');
}
}
if ($ack_status == ZBX_ACK_STS_WITH_LAST_UNACK) {
    $options['withLastEventUnacknowledged'] = 1;
}
if ($show_severity > -1) {
    $options['min_severity'] = $show_severity;
}
if ($_REQUEST['status_change']) {
    $options['lastChangeSince'] = time() - $_REQUEST['status_change_days'] * 86400;
}
$triggers = CTrigger::get($options);
// sorting && paging
order_result($triggers, $sortfield, $sortorder);
$paging = getPagingLine($triggers);
$options = array('nodeids' => get_current_nodeid(), 'triggerids' => zbx_objectValues($triggers, 'triggerid'), 'output' => API_OUTPUT_EXTEND, 'select_hosts' => array('hostid', 'host', 'maintenance_status', 'maintenance_type', 'maintenanceid'), 'select_items' => API_OUTPUT_EXTEND, 'select_dependencies' => API_OUTPUT_EXTEND);
$triggers = CTrigger::get($options);
$triggers = zbx_toHash($triggers, 'triggerid');
order_result($triggers, $sortfield, $sortorder);
//---------
if ($config['event_ack_enable']) {
    foreach ($triggers as $tnum => $trigger) {
        $options = array('countOutput' => 1, 'triggerids' => $trigger['triggerid'], 'object' => EVENT_OBJECT_TRIGGER, 'acknowledged' => 0, 'value' => TRIGGER_VALUE_TRUE, 'nopermissions' => 1);
        $triggers[$tnum]['event_count'] = CEvent::get($options);
    }
}
$tr_hostids = array();
foreach ($triggers as $tnum => $trigger) {
    $triggers[$tnum]['events'] = array();
    //getting all host ids and names
    foreach ($trigger['hosts'] as $tr_hosts) {
        $tr_hostids[$tr_hosts['hostid']] = $tr_hosts['hostid'];
 private function _updateByTrigger(&$options)
 {
     $triggers = CTrigger::get(array('triggerids' => $options['triggerid'], 'output' => API_OUTPUT_EXTEND, 'select_hosts' => API_OUTPUT_REFER, 'select_templates' => API_OUTPUT_REFER, 'select_groups' => API_OUTPUT_REFER));
     if ($trigger = reset($triggers)) {
         $groups = zbx_toHash($trigger['groups'], 'groupid');
         $hosts = zbx_toHash($trigger['hosts'], 'hostid');
         $templates = zbx_toHash($trigger['templates'], 'templateid');
         if (isset($groups[$this->_profileIds['groupid']])) {
             $options['groupid'] = $this->_profileIds['groupid'];
         } else {
             $groupids = array_keys($groups);
             $options['groupid'] = reset($groupids);
         }
         if (isset($hosts[$this->_profileIds['hostid']])) {
             $options['hostid'] = $this->_profileIds['hostid'];
         } else {
             $hostids = array_keys($hosts);
             $options['hostid'] = reset($hostids);
         }
         if (is_null($options['hostid'])) {
             if (isset($templates[$this->_profileIds['hostid']])) {
                 $options['hostid'] = $this->_profileIds['hostid'];
             } else {
                 $templateids = array_keys($templates);
                 $options['hostid'] = reset($templateids);
             }
         }
     }
 }
Exemple #7
0
 private static function trigger($action, $params)
 {
     CTrigger::$error = array();
     switch ($action) {
         case 'add':
             $result = CTrigger::add($params);
             break;
         case 'get':
             $result = CTrigger::get($params);
             break;
         case 'getById':
             $result = CTrigger::getById($params);
             break;
         case 'getId':
             $result = CTrigger::getId($params);
             break;
         case 'update':
             $result = CTrigger::update($params);
             break;
         case 'delete':
             $result = CTrigger::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 = array_shift(CTrigger::$error);
     }
 }
Exemple #8
0
require_once 'include/config.inc.php';
require_once 'include/services.inc.php';
$page['file'] = 'chart5.php';
// $page['title']	= "S_CHART";
$page['type'] = PAGE_TYPE_IMAGE;
include_once 'include/page_header.php';
//		VAR			TYPE	OPTIONAL FLAGS	VALIDATION	EXCEPTION
$fields = array('serviceid' => array(T_ZBX_INT, O_MAND, P_SYS, DB_ID, NULL));
check_fields($fields);
$sql = 'SELECT s.* FROM services s  WHERE s.serviceid=' . $_REQUEST['serviceid'];
if (!($service = DBfetch(DBselect($sql, 1)))) {
    fatal_error(S_NO_IT_SERVICE_DEFINED);
}
if (!is_null($service['triggerid'])) {
    $options = array('triggerids' => $service['triggerid'], 'output' => API_OUTPUT_SHORTEN, 'nodeids' => get_current_nodeid(true));
    $db_data = CTrigger::get($options);
    if (empty($db_data)) {
        access_deny();
    }
}
$start_time = time(NULL);
$sizeX = 900;
$sizeY = 300;
$shiftX = 12;
$shiftYup = 17;
$shiftYdown = 25 + 15 * 3;
$im = imagecreate($sizeX + $shiftX + 61, $sizeY + $shiftYup + $shiftYdown + 10);
$red = imagecolorallocate($im, 255, 0, 0);
$darkred = imagecolorallocate($im, 150, 0, 0);
$green = imagecolorallocate($im, 0, 255, 0);
$darkgreen = imagecolorallocate($im, 0, 150, 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;
}
Exemple #10
0
 $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) {
     if (!empty($trigger['dependencies'])) {
         if (!isset($dependencies[$trigger['triggerid']])) {
             $dependencies[$trigger['triggerid']] = array();
         }
         $dependencies[$trigger['triggerid']]['trigger'] = $trigger;
         $dependencies[$trigger['triggerid']]['depends_on'] = $trigger['dependencies'];
     }
 }
 // we do custom fields for export
 public static function parseMain($rules)
 {
     $triggers_for_dependencies = array();
     try {
         if (isset($rules['host']['exist']) || isset($rules['host']['missed'])) {
             $xpath = new DOMXPath(self::$xml);
             $hosts = $xpath->query('hosts/host');
             foreach ($hosts as $hnum => $host) {
                 $host_db = self::mapXML2arr($host, XML_TAG_HOST);
                 if (!isset($host_db['status'])) {
                     $host_db['status'] = HOST_STATUS_TEMPLATE;
                 }
                 $current_host = $host_db['status'] == HOST_STATUS_TEMPLATE ? CTemplate::exists($host_db) : CHost::exists($host_db);
                 if (!$current_host && !isset($rules['host']['missed'])) {
                     info('Host [' . $host_db['host'] . '] skipped - user rule');
                     continue;
                     // break if update nonexist
                 }
                 if ($current_host && !isset($rules['host']['exist'])) {
                     info('Host [' . $host_db['host'] . '] skipped - user rule');
                     continue;
                     // break if not update exist
                 }
                 if (isset($host_db['proxy_hostid'])) {
                     $proxy_exists = CProxy::get(array('proxyids' => $host_db['proxy_hostid']));
                     if (empty($proxy_exists)) {
                         $host_db['proxy_hostid'] = 0;
                     }
                 }
                 if ($current_host) {
                     $options = array('filter' => array('host' => $host_db['host']), 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                     if ($host_db['status'] == HOST_STATUS_TEMPLATE) {
                         $current_host = CTemplate::get($options);
                     } else {
                         $current_host = CHost::get($options);
                     }
                     if (empty($current_host)) {
                         throw new APIException(1, 'No permission for host [' . $host_db['host'] . ']');
                     } else {
                         $current_host = reset($current_host);
                     }
                 }
                 // HOST GROUPS {{{
                 $groups = $xpath->query('groups/group', $host);
                 $host_db['groups'] = array();
                 $groups_to_parse = array();
                 foreach ($groups as $gnum => $group) {
                     $groups_to_parse[] = array('name' => $group->nodeValue);
                 }
                 if (empty($groups_to_parse)) {
                     $groups_to_parse[] = array('name' => ZBX_DEFAULT_IMPORT_HOST_GROUP);
                 }
                 foreach ($groups_to_parse as $group) {
                     $current_group = CHostGroup::exists($group);
                     if ($current_group) {
                         $options = array('filter' => $group, 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                         $current_group = CHostGroup::get($options);
                         if (empty($current_group)) {
                             throw new APIException(1, 'No permissions for group ' . $group['name']);
                         }
                         $host_db['groups'][] = reset($current_group);
                     } else {
                         $result = CHostGroup::create($group);
                         if (!$result) {
                             throw new APIException(1, CHostGroup::resetErrors());
                         }
                         $options = array('groupids' => $result['groupids'], 'output' => API_OUTPUT_EXTEND);
                         $new_group = CHostgroup::get($options);
                         $host_db['groups'][] = reset($new_group);
                     }
                 }
                 // }}} HOST GROUPS
                 // MACROS
                 $macros = $xpath->query('macros/macro', $host);
                 $host_db['macros'] = array();
                 if ($macros->length > 0) {
                     foreach ($macros as $macro) {
                         $host_db['macros'][] = self::mapXML2arr($macro, XML_TAG_MACRO);
                     }
                 }
                 // }}} MACROS
                 // TEMPLATES {{{
                 if (isset($rules['template']['exist'])) {
                     $templates = $xpath->query('templates/template', $host);
                     $host_db['templates'] = array();
                     foreach ($templates as $tnum => $template) {
                         $options = array('filter' => array('host' => $template->nodeValue), 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                         $current_template = CTemplate::get($options);
                         if (empty($current_template)) {
                             throw new APIException(1, 'No permission for Template [' . $template->nodeValue . ']');
                         }
                         $current_template = reset($current_template);
                         if (!$current_template && !isset($rules['template']['missed'])) {
                             info('Template [' . $template->nodeValue . '] skipped - user rule');
                             continue;
                             // break if update nonexist
                         }
                         if ($current_template && !isset($rules['template']['exist'])) {
                             info('Template [' . $template->nodeValue . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         $host_db['templates'][] = $current_template;
                     }
                 }
                 // }}} TEMPLATES
                 // HOSTS
                 if ($current_host && isset($rules['host']['exist'])) {
                     if ($host_db['status'] == HOST_STATUS_TEMPLATE) {
                         $host_db['templateid'] = $current_host['hostid'];
                         $result = CTemplate::update($host_db);
                         if (!$result) {
                             throw new APIException(1, CTemplate::resetErrors());
                         }
                         $options = array('templateids' => $result['templateids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CTemplate::get($options);
                     } else {
                         $host_db['hostid'] = $current_host['hostid'];
                         $result = CHost::update($host_db);
                         if (!$result) {
                             throw new APIException(1, CHost::resetErrors());
                         }
                         $options = array('hostids' => $result['hostids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CHost::get($options);
                     }
                     if ($current_host === false) {
                         throw new APIException(1, $host_db['status'] == HOST_STATUS_TEMPLATE ? CTemplate::resetErrors() : CHost::resetErrors());
                     }
                 }
                 if (!$current_host && isset($rules['host']['missed'])) {
                     if ($host_db['status'] == HOST_STATUS_TEMPLATE) {
                         $result = CTemplate::create($host_db);
                         if (!$result) {
                             throw new APIException(1, CTemplate::resetErrors());
                         }
                         $options = array('templateids' => $result['templateids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CTemplate::get($options);
                     } else {
                         $result = CHost::create($host_db);
                         if (!$result) {
                             throw new APIException(1, CHost::resetErrors());
                         }
                         $options = array('hostids' => $result['hostids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CHost::get($options);
                     }
                 }
                 $current_host = reset($current_host);
                 // HOST PROFILES {{{
                 $profile_node = $xpath->query('host_profile/*', $host);
                 if ($profile_node->length > 0) {
                     $profile = array();
                     foreach ($profile_node as $num => $field) {
                         $profile[$field->nodeName] = $field->nodeValue;
                     }
                     delete_host_profile($current_host['hostid']);
                     add_host_profile($current_host['hostid'], $profile['devicetype'], $profile['name'], $profile['os'], $profile['serialno'], $profile['tag'], $profile['macaddress'], $profile['hardware'], $profile['software'], $profile['contact'], $profile['location'], $profile['notes']);
                 }
                 $profile_ext_node = $xpath->query('host_profiles_ext/*', $host);
                 if ($profile_ext_node->length > 0) {
                     $profile_ext = array();
                     foreach ($profile_ext_node as $num => $field) {
                         $profile_ext[$field->nodeName] = $field->nodeValue;
                     }
                     delete_host_profile_ext($current_host['hostid']);
                     add_host_profile_ext($current_host['hostid'], $profile_ext);
                 }
                 // }}} HOST PROFILES
                 // ITEMS {{{
                 if (isset($rules['item']['exist']) || isset($rules['item']['missed'])) {
                     $items = $xpath->query('items/item', $host);
                     foreach ($items as $inum => $item) {
                         $item_db = self::mapXML2arr($item, XML_TAG_ITEM);
                         $item_db['hostid'] = $current_host['hostid'];
                         if ($current_item = CItem::exists($item_db)) {
                             $options = array('filter' => array('hostid' => $item_db['hostid'], 'key_' => $item_db['key_']), 'webitems' => 1, 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                             $current_item = CItem::get($options);
                             if (empty($current_item)) {
                                 throw new APIException(1, 'No permission for Item [' . $item_db['key_'] . ']');
                             }
                             $current_item = reset($current_item);
                         }
                         if (!$current_item && !isset($rules['item']['missed'])) {
                             info('Item [' . $item_db['key_'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_item && !isset($rules['item']['exist'])) {
                             info('Item [' . $item_db['key_'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         // ITEM APPLICATIONS {{{
                         $applications = $xpath->query('applications/application', $item);
                         $item_applications = array();
                         $applications_to_add = array();
                         foreach ($applications as $application) {
                             $application_db = array('name' => $application->nodeValue, 'hostid' => $current_host['hostid']);
                             if ($current_application = CApplication::exists($application_db)) {
                                 $current_application = CApplication::get(array('filter' => $application_db, 'output' => API_OUTPUT_EXTEND));
                                 if (empty($current_application)) {
                                     throw new APIException(1, 'No permission for Application [' . $application_db['name'] . ']');
                                 }
                             }
                             if ($current_application) {
                                 $item_applications = array_merge($item_applications, $current_application);
                             } else {
                                 $applications_to_add[] = $application_db;
                             }
                         }
                         if (!empty($applications_to_add)) {
                             $result = CApplication::create($applications_to_add);
                             if (!$result) {
                                 throw new APIException(1, CApplication::resetErrors());
                             }
                             $options = array('applicationids' => $result['applicationids'], 'output' => API_OUTPUT_EXTEND);
                             $new_applications = CApplication::get($options);
                             $item_applications = array_merge($item_applications, $new_applications);
                         }
                         // }}} ITEM APPLICATIONS
                         if ($current_item && isset($rules['item']['exist'])) {
                             $item_db['itemid'] = $current_item['itemid'];
                             $result = CItem::update($item_db);
                             if (!$result) {
                                 throw new APIException(1, CItem::resetErrors());
                             }
                             $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND);
                             $current_item = CItem::get($options);
                         }
                         if (!$current_item && isset($rules['item']['missed'])) {
                             $result = CItem::create($item_db);
                             if (!$result) {
                                 throw new APIException(1, CItem::resetErrors());
                             }
                             $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND);
                             $current_item = CItem::get($options);
                         }
                         $r = CApplication::massAdd(array('applications' => $item_applications, 'items' => $current_item));
                         if ($r === false) {
                             throw new APIException(1, CApplication::resetErrors());
                         }
                     }
                 }
                 // }}} ITEMS
                 // TRIGGERS {{{
                 if (isset($rules['trigger']['exist']) || isset($rules['trigger']['missed'])) {
                     $triggers = $xpath->query('triggers/trigger', $host);
                     $triggers_to_add = array();
                     $triggers_to_upd = array();
                     foreach ($triggers as $trigger) {
                         $trigger_db = self::mapXML2arr($trigger, XML_TAG_TRIGGER);
                         $trigger_db['expression'] = str_replace('{{HOSTNAME}:', '{' . $host_db['host'] . ':', $trigger_db['expression']);
                         $trigger_db['hostid'] = $current_host['hostid'];
                         if ($current_trigger = CTrigger::exists($trigger_db)) {
                             $ctriggers = CTrigger::get(array('filter' => array('description' => $trigger_db['description']), 'hostids' => $current_host['hostid'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1));
                             $current_trigger = false;
                             foreach ($ctriggers as $tnum => $ct) {
                                 $tmp_exp = explode_exp($ct['expression'], false);
                                 if (strcmp($trigger_db['expression'], $tmp_exp) == 0) {
                                     $current_trigger = $ct;
                                     break;
                                 }
                             }
                             if (!$current_trigger) {
                                 throw new APIException(1, 'No permission for Trigger [' . $trigger_db['description'] . ']');
                             }
                         }
                         if (!$current_trigger && !isset($rules['trigger']['missed'])) {
                             info('Trigger [' . $trigger_db['description'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_trigger && !isset($rules['trigger']['exist'])) {
                             info('Trigger [' . $trigger_db['description'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_trigger && isset($rules['trigger']['exist'])) {
                             $trigger_db['triggerid'] = $current_trigger['triggerid'];
                             $triggers_to_upd[] = $trigger_db;
                         }
                         if (!$current_trigger && isset($rules['trigger']['missed'])) {
                             $triggers_to_add[] = $trigger_db;
                         }
                     }
                     if (!empty($triggers_to_upd)) {
                         $result = CTrigger::update($triggers_to_upd);
                         if (!$result) {
                             throw new APIException(1, CTrigger::resetErrors());
                         }
                         $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND);
                         $r = CTrigger::get($options);
                         $triggers_for_dependencies = array_merge($triggers_for_dependencies, $r);
                     }
                     if (!empty($triggers_to_add)) {
                         $result = CTrigger::create($triggers_to_add);
                         if (!$result) {
                             throw new APIException(1, CTrigger::resetErrors());
                         }
                         $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND);
                         $r = CTrigger::get($options);
                         $triggers_for_dependencies = array_merge($triggers_for_dependencies, $r);
                     }
                 }
                 // }}} TRIGGERS
                 // GRAPHS {{{
                 if (isset($rules['graph']['exist']) || isset($rules['graph']['missed'])) {
                     $graphs = $xpath->query('graphs/graph', $host);
                     $graphs_to_add = array();
                     $graphs_to_upd = array();
                     foreach ($graphs as $gnum => $graph) {
                         // GRAPH ITEMS {{{
                         $gitems = $xpath->query('graph_elements/graph_element', $graph);
                         $graph_hostids = array();
                         $graph_items = array();
                         foreach ($gitems as $ginum => $gitem) {
                             $gitem_db = self::mapXML2arr($gitem, XML_TAG_GRAPH_ELEMENT);
                             $data = explode(':', $gitem_db['host_key_']);
                             $gitem_host = array_shift($data);
                             $gitem_db['host'] = $gitem_host == '{HOSTNAME}' ? $host_db['host'] : $gitem_host;
                             $gitem_db['key_'] = implode(':', $data);
                             if ($current_item = CItem::exists($gitem_db)) {
                                 $current_item = CItem::get(array('filter' => array('key_' => $gitem_db['key_']), 'webitems' => 1, 'host' => $gitem_db['host'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1));
                                 if (empty($current_item)) {
                                     throw new APIException(1, 'No permission for Item [' . $gitem_db['key_'] . ']');
                                 }
                                 $current_item = reset($current_item);
                                 $graph_hostids[] = $current_item['hostid'];
                                 $gitem_db['itemid'] = $current_item['itemid'];
                                 $graph_items[] = $gitem_db;
                             } else {
                                 throw new APIException(1, 'Item [' . $gitem_db['host_key_'] . '] does not exists');
                             }
                         }
                         // }}} GRAPH ITEMS
                         $graph_db = self::mapXML2arr($graph, XML_TAG_GRAPH);
                         $graph_db['hostids'] = $graph_hostids;
                         if ($current_graph = CGraph::exists($graph_db)) {
                             $current_graph = CGraph::get(array('filter' => array('name' => $graph_db['name']), 'hostids' => $graph_db['hostids'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1));
                             if (empty($current_graph)) {
                                 throw new APIException(1, 'No permission for Graph [' . $graph_db['name'] . ']');
                             }
                             $current_graph = reset($current_graph);
                         }
                         if (!$current_graph && !isset($rules['graph']['missed'])) {
                             info('Graph [' . $graph_db['name'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_graph && !isset($rules['graph']['exist'])) {
                             info('Graph [' . $graph_db['name'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($graph_db['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                             $item_data = explode(':', $graph_db['ymin_item_key'], 2);
                             if (count($item_data) < 2) {
                                 throw new APIException(1, 'Incorrect y min item for graph [' . $graph_db['name'] . ']');
                             }
                             if (!($item = get_item_by_key($item_data[1], $item_data[0]))) {
                                 throw new APIException(1, 'Missing item [' . $graph_db['ymin_item_key'] . '] for host [' . $host_db['host'] . ']');
                             }
                             $graph_db['ymin_itemid'] = $item['itemid'];
                         }
                         if ($graph_db['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                             $item_data = explode(':', $graph_db['ymax_item_key'], 2);
                             if (count($item_data) < 2) {
                                 throw new APIException(1, 'Incorrect y max item for graph [' . $graph_db['name'] . ']');
                             }
                             if (!($item = get_item_by_key($item_data[1], $item_data[0]))) {
                                 throw new APIException(1, 'Missing item [' . $graph_db['ymax_item_key'] . '] for host [' . $host_db['host'] . ']');
                             }
                             $graph_db['ymax_itemid'] = $item['itemid'];
                         }
                         $graph_db['gitems'] = $graph_items;
                         if ($current_graph) {
                             $graph_db['graphid'] = $current_graph['graphid'];
                             $graphs_to_upd[] = $graph_db;
                         } else {
                             $graphs_to_add[] = $graph_db;
                         }
                     }
                     if (!empty($graphs_to_add)) {
                         $r = CGraph::create($graphs_to_add);
                         if ($r === false) {
                             throw new APIException(1, CGraph::resetErrors());
                         }
                     }
                     if (!empty($graphs_to_upd)) {
                         $r = CGraph::update($graphs_to_upd);
                         if ($r === false) {
                             throw new APIException(1, CGraph::resetErrors());
                         }
                     }
                 }
             }
             // DEPENDENCIES
             $dependencies = $xpath->query('dependencies/dependency');
             if ($dependencies->length > 0) {
                 $triggers_for_dependencies = zbx_objectValues($triggers_for_dependencies, 'triggerid');
                 $triggers_for_dependencies = array_flip($triggers_for_dependencies);
                 foreach ($dependencies as $dependency) {
                     $triggers_to_add_dep = array();
                     $trigger_description = $dependency->getAttribute('description');
                     $current_triggerid = get_trigger_by_description($trigger_description);
                     // sdi('<b><u>Trigger Description: </u></b>'.$trigger_description.' | <b>Current_triggerid: </b>'. $current_triggerid['triggerid']);
                     if ($current_triggerid && isset($triggers_for_dependencies[$current_triggerid['triggerid']])) {
                         $depends_on_list = $xpath->query('depends', $dependency);
                         foreach ($depends_on_list as $depends_on) {
                             $depends_triggerid = get_trigger_by_description($depends_on->nodeValue);
                             // sdi('<b>depends on description: </b>'.$depends_on->nodeValue.' | <b>depends_triggerid: </b>'. $depends_triggerid['triggerid']);
                             if ($depends_triggerid['triggerid']) {
                                 $triggers_to_add_dep[] = $depends_triggerid['triggerid'];
                             }
                         }
                         $r = update_trigger($current_triggerid['triggerid'], null, $current_triggerid['description'], null, null, null, null, null, $triggers_to_add_dep, null);
                         if ($r === false) {
                             throw new APIException();
                         }
                     }
                 }
             }
         }
         return true;
     } catch (APIException $e) {
         error($e->getErrors());
         return false;
     }
 }
Exemple #12
0
     foreach ($item['subfilters'] as $subfilter => $value) {
         if (!$value) {
             unset($items[$num]);
         }
     }
 }
 // sorting && paging
 // !!! should go after we subfiltered out items !!!
 order_result($items, $sortfield, $sortorder);
 $paging = getPagingLine($items);
 //---------
 $itemTriggerIds = array();
 foreach ($items as $num => $item) {
     $itemTriggerIds = array_merge($itemTriggerIds, zbx_objectValues($item['triggers'], 'triggerid'));
 }
 $itemTriggers = CTrigger::get(array('triggerids' => $itemTriggerIds, 'expandDescription' => true, 'output' => API_OUTPUT_EXTEND, 'select_hosts' => array('hostid', 'host', 'status'), 'select_functions' => API_OUTPUT_EXTEND, 'select_items' => API_OUTPUT_EXTEND, 'preservekeys' => true));
 $trigRealHosts = getParentHostsByTriggers($itemTriggers);
 foreach ($items as $inum => $item) {
     if ($show_host) {
         $host = array_pop($item['hosts']);
         $host = $host['host'];
     } else {
         $host = null;
     }
     $description = array();
     if ($item['templateid']) {
         $template_host = get_realhost_by_itemid($item['templateid']);
         $description[] = new CLink($template_host['host'], '?hostid=' . $template_host['hostid'], 'unknown');
         $description[] = ':';
     }
     $item['description_expanded'] = item_description($item);
 $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)) {
     $trig_lbx->setAttribute('style', 'width: 200px;');
 } else {
     foreach ($template_triggers as $tnum => $ttrigger) {
         $trigger_description = expand_trigger_description($ttrigger['triggerid']);
         $trig_lbx->addItem($ttrigger['triggerid'], $trigger_description);
     }
 }
 $template_tbl->addRow(array(S_TRIGGERS, $trig_lbx));
 // FORM ITEM : Host graphs
 $graphs_lbx = new CListBox('graphs', null, 8);
 $graphs_lbx->setAttribute('disabled', 'disabled');
 $options = array('editable' => 1, 'hostids' => $templateid, 'extendoutput' => 1);
 $template_graphs = CGraph::get($options);
 if (empty($template_graphs)) {
function getLastEvents($options)
{
    if (!isset($options['limit'])) {
        $options['limit'] = 15;
    }
    $triggerOptions = array('filter' => array(), 'skipDependent' => 1, 'select_hosts' => array('hostid', 'host'), 'output' => API_OUTPUT_EXTEND, 'expandDescription' => 1, 'sortfield' => 'lastchange', 'sortorder' => ZBX_SORT_DOWN, 'limit' => $options['limit']);
    $eventOptions = array('object' => EVENT_OBJECT_TRIGGER, 'output' => API_OUTPUT_EXTEND, 'sortfield' => 'clock', 'sortorder' => ZBX_SORT_DOWN, 'limit' => $options['limit']);
    if (isset($options['nodeids'])) {
        $triggerOptions['nodeids'] = $options['nodeids'];
    }
    if (isset($options['priority'])) {
        $triggerOptions['filter']['priority'] = $options['priority'];
    }
    if (isset($options['monitored'])) {
        $triggerOptions['monitored'] = $options['monitored'];
    }
    if (isset($options['lastChangeSince'])) {
        $triggerOptions['lastChangeSince'] = $options['lastChangeSince'];
        $eventOptions['time_from'] = $options['lastChangeSince'];
    }
    if (isset($options['value'])) {
        $triggerOptions['filter']['value'] = $options['value'];
        $eventOptions['value'] = $options['value'];
    }
    // triggers
    $triggers = CTrigger::get($triggerOptions);
    $triggers = zbx_toHash($triggers, 'triggerid');
    // events
    $eventOptions['triggerids'] = zbx_objectValues($triggers, 'triggerid');
    $events = CEvent::get($eventOptions);
    $sortClock = array();
    $sortEvent = array();
    foreach ($events as $enum => $event) {
        if (!isset($triggers[$event['objectid']])) {
            continue;
        }
        $events[$enum]['trigger'] = $triggers[$event['objectid']];
        $events[$enum]['host'] = reset($events[$enum]['trigger']['hosts']);
        $sortClock[$enum] = $event['clock'];
        $sortEvent[$enum] = $event['eventid'];
    }
    array_multisort($sortClock, SORT_DESC, $sortEvent, SORT_DESC, $events);
    return $events;
}
$trigger = CTrigger::get($options);
$trigger = reset($trigger);
if (!$trigger) {
    access_deny();
}
if (isset($_REQUEST['save'])) {
    $result = update_trigger_comments($_REQUEST['triggerid'], $_REQUEST['comments']);
    show_messages($result, S_COMMENT_UPDATED, S_CANNOT_UPDATE_COMMENT);
    $trigger['comments'] = $_REQUEST['comments'];
    if ($result) {
        add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER, S_TRIGGER . ' [' . $_REQUEST['triggerid'] . '] [' . $trigger['description'] . '] ' . S_COMMENTS . ' [' . $_REQUEST['comments'] . ']');
    }
} else {
    if (isset($_REQUEST['cancel'])) {
        jsRedirect('tr_status.php');
        exit;
    }
}
show_table_header(S_TRIGGER_COMMENTS_BIG);
//if user has no permissions to edit comments, no "save" button for him
$triggerEditable = CTrigger::get(array('editable' => 1, 'trigegrids' => $_REQUEST['triggerid'], 'output' => API_OUTPUT_SHORTEN));
$triggerEditable = !empty($triggerEditable);
$frmComent = new CFormTable(S_COMMENTS . ' for "' . $trigger['description'] . '"');
$frmComent->addVar('triggerid', $_REQUEST['triggerid']);
$frmComent->addRow(S_COMMENTS, new CTextArea('comments', $trigger['comments'], 100, 25, !$triggerEditable));
if ($triggerEditable) {
    $frmComent->addItemToBottomRow(new CButton("save", S_SAVE));
}
$frmComent->addItemToBottomRow(new CButtonCancel('&triggerid=' . $_REQUEST['triggerid']));
$frmComent->show();
include_once 'include/page_footer.php';
 public function bodyToString()
 {
     $this->cleanItems();
     $ok = $uncn = $uncl = $info = $warn = $avg = $high = $dis = 0;
     $options = array('monitored' => 1, 'skipDependent' => 1, 'output' => API_OUTPUT_SHORTEN);
     if ($this->hostid > 0) {
         $options['hostids'] = $this->hostid;
     } else {
         if ($this->groupid > 0) {
             $options['groupids'] = $this->groupid;
         }
     }
     $triggers = CTrigger::get($options);
     $triggers = zbx_objectValues($triggers, 'triggerid');
     $sql = 'SELECT t.priority,t.value,count(DISTINCT t.triggerid) as cnt ' . ' FROM triggers t ' . ' WHERE ' . DBcondition('t.triggerid', $triggers) . ' GROUP BY t.priority,t.value';
     $db_priority = DBselect($sql);
     while ($row = DBfetch($db_priority)) {
         switch ($row['value']) {
             case TRIGGER_VALUE_TRUE:
                 switch ($row['priority']) {
                     case TRIGGER_SEVERITY_NOT_CLASSIFIED:
                         $uncl += $row['cnt'];
                         break;
                     case TRIGGER_SEVERITY_INFORMATION:
                         $info += $row['cnt'];
                         break;
                     case TRIGGER_SEVERITY_WARNING:
                         $warn += $row['cnt'];
                         break;
                     case TRIGGER_SEVERITY_AVERAGE:
                         $avg += $row['cnt'];
                         break;
                     case TRIGGER_SEVERITY_HIGH:
                         $high += $row['cnt'];
                         break;
                     case TRIGGER_SEVERITY_DISASTER:
                         $dis += $row['cnt'];
                         break;
                 }
                 break;
             case TRIGGER_VALUE_FALSE:
                 $ok += $row['cnt'];
                 break;
             default:
                 $uncn += $row['cnt'];
                 break;
         }
     }
     if ($this->show_header) {
         $header_str = S_TRIGGERS_INFO . SPACE;
         if (!is_null($this->nodeid)) {
             $node = get_node_by_nodeid($this->nodeid);
             if ($node > 0) {
                 $header_str .= '(' . $node['name'] . ')' . SPACE;
             }
         }
         if (remove_nodes_from_id($this->groupid) > 0) {
             $group = get_hostgroup_by_groupid($this->groupid);
             $header_str .= S_GROUP . SPACE . '&quot;' . $group['name'] . '&quot;';
         } else {
             $header_str .= S_ALL_GROUPS;
         }
         $header = new CCol($header_str, 'header');
         if ($this->style == STYLE_HORISONTAL) {
             $header->SetColspan(8);
         }
         $this->addRow($header);
     }
     $trok = new CCol($ok . SPACE . S_OK, get_severity_style('ok', false));
     $uncn = new CCol($uncn . SPACE . S_UNKNOWN, 'unknown');
     $uncl = new CCol($uncl . SPACE . S_NOT_CLASSIFIED, get_severity_style(TRIGGER_SEVERITY_NOT_CLASSIFIED, $uncl));
     $info = new CCol($info . SPACE . S_INFORMATION, get_severity_style(TRIGGER_SEVERITY_INFORMATION, $info));
     $warn = new CCol($warn . SPACE . S_WARNING, get_severity_style(TRIGGER_SEVERITY_WARNING, $warn));
     $avg = new CCol($avg . SPACE . S_AVERAGE, get_severity_style(TRIGGER_SEVERITY_AVERAGE, $avg));
     $high = new CCol($high . SPACE . S_HIGH, get_severity_style(TRIGGER_SEVERITY_HIGH, $high));
     $dis = new CCol($dis . SPACE . S_DISASTER, get_severity_style(TRIGGER_SEVERITY_DISASTER, $dis));
     if (STYLE_HORISONTAL == $this->style) {
         $this->addRow(array($trok, $uncn, $uncl, $info, $warn, $avg, $high, $dis));
     } else {
         $this->addRow($trok);
         $this->addRow($uncn);
         $this->addRow($uncl);
         $this->addRow($info);
         $this->addRow($warn);
         $this->addRow($avg);
         $this->addRow($high);
         $this->addRow($dis);
     }
     return parent::BodyToString();
 }
 /**
  * Add events ( without alerts )
  *
  * {@source}
  * @access public
  * @static
  * @since 1.8
  * @version 1
  *
  * @param _array $events multidimensional array with events data
  * @param array $events[0,...]['source']
  * @param array $events[0,...]['object']
  * @param array $events[0,...]['objectid']
  * @param array $events[0,...]['clock'] OPTIONAL
  * @param array $events[0,...]['value'] OPTIONAL
  * @param array $events[0,...]['acknowledged'] OPTIONAL
  * @return boolean
  */
 public static function create($events)
 {
     $events = zbx_toArray($events);
     $eventids = array();
     $result = true;
     $options = array('triggerids' => zbx_objectValues($events, 'objectid'), 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1);
     $triggers = CTrigger::get($options);
     foreach ($events as $num => $event) {
         if ($event['object'] != EVENT_OBJECT_TRIGGER) {
             continue;
         }
         if (isset($triggers[$event['objectid']])) {
             $trigger = $triggers[$event['objectid']];
             if ($event['value'] != $trigger['value'] || $event['value'] == TRIGGER_VALUE_TRUE && $trigger['type'] == TRIGGER_MULT_EVENT_ENABLED) {
                 continue;
             }
         }
         unset($events[$num]);
     }
     self::BeginTransaction(__METHOD__);
     foreach ($events as $num => $event) {
         $event_db_fields = array('source' => null, 'object' => null, 'objectid' => null, 'clock' => time(), 'value' => 0, 'acknowledged' => 0);
         if (!check_db_fields($event_db_fields, $event)) {
             $result = false;
             break;
         }
         $eventid = get_dbid('events', 'eventid');
         $sql = 'INSERT INTO events (eventid, source, object, objectid, clock, value, acknowledged) ' . ' VALUES (' . $eventid . ',' . $event['source'] . ',' . $event['object'] . ',' . $event['objectid'] . ',' . $event['clock'] . ',' . $event['value'] . ',' . $event['acknowledged'] . ')';
         $result = DBexecute($sql);
         if (!$result) {
             break;
         }
         //			$triggers[] = array('triggerid' => $event['objectid'], 'value'=> $event['value'], 'lastchange'=> $event['clock']);
         $eventids[$eventid] = $eventid;
     }
     if ($result) {
         // This will create looping (Trigger->Event->Trigger->Event)
         //			$result = CTrigger::update($triggers);
     }
     $result = self::EndTransaction($result, __METHOD__);
     if ($result) {
         return $eventids;
     } else {
         self::$error[] = array('error' => ZBX_API_ERROR_INTERNAL, 'data' => 'Internal Zabbix error');
         return false;
     }
 }
    /**
     * Get Map data
     *
     * @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 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['sortorder']
     * @param string $options['sortfield']
     * @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'];
        $sort_columns = array('name');
        // 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('sysmaps' => 's.sysmapid'), 'from' => array('sysmaps' => 'sysmaps s'), 'where' => array(), 'order' => array(), 'limit' => null);
        $def_options = array('nodeids' => null, 'sysmapids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'extendoutput' => null, 'output' => API_OUTPUT_REFER, 'select_selements' => null, 'select_links' => 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_selements'])) {
                $options['select_selements'] = API_OUTPUT_EXTEND;
            }
            if (!is_null($options['select_links'])) {
                $options['select_links'] = API_OUTPUT_EXTEND;
            }
        }
        // editable + PERMISSION CHECK
        // nodeids
        $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
        // sysmapids
        if (!is_null($options['sysmapids'])) {
            zbx_value2array($options['sysmapids']);
            $sql_parts['where']['sysmapid'] = DBcondition('s.sysmapid', $options['sysmapids']);
        }
        // search
        if (!is_null($options['search'])) {
            zbx_db_search('sysmaps s', $options, $sql_parts);
        }
        // filter
        if (!is_null($options['filter'])) {
            zbx_value2array($options['filter']);
            if (isset($options['filter']['sysmapid']) && !is_null($options['filter']['sysmapid'])) {
                zbx_value2array($options['filter']['sysmapid']);
                $sql_parts['where']['sysmapid'] = DBcondition('s.sysmapid', $options['filter']['sysmapid']);
            }
            if (isset($options['filter']['name']) && !is_null($options['filter']['name'])) {
                zbx_value2array($options['filter']['name']);
                $sql_parts['where']['name'] = DBcondition('s.name', $options['filter']['name'], false, true);
            }
        }
        // output
        if ($options['output'] == API_OUTPUT_EXTEND) {
            $sql_parts['select']['sysmaps'] = 's.*';
        }
        // countOutput
        if (!is_null($options['countOutput'])) {
            $options['sortfield'] = '';
            $sql_parts['select'] = array('count(DISTINCT s.sysmapid) 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'][] = 's.' . $options['sortfield'] . ' ' . $sortorder;
            if (!str_in_array('s.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('s.*', $sql_parts['select'])) {
                $sql_parts['select'][] = 's.' . $options['sortfield'];
            }
        }
        // limit
        if (zbx_ctype_digit($options['limit']) && $options['limit']) {
            $sql_parts['limit'] = $options['limit'];
        }
        //-------
        $sysmapids = 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 ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . '
				FROM ' . $sql_from . '
				WHERE ' . DBin_node('s.sysmapid', $nodeids) . $sql_where . $sql_order;
        $res = DBselect($sql, $sql_limit);
        while ($sysmap = DBfetch($res)) {
            if ($options['countOutput']) {
                $result = $sysmap['rowscount'];
            } else {
                $sysmapids[$sysmap['sysmapid']] = $sysmap['sysmapid'];
                if ($options['output'] == API_OUTPUT_SHORTEN) {
                    $result[$sysmap['sysmapid']] = array('sysmapid' => $sysmap['sysmapid']);
                } else {
                    if (!isset($result[$sysmap['sysmapid']])) {
                        $result[$sysmap['sysmapid']] = array();
                    }
                    if (!is_null($options['select_selements']) && !isset($result[$sysmap['sysmapid']]['selements'])) {
                        $result[$sysmap['sysmapid']]['selements'] = array();
                    }
                    if (!is_null($options['select_links']) && !isset($result[$sysmap['sysmapid']]['links'])) {
                        $result[$sysmap['sysmapid']]['links'] = array();
                    }
                    if (isset($sysmap['highlight'])) {
                        $sysmap['expandproblem'] = $sysmap['highlight'] & ZBX_MAP_EXPANDPROBLEM ? 0 : 1;
                        $sysmap['markelements'] = $sysmap['highlight'] & ZBX_MAP_MARKELEMENTS ? 1 : 0;
                        if (($sysmap['highlight'] & ZBX_MAP_EXTACK_SEPARATED) == ZBX_MAP_EXTACK_SEPARATED) {
                            $sysmap['show_unack'] = EXTACK_OPTION_BOTH;
                        } else {
                            if ($sysmap['highlight'] & ZBX_MAP_EXTACK_UNACK) {
                                $sysmap['show_unack'] = EXTACK_OPTION_UNACK;
                            } else {
                                $sysmap['show_unack'] = EXTACK_OPTION_ALL;
                            }
                        }
                        $sysmap['highlight'] = $sysmap['highlight'] & ZBX_MAP_HIGHLIGHT ? 1 : 0;
                    }
                    $result[$sysmap['sysmapid']] += $sysmap;
                }
            }
        }
        if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
        } else {
            if (!empty($result)) {
                $link_triggers = array();
                $sql = 'SELECT slt.triggerid, sl.sysmapid' . ' FROM sysmaps_link_triggers slt, sysmaps_links sl' . ' WHERE ' . DBcondition('sl.sysmapid', $sysmapids) . ' AND sl.linkid=slt.linkid';
                $db_link_triggers = DBselect($sql);
                while ($link_trigger = DBfetch($db_link_triggers)) {
                    $link_triggers[$link_trigger['sysmapid']] = $link_trigger['triggerid'];
                }
                if (!empty($link_triggers)) {
                    $all_triggers = CTrigger::get(array('triggerids' => $link_triggers, 'editable' => $options['editable'], 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1));
                    foreach ($link_triggers as $id => $triggerid) {
                        if (!isset($all_triggers[$triggerid])) {
                            unset($result[$id], $sysmapids[$id]);
                        }
                    }
                }
                $hosts_to_check = array();
                $maps_to_check = array();
                $triggers_to_check = array();
                $host_groups_to_check = array();
                $selements = array();
                $db_selements = DBselect('SELECT * FROM sysmaps_elements WHERE ' . DBcondition('sysmapid', $sysmapids));
                while ($selement = DBfetch($db_selements)) {
                    $selements[$selement['selementid']] = $selement;
                    switch ($selement['elementtype']) {
                        case SYSMAP_ELEMENT_TYPE_HOST:
                            $hosts_to_check[$selement['elementid']] = $selement['elementid'];
                            break;
                        case SYSMAP_ELEMENT_TYPE_MAP:
                            $maps_to_check[$selement['elementid']] = $selement['elementid'];
                            break;
                        case SYSMAP_ELEMENT_TYPE_TRIGGER:
                            $triggers_to_check[$selement['elementid']] = $selement['elementid'];
                            break;
                        case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
                            $host_groups_to_check[$selement['elementid']] = $selement['elementid'];
                            break;
                    }
                }
                // sdi($hosts_to_check);
                // sdi($maps_to_check);
                // sdi($triggers_to_check);
                // sdi($host_groups_to_check);
                $nodeids = get_current_nodeid(true);
                if (!empty($hosts_to_check)) {
                    $host_options = array('hostids' => $hosts_to_check, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => 1, 'output' => API_OUTPUT_SHORTEN);
                    $allowed_hosts = CHost::get($host_options);
                    foreach ($hosts_to_check as $elementid) {
                        if (!isset($allowed_hosts[$elementid])) {
                            foreach ($selements as $selementid => $selement) {
                                if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST && $selement['elementid'] == $elementid) {
                                    unset($result[$selement['sysmapid']], $selements[$selementid]);
                                }
                            }
                        }
                    }
                }
                if (!empty($maps_to_check)) {
                    $map_options = array('sysmapids' => $maps_to_check, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => 1, 'output' => API_OUTPUT_SHORTEN);
                    $allowed_maps = self::get($map_options);
                    foreach ($maps_to_check as $elementid) {
                        if (!isset($allowed_maps[$elementid])) {
                            foreach ($selements as $selementid => $selement) {
                                if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_MAP && $selement['elementid'] == $elementid) {
                                    unset($result[$selement['sysmapid']], $selements[$selementid]);
                                }
                            }
                        }
                    }
                }
                if (!empty($triggers_to_check)) {
                    $trigger_options = array('triggerids' => $triggers_to_check, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => 1, 'output' => API_OUTPUT_SHORTEN);
                    $allowed_triggers = CTrigger::get($trigger_options);
                    foreach ($triggers_to_check as $elementid) {
                        if (!isset($allowed_triggers[$elementid])) {
                            foreach ($selements as $selementid => $selement) {
                                if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_TRIGGER && $selement['elementid'] == $elementid) {
                                    unset($result[$selement['sysmapid']], $selements[$selementid]);
                                }
                            }
                        }
                    }
                }
                if (!empty($host_groups_to_check)) {
                    $hostgroup_options = array('groupids' => $host_groups_to_check, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => 1, 'output' => API_OUTPUT_SHORTEN);
                    $allowed_host_groups = CHostGroup::get($hostgroup_options);
                    foreach ($host_groups_to_check as $elementid) {
                        if (!isset($allowed_host_groups[$elementid])) {
                            foreach ($selements as $selementid => $selement) {
                                if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP && $selement['elementid'] == $elementid) {
                                    unset($result[$selement['sysmapid']], $selements[$selementid]);
                                }
                            }
                        }
                    }
                }
            }
        }
        COpt::memoryPick();
        if (!is_null($options['countOutput'])) {
            if (is_null($options['preservekeys'])) {
                $result = zbx_cleanHashes($result);
            }
            return $result;
        }
        // Adding Elements
        if (!is_null($options['select_selements']) && str_in_array($options['select_selements'], $subselects_allowed_outputs)) {
            if (!isset($map_selements)) {
                $map_selements = array();
                $sql = 'SELECT se.* ' . ' FROM sysmaps_elements se ' . ' WHERE ' . DBcondition('se.sysmapid', $sysmapids);
                $db_selements = DBselect($sql);
                while ($selement = DBfetch($db_selements)) {
                    $map_selements[$selement['selementid']] = $selement;
                }
            }
            foreach ($map_selements as $num => $selement) {
                if (!isset($result[$selement['sysmapid']]['selements'])) {
                    $result[$selement['sysmapid']]['selements'] = array();
                }
                $result[$selement['sysmapid']]['selements'][] = $selement;
            }
        }
        // Adding Links
        if (!is_null($options['select_links']) && str_in_array($options['select_links'], $subselects_allowed_outputs)) {
            if (!isset($map_links)) {
                $linkids = array();
                $map_links = array();
                $sql = 'SELECT sl.* FROM sysmaps_links sl WHERE ' . DBcondition('sl.sysmapid', $sysmapids);
                $db_links = DBselect($sql);
                while ($link = DBfetch($db_links)) {
                    $link['linktriggers'] = array();
                    $map_links[$link['linkid']] = $link;
                    $linkids[$link['linkid']] = $link['linkid'];
                }
                $sql = 'SELECT DISTINCT slt.* FROM sysmaps_link_triggers slt WHERE ' . DBcondition('slt.linkid', $linkids);
                $db_link_triggers = DBselect($sql);
                while ($link_trigger = DBfetch($db_link_triggers)) {
                    $map_links[$link_trigger['linkid']]['linktriggers'][] = $link_trigger;
                }
            }
            foreach ($map_links as $num => $link) {
                if (!isset($result[$link['sysmapid']]['links'])) {
                    $result[$link['sysmapid']]['links'] = array();
                }
                $result[$link['sysmapid']]['links'][] = $link;
            }
        }
        COpt::memoryPick();
        // removing keys (hash -> array)
        if (is_null($options['preservekeys'])) {
            $result = zbx_cleanHashes($result);
        }
        return $result;
    }
Exemple #19
0
    /**
     * Get items data
     *
     * {@source}
     * @access public
     * @static
     * @since 1.8
     * @version 1
     *
     * @static
     * @param array $options
     * @param array $options['itemids']
     * @param array $options['hostids']
     * @param array $options['groupids']
     * @param array $options['triggerids']
     * @param array $options['applicationids']
     * @param boolean $options['status']
     * @param boolean $options['templated_items']
     * @param boolean $options['editable']
     * @param boolean $options['count']
     * @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;
        $result = array();
        $user_type = $USER_DETAILS['type'];
        $userid = $USER_DETAILS['userid'];
        $sort_columns = array('itemid');
        // allowed columns for sorting
        $sql_parts = array('select' => array('items' => 'i.itemid'), 'from' => array('items i'), 'where' => array('i.type<>9'), 'order' => array(), 'limit' => null);
        $def_options = array('nodeids' => 0, 'groupids' => 0, 'hostids' => 0, 'itemids' => 0, 'graphids' => 0, 'triggerids' => 0, 'applicationids' => 0, 'status' => 0, 'templated_items' => 0, 'editable' => 0, 'nopermissions' => 0, 'select_triggers' => 0, 'select_hosts' => 0, 'select_graphs' => 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']['hg'] = 'hosts_groups hg';
            $sql_parts['from']['r'] = 'rights r';
            $sql_parts['from']['ug'] = 'users_groups ug';
            $sql_parts['where'][] = '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 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['where'][] = DBcondition('hg.groupid', $options['groupids']);
            $sql_parts['where'][] = 'hg.hostid=i.hostid';
            $sql_parts['from']['hg'] = 'hosts_groups hg';
        }
        // hostids
        if ($options['hostids'] != 0) {
            zbx_value2array($options['hostids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['hostid'] = 'i.hostid';
            }
            $sql_parts['where'][] = DBcondition('i.hostid', $options['hostids']);
        }
        // itemids
        if ($options['itemids'] != 0) {
            $sql_parts['where'][] = DBcondition('i.itemid', $options['itemids']);
        }
        // triggerids
        if ($options['triggerids'] != 0) {
            zbx_value2array($options['triggerids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['triggerid'] = 'f.triggerid';
            }
            $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']);
            $sql_parts['where'][] = 'i.itemid=f.itemid';
            $sql_parts['from'][] = 'functions f';
        }
        // applicationids
        if ($options['applicationids'] != 0) {
            $sql_parts['where'][] = DBcondition('a.applicationid', $options['applicationids']);
            $sql_parts['where'][] = 'i.hostid=a.hostid';
            $sql_parts['from'][] = 'applications a';
        }
        // 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['where'][] = DBcondition('gi.graphid', $options['graphids']);
            $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
        }
        // status
        if ($options['status'] != 0) {
            $sql_parts['where'][] = 'i.status=' . $options['status'];
        }
        // templated_items
        if ($options['templated_items'] != 0) {
            $sql_parts['where'][] = 'i.templateid<>0';
        }
        // extendoutput
        if ($options['extendoutput'] != 0) {
            $sql_parts['select']['items'] = 'i.*';
        }
        // count
        if ($options['count'] != 0) {
            $sql_parts['select']['items'] = 'count(i.itemid) as count';
        }
        // pattern
        if (!zbx_empty($options['pattern'])) {
            $sql_parts['where'][] = ' UPPER(i.description) 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'][] = 'i.' . $options['order'];
            if (!str_in_array('i.' . $options['order'], $sql_parts['select'])) {
                $sql_parts['select'][] = 'i.' . $options['order'];
            }
        }
        // limit
        if (zbx_ctype_digit($options['limit']) && $options['limit']) {
            $sql_parts['limit'] = $options['limit'];
        }
        //----------
        $itemids = 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('i.itemid', $nodeids) . $sql_where . $sql_order;
        $res = DBselect($sql, $sql_limit);
        while ($item = DBfetch($res)) {
            if ($options['count']) {
                $result = $item;
            } else {
                $itemids[$item['itemid']] = $item['itemid'];
                if ($options['extendoutput'] == 0) {
                    $result[$item['itemid']] = $item['itemid'];
                } else {
                    if (!isset($result[$item['itemid']])) {
                        $result[$item['itemid']] = array();
                    }
                    if ($options['select_triggers'] && !isset($result[$item['itemid']]['triggerids'])) {
                        $result[$item['itemid']]['triggerids'] = array();
                        $result[$item['itemid']]['triggers'] = array();
                    }
                    if ($options['select_graphs'] && !isset($result[$item['itemid']]['graphids'])) {
                        $result[$item['itemid']]['graphids'] = array();
                        $result[$item['itemid']]['graphs'] = array();
                    }
                    if ($options['select_hosts'] && !isset($result[$item['itemid']]['hostids'])) {
                        $result[$item['itemid']]['hostids'] = array();
                        $result[$item['itemid']]['hosts'] = array();
                    }
                    // hostids
                    if (isset($item['hostid'])) {
                        if (!isset($result[$item['itemid']]['hostids'])) {
                            $result[$item['itemid']]['hostids'] = array();
                        }
                        $result[$item['itemid']]['hostids'][$item['hostid']] = $item['hostid'];
                        unset($item['hostid']);
                    }
                    // triggerids
                    if (isset($item['triggerid'])) {
                        if (!isset($result[$item['itemid']]['triggerids'])) {
                            $result[$item['itemid']]['triggerids'] = array();
                        }
                        $result[$item['itemid']]['triggerids'][$item['triggerid']] = $item['triggerid'];
                        unset($item['triggerid']);
                    }
                    // graphids
                    if (isset($item['graphid'])) {
                        if (!isset($result[$item['itemid']]['graphids'])) {
                            $result[$item['itemid']]['graphids'] = array();
                        }
                        $result[$item['itemid']]['graphids'][$item['graphid']] = $item['graphid'];
                        unset($item['graphid']);
                    }
                    $result[$item['itemid']] += $item;
                }
            }
        }
        // Adding Objects
        // Adding hosts
        if ($options['select_hosts']) {
            $obj_params = array('extendoutput' => 1, 'itemids' => $itemids, 'nopermissions' => 1);
            $hosts = CHost::get($obj_params);
            foreach ($hosts as $hostid => $host) {
                foreach ($host['itemids'] as $num => $itemid) {
                    $result[$itemid]['hostids'][$hostid] = $hostid;
                    $result[$itemid]['hosts'][$hostid] = $host;
                }
            }
        }
        // Adding triggers
        if ($options['select_triggers']) {
            $obj_params = array('extendoutput' => 1, 'itemids' => $itemids);
            $triggers = CTrigger::get($obj_params);
            foreach ($triggers as $triggerid => $trigger) {
                foreach ($trigger['itemids'] as $num => $itemid) {
                    $result[$itemid]['triggerids'][$triggerid] = $triggerid;
                    $result[$itemid]['triggers'][$triggerid] = $trigger;
                }
            }
        }
        // Adding graphs
        if ($options['select_graphs']) {
            $obj_params = array('extendoutput' => 1, 'itemids' => $itemids);
            $graphs = CGraph::get($obj_params);
            foreach ($graphs as $graphid => $graph) {
                foreach ($graph['itemids'] as $num => $itemid) {
                    $result[$itemid]['graphids'][$graphid] = $graphid;
                    $result[$itemid]['graphs'][$graphid] = $graph;
                }
            }
        }
        return $result;
    }
 private static function trigger($action, $params)
 {
     CTrigger::$error = array();
     switch ($action) {
         default:
             $result = call_user_func(array('CTrigger', $action), $params);
     }
     self::$result = $result;
 }
Exemple #21
0
function getSelementsInfo($sysmap)
{
    $config = select_config();
    $show_unack = $config['event_ack_enable'] ? $sysmap['show_unack'] : EXTACK_OPTION_ALL;
    $triggers_map = array();
    $triggers_map_submaps = array();
    $hostgroups_map = array();
    $hosts_map = array();
    $selements = zbx_toHash($sysmap['selements'], 'selementid');
    foreach ($selements as $selementid => $selement) {
        $selements[$selementid]['hosts'] = array();
        $selements[$selementid]['triggers'] = array();
        switch ($selement['elementtype']) {
            case SYSMAP_ELEMENT_TYPE_MAP:
                $mapids = array($selement['elementid']);
                while (!empty($mapids)) {
                    $options = array('sysmapids' => $mapids, 'output' => API_OUTPUT_EXTEND, 'select_selements' => API_OUTPUT_EXTEND, 'nopermissions' => 1, 'nodeids' => get_current_nodeid(true));
                    $maps = CMap::get($options);
                    $mapids = array();
                    foreach ($maps as $map) {
                        foreach ($map['selements'] as $sel) {
                            switch ($sel['elementtype']) {
                                case SYSMAP_ELEMENT_TYPE_MAP:
                                    $mapids[] = $sel['elementid'];
                                    break;
                                case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
                                    $hostgroups_map[$sel['elementid']][$selementid] = $selementid;
                                    break;
                                case SYSMAP_ELEMENT_TYPE_HOST:
                                    $hosts_map[$sel['elementid']][$selementid] = $selementid;
                                    break;
                                case SYSMAP_ELEMENT_TYPE_TRIGGER:
                                    $triggers_map_submaps[$sel['elementid']][$selementid] = $selementid;
                                    break;
                            }
                        }
                    }
                }
                break;
            case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
                $hostgroups_map[$selement['elementid']][$selement['selementid']] = $selement['selementid'];
                break;
            case SYSMAP_ELEMENT_TYPE_HOST:
                $hosts_map[$selement['elementid']][$selement['selementid']] = $selement['selementid'];
                break;
            case SYSMAP_ELEMENT_TYPE_TRIGGER:
                $triggers_map[$selement['elementid']][$selement['selementid']] = $selement['selementid'];
                break;
        }
    }
    // get hosts data {{{
    $all_hosts = array();
    if (!empty($hosts_map)) {
        $options = array('hostids' => array_keys($hosts_map), 'output' => API_OUTPUT_EXTEND, 'nopermissions' => 1, 'nodeids' => get_current_nodeid(true));
        $hosts = CHost::get($options);
        $all_hosts = array_merge($all_hosts, $hosts);
        foreach ($hosts as $host) {
            foreach ($hosts_map[$host['hostid']] as $belongs_to_sel) {
                $selements[$belongs_to_sel]['hosts'][$host['hostid']] = $host['hostid'];
            }
        }
    }
    if (!empty($hostgroups_map)) {
        $options = array('groupids' => array_keys($hostgroups_map), 'output' => API_OUTPUT_EXTEND, 'nopermissions' => 1, 'nodeids' => get_current_nodeid(true));
        $hosts = CHost::get($options);
        $all_hosts = array_merge($all_hosts, $hosts);
        foreach ($hosts as $host) {
            foreach ($host['groups'] as $group) {
                foreach ($hostgroups_map[$group['groupid']] as $belongs_to_sel) {
                    $selements[$belongs_to_sel]['hosts'][$host['hostid']] = $host['hostid'];
                    // add hosts to hosts_map for trigger selection;
                    if (!isset($hosts_map[$host['hostid']])) {
                        $hosts_map[$host['hostid']] = array();
                    }
                    $hosts_map[$host['hostid']][$belongs_to_sel] = $belongs_to_sel;
                }
            }
        }
    }
    $all_hosts = zbx_toHash($all_hosts, 'hostid');
    $monitored_hostids = array();
    foreach ($all_hosts as $hostid => $host) {
        if ($host['status'] == HOST_STATUS_MONITORED) {
            $monitored_hostids[$hostid] = $hostid;
        }
    }
    // }}}
    // get triggers data {{{
    $all_triggers = array();
    // triggers from current map, select all
    if (!empty($triggers_map)) {
        $options = array('nodeids' => get_current_nodeid(true), 'triggerids' => array_keys($triggers_map), 'output' => API_OUTPUT_EXTEND, 'nopermissions' => 1);
        $triggers = CTrigger::get($options);
        $all_triggers = array_merge($all_triggers, $triggers);
        foreach ($triggers as $trigger) {
            foreach ($triggers_map[$trigger['triggerid']] as $belongs_to_sel) {
                $selements[$belongs_to_sel]['triggers'][$trigger['triggerid']] = $trigger['triggerid'];
            }
        }
    }
    // triggers from submaps, skip dependent
    if (!empty($triggers_map_submaps)) {
        $options = array('nodeids' => get_current_nodeid(true), 'triggerids' => array_keys($triggers_map_submaps), 'filter' => array('value' => array(TRIGGER_VALUE_UNKNOWN, TRIGGER_VALUE_TRUE)), 'skipDependent' => 1, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => 1);
        $triggers = CTrigger::get($options);
        $all_triggers = array_merge($all_triggers, $triggers);
        foreach ($triggers as $trigger) {
            foreach ($triggers_map_submaps[$trigger['triggerid']] as $belongs_to_sel) {
                $selements[$belongs_to_sel]['triggers'][$trigger['triggerid']] = $trigger['triggerid'];
            }
        }
    }
    // triggers from all hosts/hostgroups, skip dependent
    if (!empty($monitored_hostids)) {
        $options = array('hostids' => $monitored_hostids, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => 1, 'filter' => array('value' => array(TRIGGER_VALUE_UNKNOWN, TRIGGER_VALUE_TRUE)), 'nodeids' => get_current_nodeid(true), 'monitored' => true, 'skipDependent' => 1);
        $triggers = CTrigger::get($options);
        $all_triggers = array_merge($all_triggers, $triggers);
        foreach ($triggers as $trigger) {
            foreach ($trigger['hosts'] as $host) {
                foreach ($hosts_map[$host['hostid']] as $belongs_to_sel) {
                    $selements[$belongs_to_sel]['triggers'][$trigger['triggerid']] = $trigger['triggerid'];
                }
            }
        }
    }
    $all_triggers = zbx_toHash($all_triggers, 'triggerid');
    $options = array('triggerids' => array_keys($all_triggers), 'withLastEventUnacknowledged' => true, 'output' => API_OUTPUT_SHORTEN, 'nodeids' => get_current_nodeid(true), 'nopermissions' => 1, 'monitored' => true, 'filter' => array('value' => TRIGGER_VALUE_TRUE));
    $unack_triggerids = CTrigger::get($options);
    $unack_triggerids = zbx_toHash($unack_triggerids, 'triggerid');
    // }}}
    $info = array();
    foreach ($selements as $selementid => $selement) {
        $i = array('disabled' => 0, 'maintenance' => 0, 'problem' => 0, 'problem_unack' => 0, 'unknown' => 0, 'priority' => 0, 'trigger_disabled' => 0, 'latelyChanged' => false, 'ack' => true);
        foreach ($selement['hosts'] as $hostid) {
            $host = $all_hosts[$hostid];
            $last_hostid = $hostid;
            if ($host['status'] == HOST_STATUS_NOT_MONITORED) {
                $i['disabled']++;
            } else {
                if ($host['maintenance_status'] == HOST_MAINTENANCE_STATUS_ON) {
                    $i['maintenance']++;
                }
            }
        }
        foreach ($selement['triggers'] as $triggerid) {
            $trigger = $all_triggers[$triggerid];
            if ($trigger['status'] == TRIGGER_STATUS_DISABLED) {
                $i['trigger_disabled']++;
            } else {
                if ($trigger['value'] == TRIGGER_VALUE_TRUE) {
                    $i['problem']++;
                    $last_problemid = $triggerid;
                    if ($i['priority'] < $trigger['priority']) {
                        $i['priority'] = $trigger['priority'];
                    }
                } else {
                    if ($trigger['value'] == TRIGGER_VALUE_UNKNOWN) {
                        $i['unknown']++;
                    }
                }
                if (isset($unack_triggerids[$triggerid])) {
                    $i['problem_unack']++;
                }
                $i['latelyChanged'] |= time() - $trigger['lastchange'] < TRIGGER_BLINK_PERIOD;
            }
        }
        $i['ack'] = (bool) (!$i['problem_unack']);
        if ($sysmap['expandproblem'] && $i['problem'] == 1) {
            $i['problem_title'] = expand_trigger_description_by_data($all_triggers[$last_problemid]);
        }
        if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST && $i['maintenance'] == 1) {
            $mnt = get_maintenance_by_maintenanceid($all_hosts[$last_hostid]['maintenanceid']);
            $i['maintenance_title'] = $mnt['name'];
        }
        switch ($selement['elementtype']) {
            case SYSMAP_ELEMENT_TYPE_MAP:
                $info[$selementid] = getMapsInfo($selement, $i, $show_unack);
                break;
            case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
                $info[$selementid] = getHostGroupsInfo($selement, $i, $show_unack);
                break;
            case SYSMAP_ELEMENT_TYPE_HOST:
                $info[$selementid] = getHostsInfo($selement, $i, $show_unack);
                break;
            case SYSMAP_ELEMENT_TYPE_TRIGGER:
                $info[$selementid] = getTriggersInfo($selement, $i);
                break;
            case SYSMAP_ELEMENT_TYPE_IMAGE:
                $info[$selementid] = getImagesInfo($selement);
                break;
        }
    }
    // get names if is needed
    if ($sysmap['label_type'] == MAP_LABEL_TYPE_NAME) {
        $elems = separateMapElements($sysmap);
        if (!empty($elems['sysmaps'])) {
            $maps = CMap::get(array('sysmapids' => zbx_objectValues($elems['sysmaps'], 'elementid'), 'nopermissions' => 1, 'output' => API_OUTPUT_EXTEND));
            $maps = zbx_toHash($maps, 'sysmapid');
            foreach ($elems['sysmaps'] as $elem) {
                $info[$elem['selementid']]['name'] = $maps[$elem['elementid']]['name'];
            }
        }
        if (!empty($elems['hostgroups'])) {
            $hostgroups = CHostGroup::get(array('groupids' => zbx_objectValues($elems['hostgroups'], 'elementid'), 'nopermissions' => 1, 'output' => API_OUTPUT_EXTEND));
            $hostgroups = zbx_toHash($hostgroups, 'groupid');
            foreach ($elems['hostgroups'] as $elem) {
                $info[$elem['selementid']]['name'] = $hostgroups[$elem['elementid']]['name'];
            }
        }
        if (!empty($elems['triggers'])) {
            foreach ($elems['triggers'] as $elem) {
                $info[$elem['selementid']]['name'] = expand_trigger_description_by_data($all_triggers[$elem['elementid']]);
            }
        }
        if (!empty($elems['hosts'])) {
            foreach ($elems['hosts'] as $elem) {
                $info[$elem['selementid']]['name'] = $all_hosts[$elem['elementid']]['host'];
            }
        }
    }
    return $info;
}
Exemple #22
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;
    }
Exemple #23
0
     $triggers = CTrigger::get($trigOpt);
 }
 $options = array('nodeids' => get_current_nodeid(), 'object' => EVENT_OBJECT_TRIGGER, 'time_from' => $from, 'time_till' => $till, 'output' => API_OUTPUT_SHORTEN, 'sortfield' => 'clock', 'sortorder' => ZBX_SORT_DOWN, 'limit' => $config['search_limit'] + 1);
 if ($_REQUEST['hide_unknown']) {
     $options['hide_unknown'] = 1;
 }
 if (!empty($triggers)) {
     $options['triggerids'] = zbx_objectValues($triggers, 'triggerid');
 }
 $events = CEvent::get($options);
 $paging = getPagingLine($events);
 $options = array('nodeids' => get_current_nodeid(), 'eventids' => zbx_objectValues($events, 'eventid'), 'output' => API_OUTPUT_EXTEND, 'sortfield' => 'eventid', 'sortorder' => ZBX_SORT_DOWN, 'nopermissions' => 1);
 $events = CEvent::get($options);
 order_result($events, 'clock', ZBX_SORT_DOWN);
 $triggersOptions = array('triggerids' => zbx_objectValues($events, 'objectid'), 'select_hosts' => API_OUTPUT_EXTEND, 'select_triggers' => API_OUTPUT_EXTEND, 'select_items' => API_OUTPUT_EXTEND, 'output' => API_OUTPUT_EXTEND);
 $triggers = CTrigger::get($triggersOptions);
 $triggers = zbx_toHash($triggers, 'triggerid');
 foreach ($events as $enum => $event) {
     $trigger = $triggers[$event['objectid']];
     $host = reset($trigger['hosts']);
     $items = array();
     foreach ($trigger['items'] as $inum => $item) {
         $i = array();
         $i['itemid'] = $item['itemid'];
         $i['value_type'] = $item['value_type'];
         //ZBX-3059: So it would be possible to show different caption for history for chars and numbers (KB)
         $i['action'] = str_in_array($item['value_type'], array(ITEM_VALUE_TYPE_FLOAT, ITEM_VALUE_TYPE_UINT64)) ? 'showgraph' : 'showvalues';
         $i['description'] = item_description($item);
         $items[] = $i;
     }
     // Actions
function validate_condition($conditiontype, $value)
{
    global $USER_DETAILS;
    switch ($conditiontype) {
        case CONDITION_TYPE_HOST_GROUP:
            $groups = CHostGroup::get(array('groupids' => $value, 'output' => API_OUTPUT_SHORTEN, 'nodeids' => get_current_nodeid(true)));
            if (empty($groups)) {
                error(S_INCORRECT_GROUP);
                return false;
            }
            break;
        case CONDITION_TYPE_HOST_TEMPLATE:
            $templates = CTemplate::get(array('templateids' => $value, 'output' => API_OUTPUT_SHORTEN, 'nodeids' => get_current_nodeid(true)));
            if (empty($templates)) {
                error(S_INCORRECT_HOST);
                return false;
            }
            break;
        case CONDITION_TYPE_TRIGGER:
            $triggers = CTrigger::get(array('triggerids' => $value, 'output' => API_OUTPUT_SHORTEN, 'nodeids' => get_current_nodeid(true)));
            if (empty($triggers)) {
                error(S_INCORRECT_TRIGGER);
                return false;
            }
            break;
        case CONDITION_TYPE_HOST:
            $hosts = CHost::get(array('hostids' => $value, 'output' => API_OUTPUT_SHORTEN, 'nodeids' => get_current_nodeid(true)));
            if (empty($hosts)) {
                error(S_INCORRECT_HOST);
                return false;
            }
            break;
        case CONDITION_TYPE_TIME_PERIOD:
            if (!validate_period($value)) {
                error(S_INCORRECT_PERIOD . ' [' . $value . ']');
                return false;
            }
            break;
        case CONDITION_TYPE_DHOST_IP:
            if (!validate_ip_range($value)) {
                error(S_INCORRECT_IP . ' [' . $value . ']');
                return false;
            }
            break;
        case CONDITION_TYPE_DSERVICE_TYPE:
            if (S_UNKNOWN == discovery_check_type2str($value)) {
                error(S_INCORRECT_DISCOVERY_CHECK);
                return false;
            }
            break;
        case CONDITION_TYPE_DSERVICE_PORT:
            if (!validate_port_list($value)) {
                error(S_INCORRECT_PORT . ' [' . $value . ']');
                return false;
            }
            break;
        case CONDITION_TYPE_DSTATUS:
            if (S_UNKNOWN == discovery_object_status2str($value)) {
                error(S_INCORRECT_DISCOVERY_STATUS);
                return false;
            }
            break;
        case CONDITION_TYPE_EVENT_ACKNOWLEDGED:
            if (S_UNKNOWN == condition_value2str($conditiontype, $value)) {
                error(S_INCORRECT_DISCOVERY_STATUS);
                return false;
            }
            break;
        case CONDITION_TYPE_TRIGGER_NAME:
        case CONDITION_TYPE_TRIGGER_VALUE:
        case CONDITION_TYPE_TRIGGER_SEVERITY:
        case CONDITION_TYPE_MAINTENANCE:
        case CONDITION_TYPE_NODE:
        case CONDITION_TYPE_DRULE:
        case CONDITION_TYPE_DCHECK:
        case CONDITION_TYPE_DOBJECT:
        case CONDITION_TYPE_PROXY:
        case CONDITION_TYPE_DUPTIME:
        case CONDITION_TYPE_DVALUE:
        case CONDITION_TYPE_APPLICATION:
        case CONDITION_TYPE_HOST_NAME:
            break;
        default:
            error(S_INCORRECT_CONDITION_TYPE);
            return false;
            break;
    }
    return true;
}
 /**
  * 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 copy_triggers($srcid, $destid)
{
    try {
        $options = array('hostids' => $srcid, 'output' => API_OUTPUT_EXTEND, 'templated_hosts' => 1);
        $src = CHost::get($options);
        if (empty($src)) {
            throw new Exception();
        }
        $src = reset($src);
        $options = array('hostids' => $destid, 'output' => API_OUTPUT_EXTEND, 'templated_hosts' => 1);
        $dest = CHost::get($options);
        if (empty($dest)) {
            throw new Exception();
        }
        $dest = reset($dest);
        $options = array('hostids' => $srcid, 'output' => API_OUTPUT_EXTEND, 'inherited' => 0, 'select_dependencies' => API_OUTPUT_EXTEND);
        $triggers = CTrigger::get($options);
        $hash = array();
        foreach ($triggers as $trigger) {
            $expr = explode_exp($trigger['expression'], 0);
            $expr = str_replace($src['host'] . ':', $dest['host'] . ':', $expr);
            $trigger['expression'] = $expr;
            $result = CTrigger::create($trigger);
            if (!$result) {
                throw new Exception();
            }
            $hash[$trigger['triggerid']] = reset($result['triggerids']);
        }
        foreach ($triggers as $trigger) {
            foreach ($trigger['dependencies'] as $dep) {
                if (isset($hash[$dep['triggerid']])) {
                    $dep = $hash[$dep['triggerid']];
                } else {
                    $dep = $dep['triggerid'];
                }
                $res = add_trigger_dependency($hash[$trigger['triggerid']], $dep);
                if (!$res) {
                    throw new Exception();
                }
            }
        }
        return true;
    } catch (Exception $e) {
        return false;
    }
}