Example #1
0
 public static function login($login, $password)
 {
     try {
         self::setDefault();
         self::$data = API::User()->login(array('user' => $login, 'password' => $password, 'userData' => true));
         if (!self::$data) {
             throw new Exception();
         }
         if (self::$data['gui_access'] == GROUP_GUI_ACCESS_DISABLED) {
             error(_('GUI access disabled.'));
             throw new Exception();
         }
         if (empty(self::$data['url'])) {
             self::$data['url'] = CProfile::get('web.menu.view.last', 'index.php');
         }
         if (isset(self::$data['attempt_failed']) && self::$data['attempt_failed']) {
             CProfile::init();
             CProfile::update('web.login.attempt.failed', self::$data['attempt_failed'], PROFILE_TYPE_INT);
             CProfile::update('web.login.attempt.ip', self::$data['attempt_ip'], PROFILE_TYPE_STR);
             CProfile::update('web.login.attempt.clock', self::$data['attempt_clock'], PROFILE_TYPE_INT);
             CProfile::flush();
         }
         // remove guest session after successful login
         DBexecute('DELETE FROM sessions WHERE sessionid=' . zbx_dbstr(get_cookie('zbx_sessionid')));
         zbx_setcookie('zbx_sessionid', self::$data['sessionid'], self::$data['autologin'] ? time() + SEC_PER_DAY * 31 : 0);
         return true;
     } catch (Exception $e) {
         self::setDefault();
         return false;
     }
 }
Example #2
0
function zbx_session_start($userid, $name, $password)
{
    $sessionid = md5(time() . $password . $name . rand(0, 10000000));
    zbx_setcookie('zbx_sessionid', $sessionid);
    DBexecute('INSERT INTO sessions (sessionid,userid,lastaccess,status) VALUES (' . zbx_dbstr($sessionid) . ',' . $userid . ',' . time() . ',' . ZBX_SESSION_ACTIVE . ')');
    return $sessionid;
}
Example #3
0
 /**
  * Tries to login a user and populates self::$data on success.
  *
  * @param string $login			user login
  * @param string $password		user password
  *
  * @throws Exception if user cannot be logged in
  *
  * @return bool
  */
 public static function login($login, $password)
 {
     try {
         self::setDefault();
         self::$data = API::User()->login(array('user' => $login, 'password' => $password, 'userData' => true));
         if (!self::$data) {
             throw new Exception();
         }
         if (self::$data['gui_access'] == GROUP_GUI_ACCESS_DISABLED) {
             error(_('GUI access disabled.'));
             throw new Exception();
         }
         if (empty(self::$data['url'])) {
             self::$data['url'] = CProfile::get('web.menu.view.last', 'index.php');
         }
         $result = (bool) self::$data;
         if (isset(self::$data['attempt_failed']) && self::$data['attempt_failed']) {
             CProfile::init();
             CProfile::update('web.login.attempt.failed', self::$data['attempt_failed'], PROFILE_TYPE_INT);
             CProfile::update('web.login.attempt.ip', self::$data['attempt_ip'], PROFILE_TYPE_STR);
             CProfile::update('web.login.attempt.clock', self::$data['attempt_clock'], PROFILE_TYPE_INT);
             $result &= CProfile::flush();
         }
         // remove guest session after successful login
         $result &= DBexecute('DELETE FROM sessions WHERE sessionid=' . zbx_dbstr(get_cookie('zbx_sessionid')));
         if ($result) {
             self::setSessionCookie(self::$data['sessionid']);
             add_audit_ext(AUDIT_ACTION_LOGIN, AUDIT_RESOURCE_USER, self::$data['userid'], '', null, null, null);
         }
         return $result;
     } catch (Exception $e) {
         self::setDefault();
         return false;
     }
 }
function disable_httptest($httptestid)
{
    $result = DBexecute('UPDATE httptest SET status=' . HTTPTEST_STATUS_DISABLED . ' WHERE httptestid=' . zbx_dbstr($httptestid));
    $itemids = array();
    $items_db = DBselect('SELECT hti.itemid FROM httptestitem hti WHERE hti.httptestid=' . zbx_dbstr($httptestid));
    while ($itemid = Dbfetch($items_db)) {
        $itemids[] = $itemid['itemid'];
    }
    $items_db = DBselect('SELECT hsi.itemid' . ' FROM httpstep hs,httpstepitem hsi' . ' WHERE hs.httpstepid=hsi.httpstepid' . ' AND hs.httptestid=' . zbx_dbstr($httptestid));
    while ($itemid = Dbfetch($items_db)) {
        $itemids[] = $itemid['itemid'];
    }
    $result &= DBexecute('UPDATE items SET status=' . ITEM_STATUS_DISABLED . ' WHERE ' . dbConditionInt('itemid', $itemids));
    return $result;
}
Example #5
0
function delete_template_triggers($hostid, $templateids = null, $unlink_mode = false)
{
    zbx_value2array($templateids);
    $triggers = get_triggers_by_hostid($hostid);
    while ($trigger = DBfetch($triggers)) {
        if ($trigger['templateid'] == 0) {
            continue;
        }
        if ($templateids != null) {
            $db_tmp_hosts = get_hosts_by_triggerid($trigger["templateid"]);
            $tmp_host = DBfetch($db_tmp_hosts);
            if (!uint_in_array($tmp_host["hostid"], $templateids)) {
                continue;
            }
        }
        if ($unlink_mode) {
            if (DBexecute('UPDATE triggers SET templateid=0 WHERE triggerid=' . $trigger['triggerid'])) {
                info('Trigger "' . $trigger["description"] . '" unlinked');
            }
        } else {
            delete_trigger($trigger["triggerid"]);
        }
    }
    return TRUE;
}
            $go_result = true;
            $host = get_host_by_applicationid($httptest_data['applicationid']);
            add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_SCENARIO, _('Scenario') . ' [' . $httptest_data['name'] . '] [' . $id . '] ' . _('Host') . ' [' . $host['host'] . ']' . _('Scenario disabled'));
        }
    }
    show_messages($go_result, _('Scenario disabled'), null);
} elseif ($_REQUEST['go'] == 'clean_history' && isset($_REQUEST['group_httptestid'])) {
    $go_result = false;
    $group_httptestid = $_REQUEST['group_httptestid'];
    foreach ($group_httptestid as $id) {
        if (!($httptest_data = get_httptest_by_httptestid($id))) {
            continue;
        }
        if (delete_history_by_httptestid($id)) {
            $go_result = true;
            DBexecute('UPDATE httptest SET nextcheck=0 WHERE httptestid=' . $id);
            $host = get_host_by_applicationid($httptest_data['applicationid']);
            add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_SCENARIO, _('Scenario') . ' [' . $httptest_data['name'] . '] [' . $id . '] ' . _('Host') . ' [' . $host['host'] . ']' . _('History cleared'));
        }
    }
    show_messages($go_result, _('History cleared'), null);
} elseif ($_REQUEST['go'] == 'delete' && isset($_REQUEST['group_httptestid'])) {
    $go_result = API::WebCheck()->delete($_REQUEST['group_httptestid']);
    show_messages($go_result, _('Scenario deleted'), null);
}
if ($_REQUEST['go'] != 'none' && isset($go_result) && $go_result) {
    $url = new CUrl();
    $path = $url->getPath();
    insert_js('cookie.eraseArray("' . $path . '")');
}
show_messages();
Example #7
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;
     }
 }
Example #8
0
 /**
  * Delete User Medias
  *
  * <code>
  * $media_data = array(
  * 	*string 'userid => 'User ID',
  * 	array 'mediaids' => array('Media ID', 'Media ID', ...)
  * );
  * </code>
  *
  * @static
  * @param array $media_data 
  * @return boolean
  */
 public static function deleteMedia($media_data)
 {
     $sql = 'DELETE FROM media WHERE userid=' . $media_data['userid'] . ' AND ' . DBcondition('mediaid', $media_data['mediaids']);
     $result = DBexecute($sql);
     if ($result) {
         return true;
     } else {
         self::$error = array('error' => ZBX_API_ERROR_INTERNAL, 'data' => 'Internal zabbix error');
         return false;
     }
 }
Example #9
0
function delete_host_profile_ext($hostids)
{
    zbx_value2array($hostids);
    $result = DBexecute('DELETE FROM hosts_profiles_ext WHERE ' . DBcondition('hostid', $hostids));
    return $result;
}
            }
        } elseif (isset($_REQUEST['test'])) {
            show_messages($login, _('LDAP login successful'), _('LDAP login was not successful'));
        }
    }
} elseif ($config['authentication_type'] == ZBX_AUTH_HTTP) {
    if (isset($_REQUEST['save'])) {
        // get groups wich use this authentication method
        $result = DBfetch(DBselect('SELECT COUNT(g.usrgrpid) AS cnt_usrgrp FROM usrgrp g WHERE g.gui_access=' . GROUP_GUI_ACCESS_INTERNAL));
        if ($result['cnt_usrgrp'] > 0) {
            info(_n('There is "%1$d" group with Internal GUI access.', 'There are "%1$d" groups with Internal GUI access.', $result['cnt_usrgrp']));
        }
        if (update_config($config)) {
            // reset all sessions
            if ($isAuthenticationTypeChanged) {
                DBexecute('UPDATE sessions SET status=' . ZBX_SESSION_PASSIVE . ' WHERE sessionid<>' . zbx_dbstr($USER_DETAILS['sessionid']));
            }
            $isAuthenticationTypeChanged = false;
            add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_ZABBIX_CONFIG, _('Authentication method changed to HTTP'));
            show_message(_('Authentication method changed to HTTP'));
        } else {
            show_error_message(_('Cannot change authentication method to HTTP'));
        }
    }
}
show_messages();
/*
 * Display
 */
