/**
  * Get UserMacros data
  *
  * @param array $options
  * @param array $options['nodeids'] Node IDs
  * @param array $options['groupids'] UserMacrosGroup IDs
  * @param array $options['macroids'] UserMacros IDs
  * @param boolean $options['monitored_macros'] only monitored UserMacros
  * @param boolean $options['templated_macros'] include templates in result
  * @param boolean $options['with_items'] only with items
  * @param boolean $options['with_historical_items'] only with historical items
  * @param boolean $options['with_triggers'] only with triggers
  * @param boolean $options['with_httptests'] only with 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['count'] count UserMacros, returned column name is rowscount
  * @param string $options['pattern'] search macros by pattern in macro names
  * @param int $options['limit'] limit selection
  * @param string $options['order'] deprecated parameter (for now)
  * @return array|boolean UserMacros data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('macro');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('macros' => 'hm.hostmacroid'), 'from' => array('hostmacro hm'), 'where' => array(), 'order' => array(), 'limit' => null);
     $sqlPartsGlobal = array('select' => array('macros' => 'gm.globalmacroid'), 'from' => array('globalmacro gm'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'hostmacroids' => null, 'globalmacroids' => null, 'templateids' => null, 'globalmacro' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectHosts' => null, 'selectTemplates' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         if (!is_null($options['editable']) && !is_null($options['globalmacro'])) {
             return array();
         } else {
             $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
             $userGroups = getUserGroupsByUserId($userid);
             $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE hm.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
         }
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // global macro
     if (!is_null($options['globalmacro'])) {
         $sqlPartsGlobal['where'][] = DBin_node('gm.globalmacroid', $nodeids);
         $options['groupids'] = null;
         $options['hostmacroids'] = null;
         $options['triggerids'] = null;
         $options['hostids'] = null;
         $options['itemids'] = null;
         $options['selectGroups'] = null;
         $options['selectTemplates'] = null;
         $options['selectHosts'] = null;
     } else {
         $sqlParts['where'][] = DBin_node('hm.hostmacroid', $nodeids);
     }
     // globalmacroids
     if (!is_null($options['globalmacroids'])) {
         zbx_value2array($options['globalmacroids']);
         $sqlPartsGlobal['where'][] = dbConditionInt('gm.globalmacroid', $options['globalmacroids']);
     }
     // hostmacroids
     if (!is_null($options['hostmacroids'])) {
         zbx_value2array($options['hostmacroids']);
         $sqlParts['where'][] = dbConditionInt('hm.hostmacroid', $options['hostmacroids']);
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']);
         $sqlParts['where']['hgh'] = 'hg.hostid=hm.hostid';
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         $sqlParts['where'][] = dbConditionInt('hm.hostid', $options['hostids']);
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['templateid'] = 'ht.templateid';
         }
         $sqlParts['from']['macros_templates'] = 'hosts_templates ht';
         $sqlParts['where'][] = dbConditionInt('ht.templateid', $options['templateids']);
         $sqlParts['where']['hht'] = 'hm.hostid=ht.hostid';
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('hostmacro hm', $options, $sqlParts);
         zbx_db_search('globalmacro gm', $options, $sqlPartsGlobal);
     }
     // filter
     if (is_array($options['filter'])) {
         if (isset($options['filter']['macro'])) {
             zbx_value2array($options['filter']['macro']);
             $sqlParts['where'][] = dbConditionString('hm.macro', $options['filter']['macro']);
             $sqlPartsGlobal['where'][] = dbConditionString('gm.macro', $options['filter']['macro']);
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['macros'] = 'hm.*';
         $sqlPartsGlobal['select']['macros'] = 'gm.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT hm.hostmacroid) as rowscount');
         $sqlPartsGlobal['select'] = array('count(DISTINCT gm.globalmacroid) as rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'hm');
     zbx_db_sorting($sqlPartsGlobal, $options, $sortColumns, 'gm');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
         $sqlPartsGlobal['limit'] = $options['limit'];
     }
     // init GLOBALS
     if (!is_null($options['globalmacro'])) {
         $res = DBselect($this->createSelectQueryFromParts($sqlPartsGlobal), $sqlPartsGlobal['limit']);
         while ($macro = DBfetch($res)) {
             if ($options['countOutput']) {
                 $result = $macro['rowscount'];
             } else {
                 $globalmacroids[$macro['globalmacroid']] = $macro['globalmacroid'];
                 if ($options['output'] == API_OUTPUT_SHORTEN) {
                     $result[$macro['globalmacroid']] = array('globalmacroid' => $macro['globalmacroid']);
                 } else {
                     if (!isset($result[$macro['globalmacroid']])) {
                         $result[$macro['globalmacroid']] = array();
                     }
                     $result[$macro['globalmacroid']] += $macro;
                 }
             }
         }
     } else {
         $hostids = array();
         $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
         while ($macro = DBfetch($res)) {
             if ($options['countOutput']) {
                 $result = $macro['rowscount'];
             } else {
                 $hostmacroids[$macro['hostmacroid']] = $macro['hostmacroid'];
                 if ($options['output'] == API_OUTPUT_SHORTEN) {
                     $result[$macro['hostmacroid']] = $macro['hostmacroid'];
                 } else {
                     $hostids[$macro['hostid']] = $macro['hostid'];
                     if (!isset($result[$macro['hostmacroid']])) {
                         $result[$macro['hostmacroid']] = array();
                     }
                     // groups
                     if ($options['selectGroups'] && !isset($result[$macro['hostmacroid']]['groups'])) {
                         $result[$macro['hostmacroid']]['groups'] = array();
                     }
                     // templates
                     if ($options['selectTemplates'] && !isset($result[$macro['hostmacroid']]['templates'])) {
                         $result[$macro['hostmacroid']]['templates'] = array();
                     }
                     // hosts
                     if ($options['selectHosts'] && !isset($result[$macro['hostmacroid']]['hosts'])) {
                         $result[$macro['hostmacroid']]['hosts'] = array();
                     }
                     // groupids
                     if (isset($macro['groupid'])) {
                         if (!isset($result[$macro['hostmacroid']]['groups'])) {
                             $result[$macro['hostmacroid']]['groups'] = array();
                         }
                         $result[$macro['hostmacroid']]['groups'][] = array('groupid' => $macro['groupid']);
                         unset($macro['groupid']);
                     }
                     // templateids
                     if (isset($macro['templateid'])) {
                         if (!isset($result[$macro['hostmacroid']]['templates'])) {
                             $result[$macro['hostmacroid']]['templates'] = array();
                         }
                         $result[$macro['hostmacroid']]['templates'][] = array('templateid' => $macro['templateid']);
                         unset($macro['templateid']);
                     }
                     // hostids
                     if (isset($macro['hostid'])) {
                         if (!isset($result[$macro['hostmacroid']]['hosts'])) {
                             $result[$macro['hostmacroid']]['hosts'] = array();
                         }
                         $result[$macro['hostmacroid']]['hosts'][] = array('hostid' => $macro['hostid']);
                     }
                     $result[$macro['hostmacroid']] += $macro;
                 }
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding groups
     if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectGroups'], 'hostids' => $hostids, 'preservekeys' => true);
         $groups = API::HostGroup()->get($objParams);
         foreach ($groups as $group) {
             $ghosts = $group['hosts'];
             unset($group['hosts']);
             foreach ($ghosts as $host) {
                 foreach ($result as $macroid => $macro) {
                     if (bccomp($macro['hostid'], $host['hostid']) == 0) {
                         $result[$macroid]['groups'][] = $group;
                     }
                 }
             }
         }
     }
     // adding templates
     if (!is_null($options['selectTemplates']) && str_in_array($options['selectTemplates'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectTemplates'], 'hostids' => $hostids, 'preservekeys' => true);
         $templates = API::Template()->get($objParams);
         foreach ($templates as $template) {
             $thosts = $template['hosts'];
             unset($template['hosts']);
             foreach ($thosts as $host) {
                 foreach ($result as $macroid => $macro) {
                     if (bccomp($macro['hostid'], $host['hostid']) == 0) {
                         $result[$macroid]['templates'][] = $template;
                     }
                 }
             }
         }
     }
     // adding hosts
     if (!is_null($options['selectHosts']) && str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectHosts'], 'hostids' => $hostids, 'preservekeys' => true);
         $hosts = API::Host()->get($objParams);
         foreach ($hosts as $hostid => $host) {
             foreach ($result as $macroid => $macro) {
                 if (bccomp($macro['hostid'], $hostid) == 0) {
                     $result[$macroid]['hosts'][] = $host;
                 }
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Itemprototype data
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('itemid', 'name', 'key_', 'delay', 'history', 'trends', 'type', 'status');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('items' => 'i.itemid'), 'from' => array('items' => 'items i'), 'where' => array('i.flags=' . ZBX_FLAG_DISCOVERY_CHILD), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'itemids' => null, 'discoveryids' => null, 'graphids' => null, 'triggerids' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectHosts' => null, 'selectApplications' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['items']);
         $dbTable = DB::getSchema('items');
         $sqlParts['select']['itemid'] = 'i.itemid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'i.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE i.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // 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) {
             $sqlParts['select']['hostid'] = 'i.hostid';
         }
         $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['hostids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['i'] = 'i.hostid';
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sqlParts['where']['itemid'] = dbConditionInt('i.itemid', $options['itemids']);
     }
     // discoveryids
     if (!is_null($options['discoveryids'])) {
         zbx_value2array($options['discoveryids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['discoveryid'] = 'id.parent_itemid';
         }
         $sqlParts['from']['item_discovery'] = 'item_discovery id';
         $sqlParts['where'][] = dbConditionInt('id.parent_itemid', $options['discoveryids']);
         $sqlParts['where']['idi'] = 'i.itemid=id.itemid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['id'] = 'id.parent_itemid';
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['triggerid'] = 'f.triggerid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
         $sqlParts['where']['if'] = 'i.itemid=f.itemid';
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['graphid'] = 'gi.graphid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']);
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sqlParts['where'][] = 'i.templateid IS NOT NULL';
         } else {
             $sqlParts['where'][] = 'i.templateid IS NULL';
         }
     }
     // templated
     if (!is_null($options['templated'])) {
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['templated']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // monitored
     if (!is_null($options['monitored'])) {
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['monitored']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_MONITORED;
             $sqlParts['where'][] = 'i.status=' . ITEM_STATUS_ACTIVE;
         } else {
             $sqlParts['where'][] = '(h.status<>' . HOST_STATUS_MONITORED . ' OR i.status<>' . ITEM_STATUS_ACTIVE . ')';
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('items i', $options, $sqlParts);
     }
     // --- FILTER ---
     if (is_array($options['filter'])) {
         $this->dbFilter('items i', $options, $sqlParts);
         if (isset($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sqlParts['from']['hosts'] = 'hosts h';
             $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
             $sqlParts['where']['h'] = dbConditionString('h.host', $options['filter']['host']);
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['items'] = 'i.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT i.itemid) as rowscount');
         //groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'i');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     //----------
     $itemids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('i.itemid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder;
     //SDI($sql);
     $res = DBselect($sql, $sqlLimit);
     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['selectHosts']) && !isset($result[$item['itemid']]['hosts'])) {
                     $result[$item['itemid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectApplications']) && !isset($result[$item['itemid']]['applications'])) {
                     $result[$item['itemid']]['applications'] = array();
                 }
                 if (!is_null($options['selectTriggers']) && !isset($result[$item['itemid']]['triggers'])) {
                     $result[$item['itemid']]['triggers'] = array();
                 }
                 if (!is_null($options['selectGraphs']) && !isset($result[$item['itemid']]['graphs'])) {
                     $result[$item['itemid']]['graphs'] = array();
                 }
                 // hostids
                 if (isset($item['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$item['itemid']]['hosts'])) {
                         $result[$item['itemid']]['hosts'] = array();
                     }
                     $result[$item['itemid']]['hosts'][] = array('hostid' => $item['hostid']);
                 }
                 // triggerids
                 if (isset($item['triggerid']) && is_null($options['selectTriggers'])) {
                     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['selectGraphs'])) {
                     if (!isset($result[$item['itemid']]['graphs'])) {
                         $result[$item['itemid']]['graphs'] = array();
                     }
                     $result[$item['itemid']]['graphs'][] = array('graphid' => $item['graphid']);
                     unset($item['graphid']);
                 }
                 // discoveryids
                 if (isset($item['discoveryids'])) {
                     if (!isset($result[$item['itemid']]['discovery'])) {
                         $result[$item['itemid']]['discovery'] = array();
                     }
                     $result[$item['itemid']]['discovery'][] = array('ruleid' => $item['item_parentid']);
                     unset($item['item_parentid']);
                 }
                 $result[$item['itemid']] += $item;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // Adding Objects
     // Adding hosts
     if (!is_null($options['selectHosts'])) {
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams = array('nodeids' => $nodeids, 'itemids' => $itemids, 'templated_hosts' => 1, 'output' => $options['selectHosts'], 'nopermissions' => 1, 'preservekeys' => 1);
             $hosts = API::Host()->get($objParams);
             foreach ($hosts as $host) {
                 $hitems = $host['items'];
                 unset($host['items']);
                 foreach ($hitems as $inum => $item) {
                     $result[$item['itemid']]['hosts'][] = $host;
                 }
             }
             $templates = API::Template()->get($objParams);
             foreach ($templates as $template) {
                 $titems = $template['items'];
                 unset($template['items']);
                 foreach ($titems as $inum => $item) {
                     $result[$item['itemid']]['hosts'][] = $template;
                 }
             }
         }
     }
     // Adding triggers
     if (!is_null($options['selectTriggers'])) {
         $objParams = array('nodeids' => $nodeids, 'itemids' => $itemids, 'preservekeys' => true);
         if (in_array($options['selectTriggers'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectTriggers'];
             $triggers = API::TriggerPrototype()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($triggers, 'description');
             }
             $count = array();
             foreach ($triggers as $triggerid => $trigger) {
                 unset($triggers[$triggerid]['items']);
                 foreach ($trigger['items'] as $item) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$item['itemid']])) {
                             $count[$item['itemid']] = 0;
                         }
                         $count[$item['itemid']]++;
                         if ($count[$item['itemid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$item['itemid']]['triggers'][] =& $triggers[$triggerid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $triggers = API::TriggerPrototype()->get($objParams);
             $triggers = zbx_toHash($triggers, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($triggers[$itemid])) {
                     $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['triggers'] = 0;
                 }
             }
         }
     }
     // Adding applications
     if (!is_null($options['selectApplications']) && str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) {
         $objParams = array('nodeids' => $nodeids, 'output' => $options['selectApplications'], 'itemids' => $itemids, 'preservekeys' => 1);
         $applications = API::Application()->get($objParams);
         foreach ($applications as $applicationid => $application) {
             $aitems = $application['items'];
             unset($application['items']);
             foreach ($aitems as $inum => $item) {
                 $result[$item['itemid']]['applications'][] = $application;
             }
         }
     }
     // Adding graphs
     if (!is_null($options['selectGraphs'])) {
         $objParams = array('nodeids' => $nodeids, 'itemids' => $itemids, 'preservekeys' => true);
         if (in_array($options['selectGraphs'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectGraphs'];
             $graphs = API::GraphPrototype()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($graphs, 'name');
             }
             $count = array();
             foreach ($graphs as $graphid => $graph) {
                 unset($graphs[$graphid]['items']);
                 foreach ($graph['items'] as $item) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$item['itemid']])) {
                             $count[$item['itemid']] = 0;
                         }
                         $count[$item['itemid']]++;
                         if ($count[$item['itemid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$item['itemid']]['graphs'][] =& $graphs[$graphid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $graphs = API::GraphPrototype()->get($objParams);
             $graphs = zbx_toHash($graphs, 'parent_itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($graphs[$itemid])) {
                     $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['graphs'] = 0;
                 }
             }
         }
     }
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get GraphPrototype data
  *
  * @param array $options
  * @return array
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('graphid', 'name', 'graphtype');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('graphs' => 'g.graphid'), 'from' => array('graphs' => 'graphs g'), 'where' => array('g.flags=' . ZBX_FLAG_DISCOVERY_CHILD), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'graphids' => null, 'itemids' => null, 'discoveryids' => null, 'type' => null, 'templated' => null, 'inherited' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectTemplates' => null, 'selectHosts' => null, 'selectItems' => null, 'selectGraphItems' => null, 'selectDiscoveryRule' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['graphs']);
         $dbTable = DB::getSchema('graphs');
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'g.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM graphs_items gi,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE g.graphid=gi.graphid' . ' AND gi.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY gi.graphid' . ' HAVING MIN(r.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) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']);
         $sqlParts['where'][] = 'hg.hostid=i.hostid';
         $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['hg'] = 'hg.groupid';
         }
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if (!is_null($options['hostids'])) {
             zbx_value2array($options['hostids']);
             $options['hostids'] = array_merge($options['hostids'], $options['templateids']);
         } else {
             $options['hostids'] = $options['templateids'];
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostid'] = 'i.hostid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('i.hostid', $options['hostids']);
         $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['i'] = 'i.hostid';
         }
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         $sqlParts['where'][] = dbConditionInt('g.graphid', $options['graphids']);
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'gi.itemid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
         $sqlParts['where'][] = dbConditionInt('gi.itemid', $options['itemids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['gi'] = 'gi.itemid';
         }
     }
     // discoveryids
     if (!is_null($options['discoveryids'])) {
         zbx_value2array($options['discoveryids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'id.parent_itemid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['from']['item_discovery'] = 'item_discovery id';
         $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
         $sqlParts['where']['giid'] = 'gi.itemid=id.itemid';
         $sqlParts['where'][] = dbConditionInt('id.parent_itemid', $options['discoveryids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['id'] = 'id.parent_itemid';
         }
     }
     // type
     if (!is_null($options['type'])) {
         $sqlParts['where'][] = 'g.type=' . zbx_dbstr($options['type']);
     }
     // templated
     if (!is_null($options['templated'])) {
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
         $sqlParts['where']['ggi'] = 'g.graphid=gi.graphid';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['templated']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sqlParts['where'][] = 'g.templateid IS NOT NULL';
         } else {
             $sqlParts['where'][] = 'g.templateid IS NULL';
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['graphs'] = 'g.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT g.graphid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('graphs g', $options, $sqlParts);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('graphs g', $options, $sqlParts);
         if (isset($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sqlParts['from']['graphs_items'] = 'graphs_items gi';
             $sqlParts['from']['items'] = 'items i';
             $sqlParts['from']['hosts'] = 'hosts h';
             $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
             $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
             $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
             $sqlParts['where']['host'] = dbConditionString('h.host', $options['filter']['host']);
         }
         if (isset($options['filter']['hostid'])) {
             zbx_value2array($options['filter']['hostid']);
             $sqlParts['from']['graphs_items'] = 'graphs_items gi';
             $sqlParts['from']['items'] = 'items i';
             $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
             $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
             $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['filter']['hostid']);
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'g');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $graphids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('g.graphid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($graph = DBfetch($dbRes)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $graph;
             } else {
                 $result = $graph['rowscount'];
             }
         } else {
             $graphids[$graph['graphid']] = $graph['graphid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$graph['graphid']] = array('graphid' => $graph['graphid']);
             } else {
                 if (!isset($result[$graph['graphid']])) {
                     $result[$graph['graphid']] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$graph['graphid']]['hosts'])) {
                     $result[$graph['graphid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectGraphItems']) && !isset($result[$graph['graphid']]['gitems'])) {
                     $result[$graph['graphid']]['gitems'] = array();
                 }
                 if (!is_null($options['selectTemplates']) && !isset($result[$graph['graphid']]['templates'])) {
                     $result[$graph['graphid']]['templates'] = array();
                 }
                 if (!is_null($options['selectItems']) && !isset($result[$graph['graphid']]['items'])) {
                     $result[$graph['graphid']]['items'] = array();
                 }
                 if (!is_null($options['selectDiscoveryRule']) && !isset($result[$graph['graphid']]['discoveryRule'])) {
                     $result[$graph['graphid']]['discoveryRule'] = array();
                 }
                 // hostids
                 if (isset($graph['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$graph['graphid']]['hosts'])) {
                         $result[$graph['graphid']]['hosts'] = array();
                     }
                     $result[$graph['graphid']]['hosts'][] = array('hostid' => $graph['hostid']);
                     unset($graph['hostid']);
                 }
                 // itemids
                 if (isset($graph['itemid']) && is_null($options['selectItems'])) {
                     if (!isset($result[$graph['graphid']]['items'])) {
                         $result[$graph['graphid']]['items'] = array();
                     }
                     $result[$graph['graphid']]['items'][] = array('itemid' => $graph['itemid']);
                     unset($graph['itemid']);
                 }
                 $result[$graph['graphid']] += $graph;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // adding GraphItems
     if (!is_null($options['selectGraphItems']) && str_in_array($options['selectGraphItems'], $subselectsAllowedOutputs)) {
         $gitems = API::GraphItem()->get(array('nodeids' => $nodeids, 'output' => $options['selectGraphItems'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true));
         foreach ($gitems as $gitem) {
             $ggraphs = $gitem['graphs'];
             unset($gitem['graphs']);
             foreach ($ggraphs as $graph) {
                 $result[$graph['graphid']]['gitems'][$gitem['gitemid']] = $gitem;
             }
         }
     }
     // adding Hostgroups
     if (!is_null($options['selectGroups'])) {
         if (is_array($options['selectGroups']) || str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) {
             $groups = API::HostGroup()->get(array('nodeids' => $nodeids, 'output' => $options['selectGroups'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true));
             foreach ($groups as $group) {
                 $ggraphs = $group['graphs'];
                 unset($group['graphs']);
                 foreach ($ggraphs as $graph) {
                     $result[$graph['graphid']]['groups'][] = $group;
                 }
             }
         }
     }
     // adding Hosts
     if (!is_null($options['selectHosts'])) {
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $hosts = API::Host()->get(array('nodeids' => $nodeids, 'output' => $options['selectHosts'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true));
             foreach ($hosts as $host) {
                 $hgraphs = $host['graphs'];
                 unset($host['graphs']);
                 foreach ($hgraphs as $graph) {
                     $result[$graph['graphid']]['hosts'][] = $host;
                 }
             }
         }
     }
     // adding Templates
     if (!is_null($options['selectTemplates']) && str_in_array($options['selectTemplates'], $subselectsAllowedOutputs)) {
         $templates = API::Template()->get(array('nodeids' => $nodeids, 'output' => $options['selectTemplates'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true));
         foreach ($templates as $template) {
             $tgraphs = $template['graphs'];
             unset($template['graphs']);
             foreach ($tgraphs as $graph) {
                 $result[$graph['graphid']]['templates'][] = $template;
             }
         }
     }
     // adding Items
     if (!is_null($options['selectItems']) && str_in_array($options['selectItems'], $subselectsAllowedOutputs)) {
         $items = API::Item()->get(array('nodeids' => $nodeids, 'output' => $options['selectItems'], 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true, 'filter' => array('flags' => null)));
         foreach ($items as $item) {
             $igraphs = $item['graphs'];
             unset($item['graphs']);
             foreach ($igraphs as $graph) {
                 $result[$graph['graphid']]['items'][] = $item;
             }
         }
     }
     // adding discoveryRule
     if (!is_null($options['selectDiscoveryRule'])) {
         $ruleids = $ruleMap = array();
         $dbRules = DBselect('SELECT id.parent_itemid,gi.graphid' . ' FROM item_discovery id,graphs_items gi' . ' WHERE ' . dbConditionInt('gi.graphid', $graphids) . ' AND gi.itemid=id.itemid');
         while ($rule = DBfetch($dbRules)) {
             $ruleids[$rule['parent_itemid']] = $rule['parent_itemid'];
             $ruleMap[$rule['graphid']] = $rule['parent_itemid'];
         }
         $objParams = array('nodeids' => $nodeids, 'itemids' => $ruleids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectDiscoveryRule']) || str_in_array($options['selectDiscoveryRule'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDiscoveryRule'];
             $discoveryRules = API::DiscoveryRule()->get($objParams);
             foreach ($result as $graphid => $graph) {
                 if (isset($ruleMap[$graphid]) && isset($discoveryRules[$ruleMap[$graphid]])) {
                     $result[$graphid]['discoveryRule'] = $discoveryRules[$ruleMap[$graphid]];
                 }
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 4
0
 /**
  * Get Host 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 boolean       $options['selectGroups']             select HostGroups
  * @param boolean       $options['selectItems']              select Items
  * @param boolean       $options['selectTriggers']           select Triggers
  * @param boolean       $options['selectGraphs']             select Graphs
  * @param boolean       $options['selectApplications']       select Applications
  * @param boolean       $options['selectMacros']             select Macros
  * @param boolean|array $options['selectInventory']          select Inventory
  * @param boolean       $options['withInventory']            select only hosts with inventory
  * @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 function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('hostid', 'host', 'name', 'status');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'proxyids' => null, 'templateids' => null, 'interfaceids' => null, 'itemids' => null, 'triggerids' => null, 'maintenanceids' => null, 'graphids' => null, 'applicationids' => null, 'dhostids' => null, 'dserviceids' => null, 'httptestids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'proxy_hosts' => null, 'with_items' => null, 'with_monitored_items' => null, 'with_historical_items' => null, 'with_simple_graph_items' => null, 'with_triggers' => null, 'with_monitored_triggers' => null, 'with_httptests' => null, 'with_monitored_httptests' => null, 'with_graphs' => null, 'with_applications' => null, 'withInventory' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectParentTemplates' => null, 'selectItems' => null, 'selectDiscoveries' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectDHosts' => null, 'selectDServices' => null, 'selectApplications' => null, 'selectMacros' => null, 'selectScreens' => null, 'selectInterfaces' => null, 'selectInventory' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['hosts']);
         $dbTable = DB::getSchema('hosts');
         $sqlParts['select']['hostid'] = 'h.hostid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'h.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE h.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         $sqlParts['where']['hostid'] = dbConditionInt('h.hostid', $options['hostids']);
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']);
         $sqlParts['where']['hgh'] = 'hg.hostid=h.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['groupid'] = 'hg.groupid';
         }
     }
     // proxyids
     if (!is_null($options['proxyids'])) {
         zbx_value2array($options['proxyids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['proxy_hostid'] = 'h.proxy_hostid';
         }
         $sqlParts['where'][] = dbConditionInt('h.proxy_hostid', $options['proxyids']);
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['templateid'] = 'ht.templateid';
         }
         $sqlParts['from']['hosts_templates'] = 'hosts_templates ht';
         $sqlParts['where'][] = dbConditionInt('ht.templateid', $options['templateids']);
         $sqlParts['where']['hht'] = 'h.hostid=ht.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['templateid'] = 'ht.templateid';
         }
     }
     // interfaceids
     if (!is_null($options['interfaceids'])) {
         zbx_value2array($options['interfaceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['interfaceid'] = 'hi.interfaceid';
         }
         $sqlParts['from']['interface'] = 'interface hi';
         $sqlParts['where'][] = dbConditionInt('hi.interfaceid', $options['interfaceids']);
         $sqlParts['where']['hi'] = 'h.hostid=hi.hostid';
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'i.itemid';
         }
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('i.itemid', $options['itemids']);
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['triggerid'] = 'f.triggerid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // httptestids
     if (!is_null($options['httptestids'])) {
         zbx_value2array($options['httptestids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['httptestid'] = 'ht.httptestid';
         }
         $sqlParts['from']['applications'] = 'applications a';
         $sqlParts['from']['httptest'] = 'httptest ht';
         $sqlParts['where'][] = dbConditionInt('ht.httptestid', $options['httptestids']);
         $sqlParts['where']['aht'] = 'a.applicationid=ht.applicationid';
         $sqlParts['where']['ah'] = 'a.hostid=h.hostid';
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['graphid'] = 'gi.graphid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']);
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['applicationid'] = 'a.applicationid';
         }
         $sqlParts['from']['applications'] = 'applications a';
         $sqlParts['where'][] = dbConditionInt('a.applicationid', $options['applicationids']);
         $sqlParts['where']['ah'] = 'a.hostid=h.hostid';
     }
     // dhostids
     if (!is_null($options['dhostids'])) {
         zbx_value2array($options['dhostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['dhostid'] = 'ds.dhostid';
         }
         $sqlParts['from']['dservices'] = 'dservices ds';
         $sqlParts['where'][] = dbConditionInt('ds.dhostid', $options['dhostids']);
         $sqlParts['where']['dsh'] = 'ds.ip=h.ip';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['dhostid'] = 'ds.dhostid';
         }
     }
     // dserviceids
     if (!is_null($options['dserviceids'])) {
         zbx_value2array($options['dserviceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['dserviceid'] = 'ds.dserviceid';
         }
         $sqlParts['from']['dservices'] = 'dservices ds';
         $sqlParts['from']['interface'] = 'interface i';
         $sqlParts['where'][] = dbConditionInt('ds.dserviceid', $options['dserviceids']);
         $sqlParts['where']['dsh'] = 'ds.ip=i.ip';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['dserviceid'] = 'ds.dserviceid';
         }
     }
     // maintenanceids
     if (!is_null($options['maintenanceids'])) {
         zbx_value2array($options['maintenanceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['maintenanceid'] = 'mh.maintenanceid';
         }
         $sqlParts['from']['maintenances_hosts'] = 'maintenances_hosts mh';
         $sqlParts['where'][] = dbConditionInt('mh.maintenanceid', $options['maintenanceids']);
         $sqlParts['where']['hmh'] = 'h.hostid=mh.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['maintenanceid'] = 'mh.maintenanceid';
         }
     }
     // monitored_hosts, templated_hosts
     if (!is_null($options['monitored_hosts'])) {
         $sqlParts['where']['status'] = 'h.status=' . HOST_STATUS_MONITORED;
     } elseif (!is_null($options['templated_hosts'])) {
         $sqlParts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')';
     } elseif (!is_null($options['proxy_hosts'])) {
         $sqlParts['where']['status'] = 'h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')';
     } else {
         $sqlParts['where']['status'] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')';
     }
     // with_items, with_monitored_items, with_historical_items, with_simple_graph_items
     if (!is_null($options['with_items'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ')';
     } elseif (!is_null($options['with_monitored_items'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ')';
     } elseif (!is_null($options['with_historical_items'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ' AND i.status IN (' . ITEM_STATUS_ACTIVE . ',' . ITEM_STATUS_NOTSUPPORTED . ')' . ' AND i.lastvalue IS NOT NULL' . ')';
     } elseif (!is_null($options['with_simple_graph_items'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE h.hostid=i.hostid' . ' AND i.value_type IN (' . ITEM_VALUE_TYPE_FLOAT . ',' . ITEM_VALUE_TYPE_UINT64 . ')' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.flags IN (' . ZBX_FLAG_DISCOVERY_NORMAL . ',' . ZBX_FLAG_DISCOVERY_CREATED . ')' . ')';
     }
     // with_triggers, with_monitored_triggers
     if (!is_null($options['with_triggers'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,functions f,triggers t' . ' WHERE h.hostid=i.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid' . ')';
     } elseif (!is_null($options['with_monitored_triggers'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,functions f,triggers t' . ' WHERE h.hostid=i.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')';
     }
     // with_httptests, with_monitored_httptests
     if (!is_null($options['with_httptests'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,httptest ht' . ' WHERE h.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ')';
     } elseif (!is_null($options['with_monitored_httptests'])) {
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,httptest ht' . ' WHERE h.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')';
     }
     // with_graphs
     if (!is_null($options['with_graphs'])) {
         $sqlParts['where'][] = 'EXISTS (' . ' SELECT 1' . ' FROM items i,graphs_items gi' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=gi.itemid ' . zbx_limit(1) . ')';
     }
     // with applications
     if (!is_null($options['with_applications'])) {
         $sqlParts['from']['applications'] = 'applications a';
         $sqlParts['where'][] = 'a.hostid=h.hostid';
     }
     // withInventory
     if (!is_null($options['withInventory']) && $options['withInventory']) {
         $sqlParts['where'][] = ' h.hostid IN (' . ' SELECT hin.hostid' . ' FROM host_inventory hin)';
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('hosts h', $options, $sqlParts);
         if (zbx_db_search('interface hi', $options, $sqlParts)) {
             $sqlParts['from']['interface'] = 'interface hi';
             $sqlParts['where']['hi'] = 'h.hostid=hi.hostid';
         }
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('hosts h', $options, $sqlParts);
         if ($this->dbFilter('interface hi', $options, $sqlParts)) {
             $sqlParts['from']['interface'] = 'interface hi';
             $sqlParts['where']['hi'] = 'h.hostid=hi.hostid';
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['hosts'] = 'h.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT h.hostid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'h');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $hostids = array();
     $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['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['selectGroups']) && !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['selectItems']) && !isset($result[$host['hostid']]['items'])) {
                     $result[$host['hostid']]['items'] = array();
                 }
                 if (!is_null($options['selectDiscoveries']) && !isset($result[$host['hostid']]['discoveries'])) {
                     $result[$host['hostid']]['discoveries'] = array();
                 }
                 if (!is_null($options['selectInventory']) && !isset($result[$host['hostid']]['inventory'])) {
                     $result[$host['hostid']]['inventory'] = array();
                 }
                 if (!is_null($options['selectTriggers']) && !isset($result[$host['hostid']]['triggers'])) {
                     $result[$host['hostid']]['triggers'] = array();
                 }
                 if (!is_null($options['selectGraphs']) && !isset($result[$host['hostid']]['graphs'])) {
                     $result[$host['hostid']]['graphs'] = array();
                 }
                 if (!is_null($options['selectDHosts']) && !isset($result[$host['hostid']]['dhosts'])) {
                     $result[$host['hostid']]['dhosts'] = array();
                 }
                 if (!is_null($options['selectDServices']) && !isset($result[$host['hostid']]['dservices'])) {
                     $result[$host['hostid']]['dservices'] = array();
                 }
                 if (!is_null($options['selectApplications']) && !isset($result[$host['hostid']]['applications'])) {
                     $result[$host['hostid']]['applications'] = array();
                 }
                 if (!is_null($options['selectMacros']) && !isset($result[$host['hostid']]['macros'])) {
                     $result[$host['hostid']]['macros'] = array();
                 }
                 if (!is_null($options['selectScreens']) && !isset($result[$host['hostid']]['screens'])) {
                     $result[$host['hostid']]['screens'] = array();
                 }
                 if (!is_null($options['selectInterfaces']) && !isset($result[$host['hostid']]['interfaces'])) {
                     $result[$host['hostid']]['interfaces'] = array();
                 }
                 // groupids
                 if (isset($host['groupid']) && is_null($options['selectGroups'])) {
                     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'], 'hostid' => $host['templateid']);
                     unset($host['templateid']);
                 }
                 // triggerids
                 if (isset($host['triggerid']) && is_null($options['selectTriggers'])) {
                     if (!isset($result[$host['hostid']]['triggers'])) {
                         $result[$host['hostid']]['triggers'] = array();
                     }
                     $result[$host['hostid']]['triggers'][] = array('triggerid' => $host['triggerid']);
                     unset($host['triggerid']);
                 }
                 // interfaceids
                 if (isset($host['interfaceid']) && is_null($options['selectInterfaces'])) {
                     if (!isset($result[$host['hostid']]['interfaces'])) {
                         $result[$host['hostid']]['interfaces'] = array();
                     }
                     $result[$host['hostid']]['interfaces'][] = array('interfaceid' => $host['interfaceid']);
                     unset($host['interfaceid']);
                 }
                 // itemids
                 if (isset($host['itemid']) && is_null($options['selectItems'])) {
                     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['selectGraphs'])) {
                     if (!isset($result[$host['hostid']]['graphs'])) {
                         $result[$host['hostid']]['graphs'] = array();
                     }
                     $result[$host['hostid']]['graphs'][] = array('graphid' => $host['graphid']);
                     unset($host['graphid']);
                 }
                 // graphids
                 if (isset($host['applicationid'])) {
                     if (!isset($result[$host['hostid']]['applications'])) {
                         $result[$host['hostid']]['applications'] = array();
                     }
                     $result[$host['hostid']]['applications'][] = array('applicationid' => $host['applicationid']);
                     unset($host['applicationid']);
                 }
                 // httptestids
                 if (isset($host['httptestid'])) {
                     if (!isset($result[$host['hostid']]['httptests'])) {
                         $result[$host['hostid']]['httptests'] = array();
                     }
                     $result[$host['hostid']]['httptests'][] = array('httptestid' => $host['httptestid']);
                     unset($host['httptestid']);
                 }
                 // dhostids
                 if (isset($host['dhostid']) && is_null($options['selectDHosts'])) {
                     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['selectDServices'])) {
                     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']]['maintenances'])) {
                         $result[$host['hostid']]['maintenances'] = array();
                     }
                     if ($host['maintenanceid'] > 0) {
                         $result[$host['hostid']]['maintenances'][] = array('maintenanceid' => $host['maintenanceid']);
                     }
                 }
                 $result[$host['hostid']] += $host;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * adding objects
      */
     // adding groups
     if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) {
         $groups = API::HostGroup()->get(array('nodeids' => $options['nodeids'], 'output' => $options['selectGroups'], 'hostids' => $hostids, 'preservekeys' => true));
         foreach ($groups as $group) {
             $ghosts = $group['hosts'];
             unset($group['hosts']);
             foreach ($ghosts as $host) {
                 $result[$host['hostid']]['groups'][] = $group;
             }
         }
     }
     // adding inventories
     if (!is_null($options['selectInventory']) && $options['selectInventory'] !== false) {
         if (is_array($options['selectInventory'])) {
             // if we are given a list of fields that needs to be fetched
             $dbTable = DB::getSchema('host_inventory');
             $selectHIn = array('hin.hostid');
             foreach ($options['selectInventory'] as $field) {
                 if (isset($dbTable['fields'][$field])) {
                     $selectHIn[] = 'hin.' . $field;
                 }
             }
         } else {
             // all fields are needed
             $selectHIn = array('hin.*');
         }
         $dbInventory = DBselect('SELECT ' . implode(', ', $selectHIn) . ' FROM host_inventory hin' . ' WHERE ' . dbConditionInt('hin.hostid', $hostids));
         while ($inventory = DBfetch($dbInventory)) {
             $result[$inventory['hostid']]['inventory'] = $inventory;
         }
     }
     // adding templates
     if (!is_null($options['selectParentTemplates'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true);
         if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectParentTemplates'];
             $templates = API::Template()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($templates, 'host');
             }
             foreach ($templates as $templateid => $template) {
                 unset($templates[$templateid]['hosts']);
                 $count = array();
                 foreach ($template['hosts'] as $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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectParentTemplates']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $templates = API::Template()->get($objParams);
             $templates = zbx_toHash($templates, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['templates'] = isset($templates[$hostid]) ? $templates[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding hostinterfaces
     if (!is_null($options['selectInterfaces'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectInterfaces']) || str_in_array($options['selectInterfaces'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectInterfaces'];
             $interfaces = API::HostInterface()->get($objParams);
             // we need to order interfaces for proper linkage and viewing
             order_result($interfaces, 'interfaceid', ZBX_SORT_UP);
             $count = array();
             foreach ($interfaces as $interfaceid => $interface) {
                 if (!is_null($options['limitSelects'])) {
                     if (!isset($count[$interface['hostid']])) {
                         $count[$interface['hostid']] = 0;
                     }
                     $count[$interface['hostid']]++;
                     if ($count[$interface['hostid']] > $options['limitSelects']) {
                         continue;
                     }
                 }
                 $result[$interface['hostid']]['interfaces'][$interfaceid] =& $interfaces[$interfaceid];
             }
         } elseif (API_OUTPUT_COUNT == $options['selectInterfaces']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $interfaces = API::HostInterface()->get($objParams);
             $interfaces = zbx_toHash($interfaces, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['interfaces'] = isset($interfaces[$hostid]) ? $interfaces[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding items
     if (!is_null($options['selectItems'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectItems'];
             $items = API::Item()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($items, 'name');
             }
             $count = array();
             foreach ($items as $itemid => $item) {
                 if (!is_null($options['limitSelects'])) {
                     if (!isset($count[$item['hostid']])) {
                         $count[$item['hostid']] = 0;
                     }
                     $count[$item['hostid']]++;
                     if ($count[$item['hostid']] > $options['limitSelects']) {
                         continue;
                     }
                 }
                 $result[$item['hostid']]['items'][] =& $items[$itemid];
             }
         } elseif (API_OUTPUT_COUNT == $options['selectItems']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $items = API::Item()->get($objParams);
             $items = zbx_toHash($items, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['items'] = isset($items[$hostid]) ? $items[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding discoveries
     if (!is_null($options['selectDiscoveries'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectDiscoveries']) || str_in_array($options['selectDiscoveries'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDiscoveries'];
             $items = API::DiscoveryRule()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($items, 'name');
             }
             $count = array();
             foreach ($items as $itemid => $item) {
                 unset($items[$itemid]['hosts']);
                 foreach ($item['hosts'] as $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']]['discoveries'][] =& $items[$itemid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectDiscoveries']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $items = API::DiscoveryRule()->get($objParams);
             $items = zbx_toHash($items, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['discoveries'] = isset($items[$hostid]) ? $items[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding triggers
     if (!is_null($options['selectTriggers'])) {
         if (is_array($options['selectTriggers']) || str_in_array($options['selectTriggers'], $subselectsAllowedOutputs)) {
             $triggers = API::Trigger()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true, 'output' => $options['selectTriggers']));
             if (!is_null($options['limitSelects'])) {
                 order_result($triggers, 'description');
             }
             $count = array();
             foreach ($triggers as $triggerid => $trigger) {
                 unset($triggers[$triggerid]['hosts']);
                 foreach ($trigger['hosts'] as $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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) {
             $triggers = API::Trigger()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'countOutput' => true, 'groupCount' => true));
             $triggers = zbx_toHash($triggers, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['triggers'] = isset($triggers[$hostid]) ? $triggers[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding graphs
     if (!is_null($options['selectGraphs'])) {
         if (is_array($options['selectGraphs']) || str_in_array($options['selectGraphs'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectGraphs'];
             $graphs = API::Graph()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'preservekeys' => true, 'output' => $options['selectGraphs']));
             if (!is_null($options['limitSelects'])) {
                 order_result($graphs, 'name');
             }
             $count = array();
             foreach ($graphs as $graphid => $graph) {
                 unset($graphs[$graphid]['hosts']);
                 foreach ($graph['hosts'] as $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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) {
             $graphs = API::Graph()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'countOutput' => true, 'groupCount' => true));
             $graphs = zbx_toHash($graphs, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['graphs'] = isset($graphs[$hostid]) ? $graphs[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding discovery hosts
     if (!is_null($options['selectDHosts'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectDHosts']) || str_in_array($options['selectDHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDHosts'];
             $dhosts = API::DHost()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($dhosts, 'dhostid');
             }
             $count = array();
             foreach ($dhosts as $dhostid => $dhost) {
                 unset($dhosts[$dhostid]['hosts']);
                 foreach ($dhost['hosts'] as $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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectDHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $dhosts = API::DHost()->get($objParams);
             $dhosts = zbx_toHash($dhosts, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['dhosts'] = isset($dhosts[$hostid]) ? $dhosts[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding applications
     if (!is_null($options['selectApplications'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectApplications']) || str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectApplications'];
             $applications = API::Application()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($applications, 'name');
             }
             $count = array();
             foreach ($applications as $applicationid => $application) {
                 unset($applications[$applicationid]['hosts']);
                 foreach ($application['hosts'] as $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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectApplications']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $applications = API::Application()->get($objParams);
             $applications = zbx_toHash($applications, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['applications'] = isset($applications[$hostid]) ? $applications[$hostid]['rowscount'] : 0;
             }
         }
     }
     // adding macros
     if (!is_null($options['selectMacros']) && str_in_array($options['selectMacros'], $subselectsAllowedOutputs)) {
         $objParams = array('nodeids' => $options['nodeids'], 'output' => $options['selectMacros'], 'hostids' => $hostids, 'preservekeys' => true);
         $macros = API::UserMacro()->get($objParams);
         foreach ($macros as $macroid => $macro) {
             $mhosts = $macro['hosts'];
             unset($macro['hosts']);
             foreach ($mhosts as $host) {
                 $result[$host['hostid']]['macros'][$macroid] = $macro;
             }
         }
     }
     // adding screens
     if (!is_null($options['selectScreens'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'hostids' => $hostids, 'editable' => $options['editable'], 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectScreens']) || str_in_array($options['selectScreens'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectScreens'];
             $screens = API::TemplateScreen()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($screens, 'name');
             }
             foreach ($screens as $snum => $screen) {
                 if (!is_null($options['limitSelects'])) {
                     if (count($result[$screen['hostid']]['screens']) >= $options['limitSelects']) {
                         continue;
                     }
                 }
                 unset($screens[$snum]['hosts']);
                 $result[$screen['hostid']]['screens'][] =& $screens[$snum];
             }
         } elseif (API_OUTPUT_COUNT == $options['selectScreens']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $screens = API::TemplateScreen()->get($objParams);
             $screens = zbx_toHash($screens, 'hostid');
             foreach ($result as $hostid => $host) {
                 $result[$hostid]['screens'] = isset($screens[$hostid]) ? $screens[$hostid]['rowscount'] : 0;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get data about web scenarios.
  *
  * @param array $options
  *
  * @return array
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('httptestid', 'name');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('httptests' => 'ht.httptestid'), 'from' => array('httptest' => 'httptest ht'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'httptestids' => null, 'applicationids' => null, 'hostids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'exludeSearch' => null, 'output' => API_OUTPUT_REFER, 'selectHosts' => null, 'selectSteps' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE a.applicationid=ht.applicationid' . ' AND a.hostid=hgg.hostid' . ' GROUP BY a.applicationid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // httptestids
     if (!is_null($options['httptestids'])) {
         zbx_value2array($options['httptestids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['httptestid'] = 'ht.httptestid';
         }
         $sqlParts['where']['httptestid'] = dbConditionInt('ht.httptestid', $options['httptestids']);
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostid'] = 'a.hostid';
         }
         $sqlParts['from']['applications'] = 'applications a';
         $sqlParts['where'][] = 'a.applicationid=ht.applicationid';
         $sqlParts['where']['hostid'] = dbConditionInt('a.hostid', $options['hostids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['hostid'] = 'a.hostid';
         }
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sqlParts['select']['applicationid'] = 'a.applicationid';
         }
         $sqlParts['where'][] = dbConditionInt('ht.applicationid', $options['applicationids']);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['httptests'] = 'ht.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(ht.httptestid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('httptest ht', $options, $sqlParts);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('httptest ht', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'ht');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $httpTestIds = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('ht.httptestid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($httpTest = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $httpTest;
             } else {
                 $result = $httpTest['rowscount'];
             }
         } else {
             $httpTestIds[$httpTest['httptestid']] = $httpTest['httptestid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$httpTest['httptestid']] = array('httptestid' => $httpTest['httptestid']);
             } else {
                 if (!isset($result[$httpTest['httptestid']])) {
                     $result[$httpTest['httptestid']] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$httpTest['httptestid']]['hosts'])) {
                     $result[$httpTest['httptestid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectSteps']) && !isset($result[$httpTest['httptestid']]['steps'])) {
                     $result[$httpTest['httptestid']]['steps'] = array();
                 }
                 // hostids
                 if (isset($httpTest['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$httpTest['httptestid']]['hosts'])) {
                         $result[$httpTest['httptestid']]['hosts'] = array();
                     }
                     $result[$httpTest['httptestid']]['hosts'][] = array('hostid' => $httpTest['hostid']);
                     unset($httpTest['hostid']);
                 }
                 $result[$httpTest['httptestid']] += $httpTest;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // adding hosts
     if (!is_null($options['selectHosts']) && str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectHosts'], 'httptestids' => $httpTestIds, 'nopermissions' => true, 'preservekeys' => true);
         $hosts = API::Host()->get($objParams);
         foreach ($hosts as $host) {
             $hwebchecks = $host['httptests'];
             unset($host['httptests']);
             foreach ($hwebchecks as $hwebcheck) {
                 $result[$hwebcheck['httptestid']]['hosts'][] = $host;
             }
         }
     }
     // adding steps
     if (!is_null($options['selectSteps']) && str_in_array($options['selectSteps'], $subselectsAllowedOutputs)) {
         $dbSteps = DBselect('SELECT h.*' . ' FROM httpstep h' . ' WHERE ' . dbConditionInt('h.httptestid', $httpTestIds));
         while ($step = DBfetch($dbSteps)) {
             $stepid = $step['httpstepid'];
             $step['webstepid'] = $stepid;
             unset($step['httpstepid']);
             $result[$step['httptestid']]['steps'][$step['webstepid']] = $step;
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Screen data
  *
  * @param array $options
  * @param array $options['nodeids'] Node IDs
  * @param boolean $options['with_items'] only with items
  * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
  * @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'] deprecated parameter (for now)
  * @return array|boolean Host data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('screenid', 'name');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('screens' => 's.screenid,s.templateid'), 'from' => array('screens' => 'screens s'), 'where' => array('template' => 's.templateid IS NOT NULL'), 'order' => array(), 'group' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'screenids' => null, 'screenitemids' => null, 'templateids' => null, 'hostids' => null, 'editable' => null, 'noInheritance' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectScreenItems' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['screens']);
         $dbTable = DB::getSchema('screens');
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 's.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     if (!is_null($options['editable']) || is_null($options['hostids']) && is_null($options['templateids'])) {
         $options['noInheritance'] = 1;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         // TODO: think how we could combine templateids && hostids options
         if (!is_null($options['templateids'])) {
             unset($options['hostids']);
             $options['templateids'] = API::Template()->get(array('templateids' => $options['templateids'], 'editable' => $options['editable'], 'preservekeys' => true));
             $options['templateids'] = array_keys($options['templateids']);
         } elseif (!is_null($options['hostids'])) {
             $options['templateids'] = API::Host()->get(array('hostids' => $options['hostids'], 'editable' => $options['editable'], 'preservekeys' => true));
             $options['templateids'] = array_keys($options['templateids']);
         } else {
             // TODO: get screen
             $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
             $userGroups = getUserGroupsByUserId($userid);
             $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE s.templateid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
         }
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // screenids
     if (!is_null($options['screenids'])) {
         zbx_value2array($options['screenids']);
         $sqlParts['where'][] = dbConditionInt('s.screenid', $options['screenids']);
     }
     // screenitemids
     if (!is_null($options['screenitemids'])) {
         zbx_value2array($options['screenitemids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sqlParts['select']['screenitemid'] = 'si.screenitemid';
         }
         $sqlParts['from']['screens_items'] = 'screens_items si';
         $sqlParts['where']['ssi'] = 'si.screenid=s.screenid';
         $sqlParts['where'][] = dbConditionInt('si.screenitemid', $options['screenitemids']);
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if (isset($options['hostids']) && !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']);
         // collecting template chain
         $templatesChain = array();
         $linkedTemplateids = $options['hostids'];
         $childTemplateids = $options['hostids'];
         while (is_null($options['noInheritance']) && !empty($childTemplateids)) {
             $sql = 'SELECT ht.*' . ' FROM hosts_templates ht' . ' WHERE ' . dbConditionInt('hostid', $childTemplateids);
             $dbTemplates = DBselect($sql);
             $childTemplateids = array();
             while ($link = DBfetch($dbTemplates)) {
                 $childTemplateids[$link['templateid']] = $link['templateid'];
                 $linkedTemplateids[$link['templateid']] = $link['templateid'];
                 createParentToChildRelation($templatesChain, $link, 'templateid', 'hostid');
             }
         }
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sqlParts['select']['templateid'] = 's.templateid';
         }
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['templateid'] = 's.templateid';
         }
         $sqlParts['where']['templateid'] = dbConditionInt('s.templateid', $linkedTemplateids);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('screens s', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('screens s', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['screens'] = 's.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT s.screenid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 's');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $screenids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlGroup .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('s.screenid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($screen = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $screen;
             } else {
                 $result = $screen['rowscount'];
             }
         } else {
             $screenids[$screen['screenid']] = $screen['screenid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$screen['screenid']] = array('screenid' => $screen['screenid'], 'templateid' => $screen['templateid']);
             } else {
                 if (!isset($result[$screen['screenid']])) {
                     $result[$screen['screenid']] = array();
                 }
                 if (!is_null($options['selectScreenItems']) && !isset($result[$screen['screenid']]['screenitems'])) {
                     $result[$screen['screenid']]['screenitems'] = array();
                 }
                 if (isset($screen['screenitemid']) && is_null($options['selectScreenItems'])) {
                     if (!isset($result[$screen['screenid']]['screenitems'])) {
                         $result[$screen['screenid']]['screenitems'] = array();
                     }
                     $result[$screen['screenid']]['screenitems'][] = array('screenitemid' => $screen['screenitemid']);
                     unset($screen['screenitemid']);
                 }
                 $result[$screen['screenid']] += $screen;
             }
         }
     }
     // hashing
     $options['hostids'] = zbx_toHash($options['hostids']);
     // adding screenitems
     if (!is_null($options['selectScreenItems']) && str_in_array($options['selectScreenItems'], $subselectsAllowedOutputs)) {
         $screensItems = array();
         $dbSitems = DBselect('SELECT si.* FROM screens_items si WHERE ' . dbConditionInt('si.screenid', $screenids));
         while ($sitem = DBfetch($dbSitems)) {
             // sorting
             $screensItems[$sitem['screenitemid']] = $sitem;
             switch ($sitem['resourcetype']) {
                 case SCREEN_RESOURCE_GRAPH:
                     $graphids[$sitem['resourceid']] = $sitem['resourceid'];
                     break;
                 case SCREEN_RESOURCE_SIMPLE_GRAPH:
                 case SCREEN_RESOURCE_PLAIN_TEXT:
                     $itemids[$sitem['resourceid']] = $sitem['resourceid'];
                     break;
             }
         }
         foreach ($screensItems as $sitem) {
             if (!isset($result[$sitem['screenid']]['screenitems'])) {
                 $result[$sitem['screenid']]['screenitems'] = array();
             }
             $result[$sitem['screenid']]['screenitems'][] = $sitem;
         }
     }
     // creating linkage of template -> real objects
     if (!is_null($options['selectScreenItems']) && !is_null($options['hostids'])) {
         // prepare graphs
         if (!empty($graphids)) {
             $tplGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'graphids' => $graphids, 'nopermissions' => true, 'preservekeys' => true));
             $dbGraphs = API::Graph()->get(array('output' => array('graphid', 'name'), 'hostids' => $options['hostids'], 'filter' => array('name' => zbx_objectValues($tplGraphs, 'name')), 'nopermissions' => true, 'preservekeys' => true));
             $realGraphs = array();
             foreach ($dbGraphs as $graph) {
                 $host = reset($graph['hosts']);
                 unset($graph['hosts']);
                 if (!isset($realGraphs[$host['hostid']])) {
                     $realGraphs[$host['hostid']] = array();
                 }
                 $realGraphs[$host['hostid']][$graph['name']] = $graph;
             }
         }
         // prepare items
         if (!empty($itemids)) {
             $tplItems = API::Item()->get(array('output' => array('itemid', 'key_'), 'itemids' => $itemids, 'nopermissions' => true, 'preservekeys' => true));
             $dbItems = API::Item()->get(array('output' => array('itemid', 'key_'), 'hostids' => $options['hostids'], 'filter' => array('key_' => zbx_objectValues($tplItems, 'key_')), 'nopermissions' => true, 'preservekeys' => true));
             $realItems = array();
             foreach ($dbItems as $item) {
                 unset($item['hosts']);
                 if (!isset($realItems[$item['hostid']])) {
                     $realItems[$item['hostid']] = array();
                 }
                 $realItems[$item['hostid']][$item['key_']] = $item;
             }
         }
     }
     if (is_null($options['countOutput']) || !is_null($options['countOutput']) && !is_null($options['groupCount'])) {
         // creating copies of templated screens (inheritance)
         // screenNum is needed due to we can't refer to screenid/hostid/templateid as they will repeat
         $screenNum = 0;
         $vrtResult = array();
         foreach ($result as $screen) {
             if (is_null($options['hostids']) || isset($options['hostids'][$screen['templateid']])) {
                 $screenNum++;
                 $vrtResult[$screenNum] = $screen;
                 $vrtResult[$screenNum]['hostid'] = $screen['templateid'];
             }
             if (!isset($templatesChain[$screen['templateid']])) {
                 continue;
             }
             foreach ($templatesChain[$screen['templateid']] as $hostid) {
                 if (!isset($options['hostids'][$hostid])) {
                     continue;
                 }
                 $screenNum++;
                 $vrtResult[$screenNum] = $screen;
                 $vrtResult[$screenNum]['hostid'] = $hostid;
                 if (!isset($vrtResult[$screenNum]['screenitems'])) {
                     continue;
                 }
                 foreach ($vrtResult[$screenNum]['screenitems'] as &$screenitem) {
                     switch ($screenitem['resourcetype']) {
                         case SCREEN_RESOURCE_GRAPH:
                             $graphName = $tplGraphs[$screenitem['resourceid']]['name'];
                             $screenitem['real_resourceid'] = $realGraphs[$hostid][$graphName]['graphid'];
                             break;
                         case SCREEN_RESOURCE_SIMPLE_GRAPH:
                         case SCREEN_RESOURCE_PLAIN_TEXT:
                             $itemKey = $tplItems[$screenitem['resourceid']]['key_'];
                             $screenitem['real_resourceid'] = $realItems[$hostid][$itemKey]['itemid'];
                             break;
                     }
                 }
                 unset($screenitem);
             }
         }
         $result = array_values($vrtResult);
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     } elseif (!is_null($options['noInheritance'])) {
         $result = zbx_toHash($result, 'screenid');
     }
     return $result;
 }
 /**
  * Modifies the SQL parts to implement all of the sorting related options.
  * Soring is currently only supported for CZBXAPI::get() methods.
  *
  * @param $tableName
  * @param $tableAlias
  * @param array $options
  * @param array $sqlParts
  *
  * @return array
  */
 protected function applyQuerySortOptions($tableName, $tableAlias, array $options, array $sqlParts)
 {
     if ($this->sortColumns && $options['countOutput'] === null) {
         zbx_db_sorting($sqlParts, $options, $this->sortColumns, $tableAlias);
     }
     return $sqlParts;
 }
 /**
  * Get events data.
  *
  * @param _array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['eventids']
  * @param array $options['applicationids']
  * @param array $options['status']
  * @param array $options['editable']
  * @param array $options['count']
  * @param array $options['pattern']
  * @param array $options['limit']
  * @param array $options['order']
  *
  * @return array|int item data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('eventid', 'object', 'objectid');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array($this->fieldId('eventid')), 'from' => array('events' => 'events e'), 'where' => array(), 'order' => array(), 'group' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'triggerids' => null, 'eventids' => null, 'editable' => null, 'object' => null, 'source' => null, 'acknowledged' => null, 'nopermissions' => null, 'showUnknown' => null, 'value' => null, 'time_from' => null, 'time_till' => null, 'eventid_from' => null, 'eventid_till' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectHosts' => null, 'selectItems' => null, 'selectTriggers' => null, 'select_alerts' => null, 'select_acknowledges' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         if (is_null($options['source']) && is_null($options['object'])) {
             $options['object'] = EVENT_OBJECT_TRIGGER;
         }
         if ($options['object'] !== null && $options['object'] == EVENT_OBJECT_TRIGGER || $options['source'] !== null && $options['source'] == EVENT_SOURCE_TRIGGERS) {
             if (!is_null($options['triggerids'])) {
                 $triggers = API::Trigger()->get(array('triggerids' => $options['triggerids'], 'editable' => $options['editable']));
                 $options['triggerids'] = zbx_objectValues($triggers, 'triggerid');
             } else {
                 $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
                 $userGroups = getUserGroupsByUserId($userid);
                 $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' AND e.object=' . EVENT_OBJECT_TRIGGER . ' GROUP BY f.triggerid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
             }
         }
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // eventids
     if (!is_null($options['eventids'])) {
         zbx_value2array($options['eventids']);
         $sqlParts['where'][] = dbConditionInt('e.eventid', $options['eventids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('e.objectid', $nodeids);
         }
     }
     // triggerids
     if (!is_null($options['triggerids']) && $options['object'] == EVENT_OBJECT_TRIGGER) {
         zbx_value2array($options['triggerids']);
         $sqlParts['where'][] = dbConditionInt('e.objectid', $options['triggerids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['objectid'] = 'e.objectid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('e.objectid', $nodeids);
         }
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts = $this->addQuerySelect('hg.groupid', $sqlParts);
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hg'] = dbConditionInt('hg.groupid', $options['groupids']);
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sqlParts['where']['fe'] = 'f.triggerid=e.objectid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts = $this->addQuerySelect('i.hostid', $sqlParts);
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']);
         $sqlParts['where']['ft'] = 'f.triggerid=e.objectid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('e.eventid', $nodeids);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts = $this->addQuerySelect('e.*', $sqlParts);
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT e.eventid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // object
     if (!is_null($options['object'])) {
         $sqlParts['where']['o'] = 'e.object=' . zbx_dbstr($options['object']);
     }
     // source
     if (!is_null($options['source'])) {
         $sqlParts['where'][] = 'e.source=' . zbx_dbstr($options['source']);
     }
     // acknowledged
     if (!is_null($options['acknowledged'])) {
         $sqlParts['where'][] = 'e.acknowledged=' . ($options['acknowledged'] ? 1 : 0);
     }
     // showUnknown
     if (!is_null($options['showUnknown'])) {
         if (is_null($options['filter'])) {
             $options['filter'] = array();
         }
         $options['filter']['value_changed'] = null;
     }
     // time_from
     if (!is_null($options['time_from'])) {
         $sqlParts['where'][] = 'e.clock>=' . zbx_dbstr($options['time_from']);
     }
     // time_till
     if (!is_null($options['time_till'])) {
         $sqlParts['where'][] = 'e.clock<=' . zbx_dbstr($options['time_till']);
     }
     // eventid_from
     if (!is_null($options['eventid_from'])) {
         $sqlParts['where'][] = 'e.eventid>=' . zbx_dbstr($options['eventid_from']);
     }
     // eventid_till
     if (!is_null($options['eventid_till'])) {
         $sqlParts['where'][] = 'e.eventid<=' . zbx_dbstr($options['eventid_till']);
     }
     // value
     if (!is_null($options['value'])) {
         zbx_value2array($options['value']);
         $sqlParts['where'][] = dbConditionInt('e.value', $options['value']);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('events e', $options, $sqlParts);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('events e', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, $this->tableAlias());
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     // selectHosts, selectTriggers, selectItems
     if ($options['output'] != API_OUTPUT_EXTEND && (!is_null($options['selectHosts']) || !is_null($options['selectTriggers']) || !is_null($options['selectItems']))) {
         $sqlParts = $this->addQuerySelect($this->fieldId('object'), $sqlParts);
         $sqlParts = $this->addQuerySelect($this->fieldId('objectid'), $sqlParts);
     }
     $eventids = array();
     $triggerids = array();
     // event fields
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     $sqlGroup = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlGroup .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($event = DBfetch($dbRes)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $event;
             } else {
                 $result = $event['rowscount'];
             }
         } else {
             $eventids[$event['eventid']] = $event['eventid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$event['eventid']] = array('eventid' => $event['eventid']);
             } else {
                 if (isset($event['object']) && $event['object'] == EVENT_OBJECT_TRIGGER) {
                     $triggerids[$event['objectid']] = $event['objectid'];
                 }
                 if (!isset($result[$event['eventid']])) {
                     $result[$event['eventid']] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$event['eventid']]['hosts'])) {
                     $result[$event['eventid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectTriggers']) && !isset($result[$event['eventid']]['triggers'])) {
                     $result[$event['eventid']]['triggers'] = array();
                 }
                 if (!is_null($options['selectItems']) && !isset($result[$event['eventid']]['items'])) {
                     $result[$event['eventid']]['items'] = array();
                 }
                 if (!is_null($options['select_alerts']) && !isset($result[$event['eventid']]['alerts'])) {
                     $result[$event['eventid']]['alerts'] = array();
                 }
                 if (!is_null($options['select_acknowledges']) && !isset($result[$event['eventid']]['acknowledges'])) {
                     $result[$event['eventid']]['acknowledges'] = array();
                 }
                 // hostids
                 if (isset($event['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$event['eventid']]['hosts'])) {
                         $result[$event['eventid']]['hosts'] = array();
                     }
                     $result[$event['eventid']]['hosts'][] = array('hostid' => $event['hostid']);
                     unset($event['hostid']);
                 }
                 // triggerids
                 if (isset($event['triggerid']) && is_null($options['selectTriggers'])) {
                     if (!isset($result[$event['eventid']]['triggers'])) {
                         $result[$event['eventid']]['triggers'] = array();
                     }
                     $result[$event['eventid']]['triggers'][] = array('triggerid' => $event['triggerid']);
                     unset($event['triggerid']);
                 }
                 // itemids
                 if (isset($event['itemid']) && is_null($options['selectItems'])) {
                     if (!isset($result[$event['eventid']]['items'])) {
                         $result[$event['eventid']]['items'] = array();
                     }
                     $result[$event['eventid']]['items'][] = array('itemid' => $event['itemid']);
                     unset($event['itemid']);
                 }
                 $result[$event['eventid']] += $event;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding hosts
     if (!is_null($options['selectHosts']) && str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
         $hosts = API::Host()->get(array('nodeids' => $nodeids, 'output' => $options['selectHosts'], 'triggerids' => $triggerids, 'nopermissions' => true, 'preservekeys' => true));
         $triggers = array();
         foreach ($hosts as $hostid => $host) {
             $htriggers = $host['triggers'];
             unset($host['triggers']);
             foreach ($htriggers as $tnum => $trigger) {
                 $triggerid = $trigger['triggerid'];
                 if (!isset($triggers[$triggerid])) {
                     $triggers[$triggerid] = array('hosts' => array());
                 }
                 $triggers[$triggerid]['hosts'][] = $host;
             }
         }
         foreach ($result as $eventid => $event) {
             if (isset($triggers[$event['objectid']])) {
                 $result[$eventid]['hosts'] = $triggers[$event['objectid']]['hosts'];
             } else {
                 $result[$eventid]['hosts'] = array();
             }
         }
     }
     // adding triggers
     if (!is_null($options['selectTriggers']) && str_in_array($options['selectTriggers'], $subselectsAllowedOutputs)) {
         $triggers = API::Trigger()->get(array('nodeids' => $nodeids, 'output' => $options['selectTriggers'], 'triggerids' => $triggerids, 'nopermissions' => true, 'preservekeys' => true));
         foreach ($result as $eventid => $event) {
             if (isset($triggers[$event['objectid']])) {
                 $result[$eventid]['triggers'][] = $triggers[$event['objectid']];
             } else {
                 $result[$eventid]['triggers'] = array();
             }
         }
     }
     // adding items
     if (!is_null($options['selectItems']) && str_in_array($options['selectItems'], $subselectsAllowedOutputs)) {
         $dbItems = API::Item()->get(array('nodeids' => $nodeids, 'output' => $options['selectItems'], 'triggerids' => $triggerids, 'webitems' => true, 'nopermissions' => true, 'preservekeys' => true));
         $items = array();
         foreach ($dbItems as $itemid => $item) {
             $itriggers = $item['triggers'];
             unset($item['triggers']);
             foreach ($itriggers as $trigger) {
                 if (!isset($items[$trigger['triggerid']])) {
                     $items[$trigger['triggerid']] = array();
                 }
                 $items[$trigger['triggerid']][] = $item;
             }
         }
         foreach ($result as $eventid => $event) {
             if (isset($items[$event['objectid']])) {
                 $result[$eventid]['items'] = $items[$event['objectid']];
             } else {
                 $result[$eventid]['items'] = array();
             }
         }
     }
     // adding alerts
     if (!is_null($options['select_alerts']) && str_in_array($options['select_alerts'], $subselectsAllowedOutputs)) {
         $dbAlerts = API::Alert()->get(array('output' => $options['select_alerts'], 'selectMediatypes' => API_OUTPUT_EXTEND, 'nodeids' => $nodeids, 'eventids' => $eventids, 'nopermissions' => true, 'preservekeys' => true, 'sortfield' => 'clock', 'sortorder' => ZBX_SORT_DOWN));
         foreach ($dbAlerts as $alert) {
             $result[$alert['eventid']]['alerts'][] = $alert;
         }
     }
     // adding acknowledges
     if (!is_null($options['select_acknowledges'])) {
         if (is_array($options['select_acknowledges']) || str_in_array($options['select_acknowledges'], $subselectsAllowedOutputs)) {
             $res = DBselect('SELECT a.*,u.alias' . ' FROM acknowledges a' . ' LEFT JOIN users u ON u.userid=a.userid' . ' WHERE ' . dbConditionInt('a.eventid', $eventids) . ' ORDER BY a.clock DESC');
             while ($ack = DBfetch($res)) {
                 $result[$ack['eventid']]['acknowledges'][] = $ack;
             }
         } elseif ($options['select_acknowledges'] == API_OUTPUT_COUNT) {
             $res = DBselect('SELECT COUNT(a.acknowledgeid) AS rowscount,a.eventid' . ' FROM acknowledges a' . ' WHERE ' . dbConditionInt('a.eventid', $eventids) . ' GROUP BY a.eventid');
             while ($ack = DBfetch($res)) {
                 $result[$ack['eventid']]['acknowledges'] = $ack['rowscount'];
             }
         } elseif ($options['select_acknowledges'] == API_OUTPUT_EXTEND) {
             $res = DBselect('SELECT a.*' . ' FROM acknowledges a' . ' WHERE ' . dbConditionInt('a.eventid', $eventids) . ' ORDER BY a.clock DESC');
             while ($ack = DBfetch($res)) {
                 $result[$ack['eventid']]['acknowledges'] = $ack['rowscount'];
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 protected function getLinks($options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     $sortColumns = array('linkid');
     // allowed columns for sorting
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     // allowed output options for [ select_* ] params
     $sqlParts = array('select' => array('sysmaps_links' => 'sl.linkid'), 'from' => array('sysmaps_links' => 'sysmaps_links sl'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'sysmapids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['sysmaps_links']);
         $dbTable = DB::getSchema('sysmaps_links');
         $sqlParts['select']['linkid'] = 'sl.linkid';
         foreach ($options['output'] as $key => $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'sl.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // linkids
     if (!is_null($options['linkids'])) {
         zbx_value2array($options['linkids']);
         $sqlParts['where']['linkid'] = dbConditionInt('sl.linkid', $options['linkids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('sl.linkid', $nodeids);
         }
     }
     // sysmapids
     if (!is_null($options['sysmapids'])) {
         zbx_value2array($options['sysmapids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['sysmapid'] = 'sl.sysmapid';
         }
         $sqlParts['where']['sysmapid'] = dbConditionInt('sl.sysmapid', $options['sysmapids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['sysmapid'] = 'sl.sysmapid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('sl.sysmapid', $nodeids);
         }
     }
     // node check !!!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('sl.linkid', $nodeids);
     }
     // search
     if (!is_null($options['search'])) {
         zbx_db_search('sysmaps_links sl', $options, $sqlParts);
     }
     // filter
     if (!is_null($options['filter'])) {
         $this->dbFilter('sysmaps_links sl', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['sysmaps'] = 'sl.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT s.sysmapid) as rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'sl');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     //-------
     $linkids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     //SDI($sql);
     $res = DBselect($sql, $sqlLimit);
     while ($link = DBfetch($res)) {
         if ($options['countOutput']) {
             $result = $link['rowscount'];
         } else {
             $linkids[$link['linkid']] = $link['linkid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$link['linkid']] = array('linkid' => $link['linkid']);
             } else {
                 $result[$link['linkid']] = $link;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 10
0
 /**
  * Get Users data
  *
  * @param array $options
  * @param array $options['nodeids'] filter by Node IDs
  * @param array $options['usrgrpids'] filter by UserGroup IDs
  * @param array $options['userids'] filter by User IDs
  * @param boolean $options['type'] filter by User type [ USER_TYPE_ZABBIX_USER: 1, USER_TYPE_ZABBIX_ADMIN: 2, USER_TYPE_SUPER_ADMIN: 3 ]
  * @param boolean $options['selectUsrgrps'] extend with UserGroups data for each User
  * @param boolean $options['getAccess'] extend with access data for each User
  * @param boolean $options['count'] output only count of objects in result. ( result returned in property 'rowscount' )
  * @param string $options['pattern'] filter by Host name containing only give pattern
  * @param int $options['limit'] output will be limited to given number
  * @param string $options['sortfield'] output will be sorted by given property [ 'userid', 'alias' ]
  * @param string $options['sortorder'] output will be sorted in given order [ 'ASC', 'DESC' ]
  * @return array
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     // allowed columns for sorting
     $sortColumns = array('userid', 'alias');
     $sqlParts = array('select' => array('users' => 'u.userid'), 'from' => array('users' => 'users u'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'usrgrpids' => null, 'userids' => null, 'mediaids' => null, 'mediatypeids' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'editable' => null, 'selectUsrgrps' => null, 'selectMedias' => null, 'selectMediatypes' => null, 'getAccess' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['users']);
         $dbTable = DB::getSchema('users');
         $sqlParts['select']['userid'] = ' u.userid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'u.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // permission check
     if (USER_TYPE_SUPER_ADMIN == $userType) {
     } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) {
         $sqlParts['from']['users_groups'] = 'users_groups ug';
         $sqlParts['where']['uug'] = 'u.userid=ug.userid';
         $sqlParts['where'][] = 'ug.usrgrpid IN (' . ' SELECT uug.usrgrpid' . ' FROM users_groups uug' . ' WHERE uug.userid=' . self::$userData['userid'] . ')';
     } elseif (!is_null($options['editable']) || self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         $options['userids'] = self::$userData['userid'];
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         $sqlParts['where'][] = dbConditionInt('u.userid', $options['userids']);
     }
     // usrgrpids
     if (!is_null($options['usrgrpids'])) {
         zbx_value2array($options['usrgrpids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['usrgrpid'] = 'ug.usrgrpid';
         }
         $sqlParts['from']['users_groups'] = 'users_groups ug';
         $sqlParts['where'][] = dbConditionInt('ug.usrgrpid', $options['usrgrpids']);
         $sqlParts['where']['uug'] = 'u.userid=ug.userid';
     }
     // mediaids
     if (!is_null($options['mediaids'])) {
         zbx_value2array($options['mediaids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediaid'] = 'm.mediaid';
         }
         $sqlParts['from']['media'] = 'media m';
         $sqlParts['where'][] = dbConditionInt('m.mediaid', $options['mediaids']);
         $sqlParts['where']['mu'] = 'm.userid=u.userid';
     }
     // mediatypeids
     if (!is_null($options['mediatypeids'])) {
         zbx_value2array($options['mediatypeids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediatypeid'] = 'm.mediatypeid';
         }
         $sqlParts['from']['media'] = 'media m';
         $sqlParts['where'][] = dbConditionInt('m.mediatypeid', $options['mediatypeids']);
         $sqlParts['where']['mu'] = 'm.userid=u.userid';
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['users'] = 'u.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT u.userid) AS rowscount');
     }
     // filter
     if (is_array($options['filter'])) {
         if (isset($options['filter']['passwd'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('It is not possible to filter by user password.'));
         }
         $this->dbFilter('users u', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         if ($options['search']['passwd']) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('It is not possible to search by user password.'));
         }
         zbx_db_search('users u', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'u');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $userids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($user = DBfetch($res)) {
         unset($user['passwd']);
         if (!is_null($options['countOutput'])) {
             $result = $user['rowscount'];
         } else {
             $userids[$user['userid']] = $user['userid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$user['userid']] = array('userid' => $user['userid']);
             } else {
                 if (!isset($result[$user['userid']])) {
                     $result[$user['userid']] = array();
                 }
                 if ($options['selectUsrgrps'] && !isset($result[$user['userid']]['usrgrps'])) {
                     $result[$user['userid']]['usrgrps'] = array();
                 }
                 // usrgrpids
                 if (isset($user['usrgrpid']) && is_null($options['selectUsrgrps'])) {
                     if (!isset($result[$user['userid']]['usrgrps'])) {
                         $result[$user['userid']]['usrgrps'] = array();
                     }
                     $result[$user['userid']]['usrgrps'][] = array('usrgrpid' => $user['usrgrpid']);
                     unset($user['usrgrpid']);
                 }
                 // mediaids
                 if (isset($user['mediaid']) && is_null($options['selectMedias'])) {
                     if (!isset($result[$user['userid']]['medias'])) {
                         $result[$user['userid']]['medias'] = array();
                     }
                     $result[$user['userid']]['medias'][] = array('mediaid' => $user['mediaid']);
                     unset($user['mediaid']);
                 }
                 // mediatypeids
                 if (isset($user['mediatypeid']) && is_null($options['selectMediatypes'])) {
                     if (!isset($result[$user['userid']]['mediatypes'])) {
                         $result[$user['userid']]['mediatypes'] = array();
                     }
                     $result[$user['userid']]['mediatypes'][] = array('mediatypeid' => $user['mediatypeid']);
                     unset($user['mediatypeid']);
                 }
                 $result[$user['userid']] += $user;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     if (!is_null($options['getAccess'])) {
         foreach ($result as $userid => $user) {
             $result[$userid] += array('gui_access' => 0, 'debug_mode' => 0, 'users_status' => 0);
         }
         $access = DBselect('SELECT ug.userid,MAX(g.gui_access) AS gui_access,' . ' MAX(g.debug_mode) AS debug_mode,MAX(g.users_status) AS users_status' . ' FROM usrgrp g,users_groups ug' . ' WHERE ' . dbConditionInt('ug.userid', $userids) . ' AND g.usrgrpid=ug.usrgrpid' . ' GROUP BY ug.userid');
         while ($userAccess = DBfetch($access)) {
             $result[$userAccess['userid']] = zbx_array_merge($result[$userAccess['userid']], $userAccess);
         }
     }
     $result = $this->addRelatedObjects($options, $result);
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 11
0
 /**
  * Get Screen data
  *
  * @param array $options
  * @param array $options['nodeids'] Node IDs
  * @param boolean $options['with_items'] only with items
  * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
  * @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'] deprecated parameter (for now)
  * @return array|boolean Host data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     // allowed columns for sorting
     $sortColumns = array('screenid', 'name');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('screens' => 's.screenid'), 'from' => array('screens' => 'screens s'), 'where' => array('template' => 's.templateid IS NULL'), 'order' => array(), 'group' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'screenids' => null, 'screenitemids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectScreenItems' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['screens']);
         $dbTable = DB::getSchema('screens');
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 's.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // screenids
     if (!is_null($options['screenids'])) {
         zbx_value2array($options['screenids']);
         $sqlParts['where'][] = dbConditionInt('s.screenid', $options['screenids']);
     }
     // screenitemids
     if (!is_null($options['screenitemids'])) {
         zbx_value2array($options['screenitemids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sqlParts['select']['screenitemid'] = 'si.screenitemid';
         }
         $sqlParts['from']['screens_items'] = 'screens_items si';
         $sqlParts['where']['ssi'] = 'si.screenid=s.screenid';
         $sqlParts['where'][] = dbConditionInt('si.screenitemid', $options['screenitemids']);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('screens s', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('screens s', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['screens'] = 's.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT s.screenid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 's');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $screenids = array();
     $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
     while ($screen = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $screen;
             } else {
                 $result = $screen['rowscount'];
             }
         } else {
             $screenids[$screen['screenid']] = $screen['screenid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$screen['screenid']] = array('screenid' => $screen['screenid']);
             } else {
                 if (!isset($result[$screen['screenid']])) {
                     $result[$screen['screenid']] = array();
                 }
                 if (!is_null($options['selectScreenItems']) && !isset($result[$screen['screenid']]['screenitems'])) {
                     $result[$screen['screenid']]['screenitems'] = array();
                 }
                 if (isset($screen['screenitemid']) && is_null($options['selectScreenItems'])) {
                     if (!isset($result[$screen['screenid']]['screenitems'])) {
                         $result[$screen['screenid']]['screenitems'] = array();
                     }
                     $result[$screen['screenid']]['screenitems'][] = array('screenitemid' => $screen['screenitemid']);
                     unset($screen['screenitemid']);
                 }
                 $result[$screen['screenid']] += $screen;
             }
         }
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $userType || $options['nopermissions']) {
     } elseif (!empty($result)) {
         $groupsToCheck = array();
         $hostsToCheck = array();
         $graphsToCheck = array();
         $itemsToCheck = array();
         $mapsToCheck = array();
         $screensToCheck = array();
         $screensItems = array();
         $dbSitems = DBselect('SELECT si.* FROM screens_items si WHERE ' . dbConditionInt('si.screenid', $screenids));
         while ($sitem = DBfetch($dbSitems)) {
             $screensItems[$sitem['screenitemid']] = $sitem;
             if ($sitem['resourceid']) {
                 switch ($sitem['resourcetype']) {
                     case SCREEN_RESOURCE_HOSTS_INFO:
                     case SCREEN_RESOURCE_TRIGGERS_INFO:
                     case SCREEN_RESOURCE_TRIGGERS_OVERVIEW:
                     case SCREEN_RESOURCE_DATA_OVERVIEW:
                     case SCREEN_RESOURCE_HOSTGROUP_TRIGGERS:
                         $groupsToCheck[] = $sitem['resourceid'];
                         break;
                     case SCREEN_RESOURCE_HOST_TRIGGERS:
                         $hostsToCheck[] = $sitem['resourceid'];
                         break;
                     case SCREEN_RESOURCE_GRAPH:
                         $graphsToCheck[] = $sitem['resourceid'];
                         break;
                     case SCREEN_RESOURCE_SIMPLE_GRAPH:
                     case SCREEN_RESOURCE_PLAIN_TEXT:
                         $itemsToCheck[] = $sitem['resourceid'];
                         break;
                     case SCREEN_RESOURCE_MAP:
                         $mapsToCheck[] = $sitem['resourceid'];
                         break;
                     case SCREEN_RESOURCE_SCREEN:
                         $screensToCheck[] = $sitem['resourceid'];
                         break;
                 }
             }
         }
         $groupsToCheck = array_unique($groupsToCheck);
         $hostsToCheck = array_unique($hostsToCheck);
         $graphsToCheck = array_unique($graphsToCheck);
         $itemsToCheck = array_unique($itemsToCheck);
         $mapsToCheck = array_unique($mapsToCheck);
         $screensToCheck = array_unique($screensToCheck);
         // group
         $allowedGroups = API::HostGroup()->get(array('nodeids' => $options['nodeids'], 'groupids' => $groupsToCheck, 'editable' => $options['editable']));
         $allowedGroups = zbx_objectValues($allowedGroups, 'groupid');
         // host
         $allowedHosts = API::Host()->get(array('nodeids' => $options['nodeids'], 'hostids' => $hostsToCheck, 'editable' => $options['editable']));
         $allowedHosts = zbx_objectValues($allowedHosts, 'hostid');
         // graph
         $allowedGraphs = API::Graph()->get(array('nodeids' => $options['nodeids'], 'graphids' => $graphsToCheck, 'editable' => $options['editable']));
         $allowedGraphs = zbx_objectValues($allowedGraphs, 'graphid');
         // item
         $allowedItems = API::Item()->get(array('nodeids' => $options['nodeids'], 'itemids' => $itemsToCheck, 'webitems' => 1, 'editable' => $options['editable']));
         $allowedItems = zbx_objectValues($allowedItems, 'itemid');
         // map
         $allowedMaps = API::Map()->get(array('nodeids' => $options['nodeids'], 'sysmapids' => $mapsToCheck, 'editable' => $options['editable']));
         $allowedMaps = zbx_objectValues($allowedMaps, 'sysmapid');
         // screen
         $allowedScreens = API::Screen()->get(array('nodeids' => $options['nodeids'], 'screenids' => $screensToCheck, 'editable' => $options['editable']));
         $allowedScreens = zbx_objectValues($allowedScreens, 'screenid');
         $restrGroups = array_diff($groupsToCheck, $allowedGroups);
         $restrHosts = array_diff($hostsToCheck, $allowedHosts);
         $restrGraphs = array_diff($graphsToCheck, $allowedGraphs);
         $restrItems = array_diff($itemsToCheck, $allowedItems);
         $restrMaps = array_diff($mapsToCheck, $allowedMaps);
         $restrScreens = array_diff($screensToCheck, $allowedScreens);
         // group
         foreach ($restrGroups as $resourceid) {
             foreach ($screensItems as $screenItemid => $screenItem) {
                 if (bccomp($screenItem['resourceid'], $resourceid) == 0 && uint_in_array($screenItem['resourcetype'], array(SCREEN_RESOURCE_HOSTS_INFO, SCREEN_RESOURCE_TRIGGERS_INFO, SCREEN_RESOURCE_TRIGGERS_OVERVIEW, SCREEN_RESOURCE_DATA_OVERVIEW, SCREEN_RESOURCE_HOSTGROUP_TRIGGERS))) {
                     unset($result[$screenItem['screenid']], $screensItems[$screenItemid]);
                 }
             }
         }
         // host
         foreach ($restrHosts as $resourceid) {
             foreach ($screensItems as $screenItemid => $screenItem) {
                 if (bccomp($screenItem['resourceid'], $resourceid) == 0 && uint_in_array($screenItem['resourcetype'], array(SCREEN_RESOURCE_HOST_TRIGGERS))) {
                     unset($result[$screenItem['screenid']], $screensItems[$screenItemid]);
                 }
             }
         }
         // graph
         foreach ($restrGraphs as $resourceid) {
             foreach ($screensItems as $screenItemid => $screenItem) {
                 if (bccomp($screenItem['resourceid'], $resourceid) == 0 && $screenItem['resourcetype'] == SCREEN_RESOURCE_GRAPH) {
                     unset($result[$screenItem['screenid']], $screensItems[$screenItemid]);
                 }
             }
         }
         // item
         foreach ($restrItems as $resourceid) {
             foreach ($screensItems as $screenItemid => $screenItem) {
                 if (bccomp($screenItem['resourceid'], $resourceid) == 0 && uint_in_array($screenItem['resourcetype'], array(SCREEN_RESOURCE_SIMPLE_GRAPH, SCREEN_RESOURCE_PLAIN_TEXT))) {
                     unset($result[$screenItem['screenid']], $screensItems[$screenItemid]);
                 }
             }
         }
         // map
         foreach ($restrMaps as $resourceid) {
             foreach ($screensItems as $screenItemid => $screenItem) {
                 if (bccomp($screenItem['resourceid'], $resourceid) == 0 && $screenItem['resourcetype'] == SCREEN_RESOURCE_MAP) {
                     unset($result[$screenItem['screenid']], $screensItems[$screenItemid]);
                 }
             }
         }
         // screen
         foreach ($restrScreens as $resourceid) {
             foreach ($screensItems as $screenItemid => $screenItem) {
                 if (bccomp($screenItem['resourceid'], $resourceid) == 0 && $screenItem['resourcetype'] == SCREEN_RESOURCE_SCREEN) {
                     unset($result[$screenItem['screenid']], $screensItems[$screenItemid]);
                 }
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // adding ScreenItems
     if (!is_null($options['selectScreenItems']) && str_in_array($options['selectScreenItems'], $subselectsAllowedOutputs)) {
         if (!isset($screensItems)) {
             $screensItems = array();
             $dbSitems = DBselect('SELECT si.* FROM screens_items si WHERE ' . dbConditionInt('si.screenid', $screenids));
             while ($sitem = DBfetch($dbSitems)) {
                 $screensItems[$sitem['screenitemid']] = $sitem;
             }
         }
         foreach ($screensItems as $sitem) {
             if (!isset($result[$sitem['screenid']]['screenitems'])) {
                 $result[$sitem['screenid']]['screenitems'] = array();
             }
             $result[$sitem['screenid']]['screenitems'][] = $sitem;
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Interface Interface data
  *
  * @param array   $options
  * @param array   $options['nodeids']     Node IDs
  * @param array   $options['hostids']     Interface IDs
  * @param boolean $options['editable']    only with read-write permission. Ignored for SuperAdmins
  * @param boolean $options['selectHosts'] select Interface hosts
  * @param boolean $options['selectItems'] select Items
  * @param int	  $options['count']       count Interfaces, returned column name is rowscount
  * @param string  $options['pattern']     search hosts by pattern in Interface name
  * @param int	  $options['limit']       limit selection
  * @param string  $options['sortfield']   field to sort by
  * @param string  $options['sortorder']   sort order
  *
  * @return array|boolean Interface data as array or false if error
  */
 public function get(array $options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('interfaceid', 'dns', 'ip');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('interface' => 'hi.interfaceid'), 'from' => array('interface' => 'interface hi'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'interfaceids' => null, 'itemids' => null, 'triggerids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectHosts' => null, 'selectItems' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['interface']);
         $dbTable = DB::getSchema('interface');
         $sqlParts['select']['interfaceid'] = 'hi.interfaceid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'hi.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE hi.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // interfaceids
     if (!is_null($options['interfaceids'])) {
         zbx_value2array($options['interfaceids']);
         $sqlParts['where']['interfaceid'] = dbConditionInt('hi.interfaceid', $options['interfaceids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('hi.interfaceid', $nodeids);
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         $sqlParts['select']['hostid'] = 'hi.hostid';
         $sqlParts['where']['hostid'] = dbConditionInt('hi.hostid', $options['hostids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('hi.hostid', $nodeids);
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'i.itemid';
         }
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('i.itemid', $options['itemids']);
         $sqlParts['where']['hi'] = 'hi.interfaceid=i.interfaceid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('i.itemid', $nodeids);
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['triggerid'] = 'f.triggerid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
         $sqlParts['where']['hi'] = 'hi.hostid=i.hostid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('f.triggerid', $nodeids);
         }
     }
     // node check !!!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('hi.interfaceid', $nodeids);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['interface'] = 'hi.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT hi.interfaceid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('interface hi', $options, $sqlParts);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('interface hi', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'hi');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $interfaceids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($interface = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $interface;
             } else {
                 $result = $interface['rowscount'];
             }
         } else {
             $interfaceids[$interface['interfaceid']] = $interface['interfaceid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$interface['interfaceid']] = array('interfaceid' => $interface['interfaceid']);
             } else {
                 if (!isset($result[$interface['interfaceid']])) {
                     $result[$interface['interfaceid']] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$interface['interfaceid']]['hosts'])) {
                     $result[$interface['interfaceid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectItems']) && !isset($result[$interface['interfaceid']]['items'])) {
                     $result[$interface['interfaceid']]['items'] = array();
                 }
                 // itemids
                 if (isset($interface['itemid']) && is_null($options['selectItems'])) {
                     if (!isset($result[$interface['interfaceid']]['items'])) {
                         $result[$interface['interfaceid']]['items'] = array();
                     }
                     $result[$interface['interfaceid']]['items'][] = array('itemid' => $interface['itemid']);
                     unset($interface['itemid']);
                 }
                 $result[$interface['interfaceid']] += $interface;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding hosts
     if (!is_null($options['selectHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'interfaceids' => $interfaceids, 'preservekeys' => true);
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectHosts'];
             $hosts = API::Host()->get($objParams);
             $count = array();
             foreach ($hosts as $hostid => $host) {
                 unset($hosts[$hostid]['interfaces']);
                 foreach ($host['interfaces'] as $tnum => $interface) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$interface['interfaceid']])) {
                             $count[$interface['interfaceid']] = 0;
                         }
                         $count[$interface['interfaceid']]++;
                         if ($count[$interface['interfaceid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$interface['interfaceid']]['hosts'][] =& $hosts[$hostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $hosts = API::Host()->get($objParams);
             $hosts = zbx_toHash($hosts, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($hosts[$templateid])) {
                     $result[$templateid]['hosts'] = $hosts[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['hosts'] = 0;
                 }
             }
         }
     }
     // adding items
     if (!is_null($options['selectItems'])) {
         $objParams = array('nodeids' => $nodeids, 'interfaceids' => $interfaceids, 'nopermissions' => true, 'preservekeys' => true, 'filter' => array('flags' => null));
         if (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectItems'];
             $items = API::Item()->get($objParams);
             $count = array();
             foreach ($items as $itemid => $item) {
                 if (!is_null($options['limitSelects'])) {
                     if (!isset($count[$item['interfaceid']])) {
                         $count[$item['interfaceid']] = 0;
                     }
                     $count[$item['interfaceid']]++;
                     if ($count[$item['interfaceid']] > $options['limitSelects']) {
                         continue;
                     }
                 }
                 $result[$item['interfaceid']]['items'][] =& $items[$itemid];
             }
         } elseif (API_OUTPUT_COUNT == $options['selectItems']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $items = API::Item()->get($objParams);
             $items = zbx_toHash($items, 'interfaceid');
             foreach ($result as $interfaceid => $interface) {
                 if (isset($items[$interfaceid])) {
                     $result[$interfaceid]['items'] = $items[$interfaceid]['rowscount'];
                 } else {
                     $result[$interfaceid]['items'] = 0;
                 }
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 13
0
 /**
  * Get Actions data
  *
  * @param _array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['actionids']
  * @param array $options['applicationids']
  * @param array $options['status']
  * @param array $options['editable']
  * @param array $options['extendoutput']
  * @param array $options['count']
  * @param array $options['pattern']
  * @param array $options['limit']
  * @param array $options['order']
  * @return array|int item data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('actionid', 'name', 'status');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('actions' => 'a.actionid'), 'from' => array('actions' => 'actions a'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'actionids' => null, 'triggerids' => null, 'mediatypeids' => null, 'usrgrpids' => null, 'userids' => null, 'scriptids' => null, 'nopermissions' => null, 'editable' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectConditions' => null, 'selectOperations' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['actions']);
         $dbTable = DB::getSchema('actions');
         $sqlParts['select']['actionid'] = 'a.actionid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'a.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         // conditions are checked here by sql, operations after, by api queries
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         // condition hostgroup
         $sqlParts['where'][] = 'NOT EXISTS (' . 'SELECT NULL' . ' FROM conditions cc' . ' LEFT JOIN rights r' . ' ON r.id=' . zbx_dbcast_2bigint('cc.value') . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE a.actionid=cc.actionid' . ' AND cc.conditiontype=' . CONDITION_TYPE_HOST_GROUP . ' GROUP BY cc.value' . ' HAVING MIN(r.permission) IS NULL' . ' OR MIN(r.permission)<' . $permission . ')';
         // condition host or template
         $sqlParts['where'][] = 'NOT EXISTS (' . 'SELECT NULL' . ' FROM conditions cc,hosts_groups hgg' . ' LEFT JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE a.actionid=cc.actionid' . ' AND ' . zbx_dbcast_2bigint('cc.value') . '=hgg.hostid' . ' AND cc.conditiontype IN (' . CONDITION_TYPE_HOST . ',' . CONDITION_TYPE_HOST_TEMPLATE . ')' . ' GROUP BY cc.value' . ' HAVING MIN(r.permission) IS NULL' . ' OR MIN(r.permission)<' . $permission . ')';
         // condition trigger
         $sqlParts['where'][] = 'NOT EXISTS (' . 'SELECT NULL' . ' FROM conditions cc,functions f,items i,hosts_groups hgg' . ' LEFT JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE a.actionid=cc.actionid' . ' AND ' . zbx_dbcast_2bigint('cc.value') . '=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' AND cc.conditiontype=' . CONDITION_TYPE_TRIGGER . ' GROUP BY cc.value' . ' HAVING MIN(r.permission) IS NULL' . ' OR MIN(r.permission)<' . $permission . ')';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // actionids
     if (!is_null($options['actionids'])) {
         zbx_value2array($options['actionids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['actionid'] = 'a.actionid';
         }
         $sqlParts['where'][] = dbConditionInt('a.actionid', $options['actionids']);
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['groupids'] = 'cg.value';
         }
         $sqlParts['from']['conditions_groups'] = 'conditions cg';
         $sqlParts['where'][] = dbConditionString('cg.value', $options['groupids']);
         $sqlParts['where']['ctg'] = 'cg.conditiontype=' . CONDITION_TYPE_HOST_GROUP;
         $sqlParts['where']['acg'] = 'a.actionid=cg.actionid';
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostids'] = 'ch.value';
         }
         $sqlParts['from']['conditions_hosts'] = 'conditions ch';
         $sqlParts['where'][] = dbConditionString('ch.value', $options['hostids']);
         $sqlParts['where']['cth'] = 'ch.conditiontype=' . CONDITION_TYPE_HOST;
         $sqlParts['where']['ach'] = 'a.actionid=ch.actionid';
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['triggerids'] = 'ct.value';
         }
         $sqlParts['from']['conditions_triggers'] = 'conditions ct';
         $sqlParts['where'][] = dbConditionString('ct.value', $options['triggerids']);
         $sqlParts['where']['ctt'] = 'ct.conditiontype=' . CONDITION_TYPE_TRIGGER;
         $sqlParts['where']['act'] = 'a.actionid=ct.actionid';
     }
     // mediatypeids
     if (!is_null($options['mediatypeids'])) {
         zbx_value2array($options['mediatypeids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediatypeid'] = 'om.mediatypeid';
         }
         $sqlParts['from']['opmessage'] = 'opmessage om';
         $sqlParts['from']['operations_media'] = 'operations omed';
         $sqlParts['where'][] = dbConditionInt('om.mediatypeid', $options['mediatypeids']);
         $sqlParts['where']['aomed'] = 'a.actionid=omed.actionid';
         $sqlParts['where']['oom'] = 'omed.operationid=om.operationid';
     }
     // operation messages
     // usrgrpids
     if (!is_null($options['usrgrpids'])) {
         zbx_value2array($options['usrgrpids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['usrgrpid'] = 'omg.usrgrpid';
         }
         $sqlParts['from']['opmessage_grp'] = 'opmessage_grp omg';
         $sqlParts['from']['operations_usergroups'] = 'operations oug';
         $sqlParts['where'][] = dbConditionInt('omg.usrgrpid', $options['usrgrpids']);
         $sqlParts['where']['aoug'] = 'a.actionid=oug.actionid';
         $sqlParts['where']['oomg'] = 'oug.operationid=omg.operationid';
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['userid'] = 'omu.userid';
         }
         $sqlParts['from']['opmessage_usr'] = '******';
         $sqlParts['from']['operations_users'] = 'operations ou';
         $sqlParts['where'][] = dbConditionInt('omu.userid', $options['userids']);
         $sqlParts['where']['aou'] = 'a.actionid=ou.actionid';
         $sqlParts['where']['oomu'] = 'ou.operationid=omu.operationid';
     }
     // operation commands
     // scriptids
     if (!is_null($options['scriptids'])) {
         zbx_value2array($options['scriptids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['scriptid'] = 'oc.scriptid';
         }
         $sqlParts['from']['opcommand'] = 'opcommand oc';
         $sqlParts['from']['operations_scripts'] = 'operations os';
         $sqlParts['where'][] = '(' . dbConditionInt('oc.scriptid', $options['scriptids']) . ' AND oc.type=' . ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT . ')';
         $sqlParts['where']['aos'] = 'a.actionid=os.actionid';
         $sqlParts['where']['ooc'] = 'os.operationid=oc.operationid';
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('actions a', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('actions a', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['actions'] = 'a.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT a.actionid) AS rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'a');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $actionids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('a.actionid', $nodeids) . $sqlWhere . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($action = DBfetch($dbRes)) {
         if ($options['countOutput']) {
             $result = $action['rowscount'];
         } else {
             $actionids[$action['actionid']] = $action['actionid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$action['actionid']] = array('actionid' => $action['actionid']);
             } else {
                 if (!isset($result[$action['actionid']])) {
                     $result[$action['actionid']] = array();
                 }
                 if (!is_null($options['selectConditions']) && !isset($result[$action['actionid']]['conditions'])) {
                     $result[$action['actionid']]['conditions'] = array();
                 }
                 if (!is_null($options['selectOperations']) && !isset($result[$action['actionid']]['operations'])) {
                     $result[$action['actionid']]['operations'] = array();
                 }
                 $result[$action['actionid']] += $action;
                 // return mediatype as array
                 if (!empty($action['mediatypeid'])) {
                     $result[$action['actionid']]['mediatypeids'][] = $action['mediatypeid'];
                 }
                 unset($result[$action['actionid']]['mediatypeid']);
             }
         }
     }
     if (USER_TYPE_SUPER_ADMIN == $userType || !is_null($options['nopermissions'])) {
     } else {
         // check hosts, templates
         $hosts = $hostids = array();
         $sql = 'SELECT o.actionid,och.hostid' . ' FROM operations o,opcommand_hst och' . ' WHERE o.operationid=och.operationid' . ' AND och.hostid<>0' . ' AND ' . dbConditionInt('o.actionid', $actionids);
         $dbHosts = DBselect($sql);
         while ($host = DBfetch($dbHosts)) {
             if (!isset($hosts[$host['hostid']])) {
                 $hosts[$host['hostid']] = array();
             }
             $hosts[$host['hostid']][$host['actionid']] = $host['actionid'];
             $hostids[$host['hostid']] = $host['hostid'];
         }
         $dbTemplates = DBselect('SELECT o.actionid,ot.templateid' . ' FROM operations o,optemplate ot' . ' WHERE o.operationid=ot.operationid' . ' AND ' . dbConditionInt('o.actionid', $actionids));
         while ($template = DBfetch($dbTemplates)) {
             if (!isset($hosts[$template['templateid']])) {
                 $hosts[$template['templateid']] = array();
             }
             $hosts[$template['templateid']][$template['actionid']] = $template['actionid'];
             $hostids[$template['templateid']] = $template['templateid'];
         }
         $allowedHosts = API::Host()->get(array('hostids' => $hostids, 'output' => API_OUTPUT_SHORTEN, 'editable' => $options['editable'], 'templated_hosts' => true, 'preservekeys' => true));
         foreach ($hostids as $hostid) {
             if (isset($allowedHosts[$hostid])) {
                 continue;
             }
             foreach ($hosts[$hostid] as $actionid) {
                 unset($result[$actionid], $actionids[$actionid]);
             }
         }
         unset($allowedHosts);
         // check hostgroups
         $groups = $groupids = array();
         $dbGroups = DBselect('SELECT o.actionid,ocg.groupid' . ' FROM operations o,opcommand_grp ocg' . ' WHERE o.operationid=ocg.operationid' . ' AND ' . dbConditionInt('o.actionid', $actionids));
         while ($group = DBfetch($dbGroups)) {
             if (!isset($groups[$group['groupid']])) {
                 $groups[$group['groupid']] = array();
             }
             $groups[$group['groupid']][$group['actionid']] = $group['actionid'];
             $groupids[$group['groupid']] = $group['groupid'];
         }
         $dbGroups = DBselect('SELECT o.actionid,og.groupid' . ' FROM operations o,opgroup og' . ' WHERE o.operationid=og.operationid' . ' AND ' . dbConditionInt('o.actionid', $actionids));
         while ($group = DBfetch($dbGroups)) {
             if (!isset($groups[$group['groupid']])) {
                 $groups[$group['groupid']] = array();
             }
             $groups[$group['groupid']][$group['actionid']] = $group['actionid'];
             $groupids[$group['groupid']] = $group['groupid'];
         }
         $allowedGroups = API::HostGroup()->get(array('groupids' => $groupids, 'output' => API_OUTPUT_SHORTEN, 'editable' => $options['editable'], 'preservekeys' => true));
         foreach ($groupids as $groupid) {
             if (isset($allowedGroups[$groupid])) {
                 continue;
             }
             foreach ($groups[$groupid] as $actionid) {
                 unset($result[$actionid], $actionids[$actionid]);
             }
         }
         unset($allowedGroups);
         // check scripts
         $scripts = $scriptids = array();
         $dbScripts = DBselect('SELECT o.actionid,oc.scriptid' . ' FROM operations o,opcommand oc' . ' WHERE o.operationid=oc.operationid' . ' AND ' . dbConditionInt('o.actionid', $actionids) . ' AND oc.type=' . ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT);
         while ($script = DBfetch($dbScripts)) {
             if (!isset($scripts[$script['scriptid']])) {
                 $scripts[$script['scriptid']] = array();
             }
             $scripts[$script['scriptid']][$script['actionid']] = $script['actionid'];
             $scriptids[$script['scriptid']] = $script['scriptid'];
         }
         $allowedScripts = API::Script()->get(array('scriptids' => $scriptids, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true));
         foreach ($scriptids as $scriptid) {
             if (isset($allowedScripts[$scriptid])) {
                 continue;
             }
             foreach ($scripts[$scriptid] as $actionid) {
                 unset($result[$actionid], $actionids[$actionid]);
             }
         }
         unset($allowedScripts);
         // check users
         $users = $userids = array();
         $dbUsers = DBselect('SELECT o.actionid,omu.userid' . ' FROM operations o,opmessage_usr omu' . ' WHERE o.operationid=omu.operationid' . ' AND ' . dbConditionInt('o.actionid', $actionids));
         while ($user = DBfetch($dbUsers)) {
             if (!isset($users[$user['userid']])) {
                 $users[$user['userid']] = array();
             }
             $users[$user['userid']][$user['actionid']] = $user['actionid'];
             $userids[$user['userid']] = $user['userid'];
         }
         $allowedUsers = API::User()->get(array('userids' => $userids, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true));
         foreach ($userids as $userid) {
             if (isset($allowedUsers[$userid])) {
                 continue;
             }
             foreach ($users[$userid] as $actionid) {
                 unset($result[$actionid], $actionids[$actionid]);
             }
         }
         // check usergroups
         $usrgrps = $usrgrpids = array();
         $dbUsergroups = DBselect('SELECT o.actionid,omg.usrgrpid' . ' FROM operations o,opmessage_grp omg' . ' WHERE o.operationid=omg.operationid' . ' AND ' . dbConditionInt('o.actionid', $actionids));
         while ($usrgrp = DBfetch($dbUsergroups)) {
             if (!isset($usrgrps[$usrgrp['usrgrpid']])) {
                 $usrgrps[$usrgrp['usrgrpid']] = array();
             }
             $usrgrps[$usrgrp['usrgrpid']][$usrgrp['actionid']] = $usrgrp['actionid'];
             $usrgrpids[$usrgrp['usrgrpid']] = $usrgrp['usrgrpid'];
         }
         $allowedUsergrps = API::UserGroup()->get(array('usrgrpids' => $usrgrpids, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true));
         foreach ($usrgrpids as $usrgrpid) {
             if (isset($allowedUsergrps[$usrgrpid])) {
                 continue;
             }
             foreach ($usrgrps[$usrgrpid] as $actionid) {
                 unset($result[$actionid], $actionids[$actionid]);
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding conditions
     if (!is_null($options['selectConditions']) && str_in_array($options['selectConditions'], $subselectsAllowedOutputs)) {
         $res = DBselect('SELECT c.* FROM conditions c WHERE ' . dbConditionInt('c.actionid', $actionids));
         while ($condition = DBfetch($res)) {
             $result[$condition['actionid']]['conditions'][$condition['conditionid']] = $condition;
         }
     }
     // adding operations
     if (!is_null($options['selectOperations']) && str_in_array($options['selectOperations'], $subselectsAllowedOutputs)) {
         $operations = array();
         $operationids = array();
         $res = DBselect('SELECT o.*' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.actionid', $actionids));
         while ($operation = DBfetch($res)) {
             $operation['opconditions'] = array();
             $operations[$operation['operationid']] = $operation;
             $operationids[$operation['operationid']] = $operation['operationid'];
         }
         $res = DBselect('SELECT op.* FROM opconditions op WHERE ' . dbConditionInt('op.operationid', $operationids));
         while ($opcondition = DBfetch($res)) {
             if (!isset($operations[$opcondition['operationid']]['opconditions'])) {
                 $operations[$opcondition['operationid']]['opconditions'] = array();
             }
             $operations[$opcondition['operationid']]['opconditions'][] = $opcondition;
         }
         $opmessage = $opcommand = $opgroup = $optemplate = array();
         foreach ($operations as $operationid => $operation) {
             switch ($operation['operationtype']) {
                 case OPERATION_TYPE_MESSAGE:
                     $opmessage[] = $operationid;
                     break;
                 case OPERATION_TYPE_COMMAND:
                     $opcommand[] = $operationid;
                     break;
                 case OPERATION_TYPE_GROUP_ADD:
                 case OPERATION_TYPE_GROUP_REMOVE:
                     $opgroup[] = $operationid;
                     break;
                 case OPERATION_TYPE_TEMPLATE_ADD:
                 case OPERATION_TYPE_TEMPLATE_REMOVE:
                     $optemplate[] = $operationid;
                     break;
                 case OPERATION_TYPE_HOST_ADD:
                 case OPERATION_TYPE_HOST_REMOVE:
                 case OPERATION_TYPE_HOST_ENABLE:
                 case OPERATION_TYPE_HOST_DISABLE:
             }
         }
         // get OPERATION_TYPE_MESSAGE data
         if (!empty($opmessage)) {
             $dbOpmessages = DBselect('SELECT o.operationid,o.default_msg,o.subject,o.message,o.mediatypeid' . ' FROM opmessage o' . ' WHERE ' . dbConditionInt('o.operationid', $opmessage));
             while ($dbOpmessage = DBfetch($dbOpmessages)) {
                 $operations[$dbOpmessage['operationid']]['opmessage_grp'] = array();
                 $operations[$dbOpmessage['operationid']]['opmessage_usr'] = array();
                 $operations[$dbOpmessage['operationid']]['opmessage'] = $dbOpmessage;
             }
             $dbOpmessageGrp = DBselect('SELECT og.operationid,og.usrgrpid' . ' FROM opmessage_grp og' . ' WHERE ' . dbConditionInt('og.operationid', $opmessage));
             while ($opmessageGrp = DBfetch($dbOpmessageGrp)) {
                 $operations[$opmessageGrp['operationid']]['opmessage_grp'][] = $opmessageGrp;
             }
             $dbOpmessageUsr = DBselect('SELECT ou.operationid,ou.userid' . ' FROM opmessage_usr ou' . ' WHERE ' . dbConditionInt('ou.operationid', $opmessage));
             while ($opmessageUsr = DBfetch($dbOpmessageUsr)) {
                 $operations[$opmessageUsr['operationid']]['opmessage_usr'][] = $opmessageUsr;
             }
         }
         // get OPERATION_TYPE_COMMAND data
         if (!empty($opcommand)) {
             $dbOpcommands = DBselect('SELECT o.*' . ' FROM opcommand o' . ' WHERE ' . dbConditionInt('o.operationid', $opcommand));
             while ($dbOpcommand = DBfetch($dbOpcommands)) {
                 $operations[$dbOpcommand['operationid']]['opcommand_grp'] = array();
                 $operations[$dbOpcommand['operationid']]['opcommand_hst'] = array();
                 $operations[$dbOpcommand['operationid']]['opcommand'] = $dbOpcommand;
             }
             $dbOpcommandHst = DBselect('SELECT oh.opcommand_hstid,oh.operationid,oh.hostid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('oh.operationid', $opcommand));
             while ($opcommandHst = DBfetch($dbOpcommandHst)) {
                 $operations[$opcommandHst['operationid']]['opcommand_hst'][] = $opcommandHst;
             }
             $dbOpcommandGrp = DBselect('SELECT og.opcommand_grpid,og.operationid,og.groupid' . ' FROM opcommand_grp og' . ' WHERE ' . dbConditionInt('og.operationid', $opcommand));
             while ($opcommandGrp = DBfetch($dbOpcommandGrp)) {
                 $operations[$opcommandGrp['operationid']]['opcommand_grp'][] = $opcommandGrp;
             }
         }
         // get OPERATION_TYPE_GROUP_ADD, OPERATION_TYPE_GROUP_REMOVE data
         if (!empty($opgroup)) {
             $dbOpgroup = DBselect('SELECT o.operationid,o.groupid' . ' FROM opgroup o' . ' WHERE ' . dbConditionInt('o.operationid', $opgroup));
             while ($opgroup = DBfetch($dbOpgroup)) {
                 if (!isset($operations[$opgroup['operationid']]['opgroup'])) {
                     $operations[$opgroup['operationid']]['opgroup'] = array();
                 }
                 $operations[$opgroup['operationid']]['opgroup'][] = $opgroup;
             }
         }
         // get OPERATION_TYPE_TEMPLATE_ADD, OPERATION_TYPE_TEMPLATE_REMOVE data
         if (!empty($optemplate)) {
             $dbOptemplate = DBselect('SELECT o.operationid,o.templateid' . ' FROM optemplate o' . ' WHERE ' . dbConditionInt('o.operationid', $optemplate));
             while ($optemplate = DBfetch($dbOptemplate)) {
                 if (!isset($operations[$optemplate['operationid']]['optemplate'])) {
                     $operations[$optemplate['operationid']]['optemplate'] = array();
                 }
                 $operations[$optemplate['operationid']]['optemplate'][] = $optemplate;
             }
         }
         foreach ($operations as $operation) {
             $result[$operation['actionid']]['operations'][$operation['operationid']] = $operation;
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get GraphItems data
  *
  * @param array $options
  * @return array|boolean
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('gitemid');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('gitems' => 'gi.gitemid'), 'from' => array('graphs_items' => 'graphs_items gi'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'graphids' => null, 'itemids' => null, 'type' => null, 'editable' => null, 'nopermissions' => null, 'selectGraphs' => null, 'output' => API_OUTPUT_REFER, 'expandData' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE gi.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY i.itemid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['graphid'] = 'gi.graphid';
         }
         $sqlParts['from']['graphs'] = 'graphs g';
         $sqlParts['where']['gig'] = 'gi.graphid=g.graphid';
         $sqlParts['where'][] = dbConditionInt('g.graphid', $options['graphids']);
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'gi.itemid';
         }
         $sqlParts['where'][] = dbConditionInt('gi.itemid', $options['itemids']);
     }
     // type
     if (!is_null($options['type'])) {
         $sqlParts['where'][] = 'gi.type=' . zbx_dbstr($options['type']);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['gitems'] = 'gi.*';
     }
     // expandData
     if (!is_null($options['expandData'])) {
         $sqlParts['select']['key'] = 'i.key_';
         $sqlParts['select']['hostid'] = 'i.hostid';
         $sqlParts['select']['flags'] = 'i.flags';
         $sqlParts['select']['host'] = 'h.host';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['gii'] = 'gi.itemid=i.itemid';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT gi.gitemid) as rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'gi');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $gitemids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('gi.gitemid', $nodeids) . $sqlWhere . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($gitem = DBfetch($dbRes)) {
         if (!is_null($options['countOutput'])) {
             $result = $gitem['rowscount'];
         } else {
             $gitemids[$gitem['gitemid']] = $gitem['gitemid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$gitem['gitemid']] = array('gitemid' => $gitem['gitemid']);
             } else {
                 if (!isset($result[$gitem['gitemid']])) {
                     $result[$gitem['gitemid']] = array();
                 }
                 // graphids
                 if (isset($gitem['graphid']) && is_null($options['selectGraphs'])) {
                     if (!isset($result[$gitem['gitemid']]['graphs'])) {
                         $result[$gitem['gitemid']]['graphs'] = array();
                     }
                     $result[$gitem['gitemid']]['graphs'][] = array('graphid' => $gitem['graphid']);
                 }
                 $result[$gitem['gitemid']] += $gitem;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // adding graphs
     if (!is_null($options['selectGraphs']) && str_in_array($options['selectGraphs'], $subselectsAllowedOutputs)) {
         $graphs = API::Graph()->get(array('nodeids' => $nodeids, 'output' => $options['selectGraphs'], 'gitemids' => $gitemids, 'preservekeys' => true));
         foreach ($graphs as $graph) {
             $gitems = $graph['gitems'];
             unset($graph['gitems']);
             foreach ($gitems as $item) {
                 $result[$gitem['gitemid']]['graphs'][] = $graph;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get maintenances data
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['triggerids']
  * @param array $options['maintenanceids']
  * @param boolean $options['status']
  * @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 function get(array $options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('maintenanceid', 'name', 'maintenance_type');
     $sqlParts = array('select' => array('maintenance' => 'm.maintenanceid'), 'from' => array('maintenances' => 'maintenances m'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'maintenanceids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'filter' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectHosts' => null, 'selectTimeperiods' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     $maintenanceids = array();
     if ($userType == USER_TYPE_SUPER_ADMIN || $options['nopermissions']) {
         if (!is_null($options['groupids']) || !is_null($options['hostids'])) {
             if (!is_null($options['groupids'])) {
                 zbx_value2array($options['groupids']);
                 $res = DBselect('SELECT mmg.maintenanceid' . ' FROM maintenances_groups mmg' . ' WHERE ' . dbConditionInt('mmg.groupid', $options['groupids']));
                 while ($maintenance = DBfetch($res)) {
                     $maintenanceids[] = $maintenance['maintenanceid'];
                 }
             }
             $sql = 'SELECT mmh.maintenanceid' . ' FROM maintenances_hosts mmh,hosts_groups hg' . ' WHERE hg.hostid=mmh.hostid';
             if (!is_null($options['groupids'])) {
                 zbx_value2array($options['groupids']);
                 $sql .= ' AND ' . dbConditionInt('hg.groupid', $options['groupids']);
             }
             if (!is_null($options['hostids'])) {
                 zbx_value2array($options['hostids']);
                 $sql .= ' AND ' . dbConditionInt('hg.hostid', $options['hostids']);
             }
             $res = DBselect($sql);
             while ($maintenance = DBfetch($res)) {
                 $maintenanceids[] = $maintenance['maintenanceid'];
             }
             $sqlParts['where'][] = dbConditionInt('m.maintenanceid', $maintenanceids);
         }
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sql = 'SELECT m.maintenanceid' . ' FROM maintenances m' . ' WHERE NOT EXISTS (' . 'SELECT NULL' . ' FROM maintenances_hosts mh,hosts_groups hg' . ' LEFT JOIN rights r' . ' ON r.id=hg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE m.maintenanceid=mh.maintenanceid' . ' AND mh.hostid=hg.hostid' . ' GROUP by mh.hostid' . ' HAVING MIN(r.permission) IS NULL' . ' OR MIN(r.permission)<' . $permission . ')' . ' AND NOT EXISTS (' . 'SELECT NULL' . ' FROM maintenances_groups mg' . ' LEFT JOIN rights r' . ' ON r.id=mg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE m.maintenanceid=mg.maintenanceid' . ' GROUP by mg.groupid' . ' HAVING MIN(r.permission) IS NULL' . ' OR MIN(r.permission)<' . $permission . ')';
         if (!is_null($options['groupids'])) {
             zbx_value2array($options['groupids']);
             $sql .= ' AND (' . 'EXISTS (' . 'SELECT NULL' . ' FROM maintenances_groups mg' . ' WHERE m.maintenanceid=mg.maintenanceid' . ' AND ' . dbConditionInt('mg.groupid', $options['groupids']) . ')' . ' OR EXISTS (' . 'SELECT NULL' . ' FROM maintenances_hosts mh,hosts_groups hg' . ' WHERE m.maintenanceid=mh.maintenanceid' . ' AND mh.hostid=hg.hostid' . ' AND ' . dbConditionInt('hg.groupid', $options['groupids']) . ')' . ')';
         }
         if (!is_null($options['hostids'])) {
             zbx_value2array($options['hostids']);
             $sql .= ' AND EXISTS (' . 'SELECT NULL' . ' FROM maintenances_hosts mh' . ' WHERE m.maintenanceid=mh.maintenanceid' . ' AND ' . dbConditionInt('mh.hostid', $options['hostids']) . ')';
         }
         if (!is_null($options['maintenanceids'])) {
             zbx_value2array($options['maintenanceids']);
             $sql .= ' AND ' . dbConditionInt('m.maintenanceid', $options['maintenanceids']);
         }
         $res = DBselect($sql);
         while ($maintenance = DBfetch($res)) {
             $maintenanceids[] = $maintenance['maintenanceid'];
         }
         $sqlParts['where'][] = dbConditionInt('m.maintenanceid', $maintenanceids);
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // groupids
     if (!is_null($options['groupids'])) {
         $options['selectGroups'] = 1;
     }
     // hostids
     if (!is_null($options['hostids'])) {
         $options['selectHosts'] = 1;
     }
     // maintenanceids
     if (!is_null($options['maintenanceids'])) {
         zbx_value2array($options['maintenanceids']);
         $sqlParts['where'][] = dbConditionInt('m.maintenanceid', $options['maintenanceids']);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['maintenance'] = 'm.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT m.maintenanceid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('maintenances m', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('maintenances m', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'm');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $maintenanceids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('m.maintenanceid', $nodeids) . $sqlWhere . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($maintenance = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $maintenance;
             } else {
                 $result = $maintenance['rowscount'];
             }
         } else {
             $maintenanceids[$maintenance['maintenanceid']] = $maintenance['maintenanceid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$maintenance['maintenanceid']] = array('maintenanceid' => $maintenance['maintenanceid']);
             } else {
                 if (!isset($result[$maintenance['maintenanceid']])) {
                     $result[$maintenance['maintenanceid']] = array();
                 }
                 if (!is_null($options['selectGroups']) && !isset($result[$maintenance['maintenanceid']]['groups'])) {
                     $result[$maintenance['maintenanceid']]['groups'] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$maintenance['maintenanceid']]['hosts'])) {
                     $result[$maintenance['maintenanceid']]['hosts'] = array();
                 }
                 // groupids
                 if (isset($maintenance['groupid']) && is_null($options['selectGroups'])) {
                     if (!isset($result[$maintenance['maintenanceid']]['groups'])) {
                         $result[$maintenance['maintenanceid']]['groups'] = array();
                     }
                     $result[$maintenance['maintenanceid']]['groups'][] = array('groupid' => $maintenance['groupid']);
                     unset($maintenance['groupid']);
                 }
                 // hostids
                 if (isset($maintenance['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$maintenance['maintenanceid']]['hosts'])) {
                         $result[$maintenance['maintenanceid']]['hosts'] = array();
                     }
                     $result[$maintenance['maintenanceid']]['hosts'][] = array('hostid' => $maintenance['hostid']);
                     unset($maintenance['hostid']);
                 }
                 $result[$maintenance['maintenanceid']] += $maintenance;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     if ($result) {
         $result = $this->addRelatedObjects($options, $result);
     }
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 16
0
 /**
  * Get images data
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['triggerids']
  * @param array $options['imageids']
  * @param boolean $options['status']
  * @param boolean $options['editable']
  * @param boolean $options['count']
  * @param string $options['pattern']
  * @param int $options['limit']
  * @param string $options['order']
  * @return array|boolean image data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     // allowed columns for sorting
     $sortColumns = array('imageid', 'name');
     $sqlParts = array('select' => array('images' => 'i.imageid'), 'from' => array('images' => 'images i'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'imageids' => null, 'sysmapids' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'select_image' => null, 'editable' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     if (!is_null($options['editable']) && self::$userData['type'] < USER_TYPE_ZABBIX_ADMIN) {
         return $result;
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // imageids
     if (!is_null($options['imageids'])) {
         zbx_value2array($options['imageids']);
         $sqlParts['where']['imageid'] = dbConditionInt('i.imageid', $options['imageids']);
     }
     // sysmapids
     if (!is_null($options['sysmapids'])) {
         zbx_value2array($options['sysmapids']);
         $sqlParts['select']['sm'] = 'sm.sysmapid';
         $sqlParts['from']['sysmaps'] = 'sysmaps sm';
         $sqlParts['from']['sysmaps_elements'] = 'sysmaps_elements se';
         $sqlParts['where']['sm'] = dbConditionInt('sm.sysmapid', $options['sysmapids']);
         $sqlParts['where']['smse'] = 'sm.sysmapid=se.sysmapid ';
         $sqlParts['where']['se'] = '(' . 'se.iconid_off=i.imageid' . ' OR se.iconid_on=i.imageid' . ' OR se.iconid_disabled=i.imageid' . ' OR se.iconid_maintenance=i.imageid' . ' OR sm.backgroundid=i.imageid)';
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['images'] = 'i.imageid, i.imagetype, i.name';
     }
     // count
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT i.imageid) as rowscount');
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('images i', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('images i', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'i');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $imageids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('i.imageid', $nodeids) . $sqlWhere . $sqlOrder;
     $res = DBselect($sql, $sqlParts['limit']);
     while ($image = DBfetch($res)) {
         if ($options['countOutput']) {
             return $image['rowscount'];
         } else {
             $imageids[$image['imageid']] = $image['imageid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$image['imageid']] = array('imageid' => $image['imageid']);
             } else {
                 if (!isset($result[$image['imageid']])) {
                     $result[$image['imageid']] = array();
                 }
                 // sysmapds
                 if (isset($image['sysmapid'])) {
                     if (!isset($result[$image['imageid']]['sysmaps'])) {
                         $result[$image['imageid']]['sysmaps'] = array();
                     }
                     $result[$image['imageid']]['sysmaps'][] = array('sysmapid' => $image['sysmapid']);
                 }
                 $result[$image['imageid']] += $image;
             }
         }
     }
     // adding objects
     if (!is_null($options['select_image'])) {
         $dbImg = DBselect('SELECT i.imageid,i.image FROM images i WHERE ' . dbConditionInt('i.imageid', $imageids));
         while ($img = DBfetch($dbImg)) {
             // PostgreSQL and SQLite images are stored escaped in the DB
             $img['image'] = zbx_unescape_image($img['image']);
             $result[$img['imageid']]['image'] = base64_encode($img['image']);
         }
     }
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 17
0
 /**
  * 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_historical_items'] only with historical items
  * @param boolean $options['with_triggers'] only with triggers
  * @param boolean $options['with_httptests'] only with 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['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 function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     // allowed columns for sorting
     $sortColumns = array('name', 'width', 'height');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('sysmaps' => 's.sysmapid'), 'from' => array('sysmaps' => 'sysmaps s'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'sysmapids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectSelements' => null, 'selectLinks' => null, 'selectIconMap' => null, 'countOutput' => null, 'expandUrls' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['sysmaps']);
         $dbTable = DB::getSchema('sysmaps');
         $sqlParts['select']['sysmapid'] = 's.sysmapid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 's.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // sysmapids
     if (!is_null($options['sysmapids'])) {
         zbx_value2array($options['sysmapids']);
         $sqlParts['where']['sysmapid'] = dbConditionInt('s.sysmapid', $options['sysmapids']);
     }
     // search
     if (!is_null($options['search'])) {
         zbx_db_search('sysmaps s', $options, $sqlParts);
     }
     // filter
     if (!is_null($options['filter'])) {
         $this->dbFilter('sysmaps s', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['sysmaps'] = 's.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT s.sysmapid) as rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 's');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $sysmapids = array();
     $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['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();
                 }
                 // originally we intended not to pass those parameters if advanced labels are off, but they might be useful
                 // leaving this block commented
                 // if (isset($sysmap['label_format']) && ($sysmap['label_format'] == SYSMAP_LABEL_ADVANCED_OFF)) {
                 // 	unset($sysmap['label_string_hostgroup'], $sysmap['label_string_host'], $sysmap['label_string_trigger'], $sysmap['label_string_map'], $sysmap['label_string_image']);
                 // }
                 if (!is_null($options['selectSelements']) && !isset($result[$sysmap['sysmapid']]['selements'])) {
                     $result[$sysmap['sysmapid']]['selements'] = array();
                 }
                 if (!is_null($options['selectLinks']) && !isset($result[$sysmap['sysmapid']]['links'])) {
                     $result[$sysmap['sysmapid']]['links'] = array();
                 }
                 if (!is_null($options['selectIconMap']) && !isset($result[$sysmap['sysmapid']]['iconmap'])) {
                     $result[$sysmap['sysmapid']]['iconmap'] = array();
                 }
                 if (!isset($result[$sysmap['sysmapid']]['urls'])) {
                     $result[$sysmap['sysmapid']]['urls'] = array();
                 }
                 $result[$sysmap['sysmapid']] += $sysmap;
             }
         }
     }
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         if (!empty($result)) {
             $linkTriggers = array();
             $dbLinkTriggers = DBselect('SELECT slt.triggerid,sl.sysmapid' . ' FROM sysmaps_link_triggers slt,sysmaps_links sl' . ' WHERE ' . dbConditionInt('sl.sysmapid', $sysmapids) . ' AND sl.linkid=slt.linkid');
             while ($linkTrigger = DBfetch($dbLinkTriggers)) {
                 $linkTriggers[$linkTrigger['sysmapid']] = $linkTrigger['triggerid'];
             }
             if (!empty($linkTriggers)) {
                 $trigOptions = array('triggerids' => $linkTriggers, 'editable' => $options['editable'], 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true);
                 $allTriggers = API::Trigger()->get($trigOptions);
                 foreach ($linkTriggers as $id => $triggerid) {
                     if (!isset($allTriggers[$triggerid])) {
                         unset($result[$id], $sysmapids[$id]);
                     }
                 }
             }
             $hostsToCheck = array();
             $mapsToCheck = array();
             $triggersToCheck = array();
             $hostGroupsToCheck = array();
             $selements = array();
             $dbSelements = DBselect('SELECT se.* FROM sysmaps_elements se WHERE ' . dbConditionInt('se.sysmapid', $sysmapids));
             while ($selement = DBfetch($dbSelements)) {
                 $selements[$selement['selementid']] = $selement;
                 switch ($selement['elementtype']) {
                     case SYSMAP_ELEMENT_TYPE_HOST:
                         $hostsToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                     case SYSMAP_ELEMENT_TYPE_MAP:
                         $mapsToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                     case SYSMAP_ELEMENT_TYPE_TRIGGER:
                         $triggersToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                     case SYSMAP_ELEMENT_TYPE_HOST_GROUP:
                         $hostGroupsToCheck[$selement['elementid']] = $selement['elementid'];
                         break;
                 }
             }
             $nodeids = get_current_nodeid(true);
             if (!empty($hostsToCheck)) {
                 $hostOptions = array('hostids' => $hostsToCheck, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => API_OUTPUT_SHORTEN);
                 $allowedHosts = API::Host()->get($hostOptions);
                 foreach ($hostsToCheck as $elementid) {
                     if (!isset($allowedHosts[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
             if (!empty($mapsToCheck)) {
                 $mapOptions = array('sysmapids' => $mapsToCheck, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => API_OUTPUT_SHORTEN);
                 $allowedMaps = $this->get($mapOptions);
                 foreach ($mapsToCheck as $elementid) {
                     if (!isset($allowedMaps[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_MAP && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
             if (!empty($triggersToCheck)) {
                 $triggeridOptions = array('triggerids' => $triggersToCheck, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => API_OUTPUT_SHORTEN);
                 $allowedTriggers = API::Trigger()->get($triggeridOptions);
                 foreach ($triggersToCheck as $elementid) {
                     if (!isset($allowedTriggers[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_TRIGGER && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
             if (!empty($hostGroupsToCheck)) {
                 $hostgroupOptions = array('groupids' => $hostGroupsToCheck, 'nodeids' => $nodeids, 'editable' => $options['editable'], 'preservekeys' => true, 'output' => API_OUTPUT_SHORTEN);
                 $allowedHostGroups = API::HostGroup()->get($hostgroupOptions);
                 foreach ($hostGroupsToCheck as $elementid) {
                     if (!isset($allowedHostGroups[$elementid])) {
                         foreach ($selements as $selementid => $selement) {
                             if ($selement['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST_GROUP && bccomp($selement['elementid'], $elementid) == 0) {
                                 unset($result[$selement['sysmapid']], $selements[$selementid]);
                             }
                         }
                     }
                 }
             }
             $sysmapids = array_keys($result);
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // adding elements
     if (!is_null($options['selectSelements']) && str_in_array($options['selectSelements'], $subselectsAllowedOutputs)) {
         $selements = array();
         $dbSelements = DBselect('SELECT se.*' . ' FROM sysmaps_elements se' . ' WHERE ' . dbConditionInt('se.sysmapid', $sysmapids));
         while ($selement = DBfetch($dbSelements)) {
             $selement['urls'] = array();
             $selements[$selement['selementid']] = $selement;
         }
         if (!is_null($options['expandUrls'])) {
             $dbMapUrls = DBselect('SELECT sysmapurlid, sysmapid, name, url, elementtype' . ' FROM sysmap_url' . ' WHERE ' . dbConditionInt('sysmapid', $sysmapids));
             while ($mapUrl = DBfetch($dbMapUrls)) {
                 foreach ($selements as $snum => $selement) {
                     if (bccomp($selement['sysmapid'], $mapUrl['sysmapid']) == 0 && ($selement['elementtype'] == $mapUrl['elementtype'] && $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP || $selement['elementsubtype'] == SYSMAP_ELEMENT_SUBTYPE_HOST_GROUP_ELEMENTS && $mapUrl['elementtype'] == SYSMAP_ELEMENT_TYPE_HOST)) {
                         $selements[$snum]['urls'][] = $this->expandUrlMacro($mapUrl, $selement);
                     }
                 }
             }
         }
         $dbSelementUrls = DBselect('SELECT seu.sysmapelementurlid,seu.selementid,seu.name,seu.url' . ' FROM sysmap_element_url seu' . ' WHERE ' . dbConditionInt('seu.selementid', array_keys($selements)));
         while ($selementUrl = DBfetch($dbSelementUrls)) {
             if (is_null($options['expandUrls'])) {
                 $selements[$selementUrl['selementid']]['urls'][] = $selementUrl;
             } else {
                 $selements[$selementUrl['selementid']]['urls'][] = $this->expandUrlMacro($selementUrl, $selements[$selementUrl['selementid']]);
             }
         }
         foreach ($selements as $selement) {
             if (!isset($result[$selement['sysmapid']]['selements'])) {
                 $result[$selement['sysmapid']]['selements'] = array();
             }
             if (!is_null($options['preservekeys'])) {
                 $result[$selement['sysmapid']]['selements'][$selement['selementid']] = $selement;
             } else {
                 $result[$selement['sysmapid']]['selements'][] = $selement;
             }
         }
     }
     // adding icon maps
     if (!is_null($options['selectIconMap']) && str_in_array($options['selectIconMap'], $subselectsAllowedOutputs)) {
         $iconMaps = API::IconMap()->get(array('sysmapids' => $sysmapids, 'output' => $options['selectIconMap'], 'selectMappings' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'nopermissions' => true));
         foreach ($iconMaps as $iconMap) {
             $isysmaps = $iconMap['sysmaps'];
             unset($iconMap['sysmaps']);
             foreach ($isysmaps as $sysmap) {
                 $result[$sysmap['sysmapid']]['iconmap'] = $iconMap;
             }
         }
     }
     // adding links
     if (!is_null($options['selectLinks']) && str_in_array($options['selectLinks'], $subselectsAllowedOutputs)) {
         $linkids = array();
         $mapLinks = array();
         $dbLinks = DBselect('SELECT sl.* FROM sysmaps_links sl WHERE ' . dbConditionInt('sl.sysmapid', $sysmapids));
         while ($link = DBfetch($dbLinks)) {
             $link['linktriggers'] = array();
             $mapLinks[$link['linkid']] = $link;
             $linkids[$link['linkid']] = $link['linkid'];
         }
         $dbLinkTriggers = DBselect('SELECT DISTINCT slt.* FROM sysmaps_link_triggers slt WHERE ' . dbConditionInt('slt.linkid', $linkids));
         while ($linkTrigger = DBfetch($dbLinkTriggers)) {
             $mapLinks[$linkTrigger['linkid']]['linktriggers'][$linkTrigger['linktriggerid']] = $linkTrigger;
         }
         foreach ($mapLinks as $link) {
             if (!isset($result[$link['sysmapid']]['links'])) {
                 $result[$link['sysmapid']]['links'] = array();
             }
             if (!is_null($options['preservekeys'])) {
                 $result[$link['sysmapid']]['links'][$link['linkid']] = $link;
             } else {
                 $result[$link['sysmapid']]['links'][] = $link;
             }
         }
     }
     // adding urls
     if ($options['output'] != API_OUTPUT_SHORTEN) {
         $dbUrls = DBselect('SELECT su.* FROM sysmap_url su WHERE ' . dbConditionInt('su.sysmapid', $sysmapids));
         while ($url = DBfetch($dbUrls)) {
             $sysmapid = $url['sysmapid'];
             unset($url['sysmapid']);
             $result[$sysmapid]['urls'][] = $url;
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 18
0
 /**
  * Get items data.
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['triggerids']
  * @param array $options['applicationids']
  * @param 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 function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('itemid', 'name', 'key_', 'delay', 'history', 'trends', 'type', 'status');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('items' => 'i.itemid'), 'from' => array('items' => 'items i'), 'where' => array('webtype' => 'i.type<>' . ITEM_TYPE_HTTPTEST, 'flags' => 'i.flags IN (' . ZBX_FLAG_DISCOVERY_NORMAL . ',' . ZBX_FLAG_DISCOVERY_CREATED . ')'), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'proxyids' => null, 'itemids' => null, 'interfaceids' => null, 'graphids' => null, 'triggerids' => null, 'applicationids' => null, 'webitems' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'editable' => null, 'nopermissions' => null, 'group' => null, 'host' => null, 'application' => null, 'with_triggers' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectHosts' => null, 'selectInterfaces' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectApplications' => null, 'selectDiscoveryRule' => null, 'selectItemDiscovery' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['items']);
         $dbTable = DB::getSchema('items');
         $sqlParts['select']['itemid'] = 'i.itemid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'i.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + permission check
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE i.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sqlParts['where']['itemid'] = dbConditionInt('i.itemid', $options['itemids']);
     }
     // 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) {
             $sqlParts['select']['hostid'] = 'i.hostid';
         }
         $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['hostids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['i'] = 'i.hostid';
         }
     }
     // interfaceids
     if (!is_null($options['interfaceids'])) {
         zbx_value2array($options['interfaceids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sqlParts['select']['interfaceid'] = 'i.interfaceid';
         }
         $sqlParts['where']['interfaceid'] = dbConditionInt('i.interfaceid', $options['interfaceids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['i'] = 'i.interfaceid';
         }
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']);
         $sqlParts['where'][] = 'hg.hostid=i.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['hg'] = 'hg.groupid';
         }
     }
     // proxyids
     if (!is_null($options['proxyids'])) {
         zbx_value2array($options['proxyids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sqlParts['select']['proxyid'] = 'h.proxy_hostid';
         }
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where'][] = dbConditionInt('h.proxy_hostid', $options['proxyids']);
         $sqlParts['where'][] = 'h.hostid=i.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['h'] = 'h.proxy_hostid';
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['triggerid'] = 'f.triggerid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
         $sqlParts['where']['if'] = 'i.itemid=f.itemid';
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['applicationid'] = 'ia.applicationid';
         }
         $sqlParts['from']['items_applications'] = 'items_applications ia';
         $sqlParts['where'][] = dbConditionInt('ia.applicationid', $options['applicationids']);
         $sqlParts['where']['ia'] = 'ia.itemid=i.itemid';
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['graphid'] = 'gi.graphid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']);
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
     }
     // webitems
     if (!is_null($options['webitems'])) {
         unset($sqlParts['where']['webtype']);
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sqlParts['where'][] = 'i.templateid IS NOT NULL';
         } else {
             $sqlParts['where'][] = 'i.templateid IS NULL';
         }
     }
     // templated
     if (!is_null($options['templated'])) {
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['templated']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // monitored
     if (!is_null($options['monitored'])) {
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['monitored']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_MONITORED;
             $sqlParts['where'][] = 'i.status=' . ITEM_STATUS_ACTIVE;
         } else {
             $sqlParts['where'][] = '(h.status<>' . HOST_STATUS_MONITORED . ' OR i.status<>' . ITEM_STATUS_ACTIVE . ')';
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('items i', $options, $sqlParts);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('items i', $options, $sqlParts);
         if (isset($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sqlParts['from']['hosts'] = 'hosts h';
             $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
             $sqlParts['where']['h'] = dbConditionString('h.host', $options['filter']['host'], false, true);
         }
         if (array_key_exists('flags', $options['filter']) && ($options['filter']['flags'] === null || !zbx_empty($options['filter']['flags']))) {
             unset($sqlParts['where']['flags']);
         }
     }
     // group
     if (!is_null($options['group'])) {
         $sqlParts['from']['groups'] = 'groups g';
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['ghg'] = 'g.groupid=hg.groupid';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sqlParts['where'][] = ' g.name=' . zbx_dbstr($options['group']);
     }
     // host
     if (!is_null($options['host'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['host'] = 'h.host';
         }
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         $sqlParts['where'][] = ' h.host=' . zbx_dbstr($options['host']);
     }
     // application
     if (!is_null($options['application'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['application'] = 'a.name as application';
         }
         $sqlParts['from']['applications'] = 'applications a';
         $sqlParts['from']['items_applications'] = 'items_applications ia';
         $sqlParts['where']['aia'] = 'a.applicationid = ia.applicationid';
         $sqlParts['where']['iai'] = 'ia.itemid=i.itemid';
         $sqlParts['where'][] = ' a.name=' . zbx_dbstr($options['application']);
     }
     // with_triggers
     if (!is_null($options['with_triggers'])) {
         if ($options['with_triggers'] == 1) {
             $sqlParts['where'][] = ' EXISTS (SELECT NULL FROM functions ff WHERE ff.itemid=i.itemid)';
         } else {
             $sqlParts['where'][] = 'NOT EXISTS (SELECT NULL FROM functions ff WHERE ff.itemid=i.itemid)';
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['items'] = 'i.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT i.itemid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'i');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $itemids = array();
     $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['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['selectHosts']) && !isset($result[$item['itemid']]['hosts'])) {
                     $result[$item['itemid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectTriggers']) && !isset($result[$item['itemid']]['triggers'])) {
                     $result[$item['itemid']]['triggers'] = array();
                 }
                 if (!is_null($options['selectGraphs']) && !isset($result[$item['itemid']]['graphs'])) {
                     $result[$item['itemid']]['graphs'] = array();
                 }
                 if (!is_null($options['selectApplications']) && !isset($result[$item['itemid']]['applications'])) {
                     $result[$item['itemid']]['applications'] = array();
                 }
                 if (!is_null($options['selectDiscoveryRule']) && !isset($result[$item['itemid']]['discoveryRule'])) {
                     $result[$item['itemid']]['discoveryRule'] = array();
                 }
                 if (!is_null($options['selectInterfaces']) && !isset($result[$item['itemid']]['interfaces'])) {
                     $result[$item['itemid']]['interfaces'] = array();
                 }
                 // triggerids
                 if (isset($item['triggerid']) && is_null($options['selectTriggers'])) {
                     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['selectGraphs'])) {
                     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['selectApplications'])) {
                     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;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding hosts
     if (!is_null($options['selectHosts'])) {
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams = array('nodeids' => $options['nodeids'], 'itemids' => $itemids, 'templated_hosts' => true, 'output' => $options['selectHosts'], 'nopermissions' => true, 'preservekeys' => true);
             $hosts = API::Host()->get($objParams);
             foreach ($hosts as $host) {
                 $hitems = $host['items'];
                 unset($host['items']);
                 foreach ($hitems as $item) {
                     $result[$item['itemid']]['hosts'][] = $host;
                 }
             }
             $templates = API::Template()->get($objParams);
             foreach ($templates as $template) {
                 $titems = $template['items'];
                 unset($template['items']);
                 foreach ($titems as $item) {
                     $result[$item['itemid']]['hosts'][] = $template;
                 }
             }
         }
     }
     // adding interfaces
     if (!is_null($options['selectInterfaces'])) {
         if (is_array($options['selectInterfaces']) || str_in_array($options['selectInterfaces'], $subselectsAllowedOutputs)) {
             $interfaces = API::HostInterface()->get(array('nodeids' => $options['nodeids'], 'itemids' => $itemids, 'output' => $options['selectInterfaces'], 'nopermissions' => true, 'preservekeys' => true));
             foreach ($interfaces as $interface) {
                 $hitems = $interface['items'];
                 unset($interface['items']);
                 foreach ($hitems as $item) {
                     $result[$item['itemid']]['interfaces'][] = $interface;
                 }
             }
         }
     }
     // adding triggers
     if (!is_null($options['selectTriggers'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'itemids' => $itemids, 'preservekeys' => true);
         if (in_array($options['selectTriggers'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectTriggers'];
             $triggers = API::Trigger()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($triggers, 'description');
             }
             foreach ($triggers as $triggerid => $trigger) {
                 unset($triggers[$triggerid]['items']);
                 $count = array();
                 foreach ($trigger['items'] as $item) {
                     // skip trigger assignment for unwanted items from other hosts
                     if (!isset($result[$item['itemid']])) {
                         continue;
                     }
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$item['itemid']])) {
                             $count[$item['itemid']] = 0;
                         }
                         $count[$item['itemid']]++;
                         if ($count[$item['itemid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$item['itemid']]['triggers'][] =& $triggers[$triggerid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $triggers = API::Trigger()->get($objParams);
             $triggers = zbx_toHash($triggers, 'itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($triggers[$itemid])) {
                     $result[$itemid]['triggers'] = $triggers[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['triggers'] = 0;
                 }
             }
         }
     }
     // adding graphs
     if (!is_null($options['selectGraphs'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'itemids' => $itemids, 'preservekeys' => true);
         if (in_array($options['selectGraphs'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectGraphs'];
             $graphs = API::Graph()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($graphs, 'name');
             }
             foreach ($graphs as $graphid => $graph) {
                 unset($graphs[$graphid]['items']);
                 $count = array();
                 foreach ($graph['items'] as $item) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$item['itemid']])) {
                             $count[$item['itemid']] = 0;
                         }
                         $count[$item['itemid']]++;
                         if ($count[$item['itemid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$item['itemid']]['graphs'][] =& $graphs[$graphid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $graphs = API::Graph()->get($objParams);
             $graphs = zbx_toHash($graphs, 'itemid');
             foreach ($result as $itemid => $item) {
                 if (isset($graphs[$itemid])) {
                     $result[$itemid]['graphs'] = $graphs[$itemid]['rowscount'];
                 } else {
                     $result[$itemid]['graphs'] = 0;
                 }
             }
         }
     }
     // adding applications
     if (!is_null($options['selectApplications']) && str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) {
         $applications = API::Application()->get(array('nodeids' => $options['nodeids'], 'output' => $options['selectApplications'], 'itemids' => $itemids, 'preservekeys' => true));
         foreach ($applications as $application) {
             $aitems = $application['items'];
             unset($application['items']);
             foreach ($aitems as $item) {
                 $result[$item['itemid']]['applications'][] = $application;
             }
         }
     }
     // adding discoveryrule
     if (!is_null($options['selectDiscoveryRule'])) {
         $ruleids = $ruleMap = array();
         $dbRules = DBselect('SELECT id1.itemid,id2.parent_itemid' . ' FROM item_discovery id1,item_discovery id2,items i' . ' WHERE ' . dbConditionInt('id1.itemid', $itemids) . ' AND id1.parent_itemid=id2.itemid' . ' AND i.itemid=id1.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_CREATED);
         while ($rule = DBfetch($dbRules)) {
             $ruleids[$rule['parent_itemid']] = $rule['parent_itemid'];
             $ruleMap[$rule['itemid']] = $rule['parent_itemid'];
         }
         $dbRules = DBselect('SELECT id.parent_itemid,id.itemid' . ' FROM item_discovery id,items i' . ' WHERE ' . dbConditionInt('id.itemid', $itemids) . ' AND i.itemid=id.itemid' . ' AND i.flags=' . ZBX_FLAG_DISCOVERY_CHILD);
         while ($rule = DBfetch($dbRules)) {
             $ruleids[$rule['parent_itemid']] = $rule['parent_itemid'];
             $ruleMap[$rule['itemid']] = $rule['parent_itemid'];
         }
         $objParams = array('nodeids' => $options['nodeids'], 'itemids' => $ruleids, 'filter' => array('flags' => null), 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectDiscoveryRule']) || str_in_array($options['selectDiscoveryRule'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDiscoveryRule'];
             $discoveryRules = $this->get($objParams);
             foreach ($result as $itemid => $item) {
                 if (isset($ruleMap[$itemid]) && isset($discoveryRules[$ruleMap[$itemid]])) {
                     $result[$itemid]['discoveryRule'] = $discoveryRules[$ruleMap[$itemid]];
                 }
             }
         }
     }
     // add other related objects
     if ($result) {
         $result = $this->addRelatedObjects($options, $result);
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Users data
  *
  * @param array $options
  * @param array $options['nodeids'] filter by Node IDs
  * @param array $options['usrgrpids'] filter by UserGroup IDs
  * @param array $options['userids'] filter by User IDs
  * @param boolean $options['type'] filter by User type [ USER_TYPE_ZABBIX_USER: 1, USER_TYPE_ZABBIX_ADMIN: 2, USER_TYPE_SUPER_ADMIN: 3 ]
  * @param boolean $options['getAccess'] extend with access data for each User
  * @param boolean $options['count'] output only count of objects in result. ( result returned in property 'rowscount' )
  * @param string $options['pattern'] filter by Host name containing only give pattern
  * @param int $options['limit'] output will be limited to given number
  * @param string $options['sortfield'] output will be sorted by given property [ 'userid', 'alias' ]
  * @param string $options['sortorder'] output will be sorted in given order [ 'ASC', 'DESC' ]
  * @return array
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('mediaid', 'userid', 'mediatypeid');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('media' => 'm.mediaid'), 'from' => array('media' => 'media m'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'usrgrpids' => null, 'userids' => null, 'mediaids' => null, 'mediatypeids' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'editable' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['media']);
         $dbTable = DB::getSchema('media');
         $sqlParts['select']['mediaid'] = 'm.mediaid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'm.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // permission check
     if (USER_TYPE_SUPER_ADMIN == $userType) {
     } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) {
         $sqlParts['from']['users_groups'] = 'users_groups ug';
         $sqlParts['where']['mug'] = 'm.userid=ug.userid';
         $sqlParts['where'][] = 'ug.usrgrpid IN (' . ' SELECT uug.usrgrpid' . ' FROM users_groups uug' . ' WHERE uug.userid=' . self::$userData['userid'] . ' )';
     } elseif (!is_null($options['editable']) || self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         $options['userids'] = self::$userData['userid'];
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // mediaids
     if (!is_null($options['mediaids'])) {
         zbx_value2array($options['mediaids']);
         $sqlParts['where'][] = dbConditionInt('m.mediaid', $options['mediaids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('m.mediaid', $nodeids);
         }
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['userid'] = 'u.userid';
         }
         $sqlParts['from']['users'] = 'users u';
         $sqlParts['where'][] = dbConditionInt('u.userid', $options['userids']);
         $sqlParts['where']['mu'] = 'm.userid=u.userid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['userid'] = 'm.userid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('u.userid', $nodeids);
         }
     }
     // usrgrpids
     if (!is_null($options['usrgrpids'])) {
         zbx_value2array($options['usrgrpids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['usrgrpid'] = 'ug.usrgrpid';
         }
         $sqlParts['from']['users_groups'] = 'users_groups ug';
         $sqlParts['where'][] = dbConditionInt('ug.usrgrpid', $options['usrgrpids']);
         $sqlParts['where']['mug'] = 'm.userid=ug.userid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['usrgrpid'] = 'ug.usrgrpid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('ug.usrgrpid', $nodeids);
         }
     }
     // mediatypeids
     if (!is_null($options['mediatypeids'])) {
         zbx_value2array($options['mediatypeids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediatypeid'] = 'm.mediatypeid';
         }
         $sqlParts['where'][] = dbConditionInt('m.mediatypeid', $options['mediatypeids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['mediatypeid'] = 'm.mediatypeid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('m.mediatypeid', $nodeids);
         }
     }
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('m.mediaid', $nodeids);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('media m', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         if ($options['search']['passwd']) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('It is not possible to search by user password.'));
         }
         zbx_db_search('media m', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['media'] = 'm.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT m.mediaid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'm');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $mediaids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($media = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $media;
             } else {
                 $result = $media['rowscount'];
             }
         } else {
             $mediaids[$media['mediaid']] = $media['mediaid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$media['mediaid']] = array('mediaid' => $media['mediaid']);
             } else {
                 if (!isset($result[$media['mediaid']])) {
                     $result[$media['mediaid']] = array();
                 }
                 $result[$media['mediaid']] += $media;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Media types data
  *
  * @param array $options
  * @param array $options['nodeids'] filter by Node IDs
  * @param array $options['mediatypeids'] filter by Mediatype IDs
  * @param boolean $options['type'] filter by Mediatype type [ USER_TYPE_ZABBIX_USER: 1, USER_TYPE_ZABBIX_ADMIN: 2, USER_TYPE_SUPER_ADMIN: 3 ]
  * @param boolean $options['output'] output only Mediatype IDs if not set.
  * @param boolean $options['count'] output only count of objects in result. ( result returned in property 'rowscount' )
  * @param string $options['pattern'] filter by Host name containing only give pattern
  * @param int $options['limit'] output will be limited to given number
  * @param string $options['sortfield'] output will be sorted by given property [ 'mediatypeid', 'alias' ]
  * @param string $options['sortorder'] output will be sorted in given order [ 'ASC', 'DESC' ]
  * @return array
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('mediatypeid');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('media_type' => 'mt.mediatypeid'), 'from' => array('media_type' => 'media_type mt'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'mediatypeids' => null, 'mediaids' => null, 'userids' => null, 'editable' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectUsers' => null, 'selectMedias' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // permission check
     if (USER_TYPE_SUPER_ADMIN == $userType) {
     } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) {
     } elseif (!is_null($options['editable']) || self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         return array();
     }
     // output
     $sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // mediatypeids
     if (!is_null($options['mediatypeids'])) {
         zbx_value2array($options['mediatypeids']);
         $sqlParts['where'][] = dbConditionInt('mt.mediatypeid', $options['mediatypeids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('mt.mediatypeid', $nodeids);
         }
     }
     // mediaids
     if (!is_null($options['mediaids'])) {
         zbx_value2array($options['mediaids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediaid'] = 'm.mediaid';
         }
         $sqlParts['from']['media'] = 'media m';
         $sqlParts['where'][] = dbConditionInt('m.mediaid', $options['mediaids']);
         $sqlParts['where']['mmt'] = 'm.mediatypeid=mt.mediatypeid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('m.mediaid', $nodeids);
         }
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['userid'] = 'm.userid';
         }
         $sqlParts['from']['media'] = 'media m';
         $sqlParts['where'][] = dbConditionInt('m.userid', $options['userids']);
         $sqlParts['where']['mmt'] = 'm.mediatypeid=mt.mediatypeid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('m.userid', $nodeids);
         }
     }
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('mt.mediatypeid', $nodeids);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('media_type mt', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('media_type mt', $options, $sqlParts);
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'mt');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $mediatypeids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($mediatype = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $mediatype;
             } else {
                 $result = $mediatype['rowscount'];
             }
         } else {
             $mediatypeids[$mediatype['mediatypeid']] = $mediatype['mediatypeid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$mediatype['mediatypeid']] = array('mediatypeid' => $mediatype['mediatypeid']);
             } else {
                 if (!isset($result[$mediatype['mediatypeid']])) {
                     $result[$mediatype['mediatypeid']] = array();
                 }
                 // mediaids
                 if (isset($mediatype['mediaid']) && is_null($options['selectMedias'])) {
                     if (!isset($result[$mediatype['mediatypeid']]['medias'])) {
                         $result[$mediatype['mediatypeid']]['medias'] = array();
                     }
                     $result[$mediatype['mediatypeid']]['medias'][] = array('mediaid' => $mediatype['mediaid']);
                     unset($mediatype['mediaid']);
                 }
                 // userids
                 if (isset($mediatype['userid']) && is_null($options['selectUsers'])) {
                     if (!isset($result[$mediatype['mediatypeid']]['users'])) {
                         $result[$mediatype['mediatypeid']]['users'] = array();
                     }
                     $result[$mediatype['mediatypeid']]['users'][] = array('userid' => $mediatype['userid']);
                     unset($mediatype['userid']);
                 }
                 $result[$mediatype['mediatypeid']] += $mediatype;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding users
     if (!is_null($options['selectUsers']) && str_in_array($options['selectUsers'], $subselectsAllowedOutputs)) {
         $users = API::User()->get(array('output' => $options['selectUsers'], 'mediatypeids' => $mediatypeids, 'preservekeys' => true));
         foreach ($users as $user) {
             $umediatypes = $user['mediatypes'];
             unset($user['mediatypes']);
             foreach ($umediatypes as $mediatype) {
                 $result[$mediatype['mediatypeid']]['users'][] = $user;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Template data
  *
  * @param array $options
  * @return array|boolean Template data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('hostid', 'host', 'name');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('templates' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array('h.status=' . HOST_STATUS_TEMPLATE), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'parentTemplateids' => null, 'hostids' => null, 'graphids' => null, 'itemids' => null, 'triggerids' => null, 'with_items' => null, 'with_triggers' => null, 'with_graphs' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => '', 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectHosts' => null, 'selectTemplates' => null, 'selectParentTemplates' => null, 'selectItems' => null, 'selectDiscoveries' => null, 'selectTriggers' => null, 'selectGraphs' => null, 'selectApplications' => null, 'selectMacros' => null, 'selectScreens' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['templates']);
         $dbTable = DB::getSchema('hosts');
         $sqlParts['select']['hostid'] = 'h.hostid';
         foreach ($options['output'] as $field) {
             if ($field == 'templateid') {
                 continue;
             }
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'h.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE h.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.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) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']);
         $sqlParts['where']['hgh'] = 'hg.hostid=h.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['hg'] = 'hg.groupid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('hg.groupid', $nodeids);
         }
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         $sqlParts['where']['templateid'] = dbConditionInt('h.hostid', $options['templateids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('h.hostid', $nodeids);
         }
     }
     // parentTemplateids
     if (!is_null($options['parentTemplateids'])) {
         zbx_value2array($options['parentTemplateids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['parentTemplateid'] = 'ht.templateid as parentTemplateid';
         }
         $sqlParts['from']['hosts_templates'] = 'hosts_templates ht';
         $sqlParts['where'][] = dbConditionInt('ht.templateid', $options['parentTemplateids']);
         $sqlParts['where']['hht'] = 'h.hostid=ht.hostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['templateid'] = 'ht.templateid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('ht.templateid', $nodeids);
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['linked_hostid'] = 'ht.hostid as linked_hostid';
         }
         $sqlParts['from']['hosts_templates'] = 'hosts_templates ht';
         $sqlParts['where'][] = dbConditionInt('ht.hostid', $options['hostids']);
         $sqlParts['where']['hht'] = 'h.hostid=ht.templateid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['ht'] = 'ht.hostid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('ht.hostid', $nodeids);
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'i.itemid';
         }
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('i.itemid', $options['itemids']);
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('i.itemid', $nodeids);
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['triggerid'] = 'f.triggerid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('f.triggerid', $nodeids);
         }
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['graphid'] = 'gi.graphid';
         }
         $sqlParts['from']['graphs_items'] = 'graphs_items gi';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']);
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('gi.graphid', $nodeids);
         }
     }
     // node check !!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $sqlParts['where'][] = DBin_node('h.hostid', $nodeids);
     }
     // with_items
     if (!is_null($options['with_items'])) {
         $sqlParts['where'][] = 'EXISTS (SELECT NULL FROM items i WHERE h.hostid=i.hostid )';
     }
     // with_triggers
     if (!is_null($options['with_triggers'])) {
         $sqlParts['where'][] = 'EXISTS(' . 'SELECT NULL' . ' FROM items i,functions f,triggers t' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid)';
     }
     // with_graphs
     if (!is_null($options['with_graphs'])) {
         $sqlParts['where'][] = 'EXISTS(' . 'SELECT NULL' . ' FROM items i,graphs_items gi' . ' WHERE i.hostid=h.hostid' . ' AND i.itemid=gi.itemid)';
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('hosts h', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('hosts h', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['templates'] = 'h.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT h.hostid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'h');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     //-------------
     $templateids = array();
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
     while ($template = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $template;
             } else {
                 $result = $template['rowscount'];
             }
         } else {
             $template['templateid'] = $template['hostid'];
             $templateids[$template['templateid']] = $template['templateid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$template['templateid']] = array('templateid' => $template['templateid']);
             } else {
                 if (!isset($result[$template['templateid']])) {
                     $result[$template['templateid']] = array();
                 }
                 if (!is_null($options['selectGroups']) && !isset($result[$template['templateid']]['groups'])) {
                     $template['groups'] = array();
                 }
                 if (!is_null($options['selectTemplates']) && !isset($result[$template['templateid']]['templates'])) {
                     $template['templates'] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$template['templateid']]['hosts'])) {
                     $template['hosts'] = array();
                 }
                 if (!is_null($options['selectParentTemplates']) && !isset($result[$template['templateid']]['parentTemplates'])) {
                     $template['parentTemplates'] = array();
                 }
                 if (!is_null($options['selectItems']) && !isset($result[$template['templateid']]['items'])) {
                     $template['items'] = array();
                 }
                 if (!is_null($options['selectDiscoveries']) && !isset($result[$template['hostid']]['discoveries'])) {
                     $result[$template['hostid']]['discoveries'] = array();
                 }
                 if (!is_null($options['selectTriggers']) && !isset($result[$template['templateid']]['triggers'])) {
                     $template['triggers'] = array();
                 }
                 if (!is_null($options['selectGraphs']) && !isset($result[$template['templateid']]['graphs'])) {
                     $template['graphs'] = array();
                 }
                 if (!is_null($options['selectApplications']) && !isset($result[$template['templateid']]['applications'])) {
                     $template['applications'] = array();
                 }
                 if (!is_null($options['selectMacros']) && !isset($result[$template['templateid']]['macros'])) {
                     $template['macros'] = array();
                 }
                 if (!is_null($options['selectScreens']) && !isset($result[$template['templateid']]['screens'])) {
                     $template['screens'] = array();
                 }
                 // groupids
                 if (isset($template['groupid']) && is_null($options['selectGroups'])) {
                     if (!isset($result[$template['templateid']]['groups'])) {
                         $result[$template['templateid']]['groups'] = array();
                     }
                     $result[$template['templateid']]['groups'][] = array('groupid' => $template['groupid']);
                     unset($template['groupid']);
                 }
                 // hostids
                 if (isset($template['linked_hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$template['templateid']]['hosts'])) {
                         $result[$template['templateid']]['hosts'] = array();
                     }
                     $result[$template['templateid']]['hosts'][] = array('hostid' => $template['linked_hostid']);
                     unset($template['linked_hostid']);
                 }
                 // parentTemplateids
                 if (isset($template['parentTemplateid']) && is_null($options['selectParentTemplates'])) {
                     if (!isset($result[$template['templateid']]['parentTemplates'])) {
                         $result[$template['templateid']]['parentTemplates'] = array();
                     }
                     $result[$template['templateid']]['parentTemplates'][] = array('templateid' => $template['parentTemplateid']);
                     unset($template['parentTemplateid']);
                 }
                 // itemids
                 if (isset($template['itemid']) && is_null($options['selectItems'])) {
                     if (!isset($result[$template['templateid']]['items'])) {
                         $result[$template['templateid']]['items'] = array();
                     }
                     $result[$template['templateid']]['items'][] = array('itemid' => $template['itemid']);
                     unset($template['itemid']);
                 }
                 // triggerids
                 if (isset($template['triggerid']) && is_null($options['selectTriggers'])) {
                     if (!isset($result[$template['hostid']]['triggers'])) {
                         $result[$template['hostid']]['triggers'] = array();
                     }
                     $result[$template['hostid']]['triggers'][] = array('triggerid' => $template['triggerid']);
                     unset($template['triggerid']);
                 }
                 // graphids
                 if (isset($template['graphid']) && is_null($options['selectGraphs'])) {
                     if (!isset($result[$template['templateid']]['graphs'])) {
                         $result[$template['templateid']]['graphs'] = array();
                     }
                     $result[$template['templateid']]['graphs'][] = array('graphid' => $template['graphid']);
                     unset($template['graphid']);
                 }
                 $result[$template['templateid']] += $template;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // Adding Objects
     // Adding Groups
     if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) {
         $objParams = array('nodeids' => $nodeids, 'output' => $options['selectGroups'], 'hostids' => $templateids, 'preservekeys' => 1);
         $groups = API::HostGroup()->get($objParams);
         foreach ($groups as $groupid => $group) {
             $ghosts = $group['hosts'];
             unset($group['hosts']);
             foreach ($ghosts as $hnum => $template) {
                 $result[$template['hostid']]['groups'][] = $group;
             }
         }
     }
     // Adding Templates
     if (!is_null($options['selectTemplates'])) {
         $objParams = array('nodeids' => $nodeids, 'parentTemplateids' => $templateids, 'preservekeys' => 1);
         if (is_array($options['selectTemplates']) || str_in_array($options['selectTemplates'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectTemplates'];
             $templates = API::Template()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($templates, 'host');
             }
             foreach ($templates as $templateid => $template) {
                 unset($templates[$templateid]['parentTemplates']);
                 if (isset($template['parentTemplates']) && is_array($template['parentTemplates'])) {
                     $count = array();
                     foreach ($template['parentTemplates'] as $parentTemplate) {
                         if (!is_null($options['limitSelects'])) {
                             if (!isset($count[$parentTemplate['templateid']])) {
                                 $count[$parentTemplate['templateid']] = 0;
                             }
                             $count[$parentTemplate['hostid']]++;
                             if ($count[$parentTemplate['templateid']] > $options['limitSelects']) {
                                 continue;
                             }
                         }
                         $result[$parentTemplate['templateid']]['templates'][] =& $templates[$templateid];
                     }
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectTemplates']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $templates = API::Template()->get($objParams);
             $templates = zbx_toHash($templates, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($templates[$groupid])) {
                     $result[$templateid]['templates'] = $templates[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['templates'] = 0;
                 }
             }
         }
     }
     // Adding Hosts
     if (!is_null($options['selectHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'templateids' => $templateids, 'preservekeys' => 1);
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectHosts'];
             $hosts = API::Host()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($hosts, 'host');
             }
             foreach ($hosts as $hostid => $host) {
                 unset($hosts[$hostid]['templates']);
                 foreach ($host['templates'] as $tnum => $template) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$template['templateid']])) {
                             $count[$template['templateid']] = 0;
                         }
                         $count[$template['templateid']]++;
                         if ($count[$template['templateid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$template['templateid']]['hosts'][] =& $hosts[$hostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $hosts = API::Host()->get($objParams);
             $hosts = zbx_toHash($hosts, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($hosts[$templateid])) {
                     $result[$templateid]['hosts'] = $hosts[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['hosts'] = 0;
                 }
             }
         }
     }
     // Adding parentTemplates
     if (!is_null($options['selectParentTemplates'])) {
         $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => 1);
         if (is_array($options['selectParentTemplates']) || str_in_array($options['selectParentTemplates'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectParentTemplates'];
             $templates = API::Template()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($templates, 'host');
             }
             foreach ($templates as $templateid => $template) {
                 unset($templates[$templateid]['hosts']);
                 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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectTemplates']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $templates = API::Template()->get($objParams);
             $templates = zbx_toHash($templates, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($templates[$groupid])) {
                     $result[$templateid]['parentTemplates'] = $templates[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['parentTemplates'] = 0;
                 }
             }
         }
     }
     // Adding Items
     if (!is_null($options['selectItems'])) {
         $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectItems'];
             $items = API::Item()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($items, 'name');
             }
             $count = array();
             foreach ($items as $itemid => $item) {
                 if (!is_null($options['limitSelects'])) {
                     if (!isset($count[$item['hostid']])) {
                         $count[$item['hostid']] = 0;
                     }
                     $count[$item['hostid']]++;
                     if ($count[$item['hostid']] > $options['limitSelects']) {
                         continue;
                     }
                 }
                 $result[$item['hostid']]['items'][] =& $items[$itemid];
             }
         } elseif (API_OUTPUT_COUNT == $options['selectItems']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $items = API::Item()->get($objParams);
             $items = zbx_toHash($items, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($items[$templateid])) {
                     $result[$templateid]['items'] = $items[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['items'] = 0;
                 }
             }
         }
     }
     // Adding Discoveries
     if (!is_null($options['selectDiscoveries'])) {
         $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['selectDiscoveries']) || str_in_array($options['selectDiscoveries'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDiscoveries'];
             $items = API::DiscoveryRule()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($items, 'name');
             }
             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']]['discoveries'][] =& $items[$itemid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectDiscoveries']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $items = API::DiscoveryRule()->get($objParams);
             $items = zbx_toHash($items, 'hostid');
             foreach ($result as $hostid => $host) {
                 if (isset($items[$hostid])) {
                     $result[$hostid]['discoveries'] = $items[$hostid]['rowscount'];
                 } else {
                     $result[$hostid]['discoveries'] = 0;
                 }
             }
         }
     }
     // Adding triggers
     if (!is_null($options['selectTriggers'])) {
         if (is_array($options['selectTriggers']) || str_in_array($options['selectTriggers'], $subselectsAllowedOutputs)) {
             $triggers = API::Trigger()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => true, 'output' => $options['selectTriggers']));
             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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectTriggers']) {
             $triggers = API::Trigger()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'countOutput' => true, 'groupCount' => true));
             $triggers = zbx_toHash($triggers, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($triggers[$templateid])) {
                     $result[$templateid]['triggers'] = $triggers[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['triggers'] = 0;
                 }
             }
         }
     }
     // Adding graphs
     if (!is_null($options['selectGraphs'])) {
         if (is_array($options['selectGraphs']) || str_in_array($options['selectGraphs'], $subselectsAllowedOutputs)) {
             $graphs = API::Graph()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'preservekeys' => true, 'output' => $options['selectGraphs']));
             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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectGraphs']) {
             $graphs = API::Graph()->get(array('nodeids' => $nodeids, 'hostids' => $templateids, 'countOutput' => true, 'groupCount' => true));
             $graphs = zbx_toHash($graphs, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($graphs[$templateid])) {
                     $result[$templateid]['graphs'] = $graphs[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['graphs'] = 0;
                 }
             }
         }
     }
     // Adding applications
     if (!is_null($options['selectApplications'])) {
         $objParams = array('nodeids' => $nodeids, 'hostids' => $templateids, 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['selectApplications']) || str_in_array($options['selectApplications'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectApplications'];
             $applications = API::Application()->get($objParams);
             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];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectApplications']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $applications = API::Application()->get($objParams);
             $applications = zbx_toHash($applications, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($applications[$templateid])) {
                     $result[$templateid]['applications'] = $applications[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['applications'] = 0;
                 }
             }
         }
     }
     // Adding screens
     if (!is_null($options['selectScreens'])) {
         $objParams = array('nodeids' => $nodeids, 'templateids' => $templateids, 'editable' => $options['editable'], 'nopermissions' => 1, 'preservekeys' => 1);
         if (is_array($options['selectScreens']) || str_in_array($options['selectScreens'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectScreens'];
             $screens = API::TemplateScreen()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($screens, 'name');
             }
             foreach ($screens as $screenid => $screen) {
                 if (!is_null($options['limitSelects'])) {
                     if (count($result[$screen['hostid']]['screens']) >= $options['limitSelects']) {
                         continue;
                     }
                 }
                 unset($screens[$screenid]['templates']);
                 $result[$screen['hostid']]['screens'][] =& $screens[$screenid];
             }
         } elseif (API_OUTPUT_COUNT == $options['selectScreens']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $screens = API::TemplateScreen()->get($objParams);
             $screens = zbx_toHash($screens, 'hostid');
             foreach ($result as $templateid => $template) {
                 if (isset($screens[$templateid])) {
                     $result[$templateid]['screens'] = $screens[$templateid]['rowscount'];
                 } else {
                     $result[$templateid]['screens'] = 0;
                 }
             }
         }
     }
     // Adding macros
     if (!is_null($options['selectMacros']) && str_in_array($options['selectMacros'], $subselectsAllowedOutputs)) {
         $objParams = array('nodeids' => $nodeids, 'output' => $options['selectMacros'], 'hostids' => $templateids, 'preservekeys' => 1);
         $macros = API::UserMacro()->get($objParams);
         foreach ($macros as $macroid => $macro) {
             unset($macros[$macroid]['hosts']);
             foreach ($macro['hosts'] as $hnum => $host) {
                 $result[$host['hostid']]['macros'][] = $macros[$macroid];
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 22
0
 /**
  * Get Alerts data.
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['alertids']
  * @param array $options['applicationids']
  * @param array $options['status']
  * @param array $options['editable']
  * @param array $options['extendoutput']
  * @param array $options['count']
  * @param array $options['pattern']
  * @param array $options['limit']
  * @param array $options['order']
  *
  * @return array|int item data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('alertid', 'clock', 'eventid', 'status');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('alerts' => 'a.alertid'), 'from' => array('alerts' => 'alerts a'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'alertids' => null, 'triggerids' => null, 'eventids' => null, 'actionids' => null, 'mediatypeids' => null, 'userids' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'time_from' => null, 'time_till' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectMediatypes' => null, 'selectUsers' => null, 'selectHosts' => null, 'countOutput' => null, 'preservekeys' => null, 'editable' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['alerts']);
         $dbTable = DB::getSchema('alerts');
         $sqlParts['select']['alertid'] = 'a.alertid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'a.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM events e,functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE a.eventid=e.eventid' . ' AND e.objectid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' AND e.object=' . EVENT_OBJECT_TRIGGER . ' GROUP BY e.eventid' . ' HAVING MIN(r.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) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sqlParts['where']['e'] = 'e.object=' . EVENT_OBJECT_TRIGGER;
         $sqlParts['where']['ef'] = 'e.objectid=f.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['hg'] = dbConditionInt('hg.groupid', $options['groupids']);
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostid'] = 'i.hostid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']);
         $sqlParts['where']['e'] = 'e.object=' . EVENT_OBJECT_TRIGGER;
         $sqlParts['where']['ef'] = 'e.objectid=f.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // alertids
     if (!is_null($options['alertids'])) {
         zbx_value2array($options['alertids']);
         $sqlParts['where'][] = dbConditionInt('a.alertid', $options['alertids']);
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['actionid'] = 'a.actionid';
         }
         $sqlParts['where']['ae'] = 'a.eventid=e.eventid';
         $sqlParts['where']['e'] = 'e.object=' . EVENT_OBJECT_TRIGGER;
         $sqlParts['where'][] = dbConditionInt('e.objectid', $options['triggerids']);
     }
     // eventids
     if (!is_null($options['eventids'])) {
         zbx_value2array($options['eventids']);
         $sqlParts['where'][] = dbConditionInt('a.eventid', $options['eventids']);
     }
     // actionids
     if (!is_null($options['actionids'])) {
         zbx_value2array($options['actionids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['actionid'] = 'a.actionid';
         }
         $sqlParts['where'][] = dbConditionInt('a.actionid', $options['actionids']);
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         $field = 'a.userid';
         if (!is_null($options['time_from']) || !is_null($options['time_till'])) {
             $field = '(a.userid+0)';
         }
         $sqlParts['where'][] = dbConditionInt($field, $options['userids']);
     }
     // mediatypeids
     if (!is_null($options['mediatypeids'])) {
         zbx_value2array($options['mediatypeids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['mediatypeid'] = 'a.mediatypeid';
         }
         $sqlParts['where'][] = dbConditionInt('a.mediatypeid', $options['mediatypeids']);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('alerts a', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('alerts a', $options, $sqlParts);
     }
     // time_from
     if (!is_null($options['time_from'])) {
         $sqlParts['where'][] = 'a.clock>' . zbx_dbstr($options['time_from']);
     }
     // time_till
     if (!is_null($options['time_till'])) {
         $sqlParts['where'][] = 'a.clock<' . zbx_dbstr($options['time_till']);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['alerts'] = 'a.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT a.alertid) AS rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'a');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $alertids = array();
     $userids = array();
     $hostids = array();
     $mediatypeids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('a.alertid', $nodeids) . $sqlWhere . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($alert = DBfetch($dbRes)) {
         if ($options['countOutput']) {
             $result = $alert['rowscount'];
         } else {
             $alertids[$alert['alertid']] = $alert['alertid'];
             if (isset($alert['userid'])) {
                 $userids[$alert['userid']] = $alert['userid'];
             }
             if (isset($alert['hostid'])) {
                 $hostids[$alert['hostid']] = $alert['hostid'];
             }
             if (isset($alert['mediatypeid'])) {
                 $mediatypeids[$alert['mediatypeid']] = $alert['mediatypeid'];
             }
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$alert['alertid']] = array('alertid' => $alert['alertid']);
             } else {
                 if (!isset($result[$alert['alertid']])) {
                     $result[$alert['alertid']] = array();
                 }
                 if (!is_null($options['selectMediatypes']) && !isset($result[$alert['alertid']]['mediatypes'])) {
                     $result[$alert['alertid']]['mediatypes'] = array();
                 }
                 if (!is_null($options['selectUsers']) && !isset($result[$alert['alertid']]['users'])) {
                     $result[$alert['alertid']]['users'] = array();
                 }
                 // hostids
                 if (isset($alert['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$alert['alertid']]['hosts'])) {
                         $result[$alert['alertid']]['hosts'] = array();
                     }
                     $result[$alert['alertid']]['hosts'][] = array('hostid' => $alert['hostid']);
                 }
                 // userids
                 if (isset($alert['userid']) && is_null($options['selectUsers'])) {
                     if (!isset($result[$alert['alertid']]['users'])) {
                         $result[$alert['alertid']]['users'] = array();
                     }
                     $result[$alert['alertid']]['users'][] = array('userid' => $alert['userid']);
                 }
                 // mediatypeids
                 if (isset($alert['mediatypeid']) && is_null($options['selectMediatypes'])) {
                     if (!isset($result[$alert['alertid']]['mediatypes'])) {
                         $result[$alert['alertid']]['mediatypes'] = array();
                     }
                     $result[$alert['alertid']]['mediatypes'][] = array('mediatypeid' => $alert['mediatypeid']);
                 }
                 $result[$alert['alertid']] += $alert;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     $hosts = array();
     $users = array();
     $mediatypes = array();
     // adding hosts
     if (!is_null($options['selectHosts']) && str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
         $hosts = API::Host()->get(array('output' => $options['selectHosts'], 'hostids' => $hostids, 'preservekeys' => true));
     }
     // adding users
     if (!is_null($options['selectUsers']) && str_in_array($options['selectUsers'], $subselectsAllowedOutputs)) {
         $users = API::User()->get(array('output' => $options['selectUsers'], 'userids' => $userids, 'preservekeys' => true));
     }
     // adding mediatypes
     if (!is_null($options['selectMediatypes']) && str_in_array($options['selectMediatypes'], $subselectsAllowedOutputs)) {
         $res = DBselect('SELECT mt.* FROM media_type mt WHERE ' . dbConditionInt('mt.mediatypeid', $mediatypeids));
         while ($media = DBfetch($res)) {
             $mediatypes[$media['mediatypeid']] = $media;
         }
     }
     foreach ($result as $alertid => $alert) {
         if (isset($alert['hostid']) && isset($hosts[$alert['hostid']])) {
             $result[$alertid]['hosts'][] = $hosts[$alert['hostid']];
         }
         if (isset($mediatypes[$alert['mediatypeid']])) {
             $result[$alertid]['mediatypes'][] = $mediatypes[$alert['mediatypeid']];
         }
         if (isset($users[$alert['userid']])) {
             $result[$alertid]['users'][] = $users[$alert['userid']];
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get IconMap data.
  * @param array $options
  * @param array $options['nodeids']
  * @param array $options['iconmapids']
  * @param array $options['sysmapids']
  * @param array $options['editable']
  * @param array $options['count']
  * @param array $options['limit']
  * @param array $options['order']
  * @return array
  */
 public function get(array $options = array())
 {
     $result = array();
     // allowed columns for sorting
     $sortColumns = array('iconmapid', 'name');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('icon_map' => 'im.iconmapid'), 'from' => array('icon_map' => 'icon_map im'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'iconmapids' => null, 'sysmapids' => null, 'nopermissions' => null, 'editable' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectMappings' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         $dbTable = DB::getSchema('icon_map');
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'im.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($options['editable'] && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         return array();
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // iconmapids
     if (!is_null($options['iconmapids'])) {
         zbx_value2array($options['iconmapids']);
         $sqlParts['where'][] = dbConditionInt('im.iconmapid', $options['iconmapids']);
     }
     // sysmapids
     if (!is_null($options['sysmapids'])) {
         zbx_value2array($options['sysmapids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['sysmapids'] = 's.sysmapid';
         }
         $sqlParts['from']['sysmaps'] = 'sysmaps s';
         $sqlParts['where'][] = dbConditionInt('s.sysmapid', $options['sysmapids']);
         $sqlParts['where']['ims'] = 'im.iconmapid=s.iconmapid';
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('icon_map im', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('icon_map im', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['icon_map'] = 'im.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT im.iconmapid) AS rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'im');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $iconMapids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('im.iconmapid', $nodeids) . $sqlWhere . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($iconMap = DBfetch($dbRes)) {
         if ($options['countOutput']) {
             $result = $iconMap['rowscount'];
         } else {
             $iconMapids[$iconMap['iconmapid']] = $iconMap['iconmapid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$iconMap['iconmapid']] = array('iconmapid' => $iconMap['iconmapid']);
             } else {
                 if (!isset($result[$iconMap['iconmapid']])) {
                     $result[$iconMap['iconmapid']] = array();
                 }
                 if (isset($iconMap['sysmapid'])) {
                     if (!isset($result[$iconMap['iconmapid']]['sysmaps'])) {
                         $result[$iconMap['iconmapid']]['sysmaps'] = array();
                     }
                     $result[$iconMap['iconmapid']]['sysmaps'][] = array('sysmapid' => $iconMap['sysmapid']);
                 }
                 if (!is_null($options['selectMappings']) && !isset($result[$iconMap['iconmapid']]['mappings'])) {
                     $result[$iconMap['iconmapid']]['mappings'] = array();
                 }
                 $result[$iconMap['iconmapid']] += $iconMap;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding conditions
     if (!is_null($options['selectMappings']) && str_in_array($options['selectMappings'], $subselectsAllowedOutputs)) {
         $res = DBselect('SELECT imp.* FROM icon_mapping imp WHERE ' . dbConditionInt('imp.iconmapid', $iconMapids));
         while ($mapping = DBfetch($res)) {
             $result[$mapping['iconmapid']]['mappings'][$mapping['iconmappingid']] = $mapping;
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get TriggerPrototypes data
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['triggerids']
  * @param array $options['applicationids']
  * @param array $options['status']
  * @param array $options['editable']
  * @param array $options['count']
  * @param array $options['pattern']
  * @param array $options['limit']
  * @param array $options['order']
  * @return array|int item data as array or false if error
  */
 public function get(array $options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('triggerid', 'description', 'status', 'priority');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('triggers' => 't.triggerid'), 'from' => array('t' => 'triggers t'), 'where' => array('t.flags=' . ZBX_FLAG_DISCOVERY_CHILD), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'triggerids' => null, 'itemids' => null, 'applicationids' => null, 'discoveryids' => null, 'functions' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'active' => null, 'maintenance' => null, 'nopermissions' => null, 'editable' => null, 'group' => null, 'host' => null, 'min_severity' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'expandExpression' => null, 'expandData' => null, 'output' => API_OUTPUT_REFER, 'selectGroups' => null, 'selectHosts' => null, 'selectItems' => null, 'selectFunctions' => null, 'selectDiscoveryRule' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['triggers']);
         $dbTable = DB::getSchema('triggers');
         $sqlParts['select']['triggerid'] = 't.triggerid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 't.' . $field;
             }
         }
         // ignore the "expandExpression" parameter if the expression is not requested
         if ($options['expandExpression'] !== null && !str_in_array('expression', $options['output'])) {
             $options['expandExpression'] = null;
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + permission check
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM functions f,items i,hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE t.triggerid=f.triggerid' . ' AND f.itemid=i.itemid' . ' AND i.hostid=hgg.hostid' . ' GROUP BY f.triggerid' . ' HAVING MIN(r.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) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['groupid'] = dbConditionInt('hg.groupid', $options['groupids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['hg'] = 'hg.groupid';
         }
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if (!is_null($options['hostids'])) {
             zbx_value2array($options['hostids']);
             $options['hostids'] = array_merge($options['hostids'], $options['templateids']);
         } else {
             $options['hostids'] = $options['templateids'];
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostid'] = 'i.hostid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['hostids']);
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['i'] = 'i.hostid';
         }
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         $sqlParts['where']['triggerid'] = dbConditionInt('t.triggerid', $options['triggerids']);
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'f.itemid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['where']['itemid'] = dbConditionInt('f.itemid', $options['itemids']);
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['f'] = 'f.itemid';
         }
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['applicationid'] = 'a.applicationid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['applications'] = 'applications a';
         $sqlParts['where']['a'] = dbConditionInt('a.applicationid', $options['applicationids']);
         $sqlParts['where']['ia'] = 'i.hostid=a.hostid';
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
     }
     // discoveryids
     if (!is_null($options['discoveryids'])) {
         zbx_value2array($options['discoveryids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'id.parent_itemid';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['item_discovery'] = 'item_discovery id';
         $sqlParts['where']['fid'] = 'f.itemid=id.itemid';
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where'][] = dbConditionInt('id.parent_itemid', $options['discoveryids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['id'] = 'id.parent_itemid';
         }
     }
     // functions
     if (!is_null($options['functions'])) {
         zbx_value2array($options['functions']);
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where'][] = dbConditionString('f.function', $options['functions']);
     }
     // monitored
     if (!is_null($options['monitored'])) {
         $sqlParts['where']['monitored'] = '' . ' NOT EXISTS (' . ' SELECT NULL' . ' FROM functions ff' . ' WHERE ff.triggerid=t.triggerid' . ' AND EXISTS (' . ' SELECT NULL' . ' FROM items ii, hosts hh' . ' WHERE ff.itemid=ii.itemid' . ' AND hh.hostid=ii.hostid' . ' AND (' . ' ii.status<>' . ITEM_STATUS_ACTIVE . ' OR hh.status<>' . HOST_STATUS_MONITORED . ' )' . ' )' . ' )';
         $sqlParts['where']['status'] = 't.status=' . TRIGGER_STATUS_ENABLED;
     }
     // active
     if (!is_null($options['active'])) {
         $sqlParts['where']['active'] = '' . ' NOT EXISTS (' . ' SELECT NULL' . ' FROM functions ff' . ' WHERE ff.triggerid=t.triggerid' . ' AND EXISTS (' . ' SELECT NULL' . ' FROM items ii, hosts hh' . ' WHERE ff.itemid=ii.itemid' . ' AND hh.hostid=ii.hostid' . ' AND  hh.status<>' . HOST_STATUS_MONITORED . ' )' . ' )';
         $sqlParts['where']['status'] = 't.status=' . TRIGGER_STATUS_ENABLED;
     }
     // maintenance
     if (!is_null($options['maintenance'])) {
         $sqlParts['where'][] = ($options['maintenance'] == 0 ? ' NOT ' : '') . ' EXISTS (' . ' SELECT NULL' . ' FROM functions ff' . ' WHERE ff.triggerid=t.triggerid' . ' AND EXISTS (' . ' SELECT NULL' . ' FROM items ii, hosts hh' . ' WHERE ff.itemid=ii.itemid' . ' AND hh.hostid=ii.hostid' . ' AND hh.maintenance_status=1' . ' )' . ' )';
         $sqlParts['where'][] = 't.status=' . TRIGGER_STATUS_ENABLED;
     }
     // templated
     if (!is_null($options['templated'])) {
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['templated']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sqlParts['where'][] = 't.templateid IS NOT NULL';
         } else {
             $sqlParts['where'][] = 't.templateid IS NULL';
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('triggers t', $options, $sqlParts);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('triggers t', $options, $sqlParts);
         if (isset($options['filter']['host']) && !is_null($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sqlParts['from']['functions'] = 'functions f';
             $sqlParts['from']['items'] = 'items i';
             $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
             $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
             $sqlParts['from']['hosts'] = 'hosts h';
             $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
             $sqlParts['where']['host'] = dbConditionString('h.host', $options['filter']['host']);
         }
         if (isset($options['filter']['hostid']) && !is_null($options['filter']['hostid'])) {
             zbx_value2array($options['filter']['hostid']);
             $sqlParts['from']['functions'] = 'functions f';
             $sqlParts['from']['items'] = 'items i';
             $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
             $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
             $sqlParts['where']['hostid'] = dbConditionInt('i.hostid', $options['filter']['hostid']);
         }
     }
     // group
     if (!is_null($options['group'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['name'] = 'g.name';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['from']['groups'] = 'groups g';
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sqlParts['where']['ghg'] = 'g.groupid = hg.groupid';
         $sqlParts['where']['group'] = ' g.name=' . zbx_dbstr($options['group']);
     }
     // host
     if (!is_null($options['host'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['host'] = 'h.host';
         }
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']);
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
         $sqlParts['where']['host'] = ' h.host=' . zbx_dbstr($options['host']);
     }
     // min_severity
     if (!is_null($options['min_severity'])) {
         $sqlParts['where'][] = 't.priority>=' . zbx_dbstr($options['min_severity']);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['triggers'] = 't.*';
     }
     // expandData
     if (!is_null($options['expandData'])) {
         $sqlParts['select']['host'] = 'h.host';
         $sqlParts['select']['hostid'] = 'h.hostid';
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['ft'] = 'f.triggerid=t.triggerid';
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['hi'] = 'h.hostid=i.hostid';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT t.triggerid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 't');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $triggerids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('t.triggerid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     while ($trigger = DBfetch($dbRes)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $trigger;
             } else {
                 $result = $trigger['rowscount'];
             }
         } else {
             $triggerids[$trigger['triggerid']] = $trigger['triggerid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$trigger['triggerid']] = array('triggerid' => $trigger['triggerid']);
             } else {
                 if (!isset($result[$trigger['triggerid']])) {
                     $result[$trigger['triggerid']] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$trigger['triggerid']]['hosts'])) {
                     $result[$trigger['triggerid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectItems']) && !isset($result[$trigger['triggerid']]['items'])) {
                     $result[$trigger['triggerid']]['items'] = array();
                 }
                 if (!is_null($options['selectFunctions']) && !isset($result[$trigger['triggerid']]['functions'])) {
                     $result[$trigger['triggerid']]['functions'] = array();
                 }
                 if (!is_null($options['selectDiscoveryRule']) && !isset($result[$trigger['triggerid']]['discoveryRule'])) {
                     $result[$trigger['triggerid']]['discoveryRule'] = array();
                 }
                 // groups
                 if (isset($trigger['groupid']) && is_null($options['selectGroups'])) {
                     if (!isset($result[$trigger['triggerid']]['groups'])) {
                         $result[$trigger['triggerid']]['groups'] = array();
                     }
                     $result[$trigger['triggerid']]['groups'][] = array('groupid' => $trigger['groupid']);
                     unset($trigger['groupid']);
                 }
                 // hostids
                 if (isset($trigger['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$trigger['triggerid']]['hosts'])) {
                         $result[$trigger['triggerid']]['hosts'] = array();
                     }
                     $result[$trigger['triggerid']]['hosts'][] = array('hostid' => $trigger['hostid']);
                     if (is_null($options['expandData'])) {
                         unset($trigger['hostid']);
                     }
                 }
                 // itemids
                 if (isset($trigger['itemid']) && is_null($options['selectItems'])) {
                     if (!isset($result[$trigger['triggerid']]['items'])) {
                         $result[$trigger['triggerid']]['items'] = array();
                     }
                     $result[$trigger['triggerid']]['items'][] = array('itemid' => $trigger['itemid']);
                     unset($trigger['itemid']);
                 }
                 // expand expression
                 if ($options['expandExpression'] !== null && $trigger['expression']) {
                     $trigger['expression'] = explode_exp($trigger['expression'], false, true);
                 }
                 $result[$trigger['triggerid']] += $trigger;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding groups
     if (!is_null($options['selectGroups']) && str_in_array($options['selectGroups'], $subselectsAllowedOutputs)) {
         $groups = API::HostGroup()->get(array('nodeids' => $nodeids, 'output' => $options['selectGroups'], 'triggerids' => $triggerids, 'preservekeys' => true));
         foreach ($groups as $group) {
             $gtriggers = $group['triggers'];
             unset($group['triggers']);
             foreach ($gtriggers as $trigger) {
                 $result[$trigger['triggerid']]['groups'][] = $group;
             }
         }
     }
     // adding hosts
     if (!is_null($options['selectHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'triggerids' => $triggerids, 'templated_hosts' => 1, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectHosts'];
             $hosts = API::Host()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($hosts, 'host');
             }
             foreach ($hosts as $hostid => $host) {
                 unset($hosts[$hostid]['triggers']);
                 $count = array();
                 foreach ($host['triggers'] as $trigger) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$trigger['triggerid']])) {
                             $count[$trigger['triggerid']] = 0;
                         }
                         $count[$trigger['triggerid']]++;
                         if ($count[$trigger['triggerid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$trigger['triggerid']]['hosts'][] =& $hosts[$hostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $hosts = API::Host()->get($objParams);
             $hosts = zbx_toHash($hosts, 'hostid');
             foreach ($result as $triggerid => $trigger) {
                 $result[$triggerid]['hosts'] = isset($hosts[$triggerid]) ? $hosts[$triggerid]['rowscount'] : 0;
             }
         }
     }
     // adding functions
     if (!is_null($options['selectFunctions']) && str_in_array($options['selectFunctions'], $subselectsAllowedOutputs)) {
         $sqlSelect = $options['selectFunctions'] == API_OUTPUT_EXTEND ? 'f.*' : 'f.functionid, f.triggerid';
         $res = DBselect('SELECT ' . $sqlSelect . ' FROM functions f' . ' WHERE ' . dbConditionInt('f.triggerid', $triggerids));
         while ($function = DBfetch($res)) {
             $triggerid = $function['triggerid'];
             unset($function['triggerid']);
             $result[$triggerid]['functions'][] = $function;
         }
     }
     // adding items
     if (!is_null($options['selectItems']) && (is_array($options['selectItems']) || str_in_array($options['selectItems'], $subselectsAllowedOutputs))) {
         $items = API::Item()->get(array('nodeids' => $nodeids, 'output' => $options['selectItems'], 'triggerids' => $triggerids, 'webitems' => true, 'nopermissions' => true, 'preservekeys' => true, 'filter' => array('flags' => null)));
         foreach ($items as $item) {
             $itriggers = $item['triggers'];
             unset($item['triggers']);
             foreach ($itriggers as $trigger) {
                 $result[$trigger['triggerid']]['items'][] = $item;
             }
         }
     }
     // adding discoveryrule
     if (!is_null($options['selectDiscoveryRule'])) {
         $ruleids = $ruleMap = array();
         $dbRules = DBselect('SELECT id.parent_itemid,f.triggerid' . ' FROM item_discovery id,functions f' . ' WHERE ' . dbConditionInt('f.triggerid', $triggerids) . ' AND f.itemid=id.itemid');
         while ($rule = DBfetch($dbRules)) {
             $ruleids[$rule['parent_itemid']] = $rule['parent_itemid'];
             $ruleMap[$rule['triggerid']] = $rule['parent_itemid'];
         }
         $objParams = array('nodeids' => $nodeids, 'itemids' => $ruleids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectDiscoveryRule']) || str_in_array($options['selectDiscoveryRule'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDiscoveryRule'];
             $discoveryRules = API::DiscoveryRule()->get($objParams);
             foreach ($result as $triggerid => $trigger) {
                 if (isset($ruleMap[$triggerid]) && isset($discoveryRules[$ruleMap[$triggerid]])) {
                     $result[$triggerid]['discoveryRule'] = $discoveryRules[$ruleMap[$triggerid]];
                 }
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get history data
  *
  * @param array $options
  * @param array $options['itemids']
  * @param boolean $options['editable']
  * @param string $options['pattern']
  * @param int $options['limit']
  * @param string $options['order']
  * @return array|int item data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = false;
     // allowed columns for sorting
     $sortColumns = array('itemid', 'clock');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('history' => 'h.itemid'), 'from' => array(), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('history' => ITEM_VALUE_TYPE_UINT64, 'nodeids' => null, 'hostids' => null, 'itemids' => null, 'triggerids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'time_from' => null, 'time_till' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'groupCount' => null, 'groupOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     switch ($options['history']) {
         case ITEM_VALUE_TYPE_LOG:
             $sqlParts['from']['history'] = 'history_log h';
             $sortColumns[] = 'id';
             break;
         case ITEM_VALUE_TYPE_TEXT:
             $sqlParts['from']['history'] = 'history_text h';
             $sortColumns[] = 'id';
             break;
         case ITEM_VALUE_TYPE_STR:
             $sqlParts['from']['history'] = 'history_str h';
             break;
         case ITEM_VALUE_TYPE_UINT64:
             $sqlParts['from']['history'] = 'history_uint h';
             break;
         case ITEM_VALUE_TYPE_FLOAT:
         default:
             $sqlParts['from']['history'] = 'history h';
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == self::$userData['type'] || $options['nopermissions']) {
     } else {
         $itemOptions = array('editable' => $options['editable'], 'preservekeys' => true, 'webitems' => true);
         if (!is_null($options['itemids'])) {
             $itemOptions['itemids'] = $options['itemids'];
         }
         $items = API::Item()->get($itemOptions);
         $options['itemids'] = array_keys($items);
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sqlParts['where']['itemid'] = dbConditionInt('h.itemid', $options['itemids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('h.itemid', $nodeids);
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostid'] = 'i.hostid';
         }
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where']['i'] = dbConditionInt('i.hostid', $options['hostids']);
         $sqlParts['where']['hi'] = 'h.itemid=i.itemid';
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('i.hostid', $nodeids);
         }
     }
     // should be last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('h.itemid', $nodeids);
     }
     // time_from
     if (!is_null($options['time_from'])) {
         $sqlParts['select']['clock'] = 'h.clock';
         $sqlParts['where']['clock_from'] = 'h.clock>=' . zbx_dbstr($options['time_from']);
     }
     // time_till
     if (!is_null($options['time_till'])) {
         $sqlParts['select']['clock'] = 'h.clock';
         $sqlParts['where']['clock_till'] = 'h.clock<=' . zbx_dbstr($options['time_till']);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter($sqlParts['from']['history'], $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search($sqlParts['from']['history'], $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         unset($sqlParts['select']['clock']);
         $sqlParts['select']['history'] = 'h.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT h.hostid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // groupOutput
     $groupOutput = false;
     if (!is_null($options['groupOutput'])) {
         if (str_in_array('h.' . $options['groupOutput'], $sqlParts['select']) || str_in_array('h.*', $sqlParts['select'])) {
             $groupOutput = true;
         }
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'h');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $itemids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlOrder;
     $dbRes = DBselect($sql, $sqlLimit);
     $count = 0;
     $group = array();
     while ($data = DBfetch($dbRes)) {
         if ($options['countOutput']) {
             $result = $data;
         } else {
             $itemids[$data['itemid']] = $data['itemid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$count] = array('itemid' => $data['itemid']);
             } else {
                 $result[$count] = array();
                 // hostids
                 if (isset($data['hostid'])) {
                     if (!isset($result[$count]['hosts'])) {
                         $result[$count]['hosts'] = array();
                     }
                     $result[$count]['hosts'][] = array('hostid' => $data['hostid']);
                     unset($data['hostid']);
                 }
                 // triggerids
                 if (isset($data['triggerid'])) {
                     if (!isset($result[$count]['triggers'])) {
                         $result[$count]['triggers'] = array();
                     }
                     $result[$count]['triggers'][] = array('triggerid' => $data['triggerid']);
                     unset($data['triggerid']);
                 }
                 $result[$count] += $data;
                 // grouping
                 if ($groupOutput) {
                     $dataid = $data[$options['groupOutput']];
                     if (!isset($group[$dataid])) {
                         $group[$dataid] = array();
                     }
                     $group[$dataid][] = $result[$count];
                 }
                 $count++;
             }
         }
     }
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get host groups.
  *
  * @param array $params
  *
  * @return array
  */
 public function get($params)
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('groupid', 'name');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('groups' => 'g.groupid'), 'from' => array('groups' => 'groups g'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'hostids' => null, 'templateids' => null, 'graphids' => null, 'triggerids' => null, 'maintenanceids' => null, 'monitored_hosts' => null, 'templated_hosts' => null, 'real_hosts' => null, 'not_proxy_hosts' => null, 'with_hosts_and_templates' => null, 'with_items' => null, 'with_simple_graph_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, 'with_applications' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectHosts' => null, 'selectTemplates' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $params);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['groups']);
         $dbTable = DB::getSchema('groups');
         $sqlParts['select']['groupid'] = 'g.groupid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'g.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM rights r' . ' WHERE g.groupid=r.id' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' GROUP BY r.id' . ' HAVING MIN(r.permission)>=' . $permission . ')';
     }
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         $sqlParts['where']['groupid'] = dbConditionInt('g.groupid', $options['groupids']);
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if (!is_null($options['hostids'])) {
             zbx_value2array($options['hostids']);
             $options['hostids'] = array_merge($options['hostids'], $options['templateids']);
         } else {
             $options['hostids'] = $options['templateids'];
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['hostid'] = 'hg.hostid';
         }
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where'][] = dbConditionInt('hg.hostid', $options['hostids']);
         $sqlParts['where']['hgg'] = 'hg.groupid=g.groupid';
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['triggerid'] = 'f.triggerid';
         }
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['from']['functions'] = 'functions f';
         $sqlParts['from']['items'] = 'items i';
         $sqlParts['where'][] = dbConditionInt('f.triggerid', $options['triggerids']);
         $sqlParts['where']['fi'] = 'f.itemid=i.itemid';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sqlParts['where']['hgg'] = 'hg.groupid=g.groupid';
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['graphid'] = 'gi.graphid';
         }
         $sqlParts['from']['gi'] = 'graphs_items gi';
         $sqlParts['from']['i'] = 'items i';
         $sqlParts['from']['hg'] = 'hosts_groups hg';
         $sqlParts['where'][] = dbConditionInt('gi.graphid', $options['graphids']);
         $sqlParts['where']['hgg'] = 'hg.groupid=g.groupid';
         $sqlParts['where']['igi'] = 'i.itemid=gi.itemid';
         $sqlParts['where']['hgi'] = 'hg.hostid=i.hostid';
     }
     // maintenanceids
     if (!is_null($options['maintenanceids'])) {
         zbx_value2array($options['maintenanceids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['maintenanceid'] = 'mg.maintenanceid';
         }
         $sqlParts['from']['maintenances_groups'] = 'maintenances_groups mg';
         $sqlParts['where'][] = dbConditionInt('mg.maintenanceid', $options['maintenanceids']);
         $sqlParts['where']['hmh'] = 'g.groupid=mg.groupid';
     }
     // monitored_hosts, real_hosts, templated_hosts, not_proxy_hosts, with_hosts_and_templates
     if (!is_null($options['monitored_hosts'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts h' . ' WHERE hg.hostid=h.hostid' . ' AND h.status=' . HOST_STATUS_MONITORED . ')';
     } elseif (!is_null($options['real_hosts'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hgg'] = 'hg.groupid=g.groupid';
         $sqlParts['where'][] = 'h.hostid=hg.hostid';
         $sqlParts['where'][] = 'h.status IN(' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')';
     } elseif (!is_null($options['templated_hosts'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hgg'] = 'hg.groupid=g.groupid';
         $sqlParts['where'][] = 'h.hostid=hg.hostid';
         $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
     } elseif (!is_null($options['not_proxy_hosts'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hgg'] = 'hg.groupid=g.groupid';
         $sqlParts['where'][] = 'h.hostid=hg.hostid';
         $sqlParts['where'][] = 'h.status NOT IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')';
     } elseif (!is_null($options['with_hosts_and_templates'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['hgg'] = 'hg.groupid=g.groupid';
         $sqlParts['where'][] = 'h.hostid=hg.hostid';
         $sqlParts['where'][] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')';
     }
     // with_items, with_monitored_items, with_historical_items, with_simple_graph_items
     if (!is_null($options['with_items'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE hg.hostid=i.hostid' . ')';
     } elseif (!is_null($options['with_monitored_items'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts h' . ' WHERE hg.hostid=i.hostid' . ' AND i.hostid=h.hostid' . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND i.status=' . ITEM_STATUS_ACTIVE . ')';
     } elseif (!is_null($options['with_historical_items'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE hg.hostid=i.hostid' . ' AND i.status IN (' . ITEM_STATUS_ACTIVE . ',' . ITEM_STATUS_NOTSUPPORTED . ')' . ' AND i.lastvalue IS NOT NULL' . ')';
     } elseif (!is_null($options['with_simple_graph_items'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i' . ' WHERE hg.hostid=i.hostid' . ' AND i.value_type IN (' . ITEM_VALUE_TYPE_FLOAT . ',' . ITEM_VALUE_TYPE_UINT64 . ')' . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND i.flags IN (' . ZBX_FLAG_DISCOVERY_NORMAL . ',' . ZBX_FLAG_DISCOVERY_CREATED . ')' . ')';
     }
     // with_triggers, with_monitored_triggers
     if (!is_null($options['with_triggers'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,functions f' . ' WHERE hg.hostid=i.hostid' . ' AND i.itemid=f.itemid' . ')';
     } elseif (!is_null($options['with_monitored_triggers'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,hosts h,functions f,triggers t' . ' WHERE hg.hostid=i.hostid' . ' AND i.hostid=h.hostid' . ' AND i.itemid=f.itemid' . ' AND f.triggerid=t.triggerid' . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND i.status=' . ITEM_STATUS_ACTIVE . ' AND t.status=' . TRIGGER_STATUS_ENABLED . ')';
     }
     // with_httptests, with_monitored_httptests
     if (!is_null($options['with_httptests'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM applications a,httptest ht' . ' WHERE hg.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ')';
     } elseif (!is_null($options['with_monitored_httptests'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts h,applications a,httptest ht' . ' WHERE hg.hostid=h.hostid' . ' AND hg.hostid=a.hostid' . ' AND a.applicationid=ht.applicationid' . ' AND h.status=' . HOST_STATUS_MONITORED . ' AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')';
     }
     // with_graphs
     if (!is_null($options['with_graphs'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM items i,graphs_items gi' . ' WHERE hg.hostid=i.hostid' . ' AND i.itemid=gi.itemid' . ')';
     }
     if (!is_null($options['with_applications'])) {
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['from']['applications'] = 'applications a';
         $sqlParts['where']['hgg'] = 'g.groupid=hg.groupid';
         $sqlParts['where'][] = 'hg.hostid=a.hostid';
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['groups'] = 'g.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('COUNT(DISTINCT g.groupid) AS rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('groups g', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('groups g', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'g');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $groupids = array();
     $sqlParts = $this->applyQueryNodeOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
     $res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
     while ($group = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $group;
             } else {
                 $result = $group['rowscount'];
             }
         } else {
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$group['groupid']] = array('groupid' => $group['groupid']);
             } else {
                 $groupids[$group['groupid']] = $group['groupid'];
                 if (!isset($result[$group['groupid']])) {
                     $result[$group['groupid']] = array();
                 }
                 if (!is_null($options['selectTemplates']) && !isset($result[$group['groupid']]['templates'])) {
                     $result[$group['groupid']]['templates'] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$group['groupid']]['hosts'])) {
                     $result[$group['groupid']]['hosts'] = array();
                 }
                 // hostids
                 if (isset($group['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$group['groupid']]['hosts'])) {
                         $result[$group['groupid']]['hosts'] = array();
                     }
                     $result[$group['groupid']]['hosts'][] = array('hostid' => $group['hostid']);
                     unset($group['hostid']);
                 }
                 // graphids
                 if (isset($group['graphid'])) {
                     if (!isset($result[$group['groupid']]['graphs'])) {
                         $result[$group['groupid']]['graphs'] = array();
                     }
                     $result[$group['groupid']]['graphs'][] = array('graphid' => $group['graphid']);
                     unset($group['graphid']);
                 }
                 // maintenanceids
                 if (isset($group['maintenanceid'])) {
                     if (!isset($result[$group['groupid']]['maintenanceid'])) {
                         $result[$group['groupid']]['maintenances'] = array();
                     }
                     $result[$group['groupid']]['maintenances'][] = array('maintenanceid' => $group['maintenanceid']);
                     unset($group['maintenanceid']);
                 }
                 // triggerids
                 if (isset($group['triggerid'])) {
                     if (!isset($result[$group['groupid']]['triggers'])) {
                         $result[$group['groupid']]['triggers'] = array();
                     }
                     $result[$group['groupid']]['triggers'][] = array('triggerid' => $group['triggerid']);
                     unset($group['triggerid']);
                 }
                 $result[$group['groupid']] += $group;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // adding hosts
     if (!is_null($options['selectHosts'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'groupids' => $groupids, 'preservekeys' => true);
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectHosts'];
             $hosts = API::Host()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($hosts, 'host');
             }
             $count = array();
             foreach ($hosts as $hostid => $host) {
                 $hgroups = $host['groups'];
                 unset($host['groups']);
                 foreach ($hgroups as $group) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$group['groupid']])) {
                             $count[$group['groupid']] = 0;
                         }
                         $count[$group['groupid']]++;
                         if ($count[$group['groupid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$group['groupid']]['hosts'][] = $hosts[$hostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $hosts = API::Host()->get($objParams);
             $hosts = zbx_toHash($hosts, 'groupid');
             foreach ($result as $groupid => $group) {
                 if (isset($hosts[$groupid])) {
                     $result[$groupid]['hosts'] = $hosts[$groupid]['rowscount'];
                 } else {
                     $result[$groupid]['hosts'] = 0;
                 }
             }
         }
     }
     // adding templates
     if (!is_null($options['selectTemplates'])) {
         $objParams = array('nodeids' => $options['nodeids'], 'groupids' => $groupids, 'preservekeys' => true);
         if (is_array($options['selectTemplates']) || str_in_array($options['selectTemplates'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectTemplates'];
             $templates = API::Template()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($templates, 'host');
             }
             $count = array();
             foreach ($templates as $templateid => $template) {
                 $hgroups = $template['groups'];
                 unset($template['groups']);
                 foreach ($hgroups as $group) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$group['groupid']])) {
                             $count[$group['groupid']] = 0;
                         }
                         $count[$group['groupid']]++;
                         if ($count[$group['groupid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$group['groupid']]['templates'][] = $templates[$templateid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectTemplates']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $templates = API::Template()->get($objParams);
             $templates = zbx_toHash($templates, 'groupid');
             foreach ($result as $groupid => $group) {
                 if (isset($templates[$groupid])) {
                     $result[$groupid]['templates'] = $templates[$groupid]['rowscount'];
                 } else {
                     $result[$groupid]['templates'] = 0;
                 }
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Applications data
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['triggerids']
  * @param array $options['applicationids']
  * @param boolean $options['status']
  * @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 function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     $sortColumns = array('applicationid', 'name');
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('apps' => 'a.applicationid'), 'from' => array('applications' => 'applications a'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'itemids' => null, 'applicationids' => null, 'templated' => null, 'editable' => null, 'inherited' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'exludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'expandData' => null, 'selectHosts' => null, 'selectItems' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $userGroups = getUserGroupsByUserId($userid);
         $sqlParts['where'][] = 'EXISTS (' . 'SELECT NULL' . ' FROM hosts_groups hgg' . ' JOIN rights r' . ' ON r.id=hgg.groupid' . ' AND ' . dbConditionInt('r.groupid', $userGroups) . ' WHERE a.hostid=hgg.hostid' . ' GROUP BY hgg.hostid' . ' HAVING MIN(r.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) {
             $sqlParts['select']['groupid'] = 'hg.groupid';
         }
         $sqlParts['from']['hosts_groups'] = 'hosts_groups hg';
         $sqlParts['where']['ahg'] = 'a.hostid=hg.hostid';
         $sqlParts['where'][] = dbConditionInt('hg.groupid', $options['groupids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['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) {
             $sqlParts['select']['hostid'] = 'a.hostid';
         }
         $sqlParts['where']['hostid'] = dbConditionInt('a.hostid', $options['hostids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['hostid'] = 'a.hostid';
         }
     }
     // expandData
     if (!is_null($options['expandData'])) {
         $sqlParts['select']['host'] = 'h.host';
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['ah'] = 'a.hostid=h.hostid';
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['itemid'] = 'ia.itemid';
         }
         $sqlParts['from']['items_applications'] = 'items_applications ia';
         $sqlParts['where'][] = dbConditionInt('ia.itemid', $options['itemids']);
         $sqlParts['where']['aia'] = 'a.applicationid=ia.applicationid';
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['applicationid'] = 'a.applicationid';
         }
         $sqlParts['where'][] = dbConditionInt('a.applicationid', $options['applicationids']);
     }
     // templated
     if (!is_null($options['templated'])) {
         $sqlParts['from']['hosts'] = 'hosts h';
         $sqlParts['where']['ah'] = 'a.hostid=h.hostid';
         if ($options['templated']) {
             $sqlParts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sqlParts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sqlParts['where'][] = 'a.templateid IS NOT NULL';
         } else {
             $sqlParts['where'][] = 'a.templateid IS NULL';
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['apps'] = 'a.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT a.applicationid) as rowscount');
         // groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('applications a', $options, $sqlParts);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('applications a', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'a');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $applicationids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('a.applicationid', $nodeids) . $sqlWhere . $sqlGroup . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($application = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $application;
             } else {
                 $result = $application['rowscount'];
             }
         } else {
             $applicationids[$application['applicationid']] = $application['applicationid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$application['applicationid']] = array('applicationid' => $application['applicationid']);
             } else {
                 if (!isset($result[$application['applicationid']])) {
                     $result[$application['applicationid']] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$application['applicationid']]['hosts'])) {
                     $result[$application['applicationid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectItems']) && !isset($result[$application['applicationid']]['items'])) {
                     $result[$application['applicationid']]['items'] = array();
                 }
                 // hostids
                 if (isset($application['hostid']) && is_null($options['selectHosts'])) {
                     if (!isset($result[$application['applicationid']]['hosts'])) {
                         $result[$application['applicationid']]['hosts'] = array();
                     }
                     $result[$application['applicationid']]['hosts'][] = array('hostid' => $application['hostid']);
                 }
                 // itemids
                 if (isset($application['itemid']) && is_null($options['selectItems'])) {
                     if (!isset($result[$application['applicationid']]['items'])) {
                         $result[$application['applicationid']]['items'] = array();
                     }
                     $result[$application['applicationid']]['items'][] = array('itemid' => $application['itemid']);
                     unset($application['itemid']);
                 }
                 $result[$application['applicationid']] += $application;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // adding objects
     // adding hosts
     if ($options['selectHosts'] !== null && (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs))) {
         $objParams = array('output' => $options['selectHosts'], 'applicationids' => $applicationids, 'nopermissions' => 1, 'templated_hosts' => true, 'preservekeys' => 1);
         $hosts = API::Host()->get($objParams);
         foreach ($hosts as $hostid => $host) {
             $iapplications = $host['applications'];
             unset($host['applications']);
             foreach ($iapplications as $application) {
                 $result[$application['applicationid']]['hosts'][] = $host;
             }
         }
     }
     // adding objects
     // adding items
     if (!is_null($options['selectItems']) && str_in_array($options['selectItems'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectItems'], 'applicationids' => $applicationids, 'nopermissions' => true, 'preservekeys' => true);
         $items = API::Item()->get($objParams);
         foreach ($items as $itemid => $item) {
             $iapplications = $item['applications'];
             unset($item['applications']);
             foreach ($iapplications as $application) {
                 $result[$application['applicationid']]['items'][] = $item;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Esempio n. 28
0
 /**
  * Get Proxy data
  *
  * @param array $options
  * @param array $options['nodeids']
  * @param array $options['proxyids']
  * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
  * @param int $options['count'] returns value in rowscount
  * @param string $options['pattern']
  * @param int $options['limit']
  * @param string $options['sortfield']
  * @param string $options['sortorder']
  * @return array|boolean
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     // allowed columns for sorting
     $sortColumns = array('hostid', 'host', 'status');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('hostid' => 'h.hostid'), 'from' => array('hosts' => 'hosts h'), 'where' => array('h.status IN (' . HOST_STATUS_PROXY_ACTIVE . ',' . HOST_STATUS_PROXY_PASSIVE . ')'), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'proxyids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'countOutput' => null, 'preservekeys' => null, 'selectHosts' => null, 'selectInterfaces' => null, 'limitSelects' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['hosts']);
         $dbTable = DB::getSchema('hosts');
         $sqlParts['select']['hostid'] = 'h.hostid';
         foreach ($options['output'] as $field) {
             if ($field == 'proxyid') {
                 continue;
             }
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'h.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if ($userType != USER_TYPE_SUPER_ADMIN && !$options['nopermissions']) {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         if ($permission == PERM_READ_WRITE) {
             return array();
         }
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // proxyids
     if (!is_null($options['proxyids'])) {
         zbx_value2array($options['proxyids']);
         $sqlParts['where'][] = dbConditionInt('h.hostid', $options['proxyids']);
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('hosts h', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('hosts h', $options, $sqlParts);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['hostid'] = 'h.hostid';
         $sqlParts['select']['host'] = 'h.host';
         $sqlParts['select']['status'] = 'h.status';
         $sqlParts['select']['lastaccess'] = 'h.lastaccess';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT h.hostid) as rowscount');
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'h');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $proxyids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('h.hostid', $nodeids) . $sqlWhere . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($proxy = DBfetch($res)) {
         if ($options['countOutput']) {
             $result = $proxy['rowscount'];
         } else {
             $proxyids[$proxy['hostid']] = $proxy['hostid'];
             $proxy['proxyid'] = $proxy['hostid'];
             unset($proxy['hostid']);
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$proxy['proxyid']] = array('proxyid' => $proxy['proxyid']);
             } else {
                 if (!isset($result[$proxy['proxyid']])) {
                     $result[$proxy['proxyid']] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$proxy['proxyid']]['hosts'])) {
                     $result[$proxy['proxyid']]['hosts'] = array();
                 }
                 if (!is_null($options['selectInterfaces']) && !isset($result[$proxy['proxyid']]['interfaces'])) {
                     $result[$proxy['proxyid']]['interfaces'] = array();
                 }
                 $result[$proxy['proxyid']] += $proxy;
             }
         }
     }
     if (!is_null($options['countOutput']) || empty($proxyids)) {
         return $result;
     }
     /*
      * Adding objects
      */
     // selectHosts
     if (!is_null($options['selectHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'proxyids' => $proxyids, 'preservekeys' => true);
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectHosts'];
             $hosts = API::Host()->get($objParams);
             foreach ($hosts as $host) {
                 $result[$host['proxy_hostid']]['hosts'][] = $host;
             }
         }
     }
     // adding hostinterfaces
     if (!is_null($options['selectInterfaces'])) {
         $objParams = array('nodeids' => $nodeids, 'hostids' => $proxyids, 'nopermissions' => true, 'preservekeys' => true);
         if (is_array($options['selectInterfaces']) || str_in_array($options['selectInterfaces'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectInterfaces'];
             $interfaces = API::HostInterface()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($interfaces, 'interfaceid', ZBX_SORT_UP);
             }
             $count = array();
             foreach ($interfaces as $interfaceid => $interface) {
                 if (!is_null($options['limitSelects'])) {
                     if (!isset($count[$interface['hostid']])) {
                         $count[$interface['hostid']] = 0;
                     }
                     $count[$interface['hostid']]++;
                     if ($count[$interface['hostid']] > $options['limitSelects']) {
                         continue;
                     }
                 }
                 $result[$interface['hostid']]['interfaces'][] =& $interfaces[$interfaceid];
             }
         } elseif (API_OUTPUT_COUNT == $options['selectInterfaces']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $interfaces = API::HostInterface()->get($objParams);
             $interfaces = zbx_toHash($interfaces, 'hostid');
             foreach ($result as $proxyid => $proxy) {
                 $result[$proxyid]['interfaces'] = isset($interfaces[$proxyid]) ? $interfaces[$proxyid]['rowscount'] : 0;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get Service data
  *
  * @param _array $options
  * @param array $options['nodeids'] Node IDs
  * @param array $options['groupids'] ServiceGroup IDs
  * @param array $options['hostids'] Service IDs
  * @param boolean $options['monitored_hosts'] only monitored Services
  * @param boolean $options['templated_hosts'] include templates in result
  * @param boolean $options['with_items'] only with items
  * @param boolean $options['with_historical_items'] only with historical items
  * @param boolean $options['with_triggers'] only with triggers
  * @param boolean $options['with_httptests'] only with http tests
  * @param boolean $options['with_graphs'] only with graphs
  * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
  * @param boolean $options['selectGroups'] select ServiceGroups
  * @param boolean $options['selectTemplates'] select Templates
  * @param boolean $options['selectItems'] select Items
  * @param boolean $options['selectTriggers'] select Triggers
  * @param boolean $options['selectGraphs'] select Graphs
  * @param boolean $options['selectApplications'] select Applications
  * @param boolean $options['selectMacros'] select Macros
  * @param int $options['count'] count Services, returned column name is rowscount
  * @param string $options['pattern'] search hosts by pattern in Service name
  * @param string $options['extendPattern'] search hosts by pattern in Service 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 Service data as array or false if error
  */
 public function get($options = array())
 {
     $result = array();
     $nodeCheck = false;
     $userType = self::$userData['type'];
     // allowed columns for sorting
     $sortColumns = array('dserviceid', 'dhostid', 'ip');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND, API_OUTPUT_CUSTOM);
     $sqlParts = array('select' => array('dservices' => 'ds.dserviceid'), 'from' => array('dservices' => 'dservices ds'), 'where' => array(), 'group' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'dserviceids' => null, 'dhostids' => null, 'dcheckids' => null, 'druleids' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'output' => API_OUTPUT_REFER, 'selectDRules' => null, 'selectDHosts' => null, 'selectDChecks' => null, 'selectHosts' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null, 'limitSelects' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['dservices']);
         $dbTable = DB::getSchema('dservices');
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 's.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $userType) {
     } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) {
     } elseif (!is_null($options['editable']) && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         return array();
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // dserviceids
     if (!is_null($options['dserviceids'])) {
         zbx_value2array($options['dserviceids']);
         $sqlParts['where']['dserviceid'] = dbConditionInt('ds.dserviceid', $options['dserviceids']);
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids);
         }
     }
     // dhostids
     if (!is_null($options['dhostids'])) {
         zbx_value2array($options['dhostids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['dhostid'] = 'ds.dhostid';
         }
         $sqlParts['where'][] = dbConditionInt('ds.dhostid', $options['dhostids']);
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['dhostid'] = 'ds.dhostid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('ds.dhostid', $nodeids);
         }
     }
     // dcheckids
     if (!is_null($options['dcheckids'])) {
         zbx_value2array($options['dcheckids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['dcheckid'] = 'dc.dcheckid';
         }
         $sqlParts['from']['dhosts'] = 'dhosts dh';
         $sqlParts['from']['dchecks'] = 'dchecks dc';
         $sqlParts['where'][] = dbConditionInt('dc.dcheckid', $options['dcheckids']);
         $sqlParts['where']['dhds'] = 'dh.hostid=ds.hostid';
         $sqlParts['where']['dcdh'] = 'dc.druleid=dh.druleid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['dcheckid'] = 'dc.dcheckid';
         }
     }
     // druleids
     if (!is_null($options['druleids'])) {
         zbx_value2array($options['druleids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['druleid'] = 'dh.druleid';
         }
         $sqlParts['from']['dhosts'] = 'dhosts dh';
         $sqlParts['where']['druleid'] = dbConditionInt('dh.druleid', $options['druleids']);
         $sqlParts['where']['dhds'] = 'dh.dhostid=ds.dhostid';
         if (!is_null($options['groupCount'])) {
             $sqlParts['group']['druleid'] = 'dh.druleid';
         }
         if (!$nodeCheck) {
             $nodeCheck = true;
             $sqlParts['where'][] = DBin_node('dh.druleid', $nodeids);
         }
     }
     // node check !!!!!
     // should last, after all ****IDS checks
     if (!$nodeCheck) {
         $nodeCheck = true;
         $sqlParts['where'][] = DBin_node('ds.dserviceid', $nodeids);
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['dservices'] = 'ds.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(DISTINCT ds.dserviceid) as rowscount');
         //groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sqlParts['group'] as $key => $fields) {
                 $sqlParts['select'][$key] = $fields;
             }
         }
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('dservices ds', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('dservices ds', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'ds');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     //-------
     $dserviceids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['group'] = array_unique($sqlParts['group']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlGroup = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['group'])) {
         $sqlWhere .= ' GROUP BY ' . implode(',', $sqlParts['group']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . $sqlWhere . $sqlGroup . $sqlOrder;
     //SDI($sql);
     $res = DBselect($sql, $sqlLimit);
     while ($dservice = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $dservice;
             } else {
                 $result = $dservice['rowscount'];
             }
         } else {
             $dserviceids[$dservice['dserviceid']] = $dservice['dserviceid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$dservice['dserviceid']] = array('dserviceid' => $dservice['dserviceid']);
             } else {
                 if (!isset($result[$dservice['dserviceid']])) {
                     $result[$dservice['dserviceid']] = array();
                 }
                 if (!is_null($options['selectDRules']) && !isset($result[$dservice['dserviceid']]['drules'])) {
                     $result[$dservice['dserviceid']]['drules'] = array();
                 }
                 if (!is_null($options['selectDHosts']) && !isset($result[$dservice['dserviceid']]['dhosts'])) {
                     $result[$dservice['dserviceid']]['dhosts'] = array();
                 }
                 if (!is_null($options['selectDChecks']) && !isset($result[$dservice['dserviceid']]['dchecks'])) {
                     $result[$dservice['dserviceid']]['dchecks'] = array();
                 }
                 if (!is_null($options['selectHosts']) && !isset($result[$dservice['dserviceid']]['hosts'])) {
                     $result[$dservice['dserviceid']]['hosts'] = array();
                 }
                 // druleids
                 if (isset($dservice['druleid']) && is_null($options['selectDRules'])) {
                     if (!isset($result[$dservice['dserviceid']]['drules'])) {
                         $result[$dservice['dserviceid']]['drules'] = array();
                     }
                     $result[$dservice['dserviceid']]['drules'][] = array('druleid' => $dservice['druleid']);
                 }
                 // dhostids
                 if (isset($dservice['dhostid']) && is_null($options['selectDHosts'])) {
                     if (!isset($result[$dservice['dserviceid']]['dhosts'])) {
                         $result[$dservice['dserviceid']]['dhosts'] = array();
                     }
                     $result[$dservice['dserviceid']]['dhosts'][] = array('dhostid' => $dservice['dhostid']);
                 }
                 // dcheckids
                 if (isset($dservice['dcheckid']) && is_null($options['selectDChecks'])) {
                     if (!isset($result[$dservice['dserviceid']]['dchecks'])) {
                         $result[$dservice['dserviceid']]['dchecks'] = array();
                     }
                     $result[$dservice['dserviceid']]['dchecks'][] = array('dcheckid' => $dservice['dcheckid']);
                 }
                 $result[$dservice['dserviceid']] += $dservice;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     // Adding Objects
     // select_drules
     if (!is_null($options['selectDRules'])) {
         $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1);
         if (is_array($options['selectDRules']) || str_in_array($options['selectDRules'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDRules'];
             $drules = API::DRule()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($drules, 'name');
             }
             foreach ($drules as $druleid => $drule) {
                 unset($drules[$druleid]['dservices']);
                 $count = array();
                 foreach ($drule['dservices'] as $dnum => $dservice) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$dservice['dserviceid']])) {
                             $count[$dservice['dserviceid']] = 0;
                         }
                         $count[$dservice['dserviceid']]++;
                         if ($count[$dservice['dserviceid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$dservice['dserviceid']]['drules'][] =& $drules[$druleid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectDRules']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $drules = API::DRule()->get($objParams);
             $drules = zbx_toHash($drules, 'dserviceid');
             foreach ($result as $dserviceid => $dservice) {
                 if (isset($drules[$dserviceid])) {
                     $result[$dserviceid]['drules'] = $drules[$dserviceid]['rowscount'];
                 } else {
                     $result[$dserviceid]['drules'] = 0;
                 }
             }
         }
     }
     // selectDHosts
     if (!is_null($options['selectDHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1);
         if (is_array($options['selectDHosts']) || str_in_array($options['selectDHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectDHosts'];
             $dhosts = API::DHost()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($dhosts, 'dhostid');
             }
             foreach ($dhosts as $dhostid => $dhost) {
                 unset($dhosts[$dhostid]['dservices']);
                 foreach ($dhost['dservices'] as $snum => $dservice) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$dservice['dserviceid']])) {
                             $count[$dservice['dserviceid']] = 0;
                         }
                         $count[$dservice['dserviceid']]++;
                         if ($count[$dservice['dserviceid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$dservice['dserviceid']]['dhosts'][] =& $dhosts[$dhostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectDHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $dhosts = API::DHost()->get($objParams);
             $dhosts = zbx_toHash($dhosts, 'dhostid');
             foreach ($result as $dserviceid => $dservice) {
                 if (isset($dhosts[$dserviceid])) {
                     $result[$dserviceid]['dhosts'] = $dhosts[$dserviceid]['rowscount'];
                 } else {
                     $result[$dserviceid]['dhosts'] = 0;
                 }
             }
         }
     }
     // selectHosts
     if (!is_null($options['selectHosts'])) {
         $objParams = array('nodeids' => $nodeids, 'dserviceids' => $dserviceids, 'preservekeys' => 1, 'sortfield' => 'status');
         if (is_array($options['selectHosts']) || str_in_array($options['selectHosts'], $subselectsAllowedOutputs)) {
             $objParams['output'] = $options['selectHosts'];
             $hosts = API::Host()->get($objParams);
             if (!is_null($options['limitSelects'])) {
                 order_result($hosts, 'hostid');
             }
             foreach ($hosts as $hostid => $host) {
                 unset($hosts[$hostid]['dservices']);
                 foreach ($host['dservices'] as $dnum => $dservice) {
                     if (!is_null($options['limitSelects'])) {
                         if (!isset($count[$dservice['dserviceid']])) {
                             $count[$dservice['dserviceid']] = 0;
                         }
                         $count[$dservice['dserviceid']]++;
                         if ($count[$dservice['dserviceid']] > $options['limitSelects']) {
                             continue;
                         }
                     }
                     $result[$dservice['dserviceid']]['hosts'][] =& $hosts[$hostid];
                 }
             }
         } elseif (API_OUTPUT_COUNT == $options['selectHosts']) {
             $objParams['countOutput'] = 1;
             $objParams['groupCount'] = 1;
             $hosts = API::Host()->get($objParams);
             $hosts = zbx_toHash($hosts, 'hostid');
             foreach ($result as $dserviceid => $dservice) {
                 if (isset($hosts[$dserviceid])) {
                     $result[$dserviceid]['hosts'] = $hosts[$dserviceid]['rowscount'];
                 } else {
                     $result[$dserviceid]['hosts'] = 0;
                 }
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
 /**
  * Get UserGroups
  *
  * @param array $options
  * @param array $options['nodeids'] Node IDs
  * @param array $options['usrgrpids'] UserGroup IDs
  * @param array $options['userids'] User IDs
  * @param boolean $options['status']
  * @param boolean $options['with_gui_access']
  * @param boolean $options['selectUsers']
  * @param int $options['count']
  * @param string $options['pattern']
  * @param int $options['limit'] limit selection
  * @param string $options['order']
  * @return array
  */
 public function get($options = array())
 {
     $result = array();
     $userType = self::$userData['type'];
     $userid = self::$userData['userid'];
     // allowed columns for sorting
     $sortColumns = array('usrgrpid', 'name');
     // allowed output options for [ select_* ] params
     $subselectsAllowedOutputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     $sqlParts = array('select' => array('usrgrp' => 'g.usrgrpid'), 'from' => array('usrgrp' => 'usrgrp g'), 'where' => array(), 'order' => array(), 'limit' => null);
     $defOptions = array('nodeids' => null, 'usrgrpids' => null, 'userids' => null, 'status' => null, 'with_gui_access' => null, 'filter' => null, 'search' => null, 'searchByAny' => null, 'startSearch' => null, 'excludeSearch' => null, 'searchWildcardsEnabled' => null, 'editable' => null, 'output' => API_OUTPUT_REFER, 'selectUsers' => null, 'countOutput' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($defOptions, $options);
     if (is_array($options['output'])) {
         unset($sqlParts['select']['usrgrp']);
         $dbTable = DB::getSchema('usrgrp');
         $sqlParts['select']['usrgrpid'] = 'g.usrgrpid';
         foreach ($options['output'] as $field) {
             if (isset($dbTable['fields'][$field])) {
                 $sqlParts['select'][$field] = 'g.' . $field;
             }
         }
         $options['output'] = API_OUTPUT_CUSTOM;
     }
     // permission check
     if (USER_TYPE_SUPER_ADMIN == $userType) {
     } elseif (is_null($options['editable']) && self::$userData['type'] == USER_TYPE_ZABBIX_ADMIN) {
         $sqlParts['where'][] = 'g.usrgrpid IN (' . 'SELECT uug.usrgrpid' . ' FROM users_groups uug' . ' WHERE uug.userid=' . self::$userData['userid'] . ')';
     } elseif (!is_null($options['editable']) && self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
         return array();
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // usrgrpids
     if (!is_null($options['usrgrpids'])) {
         zbx_value2array($options['usrgrpids']);
         $sqlParts['where'][] = dbConditionInt('g.usrgrpid', $options['usrgrpids']);
     }
     // userids
     if (!is_null($options['userids'])) {
         zbx_value2array($options['userids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sqlParts['select']['userid'] = 'ug.userid';
         }
         $sqlParts['from']['users_groups'] = 'users_groups ug';
         $sqlParts['where'][] = dbConditionInt('ug.userid', $options['userids']);
         $sqlParts['where']['gug'] = 'g.usrgrpid=ug.usrgrpid';
     }
     // status
     if (!is_null($options['status'])) {
         $sqlParts['where'][] = 'g.users_status=' . zbx_dbstr($options['status']);
     }
     // with_gui_access
     if (!is_null($options['with_gui_access'])) {
         $sqlParts['where'][] = 'g.gui_access=' . GROUP_GUI_ACCESS_ENABLED;
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sqlParts['select']['usrgrp'] = 'g.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sqlParts['select'] = array('count(g.usrgrpid) as rowscount');
     }
     // filter
     if (is_array($options['filter'])) {
         $this->dbFilter('usrgrp g', $options, $sqlParts);
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('usrgrp g', $options, $sqlParts);
     }
     // sorting
     zbx_db_sorting($sqlParts, $options, $sortColumns, 'g');
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sqlParts['limit'] = $options['limit'];
     }
     $usrgrpids = array();
     $sqlParts['select'] = array_unique($sqlParts['select']);
     $sqlParts['from'] = array_unique($sqlParts['from']);
     $sqlParts['where'] = array_unique($sqlParts['where']);
     $sqlParts['order'] = array_unique($sqlParts['order']);
     $sqlSelect = '';
     $sqlFrom = '';
     $sqlWhere = '';
     $sqlOrder = '';
     if (!empty($sqlParts['select'])) {
         $sqlSelect .= implode(',', $sqlParts['select']);
     }
     if (!empty($sqlParts['from'])) {
         $sqlFrom .= implode(',', $sqlParts['from']);
     }
     if (!empty($sqlParts['where'])) {
         $sqlWhere .= ' AND ' . implode(' AND ', $sqlParts['where']);
     }
     if (!empty($sqlParts['order'])) {
         $sqlOrder .= ' ORDER BY ' . implode(',', $sqlParts['order']);
     }
     $sqlLimit = $sqlParts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sqlParts) . ' ' . $sqlSelect . ' FROM ' . $sqlFrom . ' WHERE ' . DBin_node('g.usrgrpid', $nodeids) . $sqlWhere . $sqlOrder;
     $res = DBselect($sql, $sqlLimit);
     while ($usrgrp = DBfetch($res)) {
         if ($options['countOutput']) {
             $result = $usrgrp['rowscount'];
         } else {
             $usrgrpids[$usrgrp['usrgrpid']] = $usrgrp['usrgrpid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$usrgrp['usrgrpid']] = array('usrgrpid' => $usrgrp['usrgrpid']);
             } else {
                 if (!isset($result[$usrgrp['usrgrpid']])) {
                     $result[$usrgrp['usrgrpid']] = array();
                 }
                 if (!is_null($options['selectUsers']) && !isset($result[$usrgrp['usrgrpid']]['users'])) {
                     $result[$usrgrp['usrgrpid']]['users'] = array();
                 }
                 // groupids
                 if (isset($usrgrp['userid']) && is_null($options['selectUsers'])) {
                     if (!isset($result[$usrgrp['usrgrpid']]['users'])) {
                         $result[$usrgrp['usrgrpid']]['users'] = array();
                     }
                     $result[$usrgrp['usrgrpid']]['users'][] = array('userid' => $usrgrp['userid']);
                     unset($usrgrp['userid']);
                 }
                 $result[$usrgrp['usrgrpid']] += $usrgrp;
             }
         }
     }
     if (!is_null($options['countOutput'])) {
         return $result;
     }
     /*
      * Adding objects
      */
     // adding users
     if (!is_null($options['selectUsers']) && str_in_array($options['selectUsers'], $subselectsAllowedOutputs)) {
         $objParams = array('output' => $options['selectUsers'], 'usrgrpids' => $usrgrpids, 'getAccess' => $options['selectUsers'] == API_OUTPUT_EXTEND ? true : null, 'preservekeys' => true);
         $users = API::User()->get($objParams);
         foreach ($users as $user) {
             $uusrgrps = $user['usrgrps'];
             unset($user['usrgrps']);
             foreach ($uusrgrps as $usrgrp) {
                 $result[$usrgrp['usrgrpid']]['users'][] = $user;
             }
         }
     }
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }