Ejemplo n.º 1
0
 /**
  * Mass update hosts
  *
  * @param _array $hosts multidimensional array with Hosts data
  * @param array $hosts['hosts'] Array of Host objects to update
  * @param string $hosts['fields']['host'] Host name.
  * @param array $hosts['fields']['groupids'] HostGroup IDs add Host to.
  * @param int $hosts['fields']['port'] Port. OPTIONAL
  * @param int $hosts['fields']['status'] Host Status. OPTIONAL
  * @param int $hosts['fields']['useip'] Use IP. OPTIONAL
  * @param string $hosts['fields']['dns'] DNS. OPTIONAL
  * @param string $hosts['fields']['ip'] IP. OPTIONAL
  * @param int $hosts['fields']['proxy_hostid'] Proxy Host ID. OPTIONAL
  * @param int $hosts['fields']['useipmi'] Use IPMI. OPTIONAL
  * @param string $hosts['fields']['ipmi_ip'] IPMAI IP. OPTIONAL
  * @param int $hosts['fields']['ipmi_port'] IPMI port. OPTIONAL
  * @param int $hosts['fields']['ipmi_authtype'] IPMI authentication type. OPTIONAL
  * @param int $hosts['fields']['ipmi_privilege'] IPMI privilege. OPTIONAL
  * @param string $hosts['fields']['ipmi_username'] IPMI username. OPTIONAL
  * @param string $hosts['fields']['ipmi_password'] IPMI password. OPTIONAL
  * @return boolean
  */
 public static function massUpdate($data)
 {
     $hosts = zbx_toArray($data['hosts']);
     $hostids = zbx_objectValues($hosts, 'hostid');
     try {
         self::BeginTransaction(__METHOD__);
         $options = array('hostids' => $hostids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1);
         $upd_hosts = self::get($options);
         foreach ($hosts as $hnum => $host) {
             if (!isset($upd_hosts[$host['hostid']])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
             }
         }
         // CHECK IF HOSTS HAVE AT LEAST 1 GROUP {{{
         if (isset($data['groups']) && empty($data['groups'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'No groups for hosts');
         }
         // }}} CHECK IF HOSTS HAVE AT LEAST 1 GROUP
         // UPDATE HOSTS PROPERTIES {{{
         if (isset($data['host'])) {
             if (count($hosts) > 1) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot mass update host name');
             }
             $cur_host = reset($hosts);
             $options = array('filter' => array('host' => $cur_host['host']), 'output' => API_OUTPUT_SHORTEN, 'editable' => 1, 'nopermissions' => 1);
             $host_exists = self::get($options);
             $host_exist = reset($host_exists);
             if ($host_exist && $host_exist['hostid'] != $cur_host['hostid']) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_HOST . ' [ ' . $data['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
             //can't add host with the same name as existing template
             if (CTemplate::exists(array('host' => $cur_host['host']))) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_TEMPLATE . ' [ ' . $cur_host['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
         }
         if (isset($data['host']) && !preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/i', $data['host'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for Hostname [ ' . $data['host'] . ' ]');
         }
         if (isset($data['dns']) && !empty($data['dns']) && !preg_match('/^' . ZBX_PREG_DNS_FORMAT . '$/i', $data['dns'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for DNS [ ' . $data['dns'] . ' ]');
         }
         $sql_set = array();
         if (isset($data['proxy_hostid'])) {
             $sql_set[] = 'proxy_hostid=' . $data['proxy_hostid'];
         }
         if (isset($data['host'])) {
             $sql_set[] = 'host=' . zbx_dbstr($data['host']);
         }
         if (isset($data['port'])) {
             $sql_set[] = 'port=' . $data['port'];
         }
         if (isset($data['status'])) {
             $sql_set[] = 'status=' . $data['status'];
         }
         if (isset($data['useip'])) {
             $sql_set[] = 'useip=' . $data['useip'];
         }
         if (isset($data['dns'])) {
             $sql_set[] = 'dns=' . zbx_dbstr($data['dns']);
         }
         if (isset($data['ip'])) {
             $sql_set[] = 'ip=' . zbx_dbstr($data['ip']);
         }
         if (isset($data['useipmi'])) {
             $sql_set[] = 'useipmi=' . $data['useipmi'];
         }
         if (isset($data['ipmi_port'])) {
             $sql_set[] = 'ipmi_port=' . $data['ipmi_port'];
         }
         if (isset($data['ipmi_authtype'])) {
             $sql_set[] = 'ipmi_authtype=' . $data['ipmi_authtype'];
         }
         if (isset($data['ipmi_privilege'])) {
             $sql_set[] = 'ipmi_privilege=' . $data['ipmi_privilege'];
         }
         if (isset($data['ipmi_username'])) {
             $sql_set[] = 'ipmi_username='******'ipmi_username']);
         }
         if (isset($data['ipmi_password'])) {
             $sql_set[] = 'ipmi_password='******'ipmi_password']);
         }
         if (isset($data['ipmi_ip'])) {
             $sql_set[] = 'ipmi_ip=' . zbx_dbstr($data['ipmi_ip']);
         }
         if (!empty($sql_set)) {
             $sql = 'UPDATE hosts SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $hostids);
             $result = DBexecute($sql);
             if (isset($data['status'])) {
                 update_host_status($hostids, $data['status']);
             }
         }
         // }}} UPDATE HOSTS PROPERTIES
         // UPDATE HOSTGROUPS LINKAGE {{{
         if (isset($data['groups']) && !is_null($data['groups'])) {
             $data['groups'] = zbx_toArray($data['groups']);
             $host_groups = CHostGroup::get(array('hostids' => $hostids));
             $host_groupids = zbx_objectValues($host_groups, 'groupid');
             $new_groupids = zbx_objectValues($data['groups'], 'groupid');
             $groups_to_add = array_diff($new_groupids, $host_groupids);
             if (!empty($groups_to_add)) {
                 $result = self::massAdd(array('hosts' => $hosts, 'groups' => zbx_toObject($groups_to_add, 'groupid')));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t add group');
                 }
             }
             $groupids_to_del = array_diff($host_groupids, $new_groupids);
             if (!empty($groupids_to_del)) {
                 $result = self::massRemove(array('hostids' => $hostids, 'groupids' => $groupids_to_del));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove group');
                 }
             }
         }
         // }}} UPDATE HOSTGROUPS LINKAGE
         $data['templates_clear'] = isset($data['templates_clear']) ? zbx_toArray($data['templates_clear']) : array();
         $cleared_templateids = array();
         foreach ($hostids as $hostid) {
             foreach ($data['templates_clear'] as $tpl) {
                 $result = unlink_template($hostid, $tpl['templateid'], false);
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot unlink template [ ' . $tpl['templateid'] . ' ]');
                 }
                 $cleared_templateids[] = $tpl['templateid'];
             }
         }
         // UPDATE TEMPLATE LINKAGE {{{
         if (isset($data['templates']) && !is_null($data['templates'])) {
             $opt = array('hostids' => $hostids, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => true);
             $host_templates = CTemplate::get($opt);
             $host_templateids = array_keys($host_templates);
             $new_templateids = zbx_objectValues($data['templates'], 'templateid');
             $templates_to_del = array_diff($host_templateids, $new_templateids);
             $templates_to_del = array_diff($templates_to_del, $cleared_templateids);
             if (!empty($templates_to_del)) {
                 $result = self::massRemove(array('hostids' => $hostids, 'templateids' => $templates_to_del));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, S_CANNOT_UNLINK_TEMPLATE);
                 }
             }
             $result = self::massAdd(array('hosts' => $hosts, 'templates' => $data['templates']));
             if (!$result) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_CANNOT_LINK_TEMPLATE);
             }
         }
         // }}} UPDATE TEMPLATE LINKAGE
         // UPDATE MACROS {{{
         if (isset($data['macros']) && !is_null($data['macros'])) {
             $macrosToAdd = zbx_toHash($data['macros'], 'macro');
             $hostMacros = CUserMacro::get(array('hostids' => $hostids, 'output' => API_OUTPUT_EXTEND));
             $hostMacros = zbx_toHash($hostMacros, 'macro');
             // Delete
             $macrosToDelete = array();
             foreach ($hostMacros as $hmnum => $hmacro) {
                 if (!isset($macrosToAdd[$hmacro['macro']])) {
                     $macrosToDelete[] = $hmacro['macro'];
                 }
             }
             // Update
             $macrosToUpdate = array();
             foreach ($macrosToAdd as $nhmnum => $nhmacro) {
                 if (isset($hostMacros[$nhmacro['macro']])) {
                     $macrosToUpdate[] = $nhmacro;
                     unset($macrosToAdd[$nhmnum]);
                 }
             }
             //----
             if (!empty($macrosToDelete)) {
                 $result = self::massRemove(array('hostids' => $hostids, 'macros' => $macrosToDelete));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove macro');
                 }
             }
             if (!empty($macrosToUpdate)) {
                 $result = CUsermacro::massUpdate(array('hosts' => $hosts, 'macros' => $macrosToUpdate));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update macro');
                 }
             }
             if (!empty($macrosToAdd)) {
                 $result = self::massAdd(array('hosts' => $hosts, 'macros' => $macrosToAdd));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot add macro');
                 }
             }
         }
         // }}} UPDATE MACROS
         // PROFILE {{{
         if (isset($data['profile']) && !is_null($data['profile'])) {
             if (empty($data['profile'])) {
                 $sql = 'DELETE FROM hosts_profiles WHERE ' . DBcondition('hostid', $hostids);
                 if (!DBexecute($sql)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot delete profile');
                 }
             } else {
                 $existing_profiles = array();
                 $existing_profiles_db = DBselect('SELECT hostid FROM hosts_profiles WHERE ' . DBcondition('hostid', $hostids));
                 while ($existing_profile = DBfetch($existing_profiles_db)) {
                     $existing_profiles[] = $existing_profile['hostid'];
                 }
                 $hostids_without_profile = array_diff($hostids, $existing_profiles);
                 $fields = array_keys($data['profile']);
                 $fields = implode(', ', $fields);
                 $values = array_map('zbx_dbstr', $data['profile']);
                 $values = implode(', ', $values);
                 foreach ($hostids_without_profile as $hostid) {
                     $sql = 'INSERT INTO hosts_profiles (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')';
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot create profile');
                     }
                 }
                 if (!empty($existing_profiles)) {
                     $host_profile_fields = array('devicetype', 'name', 'os', 'serialno', 'tag', 'macaddress', 'hardware', 'software', 'contact', 'location', 'notes');
                     $sql_set = array();
                     foreach ($host_profile_fields as $field) {
                         if (isset($data['profile'][$field])) {
                             $sql_set[] = $field . '=' . zbx_dbstr($data['profile'][$field]);
                         }
                     }
                     $sql = 'UPDATE hosts_profiles SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $existing_profiles);
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update profile');
                     }
                 }
             }
         }
         // }}} PROFILE
         // EXTENDED PROFILE {{{
         if (isset($data['extendedProfile']) && !is_null($data['extendedProfile'])) {
             if (empty($data['extendedProfile'])) {
                 $sql = 'DELETE FROM hosts_profiles_ext WHERE ' . DBcondition('hostid', $hostids);
                 if (!DBexecute($sql)) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot delete extended profile');
                 }
             } else {
                 $existing_profiles = array();
                 $existing_profiles_db = DBselect('SELECT hostid FROM hosts_profiles_ext WHERE ' . DBcondition('hostid', $hostids));
                 while ($existing_profile = DBfetch($existing_profiles_db)) {
                     $existing_profiles[] = $existing_profile['hostid'];
                 }
                 $hostids_without_profile = array_diff($hostids, $existing_profiles);
                 $fields = array_keys($data['extendedProfile']);
                 $fields = implode(', ', $fields);
                 $values = array_map('zbx_dbstr', $data['extendedProfile']);
                 $values = implode(', ', $values);
                 foreach ($hostids_without_profile as $hostid) {
                     $sql = 'INSERT INTO hosts_profiles_ext (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')';
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot create extended profile');
                     }
                 }
                 if (!empty($existing_profiles)) {
                     $host_profile_ext_fields = array('device_alias', 'device_type', 'device_chassis', 'device_os', 'device_os_short', 'device_hw_arch', 'device_serial', 'device_model', 'device_tag', 'device_vendor', 'device_contract', 'device_who', 'device_status', 'device_app_01', 'device_app_02', 'device_app_03', 'device_app_04', 'device_app_05', 'device_url_1', 'device_url_2', 'device_url_3', 'device_networks', 'device_notes', 'device_hardware', 'device_software', 'ip_subnet_mask', 'ip_router', 'ip_macaddress', 'oob_ip', 'oob_subnet_mask', 'oob_router', 'date_hw_buy', 'date_hw_install', 'date_hw_expiry', 'date_hw_decomm', 'site_street_1', 'site_street_2', 'site_street_3', 'site_city', 'site_state', 'site_country', 'site_zip', 'site_rack', 'site_notes', 'poc_1_name', 'poc_1_email', 'poc_1_phone_1', 'poc_1_phone_2', 'poc_1_cell', 'poc_1_screen', 'poc_1_notes', 'poc_2_name', 'poc_2_email', 'poc_2_phone_1', 'poc_2_phone_2', 'poc_2_cell', 'poc_2_screen', 'poc_2_notes');
                     $sql_set = array();
                     foreach ($host_profile_ext_fields as $field) {
                         if (isset($data['extendedProfile'][$field])) {
                             $sql_set[] = $field . '=' . zbx_dbstr($data['extendedProfile'][$field]);
                         }
                     }
                     $sql = 'UPDATE hosts_profiles_ext SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $existing_profiles);
                     if (!DBexecute($sql)) {
                         self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update extended profile');
                     }
                 }
             }
         }
         // }}} EXTENDED PROFILE
         self::EndTransaction(true, __METHOD__);
         return array('hostids' => $hostids);
     } catch (APIException $e) {
         self::EndTransaction(false, __METHOD__);
         $error = $e->getErrors();
         $error = reset($error);
         self::setError(__METHOD__, $e->getCode(), $error);
         return false;
     }
 }
Ejemplo n.º 2
0
$wdgt_hgroups->setClass('header');
$wdgt_hgroups->addHeader(S_HOST_GROUPS, SPACE);
$right_tab->addRow($wdgt_hgroups);
//----------------
// FIND Templates
if ($admin) {
    $params = array('nodeids' => get_current_nodeid(true), 'search' => array('host' => $search), 'output' => API_OUTPUT_EXTEND, 'select_groups' => API_OUTPUT_REFER, 'sortfield' => 'host', 'select_items' => API_OUTPUT_COUNT, 'select_triggers' => API_OUTPUT_COUNT, 'select_graphs' => API_OUTPUT_COUNT, 'select_applications' => API_OUTPUT_COUNT, 'limit' => $rows_per_page);
    $db_templates = CTemplate::get($params);
    order_result($db_templates, 'host');
    $templates = selectByPattern($db_templates, 'host', $search, $rows_per_page);
    $templateids = zbx_objectValues($templates, 'templateid');
    $params = array('nodeids' => get_current_nodeid(true), 'templateids' => $templateids, 'editable' => 1);
    $rw_templates = CTemplate::get($params);
    $rw_templates = zbx_toHash($rw_templates, 'templateid');
    $params = array('nodeids' => get_current_nodeid(true), 'search' => array('host' => $search), 'countOutput' => 1, 'editable' => 1);
    $overalCount = CTemplate::get($params);
    $viewCount = count($templates);
    $header = array(ZBX_DISTRIBUTED ? new CCol(S_NODE) : null, new CCol(S_TEMPLATES), new CCol(S_APPLICATIONS), new CCol(S_ITEMS), new CCol(S_TRIGGERS), new CCol(S_GRAPHS));
    $table = new CTableInfo();
    $table->setHeader($header);
    foreach ($templates as $tnum => $template) {
        $templateid = $template['hostid'];
        $group = reset($template['groups']);
        $link = 'groupid=' . $group['groupid'] . '&hostid=' . $templateid . '&switch_node=' . id2nodeid($templateid);
        $caption = make_decoration($template['host'], $search);
        if (isset($rw_templates[$templateid])) {
            $template_link = new CLink($caption, 'templates.php?form=update&' . '&templateid=' . $templateid . '&switch_node=' . id2nodeid($templateid));
            $applications_link = array(new CLink(S_APPLICATIONS, 'applications.php?' . $link), ' (' . $template['applications'] . ')');
            $items_link = array(new CLink(S_ITEMS, 'items.php?' . $link), ' (' . $template['items'] . ')');
            $triggers_link = array(new CLink(S_TRIGGERS, 'triggers.php?' . $link), ' (' . $template['triggers'] . ')');
            $graphs_link = array(new CLink(S_GRAPHS, 'graphs.php?' . $link), ' (' . $template['graphs'] . ')');
Ejemplo n.º 3
0
$right_tab->addRow($wdgt_hgroups);
//----------------
// FIND Templates
if ($admin) {
    $params = array('nodeid' => get_current_nodeid(), 'extendoutput' => 1, 'pattern' => $search, 'limit' => $rows_per_page, 'order' => 'host', 'editable' => 1);
    $db_templates = CTemplate::get($params);
    $templates = selectByPattern($db_templates, 'host', $search, $rows_per_page);
    $templateids = array_keys($templates);
    $hostsgroups = array();
    $sql = 'SELECT * FROM hosts_groups hg WHERE ' . DBcondition('hg.hostid', $templateids);
    $res = DBselect($sql);
    while ($templategroup = DBfetch($res)) {
        $hostsgroups[$templategroup['hostid']] = $templategroup['groupid'];
    }
    $params = array('nodeids' => get_current_nodeid(), 'pattern' => $search, 'count' => 1, 'editable' => 1);
    $hosts_count = CTemplate::get($params);
    $overalCount = $hosts_count['rowscount'];
    $viewCount = count($templates);
    $header = array(is_show_all_nodes() ? new CCol(S_NODE) : null, new CCol(S_TEMPLATES), new CCol(S_ITEMS), new CCol(S_TRIGGERS), new CCol(S_GRAPHS));
    $table = new CTableInfo();
    $table->setHeader($header);
    foreach ($templates as $num => $template) {
        $templateid = $template['hostid'];
        $groupid = isset($hostsgroups[$templateid]) ? $hostsgroups[$templateid] : 0;
        $link = 'groupid=' . $groupid . '&hostid=' . $templateid;
        $caption = make_decoration($template['host'], $search);
        $table->addRow(array(get_node_name_by_elid($templateid), new CLink($caption, 'hosts.php?config=3&hostid=' . $templateid), new CLink(S_GO, 'items.php?' . $link), new CLink(S_GO, 'triggers.php?' . $link), new CLink(S_GO, 'graphs.php?' . $link)));
    }
    $table->setFooter(new CCol(S_DISPLAYING . SPACE . $viewCount . SPACE . S_OF_SMALL . SPACE . $overalCount . SPACE . S_FOUND_SMALL));
    $wdgt_templates = new CWidget('search_templates', $table);
    $wdgt_templates->addHeader(S_TEMPLATES, SPACE);
Ejemplo n.º 4
0
 private static function template($action, $params)
 {
     CTemplate::$error = array();
     switch ($action) {
         case 'add':
             $result = CTemplate::add($params);
             break;
         case 'get':
             $result = CTemplate::get($params);
             break;
         case 'getById':
             $result = CTemplate::getById($params);
             break;
         case 'getId':
             $result = CTemplate::getId($params);
             break;
         case 'update':
             $result = CTemplate::update($params);
             break;
         case 'linkHosts':
             $result = CTemplate::linkHosts($params);
             break;
         case 'unlinkHosts':
             $result = CTemplate::unlinkHosts($params);
             break;
         case 'linkTemplates':
             $result = CTemplate::linkTemplates($params);
             break;
         case 'unlinkTemplates':
             $result = CTemplate::unlinkTemplates($params);
             break;
         case 'delete':
             $result = CTemplate::delete($params);
             break;
         default:
             self::$result = array('error' => ZBX_API_ERROR_NO_METHOD, 'data' => 'Method: "' . $action . '" doesn\'t exist.');
             return;
             //exit function
     }
     if ($result !== false) {
         self::$result = array('result' => $result);
     } else {
         self::$result = CTemplate::$error;
     }
 }
Ejemplo n.º 5
0
 /**
  * Get graph data
  *
  * <code>
  * $options = array(
  *	array 'graphids'				=> array(graphid1, graphid2, ...),
  *	array 'itemids'					=> array(itemid1, itemid2, ...),
  *	array 'hostids'					=> array(hostid1, hostid2, ...),
  *	int 'type'					=> 'graph type, chart/pie'
  *	boolean 'templated_graphs'			=> 'only templated graphs',
  *	int 'count'					=> 'count',
  *	string 'pattern'				=> 'search hosts by pattern in graph names',
  *	integer 'limit'					=> 'limit selection',
  *	string 'order'					=> 'depricated parameter (for now)'
  * );
  * </code>
  *
  * @static
  * @param array $options
  * @return array|boolean host data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $result = array();
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $result = array();
     $sort_columns = array('graphid');
     // allowed columns for sorting
     $sql_parts = array('select' => array('graphs' => 'g.graphid'), 'from' => array('graphs g'), 'where' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => 0, 'groupids' => 0, 'hostids' => 0, 'graphids' => 0, 'itemids' => 0, 'type' => 0, 'templated_graphs' => 0, 'editable' => 0, 'nopermission' => 0, 'select_hosts' => 0, 'select_templates' => 0, 'select_items' => 0, 'extendoutput' => 0, 'count' => 0, 'pattern' => '', 'limit' => 0, 'order' => '');
     $options = array_merge($def_options, $options);
     // editable + PERMISSION CHECK
     if (defined('ZBX_API_REQUEST')) {
         $options['nopermissions'] = false;
     }
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['from']['i'] = 'items i';
         $sql_parts['from']['hg'] = 'hosts_groups hg';
         $sql_parts['from']['r'] = 'rights r';
         $sql_parts['from']['ug'] = 'users_groups ug';
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where'][] = 'r.id=hg.groupid ';
         $sql_parts['where'][] = 'r.groupid=ug.usrgrpid';
         $sql_parts['where'][] = 'ug.userid=' . $userid;
         $sql_parts['where'][] = 'r.permission>=' . $permission;
         $sql_parts['where'][] = 'NOT EXISTS( ' . ' SELECT gii.graphid ' . ' FROM graphs_items gii, items ii ' . ' WHERE gii.graphid=g.graphid ' . ' AND gii.itemid=ii.itemid ' . ' AND EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups ugg ' . ' WHERE ii.hostid=hgg.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=ugg.usrgrpid ' . ' AND ugg.userid=' . $userid . ' AND rr.permission<' . $permission . '))';
     }
     // nodeids
     $nodeids = $options['nodeids'] ? $options['nodeids'] : get_current_nodeid(false);
     // groupids
     if ($options['groupids'] != 0) {
         zbx_value2array($options['groupids']);
         if ($options['extendoutput'] != 0) {
             $sql_parts['select']['groupid'] = 'hg.groupid';
         }
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['from']['i'] = 'items i';
         $sql_parts['from']['hg'] = 'hosts_groups hg';
         $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
         $sql_parts['where'][] = 'hg.hostid=i.hostid';
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
     }
     // hostids
     if ($options['hostids'] != 0) {
         zbx_value2array($options['hostids']);
         if ($options['extendoutput'] != 0) {
             $sql_parts['select']['hostid'] = 'i.hostid';
         }
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['from']['i'] = 'items i';
         $sql_parts['where'][] = DBcondition('i.hostid', $options['hostids']);
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
     }
     // graphids
     if ($options['graphids'] != 0) {
         $sql_parts['where'][] = DBcondition('g.graphid', $options['graphids']);
     }
     // itemids
     if ($options['itemids'] != 0) {
         zbx_value2array($options['itemids']);
         if ($options['extendoutput'] != 0) {
             $sql_parts['select']['itemid'] = 'gi.itemid';
         }
         $sql_parts['from']['gi'] = 'graphs_items gi';
         $sql_parts['where']['gig'] = 'gi.graphid=g.graphid';
         $sql_parts['where'][] = DBcondition('gi.itemid', $options['itemids']);
     }
     // type
     if ($options['type'] != 0) {
         $sql_parts['where'][] = 'g.type=' . $options['type'];
     }
     // templated_graphs
     if ($options['templated_graphs'] != 0) {
         $sql_parts['where'][] = 'g.templateid<>0';
     }
     // extendoutput
     if ($options['extendoutput'] != 0) {
         $sql_parts['select']['graphs'] = 'g.*';
     }
     // count
     if ($options['count'] != 0) {
         $sql_parts['select']['graphs'] = 'count(g.graphid) as count';
     }
     // pattern
     if (!zbx_empty($options['pattern'])) {
         $sql_parts['where'][] = ' UPPER(g.name) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%');
     }
     // order
     // restrict not allowed columns for sorting
     $options['order'] = in_array($options['order'], $sort_columns) ? $options['order'] : '';
     if (!zbx_empty($options['order'])) {
         $sql_parts['order'][] = 'g.' . $options['order'];
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //------------
     $graphids = array();
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= ' AND ' . implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . DBin_node('g.graphid', $nodeids) . $sql_where . $sql_order;
     $db_res = DBselect($sql, $sql_limit);
     while ($graph = DBfetch($db_res)) {
         if ($options['count']) {
             $result = $graph;
         } else {
             if (!$options['extendoutput']) {
                 $result[$graph['graphid']] = $graph['graphid'];
             } else {
                 $graphids[$graph['graphid']] = $graph['graphid'];
                 if (!isset($result[$graph['graphid']])) {
                     $result[$graph['graphid']] = array();
                 }
                 if ($options['select_hosts'] && !isset($result[$graph['graphid']]['hostids'])) {
                     $result[$graph['graphid']]['hostids'] = array();
                     $result[$graph['graphid']]['hosts'] = array();
                 }
                 if ($options['select_templates'] && !isset($result[$graph['graphid']]['templateids'])) {
                     $result[$graph['graphid']]['templateids'] = array();
                     $result[$graph['graphid']]['templates'] = array();
                 }
                 if ($options['select_items'] && !isset($result[$graph['graphid']]['itemids'])) {
                     $result[$graph['graphid']]['itemids'] = array();
                     $result[$graph['graphid']]['items'] = array();
                 }
                 // hostids
                 if (isset($graph['hostid'])) {
                     if (!isset($result[$graph['graphid']]['hostids'])) {
                         $result[$graph['graphid']]['hostids'] = array();
                     }
                     $result[$graph['graphid']]['hostids'][$graph['hostid']] = $graph['hostid'];
                     unset($graph['hostid']);
                 }
                 // itemids
                 if (isset($graph['itemid'])) {
                     if (!isset($result[$graph['graphid']]['itemid'])) {
                         $result[$graph['graphid']]['itemid'] = array();
                     }
                     $result[$graph['graphid']]['itemids'][$graph['itemid']] = $graph['itemid'];
                     unset($graph['itemid']);
                 }
                 $result[$graph['graphid']] += $graph;
             }
         }
     }
     // Adding Hosts
     if ($options['select_hosts']) {
         $obj_params = array('extendoutput' => 1, 'graphids' => $graphids, 'nopermissions' => 1);
         $hosts = CHost::get($obj_params);
         foreach ($hosts as $hostid => $host) {
             foreach ($host['graphids'] as $num => $graphid) {
                 $result[$graphid]['hostids'][$hostid] = $hostid;
                 $result[$graphid]['hosts'][$hostid] = $host;
             }
         }
     }
     // Adding Templates
     if ($options['select_templates']) {
         $obj_params = array('extendoutput' => 1, 'graphids' => $graphids, 'nopermissions' => 1);
         $templates = CTemplate::get($obj_params);
         foreach ($templates as $templateid => $template) {
             foreach ($template['graphids'] as $num => $graphid) {
                 $result[$graphid]['templateids'][$templateid] = $templateid;
                 $result[$graphid]['templates'][$templateid] = $template;
             }
         }
     }
     // Adding Items
     if ($options['select_items']) {
         $obj_params = array('extendoutput' => 1, 'graphids' => $graphids, 'nopermissions' => 1);
         $items = CItem::get($obj_params);
         foreach ($items as $itemid => $item) {
             foreach ($item['graphids'] as $num => $graphid) {
                 $result[$graphid]['itemids'][$itemid] = $itemid;
                 $result[$graphid]['items'][$itemid] = $item;
             }
         }
     }
     return $result;
 }
Ejemplo n.º 6
0
 /**
  * Get items data
  *
  * {@source}
  * @access public
  * @static
  * @since 1.8
  * @version 1
  *
  * @param array $options
  * @param array $options['itemids']
  * @param array $options['hostids']
  * @param array $options['groupids']
  * @param array $options['triggerids']
  * @param array $options['applicationids']
  * @param boolean $options['status']
  * @param boolean $options['templated_items']
  * @param boolean $options['editable']
  * @param boolean $options['count']
  * @param string $options['pattern']
  * @param int $options['limit']
  * @param string $options['order']
  * @return array|int item data as array or false if error
  */
 public static function get($options = array())
 {
     global $USER_DETAILS;
     $result = array();
     $user_type = $USER_DETAILS['type'];
     $userid = $USER_DETAILS['userid'];
     $sort_columns = array('itemid', 'description', 'key_', 'delay', 'history', 'trends', 'type', 'status');
     // allowed columns for sorting
     $subselects_allowed_outputs = array(API_OUTPUT_REFER, API_OUTPUT_EXTEND);
     // allowed output options for [ select_* ] params
     $sql_parts = array('select' => array('items' => 'i.itemid'), 'from' => array('items' => 'items i'), 'where' => array('webtype' => 'i.type<>9'), 'group' => array(), 'order' => array(), 'limit' => null);
     $def_options = array('nodeids' => null, 'groupids' => null, 'templateids' => null, 'hostids' => null, 'proxyids' => null, 'itemids' => null, 'graphids' => null, 'triggerids' => null, 'applicationids' => null, 'webitems' => null, 'inherited' => null, 'templated' => null, 'monitored' => null, 'editable' => null, 'nopermissions' => null, 'filter' => null, 'group' => null, 'host' => null, 'application' => null, 'belongs' => null, 'with_triggers' => null, 'filter' => null, 'search' => null, 'startSearch' => null, 'excludeSearch' => null, 'output' => API_OUTPUT_REFER, 'extendoutput' => null, 'select_hosts' => null, 'select_triggers' => null, 'select_graphs' => null, 'select_applications' => null, 'countOutput' => null, 'groupCount' => null, 'preservekeys' => null, 'sortfield' => '', 'sortorder' => '', 'limit' => null);
     $options = zbx_array_merge($def_options, $options);
     if (!is_null($options['extendoutput'])) {
         $options['output'] = API_OUTPUT_EXTEND;
         if (!is_null($options['select_hosts'])) {
             $options['select_hosts'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_triggers'])) {
             $options['select_triggers'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_graphs'])) {
             $options['select_graphs'] = API_OUTPUT_EXTEND;
         }
         if (!is_null($options['select_applications'])) {
             $options['select_applications'] = API_OUTPUT_EXTEND;
         }
     }
     // editable + PERMISSION CHECK
     if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
     } else {
         $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['from']['rights'] = 'rights r';
         $sql_parts['from']['users_groups'] = 'users_groups ug';
         $sql_parts['where'][] = 'hg.hostid=i.hostid';
         $sql_parts['where'][] = 'r.id=hg.groupid ';
         $sql_parts['where'][] = 'r.groupid=ug.usrgrpid';
         $sql_parts['where'][] = 'ug.userid=' . $userid;
         $sql_parts['where'][] = 'r.permission>=' . $permission;
         $sql_parts['where'][] = 'NOT EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups gg ' . ' WHERE hgg.hostid=hg.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . ')';
     }
     // nodeids
     $nodeids = !is_null($options['nodeids']) ? $options['nodeids'] : get_current_nodeid();
     // groupids
     if (!is_null($options['groupids'])) {
         zbx_value2array($options['groupids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['groupid'] = 'hg.groupid';
         }
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
         $sql_parts['where'][] = 'hg.hostid=i.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['hg'] = 'hg.groupid';
         }
     }
     // templateids
     if (!is_null($options['templateids'])) {
         zbx_value2array($options['templateids']);
         if (!is_null($options['hostids'])) {
             zbx_value2array($options['hostids']);
             $options['hostids'] = array_merge($options['hostids'], $options['templateids']);
         } else {
             $options['hostids'] = $options['templateids'];
         }
     }
     // hostids
     if (!is_null($options['hostids'])) {
         zbx_value2array($options['hostids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sql_parts['select']['hostid'] = 'i.hostid';
         }
         $sql_parts['where']['hostid'] = DBcondition('i.hostid', $options['hostids']);
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['i'] = 'i.hostid';
         }
     }
     // proxyids
     if (!is_null($options['proxyids'])) {
         zbx_value2array($options['proxyids']);
         if ($options['output'] != API_OUTPUT_EXTEND) {
             $sql_parts['select']['proxyid'] = 'h.proxy_hostid';
         }
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where'][] = DBcondition('h.proxy_hostid', $options['proxyids']);
         $sql_parts['where'][] = 'h.hostid=i.hostid';
         if (!is_null($options['groupCount'])) {
             $sql_parts['group']['h'] = 'h.proxy_hostid';
         }
     }
     // itemids
     if (!is_null($options['itemids'])) {
         zbx_value2array($options['itemids']);
         $sql_parts['where']['itemid'] = DBcondition('i.itemid', $options['itemids']);
     }
     // triggerids
     if (!is_null($options['triggerids'])) {
         zbx_value2array($options['triggerids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['triggerid'] = 'f.triggerid';
         }
         $sql_parts['from']['functions'] = 'functions f';
         $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']);
         $sql_parts['where']['if'] = 'i.itemid=f.itemid';
     }
     // applicationids
     if (!is_null($options['applicationids'])) {
         zbx_value2array($options['applicationids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['applicationid'] = 'ia.applicationid';
         }
         $sql_parts['from']['items_applications'] = 'items_applications ia';
         $sql_parts['where'][] = DBcondition('ia.applicationid', $options['applicationids']);
         $sql_parts['where']['ia'] = 'ia.itemid=i.itemid';
     }
     // graphids
     if (!is_null($options['graphids'])) {
         zbx_value2array($options['graphids']);
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['graphid'] = 'gi.graphid';
         }
         $sql_parts['from']['graphs_items'] = 'graphs_items gi';
         $sql_parts['where'][] = DBcondition('gi.graphid', $options['graphids']);
         $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
     }
     // webitems
     if (!is_null($options['webitems'])) {
         unset($sql_parts['where']['webtype']);
     }
     // inherited
     if (!is_null($options['inherited'])) {
         if ($options['inherited']) {
             $sql_parts['where'][] = 'i.templateid>0';
         } else {
             $sql_parts['where'][] = 'i.templateid=0';
         }
     }
     // templated
     if (!is_null($options['templated'])) {
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['templated']) {
             $sql_parts['where'][] = 'h.status=' . HOST_STATUS_TEMPLATE;
         } else {
             $sql_parts['where'][] = 'h.status<>' . HOST_STATUS_TEMPLATE;
         }
     }
     // monitored
     if (!is_null($options['monitored'])) {
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         if ($options['monitored']) {
             $sql_parts['where'][] = 'h.status=' . HOST_STATUS_MONITORED;
             $sql_parts['where'][] = 'i.status=' . ITEM_STATUS_ACTIVE;
         } else {
             $sql_parts['where'][] = '(h.status<>' . HOST_STATUS_MONITORED . ' OR i.status<>' . ITEM_STATUS_ACTIVE . ')';
         }
     }
     // search
     if (is_array($options['search'])) {
         zbx_db_search('items i', $options, $sql_parts);
     }
     // --- FILTER ---
     if (is_array($options['filter'])) {
         zbx_db_filter('items i', $options, $sql_parts);
         if (isset($options['filter']['host'])) {
             zbx_value2array($options['filter']['host']);
             $sql_parts['from']['hosts'] = 'hosts h';
             $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
             $sql_parts['where']['h'] = DBcondition('h.host', $options['filter']['host'], false, true);
         }
     }
     // group
     if (!is_null($options['group'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['name'] = 'g.name';
         }
         $sql_parts['from']['groups'] = 'groups g';
         $sql_parts['from']['hosts_groups'] = 'hosts_groups hg';
         $sql_parts['where']['ghg'] = 'g.groupid = hg.groupid';
         $sql_parts['where']['hgi'] = 'hg.hostid=i.hostid';
         $sql_parts['where'][] = ' UPPER(g.name)=' . zbx_dbstr(zbx_strtoupper($options['group']));
     }
     // host
     if (!is_null($options['host'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['host'] = 'h.host';
         }
         $sql_parts['from']['hosts'] = 'hosts h';
         $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
         $sql_parts['where'][] = ' UPPER(h.host)=' . zbx_dbstr(zbx_strtoupper($options['host']));
     }
     // application
     if (!is_null($options['application'])) {
         if ($options['output'] != API_OUTPUT_SHORTEN) {
             $sql_parts['select']['application'] = 'a.name as application';
         }
         $sql_parts['from']['applications'] = 'applications a';
         $sql_parts['from']['items_applications'] = 'items_applications ia';
         $sql_parts['where']['aia'] = 'a.applicationid = ia.applicationid';
         $sql_parts['where']['iai'] = 'ia.itemid=i.itemid';
         $sql_parts['where'][] = ' UPPER(a.name)=' . zbx_dbstr(zbx_strtoupper($options['application']));
     }
     // with_triggers
     if (!is_null($options['with_triggers'])) {
         if ($options['with_triggers'] == 1) {
             $sql_parts['where'][] = ' EXISTS ( SELECT functionid FROM functions ff WHERE ff.itemid=i.itemid )';
         } else {
             $sql_parts['where'][] = 'NOT EXISTS ( SELECT functionid FROM functions ff WHERE ff.itemid=i.itemid )';
         }
     }
     // output
     if ($options['output'] == API_OUTPUT_EXTEND) {
         $sql_parts['select']['items'] = 'i.*';
     }
     // countOutput
     if (!is_null($options['countOutput'])) {
         $options['sortfield'] = '';
         $sql_parts['select'] = array('count(DISTINCT i.itemid) as rowscount');
         //groupCount
         if (!is_null($options['groupCount'])) {
             foreach ($sql_parts['group'] as $key => $fields) {
                 $sql_parts['select'][$key] = $fields;
             }
         }
     }
     // order
     // restrict not allowed columns for sorting
     $options['sortfield'] = str_in_array($options['sortfield'], $sort_columns) ? $options['sortfield'] : '';
     if (!zbx_empty($options['sortfield'])) {
         $sortorder = $options['sortorder'] == ZBX_SORT_DOWN ? ZBX_SORT_DOWN : ZBX_SORT_UP;
         $sql_parts['order'][] = 'i.' . $options['sortfield'] . ' ' . $sortorder;
         if (!str_in_array('i.' . $options['sortfield'], $sql_parts['select']) && !str_in_array('i.*', $sql_parts['select'])) {
             $sql_parts['select'][] = 'i.' . $options['sortfield'];
         }
     }
     // limit
     if (zbx_ctype_digit($options['limit']) && $options['limit']) {
         $sql_parts['limit'] = $options['limit'];
     }
     //----------
     $itemids = array();
     $sql_parts['select'] = array_unique($sql_parts['select']);
     $sql_parts['from'] = array_unique($sql_parts['from']);
     $sql_parts['where'] = array_unique($sql_parts['where']);
     $sql_parts['group'] = array_unique($sql_parts['group']);
     $sql_parts['order'] = array_unique($sql_parts['order']);
     $sql_select = '';
     $sql_from = '';
     $sql_where = '';
     $sql_group = '';
     $sql_order = '';
     if (!empty($sql_parts['select'])) {
         $sql_select .= implode(',', $sql_parts['select']);
     }
     if (!empty($sql_parts['from'])) {
         $sql_from .= implode(',', $sql_parts['from']);
     }
     if (!empty($sql_parts['where'])) {
         $sql_where .= ' AND ' . implode(' AND ', $sql_parts['where']);
     }
     if (!empty($sql_parts['group'])) {
         $sql_where .= ' GROUP BY ' . implode(',', $sql_parts['group']);
     }
     if (!empty($sql_parts['order'])) {
         $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
     }
     $sql_limit = $sql_parts['limit'];
     $sql = 'SELECT ' . zbx_db_distinct($sql_parts) . ' ' . $sql_select . ' FROM ' . $sql_from . ' WHERE ' . DBin_node('i.itemid', $nodeids) . $sql_where . $sql_group . $sql_order;
     $res = DBselect($sql, $sql_limit);
     while ($item = DBfetch($res)) {
         if (!is_null($options['countOutput'])) {
             if (!is_null($options['groupCount'])) {
                 $result[] = $item;
             } else {
                 $result = $item['rowscount'];
             }
         } else {
             $itemids[$item['itemid']] = $item['itemid'];
             if ($options['output'] == API_OUTPUT_SHORTEN) {
                 $result[$item['itemid']] = array('itemid' => $item['itemid']);
             } else {
                 if (!isset($result[$item['itemid']])) {
                     $result[$item['itemid']] = array();
                 }
                 if (!is_null($options['select_hosts']) && !isset($result[$item['itemid']]['hosts'])) {
                     $result[$item['itemid']]['hosts'] = array();
                 }
                 if (!is_null($options['select_triggers']) && !isset($result[$item['itemid']]['triggers'])) {
                     $result[$item['itemid']]['triggers'] = array();
                 }
                 if (!is_null($options['select_graphs']) && !isset($result[$item['itemid']]['graphs'])) {
                     $result[$item['itemid']]['graphs'] = array();
                 }
                 if (!is_null($options['select_applications']) && !isset($result[$item['itemid']]['applications'])) {
                     $result[$item['itemid']]['applications'] = array();
                 }
                 // hostids
                 if (isset($item['hostid']) && is_null($options['select_hosts'])) {
                     if (!isset($result[$item['itemid']]['hosts'])) {
                         $result[$item['itemid']]['hosts'] = array();
                     }
                     $result[$item['itemid']]['hosts'][] = array('hostid' => $item['hostid']);
                     //						unset($item['hostid']);
                 }
                 // triggerids
                 if (isset($item['triggerid']) && is_null($options['select_triggers'])) {
                     if (!isset($result[$item['itemid']]['triggers'])) {
                         $result[$item['itemid']]['triggers'] = array();
                     }
                     $result[$item['itemid']]['triggers'][] = array('triggerid' => $item['triggerid']);
                     unset($item['triggerid']);
                 }
                 // graphids
                 if (isset($item['graphid']) && is_null($options['select_graphs'])) {
                     if (!isset($result[$item['itemid']]['graphs'])) {
                         $result[$item['itemid']]['graphs'] = array();
                     }
                     $result[$item['itemid']]['graphs'][] = array('graphid' => $item['graphid']);
                     unset($item['graphid']);
                 }
                 // applicationids
                 if (isset($item['applicationid']) && is_null($options['select_applications'])) {
                     if (!isset($result[$item['itemid']]['applications'])) {
                         $result[$item['itemid']]['applications'] = array();
                     }
                     $result[$item['itemid']]['applications'][] = array('applicationid' => $item['applicationid']);
                     unset($item['applicationid']);
                 }
                 $result[$item['itemid']] += $item;
             }
         }
     }
     COpt::memoryPick();
     if (!is_null($options['countOutput'])) {
         if (is_null($options['preservekeys'])) {
             $result = zbx_cleanHashes($result);
         }
         return $result;
     }
     // Adding Objects
     // Adding hosts
     if (!is_null($options['select_hosts'])) {
         if (is_array($options['select_hosts']) || str_in_array($options['select_hosts'], $subselects_allowed_outputs)) {
             $obj_params = array('nodeids' => $nodeids, 'itemids' => $itemids, 'templated_hosts' => 1, 'output' => $options['select_hosts'], 'nopermissions' => 1, 'preservekeys' => 1);
             $hosts = CHost::get($obj_params);
             foreach ($hosts as $hostid => $host) {
                 $hitems = $host['items'];
                 unset($host['items']);
                 foreach ($hitems as $inum => $item) {
                     $result[$item['itemid']]['hosts'][] = $host;
                 }
             }
             $templates = CTemplate::get($obj_params);
             foreach ($templates as $templateid => $template) {
                 $titems = $template['items'];
                 unset($template['items']);
                 foreach ($titems as $inum => $item) {
                     $result[$item['itemid']]['hosts'][] = $template;
                 }
             }
         }
     }
     // Adding triggers
     if (!is_null($options['select_triggers']) && str_in_array($options['select_triggers'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_triggers'], 'itemids' => $itemids, 'preservekeys' => 1);
         $triggers = CTrigger::get($obj_params);
         foreach ($triggers as $triggerid => $trigger) {
             $titems = $trigger['items'];
             unset($trigger['items']);
             foreach ($titems as $inum => $item) {
                 $result[$item['itemid']]['triggers'][] = $trigger;
             }
         }
     }
     // Adding graphs
     if (!is_null($options['select_graphs']) && str_in_array($options['select_graphs'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_graphs'], 'itemids' => $itemids, 'preservekeys' => 1);
         $graphs = CGraph::get($obj_params);
         foreach ($graphs as $graphid => $graph) {
             $gitems = $graph['items'];
             unset($graph['items']);
             foreach ($gitems as $inum => $item) {
                 $result[$item['itemid']]['graphs'][] = $graph;
             }
         }
     }
     // Adding applications
     if (!is_null($options['select_applications']) && str_in_array($options['select_applications'], $subselects_allowed_outputs)) {
         $obj_params = array('nodeids' => $nodeids, 'output' => $options['select_applications'], 'itemids' => $itemids, 'preservekeys' => 1);
         $applications = CApplication::get($obj_params);
         foreach ($applications as $applicationid => $application) {
             $aitems = $application['items'];
             unset($application['items']);
             foreach ($aitems as $inum => $item) {
                 $result[$item['itemid']]['applications'][] = $application;
             }
         }
     }
     COpt::memoryPick();
     // removing keys (hash -> array)
     if (is_null($options['preservekeys'])) {
         $result = zbx_cleanHashes($result);
     }
     return $result;
 }
Ejemplo n.º 7
0
 /**
  * Update HostGroups with new Hosts (rewrite)
  *
  * @param array $data
  * @param array $data['groups']
  * @param array $data['hosts']
  * @param array $data['templates']
  * @return boolean
  */
 public static function massUpdate($data)
 {
     $groups = zbx_toArray($data['groups']);
     $hosts = isset($data['hosts']) ? zbx_toArray($data['hosts']) : null;
     $templates = isset($data['templates']) ? zbx_toArray($data['templates']) : null;
     $groupids = zbx_objectValues($groups, 'groupid');
     $hostids = zbx_objectValues($hosts, 'hostid');
     $templateids = zbx_objectValues($templates, 'templateid');
     try {
         self::BeginTransaction(__METHOD__);
         $hosts_to_unlink = $hosts_to_link = array();
         $options = array('groupids' => $groupids, 'preservekeys' => 1);
         if (!is_null($hosts)) {
             $groups_hosts = CHost::get($options);
             $hosts_to_unlink = array_diff(array_keys($groups_hosts), $hostids);
             $hosts_to_link = array_diff($hostids, array_keys($groups_hosts));
         }
         $templates_to_unlink = $templates_to_link = array();
         if (!is_null($templates)) {
             $groups_templates = CTemplate::get($options);
             $templates_to_unlink = array_diff(array_keys($groups_templates), $templateids);
             $templates_to_link = array_diff($templateids, array_keys($groups_templates));
         }
         $objectids_to_link = array_merge($hosts_to_link, $templates_to_link);
         $objectids_to_unlink = array_merge($hosts_to_unlink, $templates_to_unlink);
         // PERMISSION {{{
         $options = array('groupids' => $groupids, 'editable' => 1, 'preservekeys' => 1);
         $allowed_groups = self::get($options);
         foreach ($groups as $num => $group) {
             if (!isset($allowed_groups[$group['groupid']])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
             }
         }
         if (!is_null($hosts)) {
             $hosts_to_check = array_merge($hosts_to_link, $hosts_to_unlink);
             $options = array('hostids' => $hosts_to_check, 'editable' => 1, 'preservekeys' => 1);
             $allowed_hosts = CHost::get($options);
             foreach ($hosts_to_check as $num => $hostid) {
                 if (!isset($allowed_hosts[$hostid])) {
                     self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
                 }
             }
         }
         if (!is_null($templates)) {
             $templates_to_check = array_merge($templates_to_link, $templates_to_unlink);
             $options = array('templateids' => $templates_to_check, 'editable' => 1, 'preservekeys' => 1);
             $allowed_templates = CTemplate::get($options);
             foreach ($templates_to_check as $num => $templateid) {
                 if (!isset($allowed_templates[$templateid])) {
                     self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
                 }
             }
         }
         // }}} PERMISSION
         $unlinkable = getUnlinkableHosts($groupids, $objectids_to_unlink);
         if (count($objectids_to_unlink) != count($unlinkable)) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'One of the Objects is left without Hostgroup');
         }
         $sql = 'DELETE FROM hosts_groups WHERE ' . DBcondition('groupid', $groupids) . ' AND ' . DBcondition('hostid', $objectids_to_unlink);
         if (!DBexecute($sql)) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror');
         }
         foreach ($groupids as $gnum => $groupid) {
             foreach ($objectids_to_link as $objectid) {
                 $hostgroupid = get_dbid('hosts_groups', 'hostgroupid');
                 $result = DBexecute("INSERT INTO hosts_groups (hostgroupid, hostid, groupid) VALUES ({$hostgroupid}, {$objectid}, {$groupid})");
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror');
                 }
             }
         }
         self::EndTransaction(true, __METHOD__);
         return array('groupids' => $groupids);
     } catch (APIException $e) {
         self::EndTransaction(false, __METHOD__);
         $error = $e->getErrors();
         $error = reset($error);
         self::setError(__METHOD__, $e->getCode(), $error);
         return false;
     }
 }
Ejemplo n.º 8
0
 public static function getMacros($macros, $options)
 {
     zbx_value2array($macros);
     $macros = array_unique($macros);
     $result = array();
     $obj_options = array('itemids' => isset($options['itemid']) ? $options['itemid'] : null, 'triggerids' => isset($options['triggerid']) ? $options['triggerid'] : null, 'nopermissions' => 1, 'preservekeys' => 1, 'output' => API_OUTPUT_SHORTEN, 'templated_hosts' => true);
     $hosts = CHost::get($obj_options);
     $hostids = array_keys($hosts);
     do {
         $obj_options = array('hostids' => $hostids, 'macros' => $macros, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => 1, 'preservekeys' => 1);
         $host_macros = self::get($obj_options);
         order_result($host_macros, 'hostid');
         foreach ($macros as $mnum => $macro) {
             foreach ($host_macros as $hmnum => $hmacro) {
                 if ($macro == $hmacro['macro']) {
                     $result[$macro] = $hmacro['value'];
                     unset($host_macros[$hmnum], $macros[$mnum]);
                     break;
                 }
             }
         }
         if (!empty($macros)) {
             $obj_options = array('hostids' => $hostids, 'nopermissions' => 1, 'preservekeys' => 1, 'output' => API_OUTPUT_SHORTEN);
             $hosts = CTemplate::get($obj_options);
             $hostids = array_keys($hosts);
         }
     } while (!empty($macros) && !empty($hostids));
     if (!empty($macros)) {
         $obj_options = array('output' => API_OUTPUT_EXTEND, 'globalmacro' => 1, 'nopermissions' => 1, 'macros' => $macros);
         $gmacros = self::get($obj_options);
         foreach ($macros as $macro) {
             foreach ($gmacros as $mid => $gmacro) {
                 if ($macro == $gmacro['macro']) {
                     $result[$macro] = $gmacro['value'];
                     unset($gmacros[$mid]);
                     break;
                 }
             }
         }
     }
     return $result;
 }
Ejemplo n.º 9
0
function validate_operation($operation)
{
    if (isset($operation['esc_period']) && ($operation['esc_period'] > 0 && $operation['esc_period'] < 60)) {
        error(S_INCORRECT_ESCALATION_PERIOD);
        return false;
    }
    switch ($operation['operationtype']) {
        case OPERATION_TYPE_MESSAGE:
            switch ($operation['object']) {
                case OPERATION_OBJECT_USER:
                    $users = CUser::get(array('userids' => $operation['objectid'], 'output' => API_OUTPUT_EXTEND));
                    if (empty($users)) {
                        error(S_INCORRECT_USER);
                        return false;
                    }
                    break;
                case OPERATION_OBJECT_GROUP:
                    $usrgrps = CUserGroup::get(array('usrgrpids' => $operation['objectid'], 'output' => API_OUTPUT_EXTEND));
                    if (empty($usrgrps)) {
                        error(S_INCORRECT_GROUP);
                        return false;
                    }
                    break;
                default:
                    error(S_INCORRECT_OBJECT_TYPE);
                    return false;
            }
            break;
        case OPERATION_TYPE_COMMAND:
            return validate_commands($operation['longdata']);
        case OPERATION_TYPE_HOST_ADD:
        case OPERATION_TYPE_HOST_REMOVE:
        case OPERATION_TYPE_HOST_ENABLE:
        case OPERATION_TYPE_HOST_DISABLE:
            break;
        case OPERATION_TYPE_GROUP_ADD:
        case OPERATION_TYPE_GROUP_REMOVE:
            $groups = CHostGroup::get(array('groupids' => $operation['objectid'], 'output' => API_OUTPUT_SHORTEN, 'editable' => 1));
            if (empty($groups)) {
                error(S_INCORRECT_GROUP);
                return false;
            }
            break;
        case OPERATION_TYPE_TEMPLATE_ADD:
        case OPERATION_TYPE_TEMPLATE_REMOVE:
            $tpls = CTemplate::get(array('templateids' => $operation['objectid'], 'output' => API_OUTPUT_SHORTEN, 'editable' => 1));
            if (empty($tpls)) {
                error(S_INCORRECT_HOST);
                return false;
            }
            break;
        default:
            error(S_INCORRECT_OPERATION_TYPE);
            return false;
    }
    return true;
}
Ejemplo n.º 10
0
    /**
     * Get Host data
     *
     * {@source}
     * @access public
     * @static
     * @since 1.8
     * @version 1
     *
     * @param _array $options
     * @param array $options['nodeids'] Node IDs
     * @param array $options['groupids'] HostGroup IDs
     * @param array $options['hostids'] Host IDs
     * @param boolean $options['monitored_hosts'] only monitored Hosts
     * @param boolean $options['templated_hosts'] include templates in result
     * @param boolean $options['with_items'] only with items
     * @param boolean $options['with_monitored_items'] only with monitored items
     * @param boolean $options['with_historical_items'] only with historical items
     * @param boolean $options['with_triggers'] only with triggers
     * @param boolean $options['with_monitored_triggers'] only with monitores triggers
     * @param boolean $options['with_httptests'] only with http tests
     * @param boolean $options['with_monitored_httptests'] only with monitores http tests
     * @param boolean $options['with_graphs'] only with graphs
     * @param boolean $options['editable'] only with read-write permission. Ignored for SuperAdmins
     * @param int $options['extendoutput'] return all fields for Hosts
     * @param int $options['count'] count Hosts, returned column name is rowscount
     * @param string $options['pattern'] search hosts by pattern in host names
     * @param int $options['limit'] limit selection
     * @param string $options['order'] depricated parametr (for now)
     * @return array|boolean Host data as array or false if error
     */
    public static function get($options = array())
    {
        global $USER_DETAILS;
        $result = array();
        $user_type = $USER_DETAILS['type'];
        $userid = $USER_DETAILS['userid'];
        $sort_columns = array('hostid', 'host');
        // allowed columns for sorting
        $sql_parts = array('select' => array('hosts' => 'h.hostid'), 'from' => array('hosts h'), 'where' => array(), 'order' => array(), 'limit' => null);
        $def_options = array('nodeids' => 0, 'groupids' => 0, 'hostids' => 0, 'templateids' => 0, 'triggerids' => 0, 'graphids' => 0, 'monitored_hosts' => 0, 'templated_hosts' => 0, 'with_items' => 0, 'with_monitored_items' => 0, 'with_historical_items' => 0, 'with_triggers' => 0, 'with_monitored_triggers' => 0, 'with_httptests' => 0, 'with_monitored_httptests' => 0, 'with_graphs' => 0, 'editable' => 0, 'nopermissions' => 0, 'extendoutput' => 0, 'select_templates' => 0, 'select_items' => 0, 'select_triggers' => 0, 'select_graphs' => 0, 'count' => 0, 'pattern' => '', 'extend_pattern' => 0, 'order' => '', 'limit' => 0);
        $options = array_merge($def_options, $options);
        // editable + PERMISSION CHECK
        if (defined('ZBX_API_REQUEST')) {
            $options['nopermissions'] = false;
        }
        if (USER_TYPE_SUPER_ADMIN == $user_type || $options['nopermissions']) {
        } else {
            $permission = $options['editable'] ? PERM_READ_WRITE : PERM_READ_ONLY;
            $sql_parts['from']['hg'] = 'hosts_groups hg';
            $sql_parts['from']['r'] = 'rights r';
            $sql_parts['from']['ug'] = 'users_groups ug';
            $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid';
            $sql_parts['where'][] = 'r.id=hg.groupid ';
            $sql_parts['where'][] = 'r.groupid=ug.usrgrpid';
            $sql_parts['where'][] = 'ug.userid=' . $userid;
            $sql_parts['where'][] = 'r.permission>=' . $permission;
            $sql_parts['where'][] = 'NOT EXISTS( ' . ' SELECT hgg.groupid ' . ' FROM hosts_groups hgg, rights rr, users_groups gg ' . ' WHERE hgg.hostid=hg.hostid ' . ' AND rr.id=hgg.groupid ' . ' AND rr.groupid=gg.usrgrpid ' . ' AND gg.userid=' . $userid . ' AND rr.permission<' . $permission . ')';
        }
        // nodeids
        $nodeids = $options['nodeids'] ? $options['nodeids'] : get_current_nodeid(false);
        // groupids
        if ($options['groupids'] != 0) {
            zbx_value2array($options['groupids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['groupid'] = 'hg.groupid';
            }
            $sql_parts['from']['hg'] = 'hosts_groups hg';
            $sql_parts['where'][] = DBcondition('hg.groupid', $options['groupids']);
            $sql_parts['where']['hgh'] = 'hg.hostid=h.hostid';
        }
        // hostids
        if ($options['hostids'] != 0) {
            zbx_value2array($options['hostids']);
            $sql_parts['where'][] = DBcondition('h.hostid', $options['hostids']);
        }
        // templateids
        if ($options['templateids'] != 0) {
            zbx_value2array($options['templateids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['templateid'] = 'ht.templateid';
            }
            $sql_parts['from']['ht'] = 'hosts_templates ht';
            $sql_parts['where'][] = DBcondition('ht.templateid', $options['templateids']);
            $sql_parts['where']['hht'] = 'h.hostid=ht.hostid';
        }
        // triggerids
        if ($options['triggerids'] != 0) {
            zbx_value2array($options['triggerids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['triggerid'] = 'f.triggerid';
            }
            $sql_parts['from']['f'] = 'functions f';
            $sql_parts['from']['i'] = 'items i';
            $sql_parts['where'][] = DBcondition('f.triggerid', $options['triggerids']);
            $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
            $sql_parts['where']['fi'] = 'f.itemid=i.itemid';
        }
        // graphids
        if ($options['graphids'] != 0) {
            zbx_value2array($options['graphids']);
            if ($options['extendoutput'] != 0) {
                $sql_parts['select']['graphid'] = 'gi.graphid';
            }
            $sql_parts['from']['gi'] = 'graphs_items gi';
            $sql_parts['from']['i'] = 'items i';
            $sql_parts['where'][] = DBcondition('gi.graphid', $options['graphids']);
            $sql_parts['where']['igi'] = 'i.itemid=gi.itemid';
            $sql_parts['where']['hi'] = 'h.hostid=i.hostid';
        }
        // monitored_hosts, templated_hosts
        if ($options['monitored_hosts'] != 0) {
            $sql_parts['where'][] = 'h.status=' . HOST_STATUS_MONITORED;
        } else {
            if ($options['templated_hosts'] != 0) {
                $sql_parts['where'][] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ',' . HOST_STATUS_TEMPLATE . ')';
            } else {
                $sql_parts['where'][] = 'h.status IN (' . HOST_STATUS_MONITORED . ',' . HOST_STATUS_NOT_MONITORED . ')';
            }
        }
        // with_items, with_monitored_items, with_historical_items
        if ($options['with_items'] != 0) {
            $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid )';
        } else {
            if ($options['with_monitored_items'] != 0) {
                $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND i.status=' . ITEM_STATUS_ACTIVE . ')';
            } else {
                if ($options['with_historical_items']) {
                    $sql_parts['where'][] = 'EXISTS (SELECT i.hostid FROM items i WHERE h.hostid=i.hostid AND (i.status=' . ITEM_STATUS_ACTIVE . ' OR i.status=' . ITEM_STATUS_NOTSUPPORTED . ') AND i.lastvalue IS NOT NULL)';
                }
            }
        }
        // with_triggers, with_monitored_triggers
        if ($options['with_triggers'] != 0) {
            $sql_parts['where'][] = 'EXISTS( 
					SELECT i.itemid
					FROM items i, functions f, triggers t
					WHERE i.hostid=h.hostid 
						AND i.itemid=f.itemid 
						AND f.triggerid=t.triggerid)';
        } else {
            if ($options['with_monitored_triggers'] != 0) {
                $sql_parts['where'][] = 'EXISTS( 
					SELECT i.itemid 
					FROM items i, functions f, triggers t
					WHERE i.hostid=h.hostid 
						AND i.status=' . ITEM_STATUS_ACTIVE . '
						AND i.itemid=f.itemid 
						AND f.triggerid=t.triggerid 
						AND t.status=' . TRIGGER_STATUS_ENABLED . ')';
            }
        }
        // with_httptests, with_monitored_httptests
        if ($options['with_httptests'] != 0) {
            $sql_parts['where'][] = 'EXISTS( 
					SELECT a.applicationid 
					FROM applications a, httptest ht 
					WHERE a.hostid=h.hostid 
						AND ht.applicationid=a.applicationid)';
        } else {
            if ($options['with_monitored_httptests'] != 0) {
                $sql_parts['where'][] = 'EXISTS( 
					SELECT a.applicationid 	
					FROM applications a, httptest ht 	
					WHERE a.hostid=h.hostid	
						AND ht.applicationid=a.applicationid 	
						AND ht.status=' . HTTPTEST_STATUS_ACTIVE . ')';
            }
        }
        // with_graphs
        if ($options['with_graphs'] != 0) {
            $sql_parts['where'][] = 'EXISTS( 
					SELECT DISTINCT i.itemid 
					FROM items i, graphs_items gi 
					WHERE i.hostid=h.hostid 
						AND i.itemid=gi.itemid)';
        }
        // extendoutput
        if ($options['extendoutput'] != 0) {
            $sql_parts['select']['hosts'] = 'h.*';
        }
        // count
        if ($options['count'] != 0) {
            $options['select_templates'] = 0;
            $options['select_items'] = 0;
            $options['select_triggers'] = 0;
            $options['select_graphs'] = 0;
            $sql_parts['select'] = array('count(h.hostid) as rowscount');
        }
        // pattern
        if (!zbx_empty($options['pattern'])) {
            if ($options['extend_pattern']) {
                $sql_parts['where'][] = ' ( ' . 'UPPER(h.host) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%') . ' OR ' . 'h.ip LIKE ' . zbx_dbstr('%' . $options['pattern'] . '%') . ' OR ' . 'UPPER(h.dns) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%') . ' ) ';
            } else {
                $sql_parts['where'][] = ' UPPER(h.host) LIKE ' . zbx_dbstr('%' . strtoupper($options['pattern']) . '%');
            }
        }
        // order
        // restrict not allowed columns for sorting
        $options['order'] = str_in_array($options['order'], $sort_columns) ? $options['order'] : '';
        if (!zbx_empty($options['order'])) {
            $sql_parts['order'][] = 'h.' . $options['order'];
            if (!str_in_array('h.' . $options['order'], $sql_parts['select'])) {
                $sql_parts['select'][] = 'h.' . $options['order'];
            }
        }
        // limit
        if (zbx_ctype_digit($options['limit']) && $options['limit']) {
            $sql_parts['limit'] = $options['limit'];
        }
        //-------
        $hostids = array();
        $sql_parts['select'] = array_unique($sql_parts['select']);
        $sql_parts['from'] = array_unique($sql_parts['from']);
        $sql_parts['where'] = array_unique($sql_parts['where']);
        $sql_parts['order'] = array_unique($sql_parts['order']);
        $sql_select = '';
        $sql_from = '';
        $sql_where = '';
        $sql_order = '';
        if (!empty($sql_parts['select'])) {
            $sql_select .= implode(',', $sql_parts['select']);
        }
        if (!empty($sql_parts['from'])) {
            $sql_from .= implode(',', $sql_parts['from']);
        }
        if (!empty($sql_parts['where'])) {
            $sql_where .= ' AND ' . implode(' AND ', $sql_parts['where']);
        }
        if (!empty($sql_parts['order'])) {
            $sql_order .= ' ORDER BY ' . implode(',', $sql_parts['order']);
        }
        $sql_limit = $sql_parts['limit'];
        $sql = 'SELECT ' . $sql_select . '
				FROM ' . $sql_from . '
				WHERE ' . DBin_node('h.hostid', $nodeids) . $sql_where . $sql_order;
        $res = DBselect($sql, $sql_limit);
        while ($host = DBfetch($res)) {
            if ($options['count']) {
                $result = $host;
            } else {
                $hostids[$host['hostid']] = $host['hostid'];
                if ($options['extendoutput'] == 0) {
                    $result[$host['hostid']] = $host['hostid'];
                } else {
                    if (!isset($result[$host['hostid']])) {
                        $result[$host['hostid']] = array();
                    }
                    if ($options['select_templates'] && !isset($result[$host['hostid']]['templateids'])) {
                        $result[$host['hostid']]['templateids'] = array();
                        $result[$host['hostid']]['templates'] = array();
                    }
                    if ($options['select_items'] && !isset($result[$host['hostid']]['itemids'])) {
                        $result[$host['hostid']]['itemids'] = array();
                        $result[$host['hostid']]['items'] = array();
                    }
                    if ($options['select_triggers'] && !isset($result[$host['hostid']]['triggerids'])) {
                        $result[$host['hostid']]['triggerids'] = array();
                        $result[$host['hostid']]['triggers'] = array();
                    }
                    if ($options['select_graphs'] && !isset($result[$host['hostid']]['graphids'])) {
                        $result[$host['hostid']]['graphids'] = array();
                        $result[$host['hostid']]['graphs'] = array();
                    }
                    // groupids
                    if (isset($host['groupid'])) {
                        if (!isset($result[$host['hostid']]['groupids'])) {
                            $result[$host['hostid']]['groupids'] = array();
                        }
                        $result[$host['hostid']]['groupids'][$host['groupid']] = $host['groupid'];
                        unset($host['groupid']);
                    }
                    // templateids
                    if (isset($host['templateid'])) {
                        if (!isset($result[$host['hostid']]['templateids'])) {
                            $result[$host['hostid']]['templateids'] = array();
                        }
                        $result[$host['hostid']]['templateids'][$host['templateid']] = $host['templateid'];
                        unset($host['templateid']);
                    }
                    // triggerids
                    if (isset($host['triggerid'])) {
                        if (!isset($result[$host['hostid']]['triggerids'])) {
                            $result[$host['hostid']]['triggerids'] = array();
                        }
                        $result[$host['hostid']]['triggerids'][$host['triggerid']] = $host['triggerid'];
                        unset($host['triggerid']);
                    }
                    // itemids
                    if (isset($host['itemid'])) {
                        if (!isset($result[$host['hostid']]['itemids'])) {
                            $result[$host['hostid']]['itemids'] = array();
                        }
                        $result[$host['hostid']]['itemids'][$host['itemid']] = $host['itemid'];
                        unset($host['itemid']);
                    }
                    // graphids
                    if (isset($host['graphid'])) {
                        if (!isset($result[$host['hostid']]['graphids'])) {
                            $result[$host['hostid']]['graphids'] = array();
                        }
                        $result[$host['hostid']]['graphids'][$host['graphid']] = $host['graphid'];
                        unset($host['graphid']);
                    }
                    $result[$host['hostid']] += $host;
                }
            }
        }
        // Adding Objects
        // Adding Templates
        if ($options['select_templates']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids);
            $templates = CTemplate::get($obj_params);
            foreach ($templates as $templateid => $template) {
                foreach ($template['hostids'] as $num => $hostid) {
                    $result[$hostid]['templateids'][$templateid] = $templateid;
                    $result[$hostid]['templates'][$templateid] = $template;
                }
            }
        }
        // Adding Items
        if ($options['select_items']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids, 'nopermissions' => 1);
            $items = CItem::get($obj_params);
            foreach ($items as $itemid => $item) {
                foreach ($item['hostids'] as $num => $hostid) {
                    $result[$hostid]['itemids'][$itemid] = $itemid;
                    $result[$hostid]['items'][$itemid] = $item;
                }
            }
        }
        // Adding triggers
        if ($options['select_triggers']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids);
            $triggers = CTrigger::get($obj_params);
            foreach ($triggers as $triggerid => $trigger) {
                foreach ($trigger['hostids'] as $num => $hostid) {
                    $result[$hostid]['triggerids'][$triggerid] = $triggerid;
                    $result[$hostid]['triggers'][$triggerid] = $trigger;
                }
            }
        }
        // Adding graphs
        if ($options['select_graphs']) {
            $obj_params = array('extendoutput' => 1, 'hostids' => $hostids);
            $graphs = CGraph::get($obj_params);
            foreach ($graphs as $graphid => $graph) {
                foreach ($graph['hostids'] as $num => $hostid) {
                    $result[$hostid]['graphids'][$graphid] = $graphid;
                    $result[$hostid]['graphs'][$graphid] = $graph;
                }
            }
        }
        return $result;
    }
Ejemplo n.º 11
0
     foreach ($templates as $tnum => $row) {
         $name = new CSpan($row['host'], 'link');
         $action = get_window_opener($dstfrm, $dstfld1, $row[$srcfld1]) . (isset($srcfld2) ? get_window_opener($dstfrm, $dstfld2, $row[$srcfld2]) : '');
         $name->setAttribute('onclick', $action . " close_window(); return false;");
         $table->addRow($name);
     }
     $table->show();
 } else {
     if ($srctbl == 'hosts_and_templates') {
         $table = new CTableInfo(S_NO_TEMPLATES_DEFINED);
         $table->setHeader(array(S_NAME));
         $options = array('nodeids' => $nodeid, 'groupids' => $groupid, 'output' => API_OUTPUT_EXTEND, 'sortfield' => 'host');
         if (!is_null($writeonly)) {
             $options['editable'] = 1;
         }
         $templates = CTemplate::get($options);
         foreach ($templates as $tnum => $template) {
             $templates[$tnum]['hostid'] = $template['templateid'];
         }
         $hosts = CHost::get($options);
         $objects = array_merge($templates, $hosts);
         foreach ($objects as $row) {
             $name = new CSpan($row['host'], 'link');
             $action = get_window_opener($dstfrm, $dstfld1, $row[$srcfld1]) . (isset($srcfld2) ? get_window_opener($dstfrm, $dstfld2, $row[$srcfld2]) : '');
             $name->setAttribute('onclick', $action . " close_window(); return false;");
             $table->addRow($name);
         }
         $table->show();
     } else {
         if ($srctbl == 'usrgrp') {
             $table = new CTableInfo(S_NO_GROUPS_DEFINED);
Ejemplo n.º 12
0
 /**
  * Inherit template graphs from template to host
  *
  * params: templateids, hostids
  *
  * @param array $data
  * @return boolean
  */
 public static function syncTemplates($data)
 {
     try {
         self::BeginTransaction(__METHOD__);
         $data['templateids'] = zbx_toArray($data['templateids']);
         $data['hostids'] = zbx_toArray($data['hostids']);
         $options = array('hostids' => $data['hostids'], 'editable' => 1, 'preservekeys' => 1, 'templated_hosts' => 1, 'output' => API_OUTPUT_SHORTEN);
         $allowedHosts = CHost::get($options);
         foreach ($data['hostids'] as $hostid) {
             if (!isset($allowedHosts[$hostid])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
             }
         }
         $options = array('templateids' => $data['templateids'], 'preservekeys' => 1, 'output' => API_OUTPUT_SHORTEN);
         $allowedTemplates = CTemplate::get($options);
         foreach ($data['templateids'] as $templateid) {
             if (!isset($allowedTemplates[$templateid])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
             }
         }
         $sql = 'SELECT hostid, templateid' . ' FROM hosts_templates' . ' WHERE ' . DBcondition('hostid', $data['hostids']) . ' AND ' . DBcondition('templateid', $data['templateids']);
         $db_links = DBSelect($sql);
         $linkage = array();
         while ($link = DBfetch($db_links)) {
             if (!isset($linkage[$link['templateid']])) {
                 $linkage[$link['templateid']] = array();
             }
             $linkage[$link['templateid']][$link['hostid']] = 1;
         }
         $options = array('hostids' => $data['templateids'], 'preservekeys' => 1, 'output' => API_OUTPUT_EXTEND, 'select_graph_items' => API_OUTPUT_EXTEND);
         $graphs = self::get($options);
         foreach ($graphs as $graph) {
             foreach ($data['hostids'] as $hostid) {
                 if (isset($linkage[$graph['hosts'][0]['hostid']][$hostid])) {
                     self::inherit($graph, $hostid);
                 }
             }
         }
         self::EndTransaction(true, __METHOD__);
         return true;
     } catch (APIException $e) {
         self::EndTransaction(false, __METHOD__);
         $error = $e->getErrors();
         $error = reset($error);
         self::setError(__METHOD__, $e->getCode(), $error);
         return false;
     }
 }
Ejemplo n.º 13
0
}
if (get_request('hostid', 0) > 0) {
    $hostids = available_hosts($_REQUEST['hostid'], 1);
    if (empty($hostids)) {
        access_deny();
    }
}
/*** <--- ACTIONS ---> ***/
if (isset($_REQUEST['clone']) && isset($_REQUEST['groupid'])) {
    unset($_REQUEST['groupid']);
    $_REQUEST['form'] = 'clone';
} else {
    if (isset($_REQUEST['save'])) {
        $objects = get_request('hosts', array());
        $hosts = CHost::get(array('hostids' => $objects, 'output' => API_OUTPUT_SHORTEN));
        $templates = CTemplate::get(array('templateids' => $objects, 'output' => API_OUTPUT_SHORTEN));
        if (isset($_REQUEST['groupid'])) {
            DBstart();
            $old_group = CHostGroup::get(array('groupids' => $_REQUEST['groupid'], 'output' => API_OUTPUT_EXTEND));
            $old_group = reset($old_group);
            $result = CHostGroup::update(array('groupid' => $_REQUEST['groupid'], 'name' => $_REQUEST['gname']));
            if ($result) {
                $options = array('groupids' => $result['groupids'], 'output' => API_OUTPUT_EXTEND);
                $groups = CHostGroup::get($options);
                $data = array('hosts' => $hosts, 'templates' => $templates, 'groups' => $groups);
                $result = CHostGroup::massUpdate($data);
            }
            $result = DBend($result);
            if ($result) {
                $group = reset($groups);
                add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_HOST_GROUP, $group['groupid'], $group['name'], 'groups', array('name' => $old_group['name']), array('name' => $group['name']));
Ejemplo n.º 14
0
 /**
  * Mass update hosts
  *
  * @param _array $hosts multidimensional array with Hosts data
  * @param array $hosts['hosts'] Array of Host objects to update
  * @param string $hosts['fields']['host'] Host name.
  * @param array $hosts['fields']['groupids'] HostGroup IDs add Host to.
  * @param int $hosts['fields']['port'] Port. OPTIONAL
  * @param int $hosts['fields']['status'] Host Status. OPTIONAL
  * @param int $hosts['fields']['useip'] Use IP. OPTIONAL
  * @param string $hosts['fields']['dns'] DNS. OPTIONAL
  * @param string $hosts['fields']['ip'] IP. OPTIONAL
  * @param int $hosts['fields']['proxy_hostid'] Proxy Host ID. OPTIONAL
  * @param int $hosts['fields']['useipmi'] Use IPMI. OPTIONAL
  * @param string $hosts['fields']['ipmi_ip'] IPMAI IP. OPTIONAL
  * @param int $hosts['fields']['ipmi_port'] IPMI port. OPTIONAL
  * @param int $hosts['fields']['ipmi_authtype'] IPMI authentication type. OPTIONAL
  * @param int $hosts['fields']['ipmi_privilege'] IPMI privilege. OPTIONAL
  * @param string $hosts['fields']['ipmi_username'] IPMI username. OPTIONAL
  * @param string $hosts['fields']['ipmi_password'] IPMI password. OPTIONAL
  * @return boolean
  */
 public static function massUpdate($data)
 {
     $transaction = false;
     $templates = zbx_toArray($data['templates']);
     $templateids = zbx_objectValues($templates, 'templateid');
     try {
         $options = array('templateids' => $templateids, 'editable' => 1, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1);
         $upd_templates = self::get($options);
         foreach ($templates as $tnum => $template) {
             if (!isset($upd_templates[$template['templateid']])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
             }
         }
         // CHECK IF TEMPLATES HAVE AT LEAST 1 GROUP {{{
         if (isset($data['groups']) && empty($data['groups'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'No groups for template');
         }
         $data['groups'] = zbx_toArray($data['groups']);
         // }}} CHECK IF TEMPLATES HAVE AT LEAST 1 GROUP
         $transaction = self::BeginTransaction(__METHOD__);
         // UPDATE TEMPLATES PROPERTIES {{{
         if (isset($data['host'])) {
             if (count($templates) > 1) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot mass update template name');
             }
             $cur_template = reset($templates);
             $options = array('filter' => array('host' => $cur_template['host']), 'output' => API_OUTPUT_SHORTEN, 'editable' => 1, 'nopermissions' => 1);
             $template_exists = self::get($options);
             $template_exist = reset($template_exists);
             if ($template_exist && $template_exist['templateid'] != $cur_template['templateid']) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_TEMPLATE . ' [ ' . $data['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
             //can't set the same name as existing host
             if (CHost::exists(array('host' => $cur_template['host']))) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, S_HOST . ' [ ' . $template['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL);
             }
         }
         if (isset($data['host']) && !preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/i', $data['host'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for Hostname [ ' . $data['host'] . ' ]');
         }
         $sql_set = array();
         if (isset($data['host'])) {
             $sql_set[] = 'host=' . zbx_dbstr($data['host']);
         }
         if (!empty($sql_set)) {
             $sql = 'UPDATE hosts SET ' . implode(', ', $sql_set) . ' WHERE ' . DBcondition('hostid', $templateids);
             $result = DBexecute($sql);
         }
         // }}} UPDATE TEMPLATES PROPERTIES
         // UPDATE HOSTGROUPS LINKAGE {{{
         if (isset($data['groups']) && !is_null($data['groups'])) {
             $template_groups = CHostGroup::get(array('hostids' => $templateids));
             $template_groupids = zbx_objectValues($template_groups, 'groupid');
             $new_groupids = zbx_objectValues($data['groups'], 'groupid');
             $groups_to_add = array_diff($new_groupids, $template_groupids);
             if (!empty($groups_to_add)) {
                 $result = self::massAdd(array('templates' => $templates, 'groups' => zbx_toObject($groups_to_add, 'groupid')));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t add group');
                 }
             }
             $groupids_to_del = array_diff($template_groupids, $new_groupids);
             if (!empty($groupids_to_del)) {
                 $result = self::massRemove(array('templateids' => $templateids, 'groupids' => $groupids_to_del));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove group');
                 }
             }
         }
         // }}} UPDATE HOSTGROUPS LINKAGE
         $data['templates_clear'] = isset($data['templates_clear']) ? zbx_toArray($data['templates_clear']) : array();
         $cleared_templateids = array();
         foreach ($templateids as $templateid) {
             foreach ($data['templates_clear'] as $tpl) {
                 $result = unlink_template($templateid, $tpl['templateid'], false);
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot unlink template [ ' . $tpl['templateid'] . ' ]');
                 }
                 $cleared_templateids[] = $tpl['templateid'];
             }
         }
         // UPDATE TEMPLATE LINKAGE {{{
         // firstly need to unlink all things, to correctly check circulars
         if (isset($data['hosts']) && !is_null($data['hosts'])) {
             $template_hosts = CHost::get(array('templateids' => $templateids, 'templated_hosts' => 1));
             $template_hostids = zbx_objectValues($template_hosts, 'hostid');
             $new_hostids = zbx_objectValues($data['hosts'], 'hostid');
             $hosts_to_del = array_diff($template_hostids, $new_hostids);
             $hostids_to_del = array_diff($hosts_to_del, $cleared_templateids);
             if (!empty($hostids_to_del)) {
                 $result = self::massRemove(array('hostids' => $hostids_to_del, 'templateids' => $templateids));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t unlink template');
                 }
             }
         }
         if (isset($data['templates_link']) && !is_null($data['templates_link'])) {
             $template_templates = CTemplate::get(array('hostids' => $templateids));
             $template_templateids = zbx_objectValues($template_templates, 'templateid');
             $new_templateids = zbx_objectValues($data['templates_link'], 'templateid');
             $templates_to_del = array_diff($template_templateids, $new_templateids);
             $templateids_to_del = array_diff($templates_to_del, $cleared_templateids);
             if (!empty($templateids_to_del)) {
                 $result = self::massRemove(array('templateids' => $templateids, 'templateids_link' => $templateids_to_del));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t unlink template');
                 }
             }
         }
         if (isset($data['hosts']) && !is_null($data['hosts'])) {
             $hosts_to_add = array_diff($new_hostids, $template_hostids);
             if (!empty($hosts_to_add)) {
                 $result = self::massAdd(array('templates' => $templates, 'hosts' => $hosts_to_add));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t link template');
                 }
             }
         }
         if (isset($data['templates_link']) && !is_null($data['templates_link'])) {
             $templates_to_add = array_diff($new_templateids, $template_templateids);
             if (!empty($templates_to_add)) {
                 $result = self::massAdd(array('templates' => $templates, 'templates_link' => $templates_to_add));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t link template');
                 }
             }
         }
         // }}} UPDATE TEMPLATE LINKAGE
         // UPDATE MACROS {{{
         if (isset($data['macros']) && !is_null($data['macros'])) {
             $macrosToAdd = zbx_toHash($data['macros'], 'macro');
             $templateMacros = CUserMacro::get(array('hostids' => $templateids, 'output' => API_OUTPUT_EXTEND));
             $templateMacros = zbx_toHash($templateMacros, 'macro');
             // Delete
             $macrosToDelete = array();
             foreach ($templateMacros as $hmnum => $hmacro) {
                 if (!isset($macrosToAdd[$hmacro['macro']])) {
                     $macrosToDelete[] = $hmacro['macro'];
                 }
             }
             // Update
             $macrosToUpdate = array();
             foreach ($macrosToAdd as $nhmnum => $nhmacro) {
                 if (isset($templateMacros[$nhmacro['macro']])) {
                     $macrosToUpdate[] = $nhmacro;
                     unset($macrosToAdd[$nhmnum]);
                 }
             }
             //----
             if (!empty($macrosToDelete)) {
                 $result = self::massRemove(array('templateids' => $templateids, 'macros' => $macrosToDelete));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Can\'t remove macro');
                 }
             }
             if (!empty($macrosToUpdate)) {
                 $result = CUsermacro::massUpdate(array('templates' => $templates, 'macros' => $macrosToUpdate));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot update macro');
                 }
             }
             if (!empty($macrosToAdd)) {
                 $result = self::massAdd(array('templates' => $templates, 'macros' => $macrosToAdd));
                 if (!$result) {
                     self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot add macro');
                 }
             }
         }
         // }}} UPDATE MACROS
         self::EndTransaction(true, __METHOD__);
         return array('templateids' => $templateids);
     } catch (APIException $e) {
         if ($transaction) {
             self::EndTransaction(false, __METHOD__);
         }
         $error = $e->getErrors();
         $error = reset($error);
         self::setError(__METHOD__, $e->getCode(), $error);
         return false;
     }
 }