$data = array('form_refresh' => get_request('form_refresh'), 'config' => $config, 'is_authentication_type_changed' => $isAuthenticationTypeChanged, 'user' => get_request('user', $USER_DETAILS['alias']), 'user_password' => get_request('user_password', ''), 'user_list' => null, 'change_bind_password' => get_request('change_bind_password'));
// get tab title
Example #11
0
function delete_expression($expressionids)
{
    zbx_value2array($expressionids);
    $sql = 'DELETE FROM expressions WHERE ' . DBcondition('expressionid', $expressionids);
    return DBexecute($sql);
}
Example #12
0
 /**
  * Delete data from DB.
  *
  * Example:
  * DB::delete('applications', array('applicationid'=>array(1, 8, 6)));
  * DELETE FROM applications WHERE applicationid IN (1, 8, 6)
  *
  * DB::delete('applications', array('applicationid'=>array(1), 'templateid'=array(10)));
  * DELETE FROM applications WHERE applicationid IN (1) AND templateid IN (10)
  *
  * @param string $table
  * @param array  $wheres pair of fieldname => fieldvalues
  * @param bool   $use_or
  *
  * @return bool
  */
 public static function delete($table, $wheres, $use_or = false)
 {
     if (empty($wheres) || !is_array($wheres)) {
         self::exception(self::DBEXECUTE_ERROR, _s('Cannot perform delete statement on table "%1$s" without where condition.', $table));
     }
     $table_schema = self::getSchema($table);
     $sqlWhere = array();
     foreach ($wheres as $field => $values) {
         if (!isset($table_schema['fields'][$field]) || is_null($values)) {
             self::exception(self::DBEXECUTE_ERROR, _s('Incorrect field "%1$s" name or value in where statement for table "%2$s".', $field, $table));
         }
         $values = zbx_toArray($values);
         sort($values);
         // sorting ids to prevent deadlocks when two transactions depends from each other
         $sqlWhere[] = dbConditionString($field, $values);
     }
     $sql = 'DELETE FROM ' . $table . ' WHERE ' . implode($use_or ? ' OR ' : ' AND ', $sqlWhere);
     if (!DBexecute($sql)) {
         self::exception(self::DBEXECUTE_ERROR, _s('SQL statement execution has failed "%1$s"', $sql));
     }
     return true;
 }
