} elseif (isset($_REQUEST['delete_and_clear']) && isset($_REQUEST['templateid'])) { DBstart(); $result = API::Template()->delete(array(getRequest('templateid'))); $result = DBend($result); if ($result) { unset($_REQUEST['form'], $_REQUEST['templateid']); uncheckTableRows(); } unset($_REQUEST['delete']); show_messages($result, _('Template deleted'), _('Cannot delete template')); } elseif (hasRequest('action') && str_in_array(getRequest('action'), array('template.massdelete', 'template.massdeleteclear')) && hasRequest('templates')) { $templates = getRequest('templates'); DBstart(); $result = true; if (getRequest('action') == 'action.massdelete') { $result = API::Template()->massUpdate(array('templates' => zbx_toObject($templates, 'templateid'), 'hosts' => array())); } if ($result) { $result = API::Template()->delete($templates); } $result = DBend($result); if ($result) { uncheckTableRows(); } show_messages($result, _('Template deleted'), _('Cannot delete template')); } /* * Display */ $templateWidget = new CWidget(); $pageFilter = new CPageFilter(array('config' => array('individual' => 1), 'groups' => array('templated_hosts' => true, 'editable' => true), 'groupid' => getRequest('groupid')));
$bulk = !isset($_REQUEST['eventid']); if (!$bulk) { $events = API::Event()->get(array('eventids' => $_REQUEST['eventid'], 'output' => API_OUTPUT_EXTEND, 'selectRelatedObject' => API_OUTPUT_EXTEND)); if ($events) { $event = reset($events); $eventTriggerName = CMacrosResolverHelper::resolveTriggerName($event['relatedObject']); $eventAcknowledged = $event['acknowledged']; } $_REQUEST['events'] = $_REQUEST['eventid']; } if (isset($_REQUEST['save']) || isset($_REQUEST['saveandreturn'])) { if ($bulk) { $_REQUEST['message'] .= $_REQUEST['message'] == '' ? '' : "\n\r" . _('----[BULK ACKNOWLEDGE]----'); } if (isset($_REQUEST['events'])) { $_REQUEST['events'] = zbx_toObject($_REQUEST['events'], 'eventid'); } elseif (isset($_REQUEST['triggers'])) { $_REQUEST['events'] = API::Event()->get(array('source' => EVENT_SOURCE_TRIGGERS, 'object' => EVENT_OBJECT_TRIGGER, 'objectids' => $_REQUEST['triggers'], 'output' => array('eventid'), 'acknowledged' => EVENT_NOT_ACKNOWLEDGED)); } $acknowledgeEvent = API::Event()->acknowledge(array('eventids' => zbx_objectValues($_REQUEST['events'], 'eventid'), 'message' => $_REQUEST['message'])); show_messages($acknowledgeEvent, _('Event acknowledged'), _('Cannot acknowledge event')); if ($acknowledgeEvent) { $eventAcknowledged = true; add_audit(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_TRIGGER, _('Acknowledge added') . ' [' . ($bulk ? ' BULK ACKNOWLEDGE ' : $eventTriggerName) . ']' . ' [' . $_REQUEST['message'] . ']'); } if (isset($_REQUEST['saveandreturn'])) { ob_end_clean(); if (in_array($_REQUEST['backurl'], array('tr_events.php', 'events.php'))) { redirect($_REQUEST['backurl'] . '?eventid=' . $_REQUEST['eventid'] . '&triggerid=' . $_REQUEST['triggerid']); } elseif ($_REQUEST['backurl'] == 'screenedit.php') { redirect($_REQUEST['backurl'] . '?screenid=' . $_REQUEST['screenid']);
} // new group $groups = getRequest('groups', []); $newGroup = getRequest('newgroup'); if (!zbx_empty($newGroup)) { $newGroup = API::HostGroup()->create(['name' => $newGroup]); if (!$newGroup) { throw new Exception(); } $groups[] = reset($newGroup['groupids']); } $groups = zbx_toObject($groups, 'groupid'); // host data $host = ['host' => getRequest('host'), 'name' => getRequest('visiblename'), 'status' => getRequest('status', HOST_STATUS_NOT_MONITORED), 'description' => getRequest('description'), 'proxy_hostid' => getRequest('proxy_hostid', 0), 'ipmi_authtype' => getRequest('ipmi_authtype'), 'ipmi_privilege' => getRequest('ipmi_privilege'), 'ipmi_username' => getRequest('ipmi_username'), 'ipmi_password' => getRequest('ipmi_password'), 'tls_connect' => getRequest('tls_connect', HOST_ENCRYPTION_NONE), 'tls_accept' => getRequest('tls_accept', HOST_ENCRYPTION_NONE), 'tls_issuer' => getRequest('tls_issuer'), 'tls_subject' => getRequest('tls_subject'), 'tls_psk_identity' => getRequest('tls_psk_identity'), 'tls_psk' => getRequest('tls_psk'), 'groups' => $groups, 'templates' => $templates, 'interfaces' => $interfaces, 'macros' => $macros, 'inventory_mode' => getRequest('inventory_mode'), 'inventory' => getRequest('inventory_mode') == HOST_INVENTORY_DISABLED ? [] : getRequest('host_inventory', [])]; if (!$create) { $host['templates_clear'] = zbx_toObject(getRequest('clear_templates', []), 'templateid'); } } if ($create) { $hostIds = API::Host()->create($host); if ($hostIds) { $hostId = reset($hostIds['hostids']); } else { throw new Exception(); } add_audit_ext(AUDIT_ACTION_ADD, AUDIT_RESOURCE_HOST, $hostId, $host['host'], null, null, null); } else { $host['hostid'] = $hostId; if (!API::Host()->update($host)) { throw new Exception(); }
/** * 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; } }
$oldStatus = $dbHost['status']; if ($oldStatus == $status) { continue; } $go_result &= updateHostStatus($dbHost['hostid'], $status); if (!$go_result) { continue; } } } $go_result = DBend($go_result && !empty($hosts)); show_messages($go_result, _('Host status updated'), null); } elseif ($_REQUEST['go'] == 'delete' && isset($_REQUEST['hosts'])) { $hosts = get_request('hosts', array()); DBstart(); $go_result = API::Proxy()->delete(zbx_toObject($hosts, 'proxyid')); $go_result = DBend($go_result); show_messages($go_result, _('Proxy deleted'), _('Cannot delete proxy')); } if ($_REQUEST['go'] != 'none' && !empty($go_result)) { $url = new CUrl(); $path = $url->getPath(); insert_js('cookie.eraseArray("' . $path . '")'); } /* * Display */ if (isset($_REQUEST['form'])) { $data = array('form' => get_request('form', 1), 'form_refresh' => get_request('form_refresh', 0) + 1, 'proxyid' => get_request('proxyid', 0), 'name' => get_request('host', ''), 'status' => get_request('status', HOST_STATUS_PROXY_ACTIVE), 'hosts' => get_request('hosts', array()), 'interfaces' => get_request('interfaces', array()), 'interface' => get_request('interface', array()), 'proxy' => array()); // proxy if (!empty($data['proxyid'])) {
} foreach ($macros as $key => $macro) { // transform macros to uppercase {$aaa} => {$AAA} $macros[$key]['macro'] = zbx_strtoupper($macro['macro']); } // create new group if (!zbx_empty($_REQUEST['newgroup'])) { if (!($newGroup = API::HostGroup()->create(array('name' => $_REQUEST['newgroup'])))) { throw new Exception(); } $groups[] = reset($newGroup['groupids']); } $groups = zbx_toObject($groups, 'groupid'); $host = array('host' => $_REQUEST['host'], 'name' => $_REQUEST['visiblename'], 'status' => $_REQUEST['status'], 'proxy_hostid' => get_request('proxy_hostid', 0), 'ipmi_authtype' => get_request('ipmi_authtype'), 'ipmi_privilege' => get_request('ipmi_privilege'), 'ipmi_username' => get_request('ipmi_username'), 'ipmi_password' => get_request('ipmi_password'), 'groups' => $groups, 'templates' => $templates, 'interfaces' => $interfaces, 'macros' => $macros, 'inventory' => get_request('inventory_mode') != HOST_INVENTORY_DISABLED ? get_request('host_inventory', array()) : null, 'inventory_mode' => get_request('inventory_mode')); if (!$createNew) { $host['templates_clear'] = zbx_toObject(get_request('clear_templates', array()), 'templateid'); } } ############################################################################################## # update racktables object require_once 'racktablesapi.php'; $groupids = get_request('groups', array()); $groupNames = array(); foreach ($groupids as $groupid) { $group = API::HostGroup()->get(array('groupids' => $groupid, 'output' => API_OUTPUT_EXTEND)); array_push($groupNames, $group[0]['name']); } if (!zbx_empty($_REQUEST['newgroup'])) { # new group $response = addRack($_REQUEST['newgroup']); if (isset($response['error'])) {
/** * 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]; }
$result = DBend($result); show_messages($result, _('Host deleted'), _('Cannot delete host')); if ($result) { unset($_REQUEST['form'], $_REQUEST['hostid']); } unset($_REQUEST['delete']); } elseif (isset($_REQUEST['chstatus']) && isset($_REQUEST['hostid'])) { DBstart(); $result = updateHostStatus($_REQUEST['hostid'], $_REQUEST['chstatus']); $result = DBend($result); show_messages($result, _('Host status updated'), _('Cannot update host status')); unset($_REQUEST['chstatus'], $_REQUEST['hostid']); } elseif ($_REQUEST['go'] == 'delete') { $hostids = get_request('hosts', array()); DBstart(); $go_result = API::Host()->delete(zbx_toObject($hostids, 'hostid')); $go_result = DBend($go_result); show_messages($go_result, _('Host deleted'), _('Cannot delete host')); } elseif (str_in_array($_REQUEST['go'], array('activate', 'disable'))) { $status = $_REQUEST['go'] == 'activate' ? HOST_STATUS_MONITORED : HOST_STATUS_NOT_MONITORED; $hosts = get_request('hosts', array()); $act_hosts = available_hosts($hosts, 1); DBstart(); $go_result = updateHostStatus($act_hosts, $status); $go_result = DBend($go_result); show_messages($go_result, _('Host status updated'), _('Cannot update host status')); } if ($_REQUEST['go'] != 'none' && isset($go_result) && $go_result) { $url = new CUrl(); $path = $url->getPath(); insert_js('cookie.eraseArray("' . $path . '")');
if (!uint_in_array($triggerId, getRequest('dependencies'))) { $_REQUEST['dependencies'][] = $triggerId; } } } elseif (hasRequest('action') && getRequest('action') === 'triggerprototype.massupdate' && hasRequest('massupdate') && hasRequest('g_triggerid')) { $result = true; $visible = getRequest('visible', []); if ($visible) { $triggersToUpdate = []; foreach (getRequest('g_triggerid') as $triggerId) { $trigger = ['triggerid' => $triggerId]; if (isset($visible['priority'])) { $trigger['priority'] = getRequest('priority'); } if (isset($visible['dependencies'])) { $trigger['dependencies'] = zbx_toObject(getRequest('dependencies', []), 'triggerid'); } $triggersToUpdate[] = $trigger; } $result = (bool) API::TriggerPrototype()->update($triggersToUpdate); } if ($result) { unset($_REQUEST['form'], $_REQUEST['g_triggerid']); uncheckTableRows(getRequest('parent_discoveryid')); } show_messages($result, _('Trigger prototypes updated'), _('Cannot update trigger prototypes')); } elseif (getRequest('action') && str_in_array(getRequest('action'), ['triggerprototype.massenable', 'triggerprototype.massdisable']) && hasRequest('g_triggerid')) { $enable = getRequest('action') == 'triggerprototype.massenable'; $status = $enable ? TRIGGER_STATUS_ENABLED : TRIGGER_STATUS_DISABLED; $update = []; // get requested triggers with permission check
/** * Mass update. * * @param string $data['host'] * @param string $data['name'] * @param string $data['description'] * @param array $data['templates'] * @param array $data['templates_clear'] * @param array $data['templates_link'] * @param array $data['groups'] * @param array $data['hosts'] * @param array $data['macros'] * * @return array */ public function massUpdate(array $data) { $this->validateMassUpdate($data); $templates = zbx_toArray($data['templates']); $templateIds = zbx_objectValues($templates, 'templateid'); $fieldsToUpdate = array(); if (isset($data['host'])) { $fieldsToUpdate[] = 'host=' . zbx_dbstr($data['host']); } if (isset($data['name'])) { // if visible name is empty replace it with host name if (zbx_empty(trim($data['name'])) && isset($data['host'])) { $fieldsToUpdate[] = 'name=' . zbx_dbstr($data['host']); } elseif (zbx_empty(trim($data['name'])) && !isset($data['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot have empty visible template name.')); } else { $fieldsToUpdate[] = 'name=' . zbx_dbstr($data['name']); } } if (isset($data['description'])) { $fieldsToUpdate[] = 'description=' . zbx_dbstr($data['description']); } if ($fieldsToUpdate) { DBexecute('UPDATE hosts SET ' . implode(', ', $fieldsToUpdate) . ' WHERE ' . dbConditionInt('hostid', $templateIds)); } $data['templates_clear'] = isset($data['templates_clear']) ? zbx_toArray($data['templates_clear']) : array(); $templateIdsClear = zbx_objectValues($data['templates_clear'], 'templateid'); if ($data['templates_clear']) { $this->massRemove(array('templateids' => $templateIds, 'templateids_clear' => $templateIdsClear)); } // update template linkage // firstly need to unlink all things, to correctly check circulars if (isset($data['hosts']) && $data['hosts'] !== null) { /* * Get all currently linked hosts and templates (skip discovered hosts) to these templates * that user has read permissions. */ $templateHosts = API::Host()->get(array('output' => array('hostid'), 'templateids' => $templateIds, 'templated_hosts' => true, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); $templateHostIds = zbx_objectValues($templateHosts, 'hostid'); $newHostIds = zbx_objectValues($data['hosts'], 'hostid'); $hostsToDelete = array_diff($templateHostIds, $newHostIds); $hostIdsToDelete = array_diff($hostsToDelete, $templateIdsClear); $hostIdsToAdd = array_diff($newHostIds, $templateHostIds); if ($hostIdsToDelete) { $result = $this->massRemove(array('hostids' => $hostIdsToDelete, 'templateids' => $templateIds)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template.')); } } } if (isset($data['templates_link']) && $data['templates_link'] !== null) { $templateTemplates = API::Template()->get(array('output' => array('templateid'), 'hostids' => $templateIds)); $templateTemplateIds = zbx_objectValues($templateTemplates, 'templateid'); $newTemplateIds = zbx_objectValues($data['templates_link'], 'templateid'); $templatesToDelete = array_diff($templateTemplateIds, $newTemplateIds); $templateIdsToDelete = array_diff($templatesToDelete, $templateIdsClear); if ($templateIdsToDelete) { $result = $this->massRemove(array('templateids' => $templateIds, 'templateids_link' => $templateIdsToDelete)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template.')); } } } if (isset($data['hosts']) && $data['hosts'] !== null && $hostIdsToAdd) { $result = $this->massAdd(array('templates' => $templates, 'hosts' => $hostIdsToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template.')); } } if (isset($data['templates_link']) && $data['templates_link'] !== null) { $templatesToAdd = array_diff($newTemplateIds, $templateTemplateIds); if ($templatesToAdd) { $result = $this->massAdd(array('templates' => $templates, 'templates_link' => $templatesToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template.')); } } } // macros if (isset($data['macros'])) { DB::delete('hostmacro', array('hostid' => $templateIds)); $this->massAdd(array('hosts' => $templates, 'macros' => $data['macros'])); } /* * Update template 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 linking, macros update, must be done before this. */ if (isset($data['groups']) && $data['groups'] !== null && is_array($data['groups'])) { $updateGroups = zbx_toArray($data['groups']); $templateGroups = API::HostGroup()->get(array('output' => array('groupid'), 'templateids' => $templateIds)); $templateGroupIds = zbx_objectValues($templateGroups, 'groupid'); $newGroupIds = zbx_objectValues($updateGroups, 'groupid'); $groupsToAdd = array_diff($newGroupIds, $templateGroupIds); if ($groupsToAdd) { $this->massAdd(array('templates' => $templates, 'groups' => zbx_toObject($groupsToAdd, 'groupid'))); } $groupIdsToDelete = array_diff($templateGroupIds, $newGroupIds); if ($groupIdsToDelete) { $this->massRemove(array('templateids' => $templateIds, 'groupids' => $groupIdsToDelete)); } } return array('templateids' => $templateIds); }
} elseif (isset($_REQUEST['delete_and_clear']) && isset($_REQUEST['templateid'])) { DBstart(); $result = API::Template()->delete([getRequest('templateid')]); $result = DBend($result); if ($result) { unset($_REQUEST['form'], $_REQUEST['templateid']); uncheckTableRows(); } unset($_REQUEST['delete']); show_messages($result, _('Template deleted'), _('Cannot delete template')); } elseif (hasRequest('action') && str_in_array(getRequest('action'), ['template.massdelete', 'template.massdeleteclear']) && hasRequest('templates')) { $templates = getRequest('templates'); DBstart(); $result = true; if (getRequest('action') === 'template.massdelete') { $result = API::Template()->massUpdate(['templates' => zbx_toObject($templates, 'templateid'), 'hosts' => []]); } if ($result) { $result = API::Template()->delete($templates); } $result = DBend($result); if ($result) { uncheckTableRows(); } show_messages($result, _('Template deleted'), _('Cannot delete template')); } /* * Display */ $templateWidget = (new CWidget())->setTitle(_('Templates')); $pageFilter = new CPageFilter(['config' => ['individual' => 1], 'groups' => ['templated_hosts' => true, 'editable' => true], 'groupid' => getRequest('groupid')]);
/** * Mass update hosts * * @param _array $hosts multidimensional array with Hosts data * @param array $hosts['hosts'] Array of Host objects to update * @return boolean */ public function massUpdate($data) { $templates = zbx_toArray($data['templates']); $templateids = zbx_objectValues($templates, 'templateid'); $options = array('templateids' => $templateids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true); $updTemplates = $this->get($options); foreach ($templates as $tnum => $template) { if (!isset($updTemplates[$template['templateid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // 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')); } // }}} CHECK IF TEMPLATES HAVE AT LEAST 1 GROUP // UPDATE TEMPLATES PROPERTIES {{{ if (isset($data['name'])) { if (count($templates) > 1) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update visible template name')); } $curTemplate = reset($templates); $options = array('filter' => array('name' => $curTemplate['name']), 'output' => array('templateid'), 'editable' => 1, 'nopermissions' => 1); $templateExists = $this->get($options); $templateExist = reset($templateExists); if ($templateExist && bccomp($templateExist['templateid'], $curTemplate['templateid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same visible name "%1$s" already exists.', $curTemplate['name'])); } // can't set the same name as existing host if (API::Host()->exists(array('name' => $curTemplate['name']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same visible name "%1$s" already exists.', $curTemplate['name'])); } } if (isset($data['host'])) { if (count($templates) > 1) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update template name')); } $curTemplate = reset($templates); $options = array('filter' => array('host' => $curTemplate['host']), 'output' => array('templateid'), 'editable' => 1, 'nopermissions' => 1); $templateExists = $this->get($options); $templateExist = reset($templateExists); if ($templateExist && bccomp($templateExist['templateid'], $curTemplate['templateid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same name "%1$s" already exists.', $curTemplate['host'])); } // can't set the same name as existing host if (API::Host()->exists(array('host' => $curTemplate['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same name "%1$s" already exists.', $curTemplate['host'])); } } if (isset($data['host']) && !preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/', $data['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for template name "%1$s".', $data['host'])); } $sqlSet = array(); if (isset($data['host'])) { $sqlSet[] = 'host=' . zbx_dbstr($data['host']); } if (isset($data['name'])) { // if visible name is empty replace it with host name if (zbx_empty(trim($data['name'])) && isset($data['host'])) { $sqlSet[] = 'name=' . zbx_dbstr($data['host']); } elseif (zbx_empty(trim($data['name'])) && !isset($data['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot have empty visible template name')); } else { $sqlSet[] = 'name=' . zbx_dbstr($data['name']); } } if (!empty($sqlSet)) { $sql = 'UPDATE hosts SET ' . implode(', ', $sqlSet) . ' WHERE ' . dbConditionInt('hostid', $templateids); $result = DBexecute($sql); } // }}} UPDATE TEMPLATES PROPERTIES $data['templates_clear'] = isset($data['templates_clear']) ? zbx_toArray($data['templates_clear']) : array(); $templateidsClear = zbx_objectValues($data['templates_clear'], 'templateid'); if (!empty($data['templates_clear'])) { $result = $this->massRemove(array('templateids' => $templateids, 'templateids_clear' => $templateidsClear)); } // UPDATE TEMPLATE LINKAGE {{{ // firstly need to unlink all things, to correctly check circulars if (isset($data['hosts']) && !is_null($data['hosts'])) { /* * Get all currently linked hosts and templates (skip discovered hosts) to these templates * that user has read permissions. */ $templateHosts = API::Host()->get(array('output' => array('hostid'), 'templateids' => $templateids, 'templated_hosts' => 1, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); $templateHostids = zbx_objectValues($templateHosts, 'hostid'); $newHostids = zbx_objectValues($data['hosts'], 'hostid'); $hostsToDel = array_diff($templateHostids, $newHostids); $hostidsToDel = array_diff($hostsToDel, $templateidsClear); $hostIdsToAdd = array_diff($newHostids, $templateHostids); // gather both host and template IDs and validate write permissions $hostIds = array_merge($hostIdsToAdd, $hostidsToDel); if ($hostIds) { /* * Get all currently linked hosts and templates (skip discovered hosts) to these templates * that user has write permissions. */ $templatesHostsAllowed = API::Host()->get(array('output' => array('hostid'), 'templated_hosts' => true, 'editable' => true, 'preservekeys' => true, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); foreach ($hostIds as $hostId) { if (!isset($templatesHostsAllowed[$hostId])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!')); } } } if ($hostidsToDel) { $result = $this->massRemove(array('hostids' => $hostidsToDel, 'templateids' => $templateids)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't unlink template")); } } } if (isset($data['templates_link']) && !is_null($data['templates_link'])) { $templateTemplates = API::Template()->get(array('hostids' => $templateids)); $templateTemplateids = zbx_objectValues($templateTemplates, 'templateid'); $newTemplateids = zbx_objectValues($data['templates_link'], 'templateid'); $templatesToDel = array_diff($templateTemplateids, $newTemplateids); $templateidsToDel = array_diff($templatesToDel, $templateidsClear); if (!empty($templateidsToDel)) { $result = $this->massRemove(array('templateids' => $templateids, 'templateids_link' => $templateidsToDel)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't unlink template")); } } } if (isset($data['hosts']) && !is_null($data['hosts'])) { $hostsToAdd = array_diff($newHostids, $templateHostids); if (!empty($hostsToAdd)) { $result = $this->massAdd(array('templates' => $templates, 'hosts' => $hostsToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't link template")); } } } if (isset($data['templates_link']) && !is_null($data['templates_link'])) { $templatesToAdd = array_diff($newTemplateids, $templateTemplateids); if (!empty($templatesToAdd)) { $result = $this->massAdd(array('templates' => $templates, 'templates_link' => $templatesToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't link template")); } } } // }}} UPDATE TEMPLATE LINKAGE // macros if (isset($data['macros'])) { DB::delete('hostmacro', array('hostid' => $templateids)); $this->massAdd(array('hosts' => $templates, 'macros' => $data['macros'])); } /* * Update template 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 linking, macros update, must be done before this. */ if (isset($data['groups']) && is_array($data['groups'])) { $updateGroups = zbx_toArray($data['groups']); $templateGroups = API::HostGroup()->get(array('output' => array('groupid'), 'templateids' => $templateids)); $templateGroupids = zbx_objectValues($templateGroups, 'groupid'); $newGroupids = zbx_objectValues($updateGroups, 'groupid'); $groupsToAdd = array_diff($newGroupids, $templateGroupids); if ($groupsToAdd) { $this->massAdd(array('templates' => $templates, 'groups' => zbx_toObject($groupsToAdd, 'groupid'))); } $groupidsToDel = array_diff($templateGroupids, $newGroupids); if ($groupidsToDel) { $this->massRemove(array('templateids' => $templateids, 'groupids' => $groupidsToDel)); } } return array('templateids' => $templateids); }
unset($_REQUEST['form']); unset($_REQUEST['hostid']); } unset($_REQUEST['delete']); } else { if (isset($_REQUEST['chstatus']) && isset($_REQUEST['hostid'])) { DBstart(); $result = update_host_status($_REQUEST['hostid'], $_REQUEST['chstatus']); $result = DBend($result); show_messages($result, S_HOST_STATUS_UPDATED, S_CANNOT_UPDATE_HOST_STATUS); unset($_REQUEST['chstatus']); unset($_REQUEST['hostid']); } else { if ($_REQUEST['go'] == 'delete') { $hostids = get_request('hosts', array()); $hosts = zbx_toObject($hostids, 'hostid'); $go_result = CHost::delete($hosts); show_messages($go_result, S_HOST_DELETED, S_CANNOT_DELETE_HOST); } else { if (str_in_array($_REQUEST['go'], array('activate', 'disable'))) { $status = $_REQUEST['go'] == 'activate' ? HOST_STATUS_MONITORED : HOST_STATUS_NOT_MONITORED; $hosts = get_request('hosts', array()); $act_hosts = available_hosts($hosts, 1); DBstart(); $go_result = update_host_status($act_hosts, $status); $go_result = DBend($go_result); show_messages($go_result, S_HOST_STATUS_UPDATED, S_CANNOT_UPDATE_HOST); } } } }
/** * 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; } }
} if ($isValid) { $user = array(); $user['alias'] = getRequest('alias'); $user['name'] = getRequest('name'); $user['surname'] = getRequest('surname'); $user['passwd'] = getRequest('password1'); $user['url'] = getRequest('url'); $user['autologin'] = getRequest('autologin', 0); $user['autologout'] = hasRequest('autologout_visible') ? getRequest('autologout') : 0; $user['theme'] = getRequest('theme'); $user['refresh'] = getRequest('refresh'); $user['rows_per_page'] = getRequest('rows_per_page'); $user['type'] = getRequest('user_type'); $user['user_medias'] = getRequest('user_medias', array()); $user['usrgrps'] = zbx_toObject($usrgrps, 'usrgrpid'); if (hasRequest('lang')) { $user['lang'] = getRequest('lang'); } DBstart(); if (hasRequest('userid')) { $user['userid'] = getRequest('userid'); $result = API::User()->update(array($user)); if ($result) { $result = API::User()->updateMedia(array('users' => $user, 'medias' => $user['user_medias'])); } $messageSuccess = _('User updated'); $messageFailed = _('Cannot update user'); $auditAction = AUDIT_ACTION_UPDATE; } else { $result = API::User()->create($user);
foreach (array_diff($oldHostIds, $newHostIds) as $hostId) { $hostIdsToRemove[$hostId] = $hostId; } foreach (array_diff($newTemplateIds, $oldTemplateIds) as $templateId) { $templateIdsToAdd[$templateId] = $templateId; } foreach (array_diff($oldTemplateIds, $newTemplateIds) as $templateId) { $templateIdsToRemove[$templateId] = $templateId; } if ($hostIdsToAdd || $templateIdsToAdd) { $massAdd = array('groups' => array('groupid' => $groupId)); if ($hostIdsToAdd) { $massAdd['hosts'] = zbx_toObject($hostIdsToAdd, 'hostid'); } if ($templateIdsToAdd) { $massAdd['templates'] = zbx_toObject($templateIdsToAdd, 'templateid'); } $result &= (bool) API::HostGroup()->massAdd($massAdd); } if ($hostIdsToRemove || $templateIdsToRemove) { $massRemove = array('groupids' => array($groupId)); if ($hostIdsToRemove) { $massRemove['hostids'] = $hostIdsToRemove; } if ($templateIdsToRemove) { $massRemove['templateids'] = $templateIdsToRemove; } $result &= (bool) API::HostGroup()->massRemove($massRemove); } if ($result) { $group = reset($groups);
/** * Mass update hosts * * @param _array $hosts multidimensional array with Hosts data * @param array $hosts['hosts'] Array of Host objects to update * @return boolean */ public function massUpdate($data) { $templates = zbx_toArray($data['templates']); $templateids = zbx_objectValues($templates, 'templateid'); $options = array('templateids' => $templateids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true); $updTemplates = $this->get($options); foreach ($templates as $tnum => $template) { if (!isset($updTemplates[$template['templateid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // 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')); } // }}} CHECK IF TEMPLATES HAVE AT LEAST 1 GROUP // UPDATE TEMPLATES PROPERTIES {{{ if (isset($data['name'])) { if (count($templates) > 1) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update visible template name')); } $curTemplate = reset($templates); $options = array('filter' => array('name' => $curTemplate['name']), 'output' => API_OUTPUT_SHORTEN, 'editable' => 1, 'nopermissions' => 1); $templateExists = $this->get($options); $templateExist = reset($templateExists); if ($templateExist && bccomp($templateExist['templateid'], $curTemplate['templateid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same visible name "%s" already exists.', $curTemplate['name'])); } // can't set the same name as existing host if (API::Host()->exists(array('name' => $curTemplate['name']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same visible name "%s" already exists.', $curTemplate['name'])); } } if (isset($data['host'])) { if (count($templates) > 1) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot mass update template name')); } $curTemplate = reset($templates); $options = array('filter' => array('host' => $curTemplate['host']), 'output' => API_OUTPUT_SHORTEN, 'editable' => 1, 'nopermissions' => 1); $templateExists = $this->get($options); $templateExist = reset($templateExists); if ($templateExist && bccomp($templateExist['templateid'], $curTemplate['templateid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same name "%s" already exists.', $curTemplate['host'])); } // can't set the same name as existing host if (API::Host()->exists(array('host' => $curTemplate['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same name "%s" already exists.', $curTemplate['host'])); } } if (isset($data['host']) && !preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/', $data['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for template name "%s".', $data['host'])); } $sqlSet = array(); if (isset($data['host'])) { $sqlSet[] = 'host=' . zbx_dbstr($data['host']); } if (isset($data['name'])) { // if visible name is empty replace it with host name if (zbx_empty(trim($data['name'])) && isset($data['host'])) { $sqlSet[] = 'name=' . zbx_dbstr($data['host']); } elseif (zbx_empty(trim($data['name'])) && !isset($data['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot have empty visible template name')); } else { $sqlSet[] = 'name=' . zbx_dbstr($data['name']); } } if (!empty($sqlSet)) { $sql = 'UPDATE hosts SET ' . implode(', ', $sqlSet) . ' WHERE ' . dbConditionInt('hostid', $templateids); $result = DBexecute($sql); } // }}} UPDATE TEMPLATES PROPERTIES // UPDATE HOSTGROUPS LINKAGE {{{ if (isset($data['groups']) && !is_null($data['groups'])) { $data['groups'] = zbx_toArray($data['groups']); $templateGroups = API::HostGroup()->get(array('hostids' => $templateids)); $templateGroupids = zbx_objectValues($templateGroups, 'groupid'); $newGroupids = zbx_objectValues($data['groups'], 'groupid'); $groupsToAdd = array_diff($newGroupids, $templateGroupids); if (!empty($groupsToAdd)) { $result = $this->massAdd(array('templates' => $templates, 'groups' => zbx_toObject($groupsToAdd, 'groupid'))); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't add group")); } } $groupidsToDel = array_diff($templateGroupids, $newGroupids); if (!empty($groupidsToDel)) { $result = $this->massRemove(array('templateids' => $templateids, 'groupids' => $groupidsToDel)); 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(); $templateidsClear = zbx_objectValues($data['templates_clear'], 'templateid'); if (!empty($data['templates_clear'])) { $result = $this->massRemove(array('templateids' => $templateids, 'templateids_clear' => $templateidsClear)); } // UPDATE TEMPLATE LINKAGE {{{ // firstly need to unlink all things, to correctly check circulars if (isset($data['hosts']) && !is_null($data['hosts'])) { $templateHosts = API::Host()->get(array('templateids' => $templateids, 'templated_hosts' => 1)); $templateHostids = zbx_objectValues($templateHosts, 'hostid'); $newHostids = zbx_objectValues($data['hosts'], 'hostid'); $hostsToDel = array_diff($templateHostids, $newHostids); $hostidsToDel = array_diff($hostsToDel, $templateidsClear); if (!empty($hostidsToDel)) { $result = $this->massRemove(array('hostids' => $hostidsToDel, 'templateids' => $templateids)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't unlink template")); } } } if (isset($data['templates_link']) && !is_null($data['templates_link'])) { $templateTemplates = API::Template()->get(array('hostids' => $templateids)); $templateTemplateids = zbx_objectValues($templateTemplates, 'templateid'); $newTemplateids = zbx_objectValues($data['templates_link'], 'templateid'); $templatesToDel = array_diff($templateTemplateids, $newTemplateids); $templateidsToDel = array_diff($templatesToDel, $templateidsClear); if (!empty($templateidsToDel)) { $result = $this->massRemove(array('templateids' => $templateids, 'templateids_link' => $templateidsToDel)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't unlink template")); } } } if (isset($data['hosts']) && !is_null($data['hosts'])) { $hostsToAdd = array_diff($newHostids, $templateHostids); if (!empty($hostsToAdd)) { $result = $this->massAdd(array('templates' => $templates, 'hosts' => $hostsToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't link template")); } } } if (isset($data['templates_link']) && !is_null($data['templates_link'])) { $templatesToAdd = array_diff($newTemplateids, $templateTemplateids); if (!empty($templatesToAdd)) { $result = $this->massAdd(array('templates' => $templates, 'templates_link' => $templatesToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _("Can't link template")); } } } // }}} UPDATE TEMPLATE LINKAGE // macros if (isset($data['macros'])) { DB::delete('hostmacro', array('hostid' => $templateids)); $this->massAdd(array('hosts' => $templates, 'macros' => $data['macros'])); } return array('templateids' => $templateids); }
/** * Mass update. * * @param string $data['host'] * @param string $data['name'] * @param string $data['description'] * @param array $data['templates'] * @param array $data['templates_clear'] * @param array $data['templates_link'] * @param array $data['groups'] * @param array $data['hosts'] * @param array $data['macros'] * * @return array */ public function massUpdate(array $data) { $this->validateMassUpdate($data); $templates = zbx_toArray($data['templates']); $templateIds = zbx_objectValues($templates, 'templateid'); $fieldsToUpdate = array(); if (isset($data['host'])) { $fieldsToUpdate[] = 'host=' . zbx_dbstr($data['host']); } if (isset($data['name'])) { // if visible name is empty replace it with host name if (zbx_empty(trim($data['name'])) && isset($data['host'])) { $fieldsToUpdate[] = 'name=' . zbx_dbstr($data['host']); } elseif (zbx_empty(trim($data['name'])) && !isset($data['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot have empty visible template name.')); } else { $fieldsToUpdate[] = 'name=' . zbx_dbstr($data['name']); } } if (isset($data['description'])) { $fieldsToUpdate[] = 'description=' . zbx_dbstr($data['description']); } if ($fieldsToUpdate) { DBexecute('UPDATE hosts SET ' . implode(', ', $fieldsToUpdate) . ' WHERE ' . dbConditionInt('hostid', $templateIds)); } // update hostgroups linkage if (isset($data['groups']) && $data['groups'] !== null) { $data['groups'] = zbx_toArray($data['groups']); $templateGroups = API::HostGroup()->get(array('output' => array('groupid'), 'hostids' => $templateIds)); $templateGroupIds = zbx_objectValues($templateGroups, 'groupid'); $newGroupIds = zbx_objectValues($data['groups'], 'groupid'); $groupsToAdd = array_diff($newGroupIds, $templateGroupIds); if ($groupsToAdd) { $result = $this->massAdd(array('templates' => $templates, 'groups' => zbx_toObject($groupsToAdd, 'groupid'))); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot add group.')); } } $groupsToDelete = array_diff($templateGroupIds, $newGroupIds); if ($groupsToDelete) { $result = $this->massRemove(array('templateids' => $templateIds, 'groupids' => $groupsToDelete)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot remove group.')); } } } $data['templates_clear'] = isset($data['templates_clear']) ? zbx_toArray($data['templates_clear']) : array(); $templateIdsClear = zbx_objectValues($data['templates_clear'], 'templateid'); if ($data['templates_clear']) { $this->massRemove(array('templateids' => $templateIds, 'templateids_clear' => $templateIdsClear)); } // update template linkage // firstly need to unlink all things, to correctly check circulars if (isset($data['hosts']) && $data['hosts'] !== null) { $templateHosts = API::Host()->get(array('templateids' => $templateIds, 'templated_hosts' => true, 'filter' => array('flags' => ZBX_FLAG_DISCOVERY_NORMAL))); $templateHostIds = zbx_objectValues($templateHosts, 'hostid'); $newHostIds = zbx_objectValues($data['hosts'], 'hostid'); $hostsToDelete = array_diff($templateHostIds, $newHostIds); $hostIdsToDelete = array_diff($hostsToDelete, $templateIdsClear); if ($hostIdsToDelete) { $result = $this->massRemove(array('hostids' => $hostIdsToDelete, 'templateids' => $templateIds)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template.')); } } } if (isset($data['templates_link']) && $data['templates_link'] !== null) { $templateTemplates = API::Template()->get(array('output' => array('templateid'), 'hostids' => $templateIds)); $templateTemplateIds = zbx_objectValues($templateTemplates, 'templateid'); $newTemplateIds = zbx_objectValues($data['templates_link'], 'templateid'); $templatesToDelete = array_diff($templateTemplateIds, $newTemplateIds); $templateIdsToDelete = array_diff($templatesToDelete, $templateIdsClear); if ($templateIdsToDelete) { $result = $this->massRemove(array('templateids' => $templateIds, 'templateids_link' => $templateIdsToDelete)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot unlink template.')); } } } if (isset($data['hosts']) && $data['hosts'] !== null) { $hostsToAdd = array_diff($newHostIds, $templateHostIds); if ($hostsToAdd) { $result = $this->massAdd(array('templates' => $templates, 'hosts' => $hostsToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template.')); } } } if (isset($data['templates_link']) && $data['templates_link'] !== null) { $templatesToAdd = array_diff($newTemplateIds, $templateTemplateIds); if ($templatesToAdd) { $result = $this->massAdd(array('templates' => $templates, 'templates_link' => $templatesToAdd)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot link template.')); } } } // macros if (isset($data['macros'])) { DB::delete('hostmacro', array('hostid' => $templateIds)); $this->massAdd(array('hosts' => $templates, 'macros' => $data['macros'])); } return array('templateids' => $templateIds); }
/** * Update maintenances * * @param array $maintenances * @return boolean */ public function update(array $maintenances) { $maintenances = zbx_toArray($maintenances); $maintenanceids = zbx_objectValues($maintenances, 'maintenanceid'); // validate maintenance permissions if (self::$userData['type'] == USER_TYPE_ZABBIX_USER) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } $hostids = array(); $groupids = array(); $updMaintenances = $this->get(array('maintenanceids' => zbx_objectValues($maintenances, 'maintenanceid'), 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'selectGroups' => API_OUTPUT_REFER, 'selectHosts' => API_OUTPUT_REFER, 'selectTimeperiods' => API_OUTPUT_EXTEND, 'preservekeys' => true)); foreach ($maintenances as $maintenance) { if (!isset($updMaintenances[$maintenance['maintenanceid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } // Checking whether a maintenance with this name already exists. First, getting all maintenances with the same name as this $receivedMaintenances = API::Maintenance()->get(array('filter' => array('name' => $maintenance['name']))); // validate if maintenance name already exists foreach ($receivedMaintenances as $rMaintenance) { if (bccomp($rMaintenance['maintenanceid'], $maintenance['maintenanceid']) != 0) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Maintenance "%s" already exists.', $maintenance['name'])); } } // validate maintenance active since if (!validateUnixTime($maintenance['active_since'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active since'))); } // validate maintenance active till if (!validateUnixTime($maintenance['active_till'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active till'))); } // validate maintenance active interval if ($maintenance['active_since'] > $maintenance['active_till']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Maintenance "Active since" value cannot be bigger than "Active till".')); } // validate timeperiods if (empty($maintenance['timeperiods'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one maintenance period must be created.')); } $hostids = array_merge($hostids, $maintenance['hostids']); $groupids = array_merge($groupids, $maintenance['groupids']); } // validate hosts & groups if (empty($hostids) && empty($groupids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one host or group should be selected.')); } // validate hosts permissions $options = array('hostids' => $hostids, 'editable' => true, 'output' => array('hostid'), 'preservekeys' => true); $updHosts = API::Host()->get($options); foreach ($hostids as $hostid) { if (!isset($updHosts[$hostid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // validate groups permissions $options = array('groupids' => $groupids, 'editable' => true, 'output' => array('groupid'), 'preservekeys' => true); $updGroups = API::HostGroup()->get($options); foreach ($groupids as $groupid) { if (!isset($updGroups[$groupid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $this->removeSecondsFromTimes($maintenances); $update = array(); foreach ($maintenances as $mnum => $maintenance) { $dbFields = array('maintenanceid' => null); // validate fields if (!check_db_fields($dbFields, $maintenance)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect parameters for maintenance.')); } $update[$mnum] = array('values' => $maintenance, 'where' => array('maintenanceid' => $maintenance['maintenanceid'])); // update time periods $this->replaceTimePeriods($updMaintenances[$maintenance['maintenanceid']], $maintenance); } DB::update('maintenances', $update); // some of the hosts and groups bound to maintenance must be deleted, other inserted and others left alone $insertHosts = array(); $insertGroups = array(); foreach ($maintenances as $maintenance) { // putting apart those host<->maintenance connections that should be inserted, deleted and not changed // $hostDiff['first'] - new hosts, that should be inserted // $hostDiff['second'] - hosts, that should be deleted // $hostDiff['both'] - hosts, that should not be touched $hostDiff = zbx_array_diff(zbx_toObject($maintenance['hostids'], 'hostid'), $updMaintenances[$maintenance['maintenanceid']]['hosts'], 'hostid'); foreach ($hostDiff['first'] as $host) { $insertHosts[] = array('hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']); } foreach ($hostDiff['second'] as $host) { $deleteHosts = array('hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']); DB::delete('maintenances_hosts', $deleteHosts); } // now the same with the groups $groupDiff = zbx_array_diff(zbx_toObject($maintenance['groupids'], 'groupid'), $updMaintenances[$maintenance['maintenanceid']]['groups'], 'groupid'); foreach ($groupDiff['first'] as $group) { $insertGroups[] = array('groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']); } foreach ($groupDiff['second'] as $group) { $deleteGroups = array('groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']); DB::delete('maintenances_groups', $deleteGroups); } } DB::insert('maintenances_hosts', $insertHosts); DB::insert('maintenances_groups', $insertGroups); return array('maintenanceids' => $maintenanceids); }
$user['name'] = get_request('name'); $user['surname'] = get_request('surname'); $user['alias'] = get_request('alias'); $user['passwd'] = get_request('password1'); $user['url'] = get_request('url'); $user['autologin'] = get_request('autologin', 0); $user['autologout'] = get_request('autologout', 0); $user['lang'] = get_request('lang'); $user['theme'] = get_request('theme'); $user['refresh'] = get_request('refresh'); $user['rows_per_page'] = get_request('rows_per_page'); $user['type'] = get_request('user_type'); // $user['user_groups'] = get_request('user_groups', array()); $user['user_medias'] = get_request('user_medias', array()); $usrgrps = get_request('user_groups', array()); $usrgrps = zbx_toObject($usrgrps, 'usrgrpid'); $user['usrgrps'] = $usrgrps; if (isset($_REQUEST['userid'])) { $action = AUDIT_ACTION_UPDATE; $user['userid'] = $_REQUEST['userid']; DBstart(); $result = CUser::update($user); if (!$result) { error(CUser::resetErrors()); } // if($result) $result = CUserGroup::updateUsers(array('users' => $user, 'usrgrps' => $usrgrps)); // if($result === false) // error(CUserGroup::resetErrors()); if ($result !== false) { $result = CUser::updateMedia(array('users' => $user, 'medias' => $user['user_medias'])); }
/** * Update maintenances. * * @param array $maintenances * * @return boolean */ public function update(array $maintenances) { $maintenances = zbx_toArray($maintenances); $maintenanceids = zbx_objectValues($maintenances, 'maintenanceid'); // validate maintenance permissions if (self::$userData['type'] == USER_TYPE_ZABBIX_USER) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } $updMaintenances = $this->get(['maintenanceids' => zbx_objectValues($maintenances, 'maintenanceid'), 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'selectGroups' => ['groupid'], 'selectHosts' => ['hostid'], 'selectTimeperiods' => API_OUTPUT_EXTEND, 'preservekeys' => true]); $maintenanceNamesChanged = []; foreach ($maintenances as $maintenance) { if (!isset($updMaintenances[$maintenance['maintenanceid']])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } if (isset($maintenance['name']) && !zbx_empty($maintenance['name']) && $updMaintenances[$maintenance['maintenanceid']]['name'] !== $maintenance['name']) { if (isset($maintenanceNamesChanged[$maintenance['name']])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Maintenance "%1$s" already exists.', $maintenance['name'])); } else { $maintenanceNamesChanged[$maintenance['name']] = $maintenance['name']; } } } // check if maintenance already exists if ($maintenanceNamesChanged) { $dbMaintenances = $this->get(['output' => ['name'], 'filter' => ['name' => $maintenanceNamesChanged], 'nopermissions' => true, 'limit' => 1]); if ($dbMaintenances) { $dbMaintenance = reset($dbMaintenances); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Maintenance "%1$s" already exists.', $dbMaintenance['name'])); } } $hostids = []; $groupids = []; foreach ($maintenances as $maintenance) { // validate maintenance active since if (!validateUnixTime($maintenance['active_since'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active since'))); } // validate maintenance active till if (!validateUnixTime($maintenance['active_till'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('"%s" must be between 1970.01.01 and 2038.01.18.', _('Active till'))); } // validate maintenance active interval if ($maintenance['active_since'] > $maintenance['active_till']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Maintenance "Active since" value cannot be bigger than "Active till".')); } // validate timeperiods if (!array_key_exists('timeperiods', $maintenance) || !is_array($maintenance['timeperiods']) || !$maintenance['timeperiods']) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one maintenance period must be created.')); } foreach ($maintenance['timeperiods'] as $timeperiod) { if (!is_array($timeperiod)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one maintenance period must be created.')); } } $hostids = array_merge($hostids, $maintenance['hostids']); $groupids = array_merge($groupids, $maintenance['groupids']); } // validate hosts & groups if (empty($hostids) && empty($groupids)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('At least one host or group should be selected.')); } // validate hosts permissions $options = ['hostids' => $hostids, 'editable' => true, 'output' => ['hostid'], 'preservekeys' => true]; $updHosts = API::Host()->get($options); foreach ($hostids as $hostid) { if (!isset($updHosts[$hostid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // validate groups permissions $options = ['groupids' => $groupids, 'editable' => true, 'output' => ['groupid'], 'preservekeys' => true]; $updGroups = API::HostGroup()->get($options); foreach ($groupids as $groupid) { if (!isset($updGroups[$groupid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!')); } } $this->removeSecondsFromTimes($maintenances); $update = []; foreach ($maintenances as $mnum => $maintenance) { $dbFields = ['maintenanceid' => null]; // validate fields if (!check_db_fields($dbFields, $maintenance)) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Incorrect parameters for maintenance.')); } $update[$mnum] = ['values' => $maintenance, 'where' => ['maintenanceid' => $maintenance['maintenanceid']]]; // update time periods $this->replaceTimePeriods($updMaintenances[$maintenance['maintenanceid']], $maintenance); } DB::update('maintenances', $update); // some of the hosts and groups bound to maintenance must be deleted, other inserted and others left alone $insertHosts = []; $insertGroups = []; foreach ($maintenances as $maintenance) { // putting apart those host<->maintenance connections that should be inserted, deleted and not changed // $hostDiff['first'] - new hosts, that should be inserted // $hostDiff['second'] - hosts, that should be deleted // $hostDiff['both'] - hosts, that should not be touched $hostDiff = zbx_array_diff(zbx_toObject($maintenance['hostids'], 'hostid'), $updMaintenances[$maintenance['maintenanceid']]['hosts'], 'hostid'); foreach ($hostDiff['first'] as $host) { $insertHosts[] = ['hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']]; } foreach ($hostDiff['second'] as $host) { $deleteHosts = ['hostid' => $host['hostid'], 'maintenanceid' => $maintenance['maintenanceid']]; DB::delete('maintenances_hosts', $deleteHosts); } // now the same with the groups $groupDiff = zbx_array_diff(zbx_toObject($maintenance['groupids'], 'groupid'), $updMaintenances[$maintenance['maintenanceid']]['groups'], 'groupid'); foreach ($groupDiff['first'] as $group) { $insertGroups[] = ['groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']]; } foreach ($groupDiff['second'] as $group) { $deleteGroups = ['groupid' => $group['groupid'], 'maintenanceid' => $maintenance['maintenanceid']]; DB::delete('maintenances_groups', $deleteGroups); } add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_MAINTENANCE, $maintenance['maintenanceid'], array_key_exists('name', $maintenance) ? $maintenance['name'] : $updMaintenances[$maintenance['maintenanceid']]['name'], 'maintenances', $updMaintenances[$maintenance['maintenanceid']], $maintenance); } DB::insert('maintenances_hosts', $insertHosts); DB::insert('maintenances_groups', $insertGroups); return ['maintenanceids' => $maintenanceids]; }
foreach ($_REQUEST['new_dependency'] as $triggerid) { if (!uint_in_array($triggerid, $_REQUEST['dependencies'])) { array_push($_REQUEST['dependencies'], $triggerid); } } } elseif ($_REQUEST['go'] == 'massupdate' && isset($_REQUEST['mass_save']) && isset($_REQUEST['g_triggerid'])) { $visible = get_request('visible', array()); // update triggers $triggersToUpdate = array(); foreach ($_REQUEST['g_triggerid'] as $triggerid) { $trigger = array('triggerid' => $triggerid); if (isset($visible['priority'])) { $trigger['priority'] = get_request('priority'); } if (isset($visible['dependencies'])) { $trigger['dependencies'] = zbx_toObject(get_request('dependencies', array()), 'triggerid'); } $triggersToUpdate[] = $trigger; } DBstart(); $result = API::Trigger()->update($triggersToUpdate); $result = DBend($result); show_messages($result, _('Trigger updated'), _('Cannot update trigger')); clearCookies($result, $_REQUEST['hostid']); if ($result) { unset($_REQUEST['massupdate'], $_REQUEST['form'], $_REQUEST['g_triggerid']); } } elseif (str_in_array($_REQUEST['go'], array('activate', 'disable')) && isset($_REQUEST['g_triggerid'])) { $status = getRequest('go') == 'activate' ? TRIGGER_STATUS_ENABLED : TRIGGER_STATUS_DISABLED; // get requested triggers with permission check $dbTriggers = API::Trigger()->get(array('output' => array('triggerid', 'status'), 'triggerids' => getRequest('g_triggerid'), 'editable' => true));
/** * Delete Map. * * @param array $sysmapIds * * @return array */ public function delete(array $sysmapIds) { $maps = zbx_toObject($sysmapIds, 'sysmapid'); $this->checkInput($maps, __FUNCTION__); DB::delete('sysmaps_elements', array('elementid' => $sysmapIds, 'elementtype' => SYSMAP_ELEMENT_TYPE_MAP)); DB::delete('screens_items', array('resourceid' => $sysmapIds, 'resourcetype' => SCREEN_RESOURCE_MAP)); DB::delete('profiles', array('idx' => 'web.maps.sysmapid', 'value_id' => $sysmapIds)); DB::delete('profiles', array('idx' => 'web.favorite.sysmapids', 'source' => 'sysmapid', 'value_id' => $sysmapIds)); DB::delete('sysmaps', array('sysmapid' => $sysmapIds)); return array('sysmapids' => $sysmapIds); }
/** * Delete triggers. * * @param array $triggerIds * @param bool $nopermissions * * @return array */ public function delete($triggerIds, $nopermissions = false) { $triggerIds = zbx_toArray($triggerIds); $triggers = zbx_toObject($triggerIds, 'triggerid'); if (!$triggerIds) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.')); } // TODO: remove $nopermissions hack if (!$nopermissions) { $this->checkInput($triggers, __FUNCTION__); } // get child triggers $parentTriggerIds = $triggerIds; do { $dbItems = DBselect('SELECT triggerid FROM triggers WHERE ' . dbConditionInt('templateid', $parentTriggerIds)); $parentTriggerIds = array(); while ($dbTrigger = DBfetch($dbItems)) { $parentTriggerIds[] = $dbTrigger['triggerid']; $triggerIds[] = $dbTrigger['triggerid']; } } while ($parentTriggerIds); // select all triggers which are deleted (including children) $delTriggers = $this->get(array('triggerids' => $triggerIds, 'output' => array('triggerid', 'description', 'expression'), 'nopermissions' => true, 'selectHosts' => array('name'))); // TODO: REMOVE info foreach ($delTriggers as $trigger) { info(_s('Deleted: Trigger "%1$s" on "%2$s".', $trigger['description'], implode(', ', zbx_objectValues($trigger['hosts'], 'name')))); add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_TRIGGER, $trigger['triggerid'], $trigger['description'], null, null, null); } // execute delete $this->deleteByIds($triggerIds); return array('triggerids' => $triggerIds); }