Ejemplo n.º 15
0
 public static function parseMain($rules)
 {
     $triggers_for_dependencies = array();
     try {
         if (isset($rules['host']['exist']) || isset($rules['host']['missed'])) {
             $xpath = new DOMXPath(self::$xml);
             $hosts = $xpath->query('hosts/host');
             foreach ($hosts as $hnum => $host) {
                 $host_db = self::mapXML2arr($host, XML_TAG_HOST);
                 if (!isset($host_db['status'])) {
                     $host_db['status'] = HOST_STATUS_TEMPLATE;
                 }
                 $current_host = $host_db['status'] == HOST_STATUS_TEMPLATE ? CTemplate::exists($host_db) : CHost::exists($host_db);
                 if (!$current_host && !isset($rules['host']['missed'])) {
                     info('Host [' . $host_db['host'] . '] skipped - user rule');
                     continue;
                     // break if update nonexist
                 }
                 if ($current_host && !isset($rules['host']['exist'])) {
                     info('Host [' . $host_db['host'] . '] skipped - user rule');
                     continue;
                     // break if not update exist
                 }
                 if (isset($host_db['proxy_hostid'])) {
                     $proxy_exists = CProxy::get(array('proxyids' => $host_db['proxy_hostid']));
                     if (empty($proxy_exists)) {
                         $host_db['proxy_hostid'] = 0;
                     }
                 }
                 if ($current_host) {
                     $options = array('filter' => array('host' => $host_db['host']), 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                     if ($host_db['status'] == HOST_STATUS_TEMPLATE) {
                         $current_host = CTemplate::get($options);
                     } else {
                         $current_host = CHost::get($options);
                     }
                     if (empty($current_host)) {
                         throw new APIException(1, 'No permission for host [' . $host_db['host'] . ']');
                     } else {
                         $current_host = reset($current_host);
                     }
                 }
                 // HOST GROUPS {{{
                 $groups = $xpath->query('groups/group', $host);
                 $host_db['groups'] = array();
                 $groups_to_parse = array();
                 foreach ($groups as $gnum => $group) {
                     $groups_to_parse[] = array('name' => $group->nodeValue);
                 }
                 if (empty($groups_to_parse)) {
                     $groups_to_parse[] = array('name' => ZBX_DEFAULT_IMPORT_HOST_GROUP);
                 }
                 foreach ($groups_to_parse as $group) {
                     $current_group = CHostGroup::exists($group);
                     if ($current_group) {
                         $options = array('filter' => $group, 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                         $current_group = CHostGroup::get($options);
                         if (empty($current_group)) {
                             throw new APIException(1, 'No permissions for group ' . $group['name']);
                         }
                         $host_db['groups'][] = reset($current_group);
                     } else {
                         $result = CHostGroup::create($group);
                         if (!$result) {
                             throw new APIException(1, CHostGroup::resetErrors());
                         }
                         $options = array('groupids' => $result['groupids'], 'output' => API_OUTPUT_EXTEND);
                         $new_group = CHostgroup::get($options);
                         $host_db['groups'][] = reset($new_group);
                     }
                 }
                 // }}} HOST GROUPS
                 // MACROS
                 $macros = $xpath->query('macros/macro', $host);
                 $host_db['macros'] = array();
                 if ($macros->length > 0) {
                     foreach ($macros as $macro) {
                         $host_db['macros'][] = self::mapXML2arr($macro, XML_TAG_MACRO);
                     }
                 }
                 // }}} MACROS
                 // TEMPLATES {{{
                 if (isset($rules['template']['exist'])) {
                     $templates = $xpath->query('templates/template', $host);
                     $host_db['templates'] = array();
                     foreach ($templates as $tnum => $template) {
                         $options = array('filter' => array('host' => $template->nodeValue), 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                         $current_template = CTemplate::get($options);
                         if (empty($current_template)) {
                             throw new APIException(1, 'No permission for Template [' . $template->nodeValue . ']');
                         }
                         $current_template = reset($current_template);
                         if (!$current_template && !isset($rules['template']['missed'])) {
                             info('Template [' . $template->nodeValue . '] skipped - user rule');
                             continue;
                             // break if update nonexist
                         }
                         if ($current_template && !isset($rules['template']['exist'])) {
                             info('Template [' . $template->nodeValue . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         $host_db['templates'][] = $current_template;
                     }
                 }
                 // }}} TEMPLATES
                 // HOSTS
                 if ($current_host && isset($rules['host']['exist'])) {
                     if ($host_db['status'] == HOST_STATUS_TEMPLATE) {
                         $host_db['templateid'] = $current_host['hostid'];
                         $result = CTemplate::update($host_db);
                         if (!$result) {
                             throw new APIException(1, CTemplate::resetErrors());
                         }
                         $options = array('templateids' => $result['templateids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CTemplate::get($options);
                     } else {
                         $host_db['hostid'] = $current_host['hostid'];
                         $result = CHost::update($host_db);
                         if (!$result) {
                             throw new APIException(1, CHost::resetErrors());
                         }
                         $options = array('hostids' => $result['hostids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CHost::get($options);
                     }
                     if ($current_host === false) {
                         throw new APIException(1, $host_db['status'] == HOST_STATUS_TEMPLATE ? CTemplate::resetErrors() : CHost::resetErrors());
                     }
                 }
                 if (!$current_host && isset($rules['host']['missed'])) {
                     if ($host_db['status'] == HOST_STATUS_TEMPLATE) {
                         $result = CTemplate::create($host_db);
                         if (!$result) {
                             throw new APIException(1, CTemplate::resetErrors());
                         }
                         $options = array('templateids' => $result['templateids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CTemplate::get($options);
                     } else {
                         $result = CHost::create($host_db);
                         if (!$result) {
                             throw new APIException(1, CHost::resetErrors());
                         }
                         $options = array('hostids' => $result['hostids'], 'output' => API_OUTPUT_EXTEND);
                         $current_host = CHost::get($options);
                     }
                 }
                 $current_host = reset($current_host);
                 // HOST PROFILES {{{
                 $profile_node = $xpath->query('host_profile/*', $host);
                 if ($profile_node->length > 0) {
                     $profile = array();
                     foreach ($profile_node as $num => $field) {
                         $profile[$field->nodeName] = $field->nodeValue;
                     }
                     delete_host_profile($current_host['hostid']);
                     add_host_profile($current_host['hostid'], $profile['devicetype'], $profile['name'], $profile['os'], $profile['serialno'], $profile['tag'], $profile['macaddress'], $profile['hardware'], $profile['software'], $profile['contact'], $profile['location'], $profile['notes']);
                 }
                 $profile_ext_node = $xpath->query('host_profiles_ext/*', $host);
                 if ($profile_ext_node->length > 0) {
                     $profile_ext = array();
                     foreach ($profile_ext_node as $num => $field) {
                         $profile_ext[$field->nodeName] = $field->nodeValue;
                     }
                     delete_host_profile_ext($current_host['hostid']);
                     add_host_profile_ext($current_host['hostid'], $profile_ext);
                 }
                 // }}} HOST PROFILES
                 // ITEMS {{{
                 if (isset($rules['item']['exist']) || isset($rules['item']['missed'])) {
                     $items = $xpath->query('items/item', $host);
                     foreach ($items as $inum => $item) {
                         $item_db = self::mapXML2arr($item, XML_TAG_ITEM);
                         $item_db['hostid'] = $current_host['hostid'];
                         if ($current_item = CItem::exists($item_db)) {
                             $options = array('filter' => array('hostid' => $item_db['hostid'], 'key_' => $item_db['key_']), 'webitems' => 1, 'output' => API_OUTPUT_EXTEND, 'editable' => 1);
                             $current_item = CItem::get($options);
                             if (empty($current_item)) {
                                 throw new APIException(1, 'No permission for Item [' . $item_db['key_'] . ']');
                             }
                             $current_item = reset($current_item);
                         }
                         if (!$current_item && !isset($rules['item']['missed'])) {
                             info('Item [' . $item_db['key_'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_item && !isset($rules['item']['exist'])) {
                             info('Item [' . $item_db['key_'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         // ITEM APPLICATIONS {{{
                         $applications = $xpath->query('applications/application', $item);
                         $item_applications = array();
                         $applications_to_add = array();
                         foreach ($applications as $application) {
                             $application_db = array('name' => $application->nodeValue, 'hostid' => $current_host['hostid']);
                             if ($current_application = CApplication::exists($application_db)) {
                                 $current_application = CApplication::get(array('filter' => $application_db, 'output' => API_OUTPUT_EXTEND));
                                 if (empty($current_application)) {
                                     throw new APIException(1, 'No permission for Application [' . $application_db['name'] . ']');
                                 }
                             }
                             if ($current_application) {
                                 $item_applications = array_merge($item_applications, $current_application);
                             } else {
                                 $applications_to_add[] = $application_db;
                             }
                         }
                         if (!empty($applications_to_add)) {
                             $result = CApplication::create($applications_to_add);
                             if (!$result) {
                                 throw new APIException(1, CApplication::resetErrors());
                             }
                             $options = array('applicationids' => $result['applicationids'], 'output' => API_OUTPUT_EXTEND);
                             $new_applications = CApplication::get($options);
                             $item_applications = array_merge($item_applications, $new_applications);
                         }
                         // }}} ITEM APPLICATIONS
                         if ($current_item && isset($rules['item']['exist'])) {
                             $item_db['itemid'] = $current_item['itemid'];
                             $result = CItem::update($item_db);
                             if (!$result) {
                                 throw new APIException(1, CItem::resetErrors());
                             }
                             $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND);
                             $current_item = CItem::get($options);
                         }
                         if (!$current_item && isset($rules['item']['missed'])) {
                             $result = CItem::create($item_db);
                             if (!$result) {
                                 throw new APIException(1, CItem::resetErrors());
                             }
                             $options = array('itemids' => $result['itemids'], 'webitems' => 1, 'output' => API_OUTPUT_EXTEND);
                             $current_item = CItem::get($options);
                         }
                         $r = CApplication::massAdd(array('applications' => $item_applications, 'items' => $current_item));
                         if ($r === false) {
                             throw new APIException(1, CApplication::resetErrors());
                         }
                     }
                 }
                 // }}} ITEMS
                 // TRIGGERS {{{
                 if (isset($rules['trigger']['exist']) || isset($rules['trigger']['missed'])) {
                     $triggers = $xpath->query('triggers/trigger', $host);
                     $triggers_to_add = array();
                     $triggers_to_upd = array();
                     foreach ($triggers as $trigger) {
                         $trigger_db = self::mapXML2arr($trigger, XML_TAG_TRIGGER);
                         $trigger_db['expression'] = str_replace('{{HOSTNAME}:', '{' . $host_db['host'] . ':', $trigger_db['expression']);
                         $trigger_db['hostid'] = $current_host['hostid'];
                         if ($current_trigger = CTrigger::exists($trigger_db)) {
                             $ctriggers = CTrigger::get(array('filter' => array('description' => $trigger_db['description']), 'hostids' => $current_host['hostid'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1));
                             $current_trigger = false;
                             foreach ($ctriggers as $tnum => $ct) {
                                 $tmp_exp = explode_exp($ct['expression'], false);
                                 if (strcmp($trigger_db['expression'], $tmp_exp) == 0) {
                                     $current_trigger = $ct;
                                     break;
                                 }
                             }
                             if (!$current_trigger) {
                                 throw new APIException(1, 'No permission for Trigger [' . $trigger_db['description'] . ']');
                             }
                         }
                         if (!$current_trigger && !isset($rules['trigger']['missed'])) {
                             info('Trigger [' . $trigger_db['description'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_trigger && !isset($rules['trigger']['exist'])) {
                             info('Trigger [' . $trigger_db['description'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_trigger && isset($rules['trigger']['exist'])) {
                             $trigger_db['triggerid'] = $current_trigger['triggerid'];
                             $triggers_to_upd[] = $trigger_db;
                         }
                         if (!$current_trigger && isset($rules['trigger']['missed'])) {
                             $triggers_to_add[] = $trigger_db;
                         }
                     }
                     if (!empty($triggers_to_upd)) {
                         $result = CTrigger::update($triggers_to_upd);
                         if (!$result) {
                             throw new APIException(1, CTrigger::resetErrors());
                         }
                         $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND);
                         $r = CTrigger::get($options);
                         $triggers_for_dependencies = array_merge($triggers_for_dependencies, $r);
                     }
                     if (!empty($triggers_to_add)) {
                         $result = CTrigger::create($triggers_to_add);
                         if (!$result) {
                             throw new APIException(1, CTrigger::resetErrors());
                         }
                         $options = array('triggerids' => $result['triggerids'], 'output' => API_OUTPUT_EXTEND);
                         $r = CTrigger::get($options);
                         $triggers_for_dependencies = array_merge($triggers_for_dependencies, $r);
                     }
                 }
                 // }}} TRIGGERS
                 // GRAPHS {{{
                 if (isset($rules['graph']['exist']) || isset($rules['graph']['missed'])) {
                     $graphs = $xpath->query('graphs/graph', $host);
                     $graphs_to_add = array();
                     $graphs_to_upd = array();
                     foreach ($graphs as $gnum => $graph) {
                         // GRAPH ITEMS {{{
                         $gitems = $xpath->query('graph_elements/graph_element', $graph);
                         $graph_hostids = array();
                         $graph_items = array();
                         foreach ($gitems as $ginum => $gitem) {
                             $gitem_db = self::mapXML2arr($gitem, XML_TAG_GRAPH_ELEMENT);
                             $data = explode(':', $gitem_db['host_key_']);
                             $gitem_host = array_shift($data);
                             $gitem_db['host'] = $gitem_host == '{HOSTNAME}' ? $host_db['host'] : $gitem_host;
                             $gitem_db['key_'] = implode(':', $data);
                             if ($current_item = CItem::exists($gitem_db)) {
                                 $current_item = CItem::get(array('filter' => array('key_' => $gitem_db['key_']), 'webitems' => 1, 'host' => $gitem_db['host'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1));
                                 if (empty($current_item)) {
                                     throw new APIException(1, 'No permission for Item [' . $gitem_db['key_'] . ']');
                                 }
                                 $current_item = reset($current_item);
                                 $graph_hostids[] = $current_item['hostid'];
                                 $gitem_db['itemid'] = $current_item['itemid'];
                                 $graph_items[] = $gitem_db;
                             } else {
                                 throw new APIException(1, 'Item [' . $gitem_db['host_key_'] . '] does not exists');
                             }
                         }
                         // }}} GRAPH ITEMS
                         $graph_db = self::mapXML2arr($graph, XML_TAG_GRAPH);
                         $graph_db['hostids'] = $graph_hostids;
                         if ($current_graph = CGraph::exists($graph_db)) {
                             $current_graph = CGraph::get(array('filter' => array('name' => $graph_db['name']), 'hostids' => $graph_db['hostids'], 'output' => API_OUTPUT_EXTEND, 'editable' => 1));
                             if (empty($current_graph)) {
                                 throw new APIException(1, 'No permission for Graph [' . $graph_db['name'] . ']');
                             }
                             $current_graph = reset($current_graph);
                         }
                         if (!$current_graph && !isset($rules['graph']['missed'])) {
                             info('Graph [' . $graph_db['name'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($current_graph && !isset($rules['graph']['exist'])) {
                             info('Graph [' . $graph_db['name'] . '] skipped - user rule');
                             continue;
                             // break if not update exist
                         }
                         if ($graph_db['ymin_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                             $item_data = explode(':', $graph_db['ymin_item_key'], 2);
                             if (count($item_data) < 2) {
                                 throw new APIException(1, 'Incorrect y min item for graph [' . $graph_db['name'] . ']');
                             }
                             if (!($item = get_item_by_key($item_data[1], $item_data[0]))) {
                                 throw new APIException(1, 'Missing item [' . $graph_db['ymin_item_key'] . '] for host [' . $host_db['host'] . ']');
                             }
                             $graph_db['ymin_itemid'] = $item['itemid'];
                         }
                         if ($graph_db['ymax_type'] == GRAPH_YAXIS_TYPE_ITEM_VALUE) {
                             $item_data = explode(':', $graph_db['ymax_item_key'], 2);
                             if (count($item_data) < 2) {
                                 throw new APIException(1, 'Incorrect y max item for graph [' . $graph_db['name'] . ']');
                             }
                             if (!($item = get_item_by_key($item_data[1], $item_data[0]))) {
                                 throw new APIException(1, 'Missing item [' . $graph_db['ymax_item_key'] . '] for host [' . $host_db['host'] . ']');
                             }
                             $graph_db['ymax_itemid'] = $item['itemid'];
                         }
                         $graph_db['gitems'] = $graph_items;
                         if ($current_graph) {
                             $graph_db['graphid'] = $current_graph['graphid'];
                             $graphs_to_upd[] = $graph_db;
                         } else {
                             $graphs_to_add[] = $graph_db;
                         }
                     }
                     if (!empty($graphs_to_add)) {
                         $r = CGraph::create($graphs_to_add);
                         if ($r === false) {
                             throw new APIException(1, CGraph::resetErrors());
                         }
                     }
                     if (!empty($graphs_to_upd)) {
                         $r = CGraph::update($graphs_to_upd);
                         if ($r === false) {
                             throw new APIException(1, CGraph::resetErrors());
                         }
                     }
                 }
             }
             // DEPENDENCIES
             $dependencies = $xpath->query('dependencies/dependency');
             if ($dependencies->length > 0) {
                 $triggers_for_dependencies = zbx_objectValues($triggers_for_dependencies, 'triggerid');
                 $triggers_for_dependencies = array_flip($triggers_for_dependencies);
                 foreach ($dependencies as $dependency) {
                     $triggers_to_add_dep = array();
                     $trigger_description = $dependency->getAttribute('description');
                     $current_triggerid = get_trigger_by_description($trigger_description);
                     // sdi('<b><u>Trigger Description: </u></b>'.$trigger_description.' | <b>Current_triggerid: </b>'. $current_triggerid['triggerid']);
                     if ($current_triggerid && isset($triggers_for_dependencies[$current_triggerid['triggerid']])) {
                         $depends_on_list = $xpath->query('depends', $dependency);
                         foreach ($depends_on_list as $depends_on) {
                             $depends_triggerid = get_trigger_by_description($depends_on->nodeValue);
                             // sdi('<b>depends on description: </b>'.$depends_on->nodeValue.' | <b>depends_triggerid: </b>'. $depends_triggerid['triggerid']);
                             if ($depends_triggerid['triggerid']) {
                                 $triggers_to_add_dep[] = $depends_triggerid['triggerid'];
                             }
                         }
                         $r = update_trigger($current_triggerid['triggerid'], null, $current_triggerid['description'], null, null, null, null, null, $triggers_to_add_dep, null);
                         if ($r === false) {
                             throw new APIException();
                         }
                     }
                 }
             }
         }
         return true;
     } catch (APIException $e) {
         error($e->getErrors());
         return false;
     }
 }
Ejemplo n.º 16
0
function get_templates()
{
    $options = array('extendoutput' => 1, 'select_templates' => 1, 'nopermissions' => 1);
    $template = array();
    foreach (CTemplate::get($options) as $key => $value) {
        array_push($template, array('key' => $key, 'host' => $value['host']));
    }
    return $template;
}