Example #13
0
function get_dbid($table, $field)
{
    // PGSQL on transaction failure on all queries returns false..
    global $DB;
    if ($DB['TYPE'] == ZBX_DB_POSTGRESQL && $DB['TRANSACTIONS'] && !$DB['TRANSACTION_NO_FAILED_SQLS']) {
        return 0;
    }
    $found = false;
    $min = 0;
    $max = ZBX_DB_MAX_ID;
    do {
        $dbSelect = DBselect('SELECT i.nextid FROM ids i WHERE i.table_name=' . zbx_dbstr($table) . ' AND i.field_name=' . zbx_dbstr($field));
        if (!$dbSelect) {
            return false;
        }
        $row = DBfetch($dbSelect);
        if (!$row) {
            $row = DBfetch(DBselect('SELECT MAX(' . $field . ') AS id FROM ' . $table . ' WHERE ' . $field . ' BETWEEN ' . $min . ' AND ' . $max));
            if (!$row || $row['id'] == 0) {
                DBexecute("INSERT INTO ids (table_name,field_name,nextid) VALUES ('{$table}','{$field}',{$min})");
            } else {
                DBexecute("INSERT INTO ids (table_name,field_name,nextid) VALUES ('{$table}','{$field}'," . $row['id'] . ')');
            }
            continue;
        } else {
            $ret1 = $row['nextid'];
            if (bccomp($ret1, $min) < 0 || !bccomp($ret1, $max) < 0) {
                DBexecute('DELETE FROM ids WHERE table_name=' . zbx_dbstr($table) . ' AND field_name=' . zbx_dbstr($field));
                continue;
            }
            $sql = 'UPDATE ids SET nextid=nextid+1 WHERE table_name=' . zbx_dbstr($table) . ' AND field_name=' . zbx_dbstr($field);
            DBexecute($sql);
            $row = DBfetch(DBselect('SELECT i.nextid FROM ids i WHERE i.table_name=' . zbx_dbstr($table) . ' AND i.field_name=' . zbx_dbstr($field)));
            if (!$row || is_null($row['nextid'])) {
                // should never be here
                continue;
            } else {
                $ret2 = $row['nextid'];
                if (bccomp(bcadd($ret1, 1, 0), $ret2, 0) == 0) {
                    $found = true;
                }
            }
        }
    } while (false == $found);
    return $ret2;
}
Example #14
0
    if (isset($_REQUEST['operations'][$edit_operationid])) {
        $_REQUEST['new_operation'] = $_REQUEST['operations'][$edit_operationid];
        $_REQUEST['new_operation']['id'] = $edit_operationid;
        $_REQUEST['new_operation']['action'] = 'update';
    }
} elseif (str_in_array(getRequest('go'), array('activate', 'disable')) && hasRequest('g_actionid')) {
    $result = true;
    $enable = getRequest('go') == 'activate';
    $status = $enable ? ACTION_STATUS_ENABLED : ACTION_STATUS_DISABLED;
    $statusName = $enable ? 'enabled' : 'disabled';
    $actionIds = array();
    $updated = 0;
    DBstart();
    $dbActions = DBselect('SELECT a.actionid' . ' FROM actions a' . ' WHERE ' . dbConditionInt('a.actionid', $_REQUEST['g_actionid']));
    while ($row = DBfetch($dbActions)) {
        $result &= DBexecute('UPDATE actions' . ' SET status=' . zbx_dbstr($status) . ' WHERE actionid=' . zbx_dbstr($row['actionid']));
        if ($result) {
            $actionIds[] = $row['actionid'];
        }
        $updated++;
    }
    $result = DBend($result);
    if ($result) {
        add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_ACTION, ' Actions [' . implode(',', $actionIds) . '] ' . $statusName);
    }
    $messageSuccess = $enable ? _n('Action enabled', 'Actions enabled', $updated) : _n('Action disabled', 'Actions disabled', $updated);
    $messageFailed = $enable ? _n('Cannot enable action', 'Cannot enable actions', $updated) : _n('Cannot disable action', 'Cannot disable actions', $updated);
    show_messages($result, $messageSuccess, $messageFailed);
    clearCookies($result);
} elseif ($_REQUEST['go'] == 'delete' && isset($_REQUEST['g_actionid'])) {
    $goResult = API::Action()->delete($_REQUEST['g_actionid']);
Example #15
0
function update_action_status($actionid, $status)
{
    return DBexecute("update actions set status={$status} where actionid={$actionid}");
}
function delete_node($nodeid)
{
    $result = false;
    $node = DBfetch(DBselect('SELECT n.nodeid,n.masterid FROM nodes n WHERE n.nodeid=' . zbx_dbstr($nodeid)));
    $nodetype = detect_node_type($node['nodeid'], $node['masterid']);
    if ($nodetype == ZBX_NODE_LOCAL) {
        error(_('Unable to remove local node.'));
    } else {
        $result = DBexecute('UPDATE nodes SET masterid=NULL WHERE masterid=' . zbx_dbstr($nodeid)) && DBexecute('DELETE FROM nodes WHERE nodeid=' . zbx_dbstr($nodeid));
        if ($nodetype != ZBX_NODE_MASTER) {
            error(_('Please be aware that database still contains data related to the deleted node.'));
        }
    }
    return $result;
}
Example #17
0
 function checkConnection()
 {
     global $DB;
     if (!$this->getConfig('check_fields_result')) {
         return false;
     }
     $DB['TYPE'] = $this->getConfig('DB_TYPE');
     if (is_null($DB['TYPE'])) {
         return false;
     }
     $DB['SERVER'] = $this->getConfig('DB_SERVER', 'localhost');
     $DB['PORT'] = $this->getConfig('DB_PORT', '0');
     $DB['DATABASE'] = $this->getConfig('DB_DATABASE', 'zabbix');
     $DB['USER'] = $this->getConfig('DB_USER', 'root');
     $DB['PASSWORD'] = $this->getConfig('DB_PASSWORD', '');
     $DB['SCHEMA'] = $this->getConfig('DB_SCHEMA', '');
     $error = '';
     // during setup set debug to false to avoid displaying unwanted PHP errors in messages
     if (!($result = DBconnect($error))) {
         error($error);
     } else {
         $result = true;
         if (!zbx_empty($DB['SCHEMA']) && $DB['TYPE'] == ZBX_DB_DB2) {
             $db_schema = DBselect('SELECT schemaname FROM syscat.schemata WHERE schemaname=\'' . db2_escape_string($DB['SCHEMA']) . '\'');
             $result = DBfetch($db_schema);
         }
         if ($result) {
             $result = DBexecute('CREATE TABLE zabbix_installation_test (test_row INTEGER)');
             $result &= DBexecute('DROP TABLE zabbix_installation_test');
         }
     }
     DBclose();
     $DB = null;
     return $result;
 }
    }
} elseif ($config['authentication_type'] == ZBX_AUTH_HTTP) {
    if (hasRequest('update')) {
        // get groups that use this authentication method
        $result = DBfetch(DBselect('SELECT COUNT(g.usrgrpid) AS cnt_usrgrp FROM usrgrp g WHERE g.gui_access=' . GROUP_GUI_ACCESS_INTERNAL));
        if ($result['cnt_usrgrp'] > 0) {
            info(_n('There is "%1$d" group with Internal GUI access.', 'There are "%1$d" groups with Internal GUI access.', $result['cnt_usrgrp']));
        }
        $messageSuccess = _('Authentication method changed to HTTP');
        $messageFailed = _('Cannot change authentication method to HTTP');
        DBstart();
        $result = update_config($config);
        if ($result) {
            // reset all sessions
            if ($isAuthenticationTypeChanged) {
                $result &= DBexecute('UPDATE sessions SET status=' . ZBX_SESSION_PASSIVE . ' WHERE sessionid<>' . zbx_dbstr(CWebUser::$data['sessionid']));
            }
            $isAuthenticationTypeChanged = false;
            add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_ZABBIX_CONFIG, $messageSuccess);
        }
        $result = DBend($result);
        show_messages($result, $messageSuccess, $messageFailed);
    }
}
show_messages();
/*
 * Display
 */
$data = array('form_refresh' => getRequest('form_refresh'), 'config' => $config, 'is_authentication_type_changed' => $isAuthenticationTypeChanged, 'user' => getRequest('user', CWebUser::$data['alias']), 'user_password' => getRequest('user_password', ''), 'user_list' => null, 'change_bind_password' => getRequest('change_bind_password'));
// get tab title
$data['title'] = authentication2str($config['authentication_type']);
Example #19
0
function change_group_gui_access($usrgrpid, $gui_access)
{
    $res = false;
    if ($gui_access == GROUP_GUI_ACCESS_DISABLED && !granted2update_group($usrgrpid)) {
        error(S_USER_CANNOT_CHANGE_GUI_ACCESS);
        return false;
    }
    $res = DBexecute('UPDATE usrgrp SET gui_access=' . $gui_access . ' WHERE usrgrpid=' . $usrgrpid);
    return $res;
}
Example #20
0
 /**
  * Delete trigger by ids.
  *
  * @param array $triggerIds
  */
 protected function deleteByIds(array $triggerIds)
 {
     // others idx should be deleted as well if they arise at some point
     DB::delete('profiles', ['idx' => 'web.events.filter.triggerid', 'value_id' => $triggerIds]);
     DB::delete('sysmaps_elements', ['elementid' => $triggerIds, 'elementtype' => SYSMAP_ELEMENT_TYPE_TRIGGER]);
     // disable actions
     $actionIds = [];
     $dbActions = DBselect('SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_TRIGGER . ' AND ' . dbConditionString('value', $triggerIds));
     while ($dbAction = DBfetch($dbActions)) {
         $actionIds[$dbAction['actionid']] = $dbAction['actionid'];
     }
     DBexecute('UPDATE actions SET status=' . ACTION_STATUS_DISABLED . ' WHERE ' . dbConditionInt('actionid', $actionIds));
     // delete action conditions
     DB::delete('conditions', ['conditiontype' => CONDITION_TYPE_TRIGGER, 'value' => $triggerIds]);
     if ($this->usedInItServices($triggerIds)) {
         DB::update('services', ['values' => ['triggerid' => null, 'showsla' => SERVICE_SHOW_SLA_OFF], 'where' => ['triggerid' => $triggerIds]]);
         updateItServices();
     }
     parent::deleteByIds($triggerIds);
 }
Example #21
0
        unset($_REQUEST['form']);
    }
    $result = DBend($result);
    if ($result) {
        uncheckTableRows();
    }
    show_messages($result, $messageSuccess, $messageFailed);
} elseif (hasRequest('action') && getRequest('action') == 'regexp.massdelete') {
    $regExpIds = getRequest('regexpids', getRequest('regexpid', []));
    zbx_value2array($regExpIds);
    $regExps = [];
    foreach ($regExpIds as $regExpId) {
        $regExps[$regExpId] = getRegexp($regExpId);
    }
    DBstart();
    $result = DBexecute('DELETE FROM regexps WHERE ' . dbConditionInt('regexpid', $regExpIds));
    $regExpCount = count($regExpIds);
    if ($result) {
        foreach ($regExps as $regExpId => $regExp) {
            add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_REGEXP, 'Id [' . $regExpId . '] ' . _('Name') . ' [' . $regExp['name'] . ']');
        }
        unset($_REQUEST['form'], $_REQUEST['regexpid']);
    }
    $result = DBend($result);
    if ($result) {
        uncheckTableRows();
    }
    show_messages($result, _n('Regular expression deleted', 'Regular expressions deleted', $regExpCount), _n('Cannot delete regular expression', 'Cannot delete regular expressions', $regExpCount));
}
/*
 * Display
Example #22
0
function delete_slideshow($slideshowid)
{
    $result = DBexecute('DELETE FROM slideshows where slideshowid=' . zbx_dbstr($slideshowid));
    $result &= DBexecute('DELETE FROM slides where slideshowid=' . zbx_dbstr($slideshowid));
    $result &= DBexecute('DELETE FROM profiles WHERE idx=\'web.favorite.screenids\' AND source=\'slideshowid\' AND value_id=' . zbx_dbstr($slideshowid));
    return $result;
}
 protected function deleteChecks(array $checkids)
 {
     $actionids = array();
     // conditions
     $sql = 'SELECT DISTINCT actionid ' . ' FROM conditions ' . ' WHERE conditiontype=' . CONDITION_TYPE_DCHECK . ' AND ' . dbConditionString('value', $checkids);
     $dbActions = DBselect($sql);
     while ($dbAction = DBfetch($dbActions)) {
         $actionids[] = $dbAction['actionid'];
     }
     // disabling actions with deleted conditions
     if (!empty($actionids)) {
         DBexecute('UPDATE actions ' . ' SET status=' . ACTION_STATUS_DISABLED . ' WHERE ' . dbConditionInt('actionid', $actionids));
         // delete action conditions
         DBexecute('DELETE FROM conditions ' . ' WHERE conditiontype=' . CONDITION_TYPE_DCHECK . ' AND ' . dbConditionString('value', $checkids));
     }
     DB::delete('dchecks', array('dcheckid' => $checkids));
 }
Example #24
0
function get_dbid($table, $field)
{
    $nodeid = get_current_nodeid(false);
    $found = false;
    do {
        global $ZBX_LOCALNODEID;
        $min = bcadd(bcmul($nodeid, '100000000000000'), bcmul($ZBX_LOCALNODEID, '100000000000'));
        $max = bcadd(bcadd(bcmul($nodeid, '100000000000000'), bcmul($ZBX_LOCALNODEID, '100000000000')), '99999999999');
        $row = DBfetch(DBselect('SELECT nextid FROM ids WHERE nodeid=' . $nodeid . " AND table_name='{$table}' AND field_name='{$field}'"));
        if (!$row) {
            $row = DBfetch(DBselect('SELECT max(' . $field . ') AS id FROM ' . $table . ' WHERE ' . $field . '>=' . $min . ' AND ' . $field . '<=' . $max));
            if (!$row || is_null($row["id"])) {
                DBexecute('INSERT INTO ids (nodeid,table_name,field_name,nextid) ' . " VALUES ({$nodeid},'{$table}','{$field}',{$min})");
            } else {
                /*
                $ret1 = $row["id"];
                if($ret1 >= $max) {
                	"Maximum number of id's was exceeded"
                }
                */
                DBexecute("INSERT INTO ids (nodeid,table_name,field_name,nextid) VALUES ({$nodeid},'{$table}','{$field}'," . $row["id"] . ')');
            }
            continue;
        } else {
            $ret1 = $row["nextid"];
            if (bccomp($ret1, $min) < 0 || !(bccomp($ret1, $max) < 0)) {
                DBexecute("DELETE FROM ids WHERE nodeid={$nodeid} AND table_name='{$table}' AND field_name='{$field}'");
                continue;
            }
            DBexecute("UPDATE ids SET nextid=nextid+1 WHERE nodeid={$nodeid} AND table_name='{$table}' AND field_name='{$field}'");
            $row = DBfetch(DBselect('SELECT nextid FROM ids WHERE nodeid=' . $nodeid . " AND table_name='{$table}' AND field_name='{$field}'"));
            if (!$row || is_null($row["nextid"])) {
                /* Should never be here */
                continue;
            } else {
                $ret2 = $row["nextid"];
                if (bccomp(bcadd($ret1, 1), $ret2) == 0) {
                    $found = true;
                }
            }
        }
    } while (false == $found);
    return $ret2;
}
Example #25
0
function update_config($configs)
{
    $update = array();
    if (isset($configs['work_period']) && !is_null($configs['work_period'])) {
        if (!validate_period($configs['work_period'])) {
            error(S_ICORRECT_WORK_PERIOD);
            return NULL;
        }
    }
    if (isset($configs['alert_usrgrpid']) && !is_null($configs['alert_usrgrpid'])) {
        if ($configs['alert_usrgrpid'] != 0 && !DBfetch(DBselect('select usrgrpid from usrgrp where usrgrpid=' . $configs['alert_usrgrpid']))) {
            error(S_INCORRECT_GROUP);
            return NULL;
        }
    }
    foreach ($configs as $key => $value) {
        if (!is_null($value)) {
            $update[] = $key . '=' . zbx_dbstr($value);
        }
    }
    if (count($update) == 0) {
        error(S_NOTHING_TO_DO);
        return NULL;
    }
    return DBexecute('update config set ' . implode(',', $update) . ' where ' . DBin_node('configid', get_current_nodeid(false)));
}
Example #26
0
 /**
  * Acknowledges the given events.
  *
  * Supported parameters:
  * - eventids   - an event ID or an array of event IDs to acknowledge
  * - message    - acknowledgment message
  *
  * @param array $data
  *
  * @return array
  */
 public function acknowledge(array $data)
 {
     $data['eventids'] = zbx_toArray($data['eventids']);
     $this->validateAcknowledge($data);
     $eventIds = zbx_toHash($data['eventids']);
     if (!DBexecute('UPDATE events SET acknowledged=1 WHERE ' . dbConditionInt('eventid', $eventIds))) {
         self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror');
     }
     $time = time();
     $dataInsert = array();
     foreach ($eventIds as $eventId) {
         $dataInsert[] = array('userid' => self::$userData['userid'], 'eventid' => $eventId, 'clock' => $time, 'message' => $data['message']);
     }
     DB::insert('acknowledges', $dataInsert);
     return array('eventids' => array_values($eventIds));
 }
Example #27
0
function change_group_debug_mode($usrgrpids, $debug_mode)
{
    zbx_value2array($usrgrpids);
    $res = false;
    $res = DBexecute('UPDATE usrgrp SET debug_mode=' . $debug_mode . ' WHERE ' . DBcondition('usrgrpid', $usrgrpids));
    return $res;
}
Example #28
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']['bulk']			bulk. OPTIONAL
  * @param int    $hosts['fields']['proxy_hostid']	Proxy Host ID. 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 function massUpdate($data)
 {
     $hosts = zbx_toArray($data['hosts']);
     $inputHostIds = zbx_objectValues($hosts, 'hostid');
     $hostids = array_unique($inputHostIds);
     sort($hostids);
     $db_hosts = $this->get(['output' => ['hostid', 'tls_connect', 'tls_accept', 'tls_issuer', 'tls_subject', 'tls_psk_identity', 'tls_psk'], 'hostids' => $hostids, 'editable' => true, 'preservekeys' => true]);
     foreach ($hosts as $host) {
         if (!array_key_exists($host['hostid'], $db_hosts)) {
             self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.'));
         }
     }
     // Check connection fields only for massupdate action.
     if ((array_key_exists('tls_connect', $data) || array_key_exists('tls_accept', $data) || array_key_exists('tls_psk_identity', $data) || array_key_exists('tls_psk', $data) || array_key_exists('tls_issuer', $data) || array_key_exists('tls_subject', $data)) && (!array_key_exists('tls_connect', $data) || !array_key_exists('tls_accept', $data))) {
         self::exception(ZBX_API_ERROR_PERMISSIONS, _('Cannot update host encryption settings. Connection settings for both directions should be specified.'));
     }
     $this->validateEncryption([$data]);
     // Clean PSK fields.
     if (array_key_exists('tls_connect', $data) && $data['tls_connect'] != HOST_ENCRYPTION_PSK && (array_key_exists('tls_accept', $data) && ($data['tls_accept'] & HOST_ENCRYPTION_PSK) != HOST_ENCRYPTION_PSK)) {
         $data['tls_psk_identity'] = '';
         $data['tls_psk'] = '';
     }
     // Clean certificate fields.
     if (array_key_exists('tls_connect', $data) && $data['tls_connect'] != HOST_ENCRYPTION_CERTIFICATE && (array_key_exists('tls_accept', $data) && ($data['tls_accept'] & HOST_ENCRYPTION_CERTIFICATE) != HOST_ENCRYPTION_CERTIFICATE)) {
         $data['tls_issuer'] = '';
         $data['tls_subject'] = '';
     }
     // 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.'));
     }
     /*
      * Update hosts properties
      */
     if (isset($data['name'])) {
         if (count($hosts) > 1) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update visible host name.'));
         }
     }
     if (isset($data['host'])) {
         if (!preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/', $data['host'])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for host name "%s".', $data['host']));
         }
         if (count($hosts) > 1) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update host name.'));
         }
         $curHost = reset($hosts);
         $sameHostnameHost = $this->get(['output' => ['hostid'], 'filter' => ['host' => $data['host']], 'nopermissions' => true, 'limit' => 1]);
         $sameHostnameHost = reset($sameHostnameHost);
         if ($sameHostnameHost && bccomp($sameHostnameHost['hostid'], $curHost['hostid']) != 0) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host "%1$s" already exists.', $data['host']));
         }
         // can't add host with the same name as existing template
         $sameHostnameTemplate = API::Template()->get(['output' => ['templateid'], 'filter' => ['host' => $data['host']], 'nopermissions' => true, 'limit' => 1]);
         if ($sameHostnameTemplate) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template "%1$s" already exists.', $data['host']));
         }
     }
     if (isset($data['groups'])) {
         $updateGroups = $data['groups'];
     }
     if (isset($data['interfaces'])) {
         $updateInterfaces = $data['interfaces'];
     }
     if (array_key_exists('templates_clear', $data)) {
         $updateTemplatesClear = zbx_toArray($data['templates_clear']);
     }
     if (isset($data['templates'])) {
         $updateTemplates = $data['templates'];
     }
     if (isset($data['macros'])) {
         $updateMacros = $data['macros'];
     }
     // second check is necessary, because import incorrectly inputs unset 'inventory' as empty string rather than null
     if (isset($data['inventory']) && $data['inventory']) {
         if (isset($data['inventory_mode']) && $data['inventory_mode'] == HOST_INVENTORY_DISABLED) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot set inventory fields for disabled inventory.'));
         }
         $updateInventory = $data['inventory'];
         $updateInventory['inventory_mode'] = null;
     }
     if (isset($data['inventory_mode'])) {
         if (!isset($updateInventory)) {
             $updateInventory = [];
         }
         $updateInventory['inventory_mode'] = $data['inventory_mode'];
     }
     if (isset($data['status'])) {
         $updateStatus = $data['status'];
     }
     unset($data['hosts'], $data['groups'], $data['interfaces'], $data['templates_clear'], $data['templates'], $data['macros'], $data['inventory'], $data['inventory_mode'], $data['status']);
     if (!zbx_empty($data)) {
         DB::update('hosts', ['values' => $data, 'where' => ['hostid' => $hostids]]);
     }
     if (isset($updateStatus)) {
         updateHostStatus($hostids, $updateStatus);
     }
     /*
      * Update template linkage
      */
     if (isset($updateTemplatesClear)) {
         $templateIdsClear = zbx_objectValues($updateTemplatesClear, 'templateid');
         if ($updateTemplatesClear) {
             $this->massRemove(['hostids' => $hostids, 'templateids_clear' => $templateIdsClear]);
         }
     } else {
         $templateIdsClear = [];
     }
     // unlink templates
     if (isset($updateTemplates)) {
         $hostTemplates = API::Template()->get(['hostids' => $hostids, 'output' => ['templateid'], 'preservekeys' => true]);
         $hostTemplateids = array_keys($hostTemplates);
         $newTemplateids = zbx_objectValues($updateTemplates, 'templateid');
         $templatesToDel = array_diff($hostTemplateids, $newTemplateids);
         $templatesToDel = array_diff($templatesToDel, $templateIdsClear);
         if ($templatesToDel) {
             $result = $this->massRemove(['hostids' => $hostids, 'templateids' => $templatesToDel]);
             if (!$result) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template'));
             }
         }
     }
     /*
      * update interfaces
      */
     if (isset($updateInterfaces)) {
         foreach ($hostids as $hostid) {
             API::HostInterface()->replaceHostInterfaces(['hostid' => $hostid, 'interfaces' => $updateInterfaces]);
         }
     }
     // link new templates
     if (isset($updateTemplates)) {
         $result = $this->massAdd(['hosts' => $hosts, 'templates' => $updateTemplates]);
         if (!$result) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template'));
         }
     }
     // macros
     if (isset($updateMacros)) {
         DB::delete('hostmacro', ['hostid' => $hostids]);
         $this->massAdd(['hosts' => $hosts, 'macros' => $updateMacros]);
     }
     /*
      * Inventory
      */
     if (isset($updateInventory)) {
         // disabling inventory
         if ($updateInventory['inventory_mode'] == HOST_INVENTORY_DISABLED) {
             $sql = 'DELETE FROM host_inventory WHERE ' . dbConditionInt('hostid', $hostids);
             if (!DBexecute($sql)) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete inventory.'));
             }
         } else {
             $existingInventoriesDb = DBfetchArrayAssoc(DBselect('SELECT hostid,inventory_mode' . ' FROM host_inventory' . ' WHERE ' . dbConditionInt('hostid', $hostids)), 'hostid');
             // check existing host inventory data
             $automaticHostIds = [];
             if ($updateInventory['inventory_mode'] === null) {
                 foreach ($hostids as $hostid) {
                     // if inventory is disabled for one of the updated hosts, throw an exception
                     if (!isset($existingInventoriesDb[$hostid])) {
                         $host = get_host_by_hostid($hostid);
                         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Inventory disabled for host "%1$s".', $host['host']));
                     } elseif ($existingInventoriesDb[$hostid]['inventory_mode'] == HOST_INVENTORY_AUTOMATIC) {
                         $automaticHostIds[] = $hostid;
                     }
                 }
             }
             $inventoriesToSave = [];
             foreach ($hostids as $hostid) {
                 $hostInventory = $updateInventory;
                 $hostInventory['hostid'] = $hostid;
                 // if no 'inventory_mode' has been passed, set inventory 'inventory_mode' from DB
                 if ($updateInventory['inventory_mode'] === null) {
                     $hostInventory['inventory_mode'] = $existingInventoriesDb[$hostid]['inventory_mode'];
                 }
                 $inventoriesToSave[$hostid] = $hostInventory;
             }
             // when updating automatic inventory, ignore fields that have items linked to them
             if ($updateInventory['inventory_mode'] == HOST_INVENTORY_AUTOMATIC || $updateInventory['inventory_mode'] === null && $automaticHostIds) {
                 $itemsToInventories = API::item()->get(['output' => ['inventory_link', 'hostid'], 'hostids' => $automaticHostIds ? $automaticHostIds : $hostids, 'nopermissions' => true]);
                 $inventoryFields = getHostInventories();
                 foreach ($itemsToInventories as $hinv) {
                     // 0 means 'no link'
                     if ($hinv['inventory_link'] != 0) {
                         $inventoryName = $inventoryFields[$hinv['inventory_link']]['db_field'];
                         unset($inventoriesToSave[$hinv['hostid']][$inventoryName]);
                     }
                 }
             }
             // save inventory data
             foreach ($inventoriesToSave as $inventory) {
                 $hostid = $inventory['hostid'];
                 if (isset($existingInventoriesDb[$hostid])) {
                     DB::update('host_inventory', ['values' => $inventory, 'where' => ['hostid' => $hostid]]);
                 } else {
                     DB::insert('host_inventory', [$inventory], false);
                 }
             }
         }
     }
     /*
      * Update host and host group linkage. This procedure should be done the last because user can unlink
      * him self from a group with write permissions leaving only read premissions. Thus other procedures, like
      * host-template linkage, inventory update, macros update, must be done before this.
      */
     if (isset($updateGroups)) {
         $updateGroups = zbx_toArray($updateGroups);
         $hostGroups = API::HostGroup()->get(['output' => ['groupid'], 'hostids' => $hostids]);
         $hostGroupIds = zbx_objectValues($hostGroups, 'groupid');
         $newGroupIds = zbx_objectValues($updateGroups, 'groupid');
         $groupsToAdd = array_diff($newGroupIds, $hostGroupIds);
         if ($groupsToAdd) {
             $this->massAdd(['hosts' => $hosts, 'groups' => zbx_toObject($groupsToAdd, 'groupid')]);
         }
         $groupIdsToDelete = array_diff($hostGroupIds, $newGroupIds);
         if ($groupIdsToDelete) {
             $this->massRemove(['hostids' => $hostids, 'groupids' => $groupIdsToDelete]);
         }
     }
     return ['hostids' => $inputHostIds];
 }
Example #29
0
    fatal_error(_('No triggers defined.'));
}
/*
 * Permissions
 */
$trigger = API::Trigger()->get(['triggerids' => $_REQUEST['triggerid'], 'output' => API_OUTPUT_EXTEND, 'expandDescription' => true]);
if (!$trigger) {
    access_deny();
}
$trigger = reset($trigger);
/*
 * Actions
 */
if (hasRequest('update')) {
    DBstart();
    $result = DBexecute('UPDATE triggers' . ' SET comments=' . zbx_dbstr(getRequest('comments')) . ' WHERE triggerid=' . zbx_dbstr(getRequest('triggerid')));
    $trigger['comments'] = $_REQUEST['comments'];
    if ($result) {
        add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER, _('Trigger') . ' [' . $_REQUEST['triggerid'] . '] [' . $trigger['description'] . '] ' . _('Comments') . ' [' . $_REQUEST['comments'] . ']');
    }
    $result = DBend($result);
    show_messages($result, _('Description updated'), _('Cannot update description'));
} elseif (isset($_REQUEST['cancel'])) {
    jsRedirect('tr_status.php');
    exit;
}
/*
 * Display
 */
$triggerEditable = API::Trigger()->get(['triggerids' => $_REQUEST['triggerid'], 'output' => ['triggerid'], 'editable' => true]);
$data = ['triggerid' => getRequest('triggerid'), 'trigger' => $trigger, 'isTriggerEditable' => !empty($triggerEditable), 'isCommentExist' => !empty($trigger['comments'])];
Example #30
0
function setHostGroupInternal($groupids, $internal = ZBX_NOT_INTERNAL_GROUP)
{
    zbx_value2array($groupids);
    return DBexecute('UPDATE groups SET internal=' . zbx_dbstr($internal) . ' WHERE ' . dbConditionInt('groupid', $groupids));
}