Example #1
0
 /**
  * Executes API requests.
  *
  * @return string JSON encoded value
  */
 public function execute()
 {
     if ($this->json->hasError()) {
         $this->jsonError(null, '-32700', null, null, true);
         return $this->json->encode($this->_response[0]);
     }
     if ($this->_jsonDecoded === null || $this->_jsonDecoded == []) {
         $this->jsonError(null, '-32600', null, null, true);
         return $this->json->encode($this->_response[0]);
     }
     foreach (zbx_toArray($this->_jsonDecoded) as $call) {
         $call = is_array($call) ? $call : [$call];
         // notification
         if (!array_key_exists('id', $call)) {
             $call['id'] = null;
         }
         if (!$this->validate($call)) {
             continue;
         }
         list($api, $method) = array_merge(explode('.', $call['method']), [null, null]);
         $result = $this->apiClient->callMethod($api, $method, $call['params'], $call['auth']);
         $this->processResult($call, $result);
     }
     if (is_array($this->_jsonDecoded) && array_keys($this->_jsonDecoded) === range(0, count($this->_jsonDecoded) - 1)) {
         // Return response as encoded batch if $this->_jsonDecoded is associative array.
         return $this->json->encode($this->_response);
     }
     return $this->json->encode($this->_response[0]);
 }
Example #2
0
 /**
  * Delete web scenario.
  *
  * @param $httpTestIds
  *
  * @return array|bool
  */
 public function delete($httpTestIds, $nopermissions = false)
 {
     if (empty($httpTestIds)) {
         return true;
     }
     $httpTestIds = zbx_toArray($httpTestIds);
     $delHttpTests = $this->get(array('httptestids' => $httpTestIds, 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'selectHosts' => API_OUTPUT_EXTEND, 'preservekeys' => true));
     if (!$nopermissions) {
         foreach ($httpTestIds as $httpTestId) {
             if (!empty($delHttpTests[$httpTestId]['templateid'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot delete templated web scenario "%1$s".', $delHttpTests[$httpTestId]['name']));
             }
             if (!isset($delHttpTests[$httpTestId])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
             }
         }
     }
     $parentHttpTestIds = $httpTestIds;
     $childHttpTestIds = array();
     do {
         $dbTests = DBselect('SELECT ht.httptestid FROM httptest ht WHERE ' . dbConditionInt('ht.templateid', $parentHttpTestIds));
         $parentHttpTestIds = array();
         while ($dbTest = DBfetch($dbTests)) {
             $parentHttpTestIds[] = $dbTest['httptestid'];
             $childHttpTestIds[$dbTest['httptestid']] = $dbTest['httptestid'];
         }
     } while (!empty($parentHttpTestIds));
     $options = array('httptestids' => $childHttpTestIds, 'output' => API_OUTPUT_EXTEND, 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => API_OUTPUT_EXTEND);
     $delHttpTestChilds = $this->get($options);
     $delHttpTests = zbx_array_merge($delHttpTests, $delHttpTestChilds);
     $httpTestIds = array_merge($httpTestIds, $childHttpTestIds);
     $itemidsDel = array();
     $dbTestItems = DBselect('SELECT hsi.itemid' . ' FROM httptestitem hsi' . ' WHERE ' . dbConditionInt('hsi.httptestid', $httpTestIds));
     while ($testitem = DBfetch($dbTestItems)) {
         $itemidsDel[] = $testitem['itemid'];
     }
     $dbStepItems = DBselect('SELECT DISTINCT hsi.itemid' . ' FROM httpstepitem hsi,httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', $httpTestIds) . ' AND hs.httpstepid=hsi.httpstepid');
     while ($stepitem = DBfetch($dbStepItems)) {
         $itemidsDel[] = $stepitem['itemid'];
     }
     if (!empty($itemidsDel)) {
         API::Item()->delete($itemidsDel, true);
     }
     DB::delete('httptest', array('httptestid' => $httpTestIds));
     // TODO: REMOVE
     foreach ($delHttpTests as $httpTest) {
         $host = reset($httpTest['hosts']);
         info(_s('Deleted: Web scenario "%1$s" on "%2$s".', $httpTest['name'], $host['host']));
         add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_SCENARIO, 'Web scenario "' . $httpTest['name'] . '" "' . $httpTest['httptestid'] . '" host "' . $host['host'] . '".');
     }
     return array('httptestids' => $httpTestIds);
 }
Example #3
0
 /**
  * Update scripts.
  *
  * @param array $scripts
  * @param array $scripts['name']
  * @param array $scripts['hostid']
  *
  * @return array
  */
 public function update(array $scripts)
 {
     $scripts = zbx_toArray($scripts);
     $this->validateUpdate($scripts);
     $scripts = $this->trimMenuPath($scripts);
     $this->validateMenuPath($scripts, __FUNCTION__);
     $scripts = $this->unsetExecutionType($scripts);
     $update = array();
     foreach ($scripts as $script) {
         $scriptId = $script['scriptid'];
         unset($script['scriptid']);
         $update[] = array('values' => $script, 'where' => array('scriptid' => $scriptId));
     }
     DB::update('scripts', $update);
     return array('scriptids' => zbx_objectValues($scripts, 'scriptid'));
 }
Example #4
0
 /**
  * Delete Host
  *
  * @param array $hosts
  * @param array $hosts[0, ...]['hostid'] Host ID to delete
  * @return array|boolean
  */
 public static function delete($hosts)
 {
     $hosts = zbx_toArray($hosts);
     $hostids = zbx_objectValues($hosts, 'hostid');
     if (empty($hostids)) {
         return true;
     }
     try {
         self::BeginTransaction(__METHOD__);
         $options = array('hostids' => $hostids, 'editable' => 1, 'output' => API_OUTPUT_SHORTEN, 'preservekeys' => 1);
         $del_hosts = self::get($options);
         foreach ($hostids as $hnum => $hostid) {
             if (!isset($del_hosts[$hostid])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSION);
             }
         }
         $result = delete_host($hostids, false);
         if (!$result) {
             self::exception(ZBX_API_ERROR_PARAMETERS, 'Cannot delete host');
         }
         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 #5
0
 /**
  * Inherit template graphs from template to host.
  *
  * @param array $data
  *
  * @return bool
  */
 public function syncTemplates($data)
 {
     $data['templateids'] = zbx_toArray($data['templateids']);
     $data['hostids'] = zbx_toArray($data['hostids']);
     $dbLinks = DBSelect('SELECT ht.hostid,ht.templateid' . ' FROM hosts_templates ht' . ' WHERE ' . dbConditionInt('ht.hostid', $data['hostids']) . ' AND ' . dbConditionInt('ht.templateid', $data['templateids']));
     $linkage = array();
     while ($link = DBfetch($dbLinks)) {
         if (!isset($linkage[$link['templateid']])) {
             $linkage[$link['templateid']] = array();
         }
         $linkage[$link['templateid']][$link['hostid']] = 1;
     }
     $graphs = $this->get(array('hostids' => $data['templateids'], 'preservekeys' => true, 'output' => API_OUTPUT_EXTEND, 'selectGraphItems' => API_OUTPUT_EXTEND, 'selectHosts' => array('hostid'), 'filter' => array('flags' => null)));
     foreach ($graphs as $graph) {
         foreach ($data['hostids'] as $hostid) {
             if (isset($linkage[$graph['hosts'][0]['hostid']][$hostid])) {
                 $this->inherit($graph, $hostid);
             }
         }
     }
     return true;
 }
 public function syncTemplates($data)
 {
     $data['templateids'] = zbx_toArray($data['templateids']);
     $data['hostids'] = zbx_toArray($data['hostids']);
     $applications = $this->get(array('hostids' => $data['templateids'], 'preservekeys' => true, 'output' => API_OUTPUT_EXTEND));
     $this->inherit($applications, $data['hostids']);
     return true;
 }
Example #7
0
 /**
  * Delete proxy.
  *
  * @param string|array $proxyIds
  *
  * @return array
  */
 public function delete($proxyIds)
 {
     $proxyIds = zbx_toArray($proxyIds);
     // deprecated input support
     if ($proxyIds && is_array($proxyIds[0])) {
         $this->deprecated('Passing objects is deprecated, use an array of IDs instead.');
         foreach ($proxyIds as $proxyId) {
             if (!check_db_fields(array('proxyid' => null), $proxyId)) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No proxy ID given.'));
             }
         }
         $proxyIds = zbx_objectValues($proxyIds, 'proxyid');
     }
     $this->validateDelete($proxyIds);
     $dbProxies = DBselect('SELECT h.hostid,h.host' . ' FROM hosts h' . ' WHERE ' . dbConditionInt('h.hostid', $proxyIds));
     $dbProxies = DBfetchArrayAssoc($dbProxies, 'hostid');
     $actionIds = array();
     // get conditions
     $dbActions = DBselect('SELECT DISTINCT c.actionid' . ' FROM conditions c' . ' WHERE c.conditiontype=' . CONDITION_TYPE_PROXY . ' AND ' . dbConditionString('c.value', $proxyIds));
     while ($dbAction = DBfetch($dbActions)) {
         $actionIds[$dbAction['actionid']] = $dbAction['actionid'];
     }
     if ($actionIds) {
         DB::update('actions', array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionIds)));
     }
     // delete action conditions
     DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_PROXY, 'value' => $proxyIds));
     // delete interface
     DB::delete('interface', array('hostid' => $proxyIds));
     // delete host
     DB::delete('hosts', array('hostid' => $proxyIds));
     // TODO: remove info from API
     foreach ($dbProxies as $proxy) {
         info(_s('Deleted: Proxy "%1$s".', $proxy['host']));
         add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_PROXY, '[' . $proxy['host'] . '] [' . $proxy['hostid'] . ']');
     }
     return array('proxyids' => $proxyIds);
 }
Example #8
0
 /**
  * Additionally allows to remove interfaces from hosts.
  *
  * Checks write permissions for hosts.
  *
  * Additional supported $data parameters are:
  * - interfaces  - an array of interfaces to delete from the hosts
  *
  * @param array $data
  *
  * @return array
  */
 public function massRemove(array $data)
 {
     $hostids = zbx_toArray($data['hostids']);
     $this->checkPermissions($hostids);
     if (isset($data['interfaces'])) {
         $options = ['hostids' => $hostids, 'interfaces' => zbx_toArray($data['interfaces'])];
         API::HostInterface()->massRemove($options);
     }
     // rename the "templates" parameter to the common "templates_link"
     if (isset($data['templateids'])) {
         $data['templateids_link'] = $data['templateids'];
         unset($data['templateids']);
     }
     $data['templateids'] = [];
     return parent::massRemove($data);
 }
Example #9
0
 /**
  * Update IconMap.
  * @param array $iconMaps
  * @return array
  */
 public function update(array $iconMaps)
 {
     if (USER_TYPE_SUPER_ADMIN != self::$userData['type']) {
         self::exception(ZBX_API_ERROR_PERMISSIONS, _('Only Super Admins can update icon maps.'));
     }
     $iconMaps = zbx_toArray($iconMaps);
     $iconMapids = zbx_objectValues($iconMaps, 'iconmapid');
     $updates = [];
     $duplicates = [];
     foreach ($iconMaps as $iconMap) {
         if (!check_db_fields(['iconmapid' => null], $iconMap)) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect parameters for icon map update method "%s".', $iconMap['name']));
         }
         if (isset($iconMap['name'])) {
             if (zbx_empty($iconMap['name'])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map name cannot be empty.'));
             } elseif (isset($duplicates[$iconMap['name']])) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Cannot create icon maps with identical name "%s".', $iconMap['name']));
             } else {
                 $duplicates[$iconMap['name']] = $iconMap['name'];
             }
         }
     }
     $this->validateMappings($iconMaps, false);
     $iconMapsUpd = API::IconMap()->get(['iconmapids' => $iconMapids, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true, 'selectMappings' => API_OUTPUT_EXTEND]);
     $oldIconMappings = [];
     $newIconMappings = [];
     foreach ($iconMaps as $iconMap) {
         if (!isset($iconMapsUpd[$iconMap['iconmapid']])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map with iconmapid "%s" does not exist.', $iconMap['iconmapid']));
         }
         // Existence
         if (isset($iconMap['name'])) {
             $iconMapExists = $this->get(['filter' => ['name' => $iconMap['name']], 'output' => ['iconmapid'], 'editable' => true, 'nopermissions' => true, 'preservekeys' => true]);
             if (($iconMapExists = reset($iconMapExists)) && bccomp($iconMapExists['iconmapid'], $iconMap['iconmapid']) != 0) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%s" already exists.', $iconMap['name']));
             }
         }
         if (isset($iconMap['mappings'])) {
             $mappingsDb = $iconMapsUpd[$iconMap['iconmapid']]['mappings'];
             foreach ($mappingsDb as $mapping) {
                 $oldIconMappings[] = $mapping;
             }
             foreach ($iconMap['mappings'] as $mapping) {
                 $mapping['iconmapid'] = $iconMap['iconmapid'];
                 $newIconMappings[] = $mapping;
             }
         }
         $iconMapid = $iconMap['iconmapid'];
         unset($iconMap['iconmapid']);
         if (!empty($iconMap)) {
             $updates[] = ['values' => $iconMap, 'where' => ['iconmapid' => $iconMapid]];
         }
     }
     DB::save('icon_map', $iconMaps);
     DB::replace('icon_mapping', $oldIconMappings, $newIconMappings);
     return ['iconmapids' => $iconMapids];
 }
Example #10
0
 public function syncTemplates(array $data)
 {
     $data['templateids'] = zbx_toArray($data['templateids']);
     $data['hostids'] = zbx_toArray($data['hostids']);
     $triggers = $this->get(array('hostids' => $data['templateids'], 'preservekeys' => true, 'output' => array('triggerid', 'expression', 'description', 'url', 'status', 'priority', 'comments', 'type')));
     foreach ($triggers as $trigger) {
         $trigger['expression'] = explode_exp($trigger['expression']);
         $this->inherit($trigger, $data['hostids']);
     }
     return true;
 }
Example #11
0
 /**
  * Deletes screen items.
  *
  * @param array $screenItemIds
  *
  * @return array
  */
 public function delete($screenItemIds)
 {
     $screenItemIds = zbx_toArray($screenItemIds);
     // check permissions
     $dbScreenItems = $this->get(array('screenitemids' => $screenItemIds, 'preservekeys' => true));
     foreach ($screenItemIds as $screenItemId) {
         if (!isset($dbScreenItems[$screenItemId])) {
             self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!'));
         }
     }
     // delete screen items
     DB::delete($this->tableName(), array('screenitemid' => $screenItemIds));
     return array('screenitemids' => $screenItemIds);
 }
 /**
  * Delete web scenario.
  *
  * @param $httpTestIds
  *
  * @return array|bool
  */
 public function delete($httpTestIds)
 {
     if (empty($httpTestIds)) {
         return true;
     }
     $httpTestIds = zbx_toArray($httpTestIds);
     $delHttpTests = $this->get(array('httptestids' => $httpTestIds, 'output' => API_OUTPUT_EXTEND, 'editable' => true, 'selectHosts' => API_OUTPUT_EXTEND, 'preservekeys' => true));
     foreach ($httpTestIds as $httpTestId) {
         if (!isset($delHttpTests[$httpTestId])) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
         }
     }
     $itemidsDel = array();
     $dbTestItems = DBselect('SELECT hsi.itemid' . ' FROM httptestitem hsi' . ' WHERE ' . dbConditionInt('hsi.httptestid', $httpTestIds));
     while ($testitem = DBfetch($dbTestItems)) {
         $itemidsDel[] = $testitem['itemid'];
     }
     $dbStepItems = DBselect('SELECT DISTINCT hsi.itemid' . ' FROM httpstepitem hsi,httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', $httpTestIds) . ' AND hs.httpstepid=hsi.httpstepid');
     while ($stepitem = DBfetch($dbStepItems)) {
         $itemidsDel[] = $stepitem['itemid'];
     }
     if (!empty($itemidsDel)) {
         API::Item()->delete($itemidsDel, true);
     }
     DB::delete('httptest', array('httptestid' => $httpTestIds));
     // TODO: REMOVE info
     foreach ($delHttpTests as $httpTest) {
         info(_s('Scenario "%s" deleted.', $httpTest['name']));
     }
     // TODO: REMOVE audit
     foreach ($delHttpTests as $httpTest) {
         $host = reset($httpTest['hosts']);
         add_audit(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_SCENARIO, _s('Scenario "%1$s" "%2$s" host "%3$s".', $httpTest['name'], $httpTest['httptestid'], $host['host']));
     }
     return array('httptestids' => $httpTestIds);
 }
Example #13
0
 /**
  * Delete Host
  *
  * @param string|array 	$hostIds
  * @param bool			$nopermissions
  *
  * @return array|boolean
  */
 public function delete($hostIds, $nopermissions = false)
 {
     $hostIds = zbx_toArray($hostIds);
     // deprecated input support
     if ($hostIds && is_array($hostIds[0])) {
         $this->deprecated('Passing objects is deprecated, use an array of IDs instead.');
         foreach ($hostIds as $host) {
             if (!check_db_fields(array('hostid' => null), $host)) {
                 self::exception(ZBX_API_ERROR_PARAMETERS, _('No host ID given.'));
             }
         }
         $hostIds = zbx_objectValues($hostIds, 'hostid');
     }
     $this->validateDelete($hostIds, $nopermissions);
     // delete the discovery rules first
     $delRules = API::DiscoveryRule()->get(array('hostids' => $hostIds, 'nopermissions' => true, 'preservekeys' => true));
     if ($delRules) {
         API::DiscoveryRule()->delete(array_keys($delRules), true);
     }
     // delete the items
     $delItems = API::Item()->get(array('templateids' => $hostIds, 'output' => array('itemid'), 'nopermissions' => true, 'preservekeys' => true));
     if ($delItems) {
         API::Item()->delete(array_keys($delItems), true);
     }
     // delete web tests
     $delHttptests = array();
     $dbHttptests = get_httptests_by_hostid($hostIds);
     while ($dbHttptest = DBfetch($dbHttptests)) {
         $delHttptests[$dbHttptest['httptestid']] = $dbHttptest['httptestid'];
     }
     if (!empty($delHttptests)) {
         API::HttpTest()->delete($delHttptests, true);
     }
     // delete screen items
     DB::delete('screens_items', array('resourceid' => $hostIds, 'resourcetype' => SCREEN_RESOURCE_HOST_TRIGGERS));
     // delete host from maps
     if (!empty($hostIds)) {
         DB::delete('sysmaps_elements', array('elementtype' => SYSMAP_ELEMENT_TYPE_HOST, 'elementid' => $hostIds));
     }
     // disable actions
     // actions from conditions
     $actionids = array();
     $sql = 'SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_HOST . ' AND ' . dbConditionString('value', $hostIds);
     $dbActions = DBselect($sql);
     while ($dbAction = DBfetch($dbActions)) {
         $actionids[$dbAction['actionid']] = $dbAction['actionid'];
     }
     // actions from operations
     $sql = 'SELECT DISTINCT o.actionid' . ' FROM operations o, opcommand_hst oh' . ' WHERE o.operationid=oh.operationid' . ' AND ' . dbConditionInt('oh.hostid', $hostIds);
     $dbActions = DBselect($sql);
     while ($dbAction = DBfetch($dbActions)) {
         $actionids[$dbAction['actionid']] = $dbAction['actionid'];
     }
     if (!empty($actionids)) {
         $update = array();
         $update[] = array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionids));
         DB::update('actions', $update);
     }
     // delete action conditions
     DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_HOST, 'value' => $hostIds));
     // delete action operation commands
     $operationids = array();
     $sql = 'SELECT DISTINCT oh.operationid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('oh.hostid', $hostIds);
     $dbOperations = DBselect($sql);
     while ($dbOperation = DBfetch($dbOperations)) {
         $operationids[$dbOperation['operationid']] = $dbOperation['operationid'];
     }
     DB::delete('opcommand_hst', array('hostid' => $hostIds));
     // delete empty operations
     $delOperationids = array();
     $sql = 'SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS(SELECT oh.opcommand_hstid FROM opcommand_hst oh WHERE oh.operationid=o.operationid)';
     $dbOperations = DBselect($sql);
     while ($dbOperation = DBfetch($dbOperations)) {
         $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid'];
     }
     DB::delete('operations', array('operationid' => $delOperationids));
     $hosts = API::Host()->get(array('output' => array('hostid', 'name'), 'hostids' => $hostIds, 'nopermissions' => true));
     // delete host inventory
     DB::delete('host_inventory', array('hostid' => $hostIds));
     // delete host applications
     DB::delete('applications', array('hostid' => $hostIds));
     // delete host
     DB::delete('hosts', array('hostid' => $hostIds));
     // TODO: remove info from API
     foreach ($hosts as $host) {
         info(_s('Deleted: Host "%1$s".', $host['name']));
         add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['name'], 'hosts', NULL, NULL);
     }
     // remove Monitoring > Latest data toggle profile values related to given hosts
     CProfile::delete('web.latest.toggle_other', $hostIds);
     return array('hostids' => $hostIds);
 }
 /**
  * Delete IconMap.
  * @param array $iconmapids
  * @return array
  */
 public function delete($iconmapids)
 {
     $iconmapids = zbx_toArray($iconmapids);
     if (empty($iconmapids)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
     }
     if (!$this->isWritable($iconmapids)) {
         self::exception(ZBX_API_ERROR_PERMISSIONS, _('No permissions to referred object or it does not exist!'));
     }
     $sql = 'SELECT m.name as mapname, im.name as iconmapname' . ' FROM sysmaps m, icon_map im' . ' WHERE m.iconmapid=im.iconmapid' . ' AND ' . dbConditionInt('m.iconmapid', $iconmapids);
     if ($names = DBfetch(DBselect($sql))) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _s('Icon map "%1$s" cannot be deleted. Used in map "%2$s".', $names['iconmapname'], $names['mapname']));
     }
     DB::delete('icon_map', array('iconmapid' => $iconmapids));
     return array('iconmapids' => $iconmapids);
 }
 /**
  * Delete Host
  *
  * @param array $hosts
  * @param array $hosts[0, ...]['hostid'] Host ID to delete
  *
  * @return array|boolean
  */
 public function delete($hosts)
 {
     if (empty($hosts)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
     }
     $hosts = zbx_toArray($hosts);
     $hostids = zbx_objectValues($hosts, 'hostid');
     $this->checkInput($hosts, __FUNCTION__);
     // delete the discovery rules first
     $delRules = API::DiscoveryRule()->get(array('hostids' => $hostids, 'nopermissions' => true, 'preservekeys' => true));
     if ($delRules) {
         API::DiscoveryRule()->delete(array_keys($delRules), true);
     }
     // delete the items
     $delItems = API::Item()->get(array('templateids' => $hostids, 'output' => API_OUTPUT_SHORTEN, 'nopermissions' => true, 'preservekeys' => true));
     if ($delItems) {
         API::Item()->delete(array_keys($delItems), true);
     }
     // delete web tests
     $delHttptests = array();
     $dbHttptests = get_httptests_by_hostid($hostids);
     while ($dbHttptest = DBfetch($dbHttptests)) {
         $delHttptests[$dbHttptest['httptestid']] = $dbHttptest['httptestid'];
     }
     if (!empty($delHttptests)) {
         API::WebCheck()->delete($delHttptests);
     }
     // delete screen items
     DB::delete('screens_items', array('resourceid' => $hostids, 'resourcetype' => SCREEN_RESOURCE_HOST_TRIGGERS));
     // delete host from maps
     if (!empty($hostids)) {
         DB::delete('sysmaps_elements', array('elementtype' => SYSMAP_ELEMENT_TYPE_HOST, 'elementid' => $hostids));
     }
     // disable actions
     // actions from conditions
     $actionids = array();
     $sql = 'SELECT DISTINCT actionid' . ' FROM conditions' . ' WHERE conditiontype=' . CONDITION_TYPE_HOST . ' AND ' . dbConditionString('value', $hostids);
     $dbActions = DBselect($sql);
     while ($dbAction = DBfetch($dbActions)) {
         $actionids[$dbAction['actionid']] = $dbAction['actionid'];
     }
     // actions from operations
     $sql = 'SELECT DISTINCT o.actionid' . ' FROM operations o, opcommand_hst oh' . ' WHERE o.operationid=oh.operationid' . ' AND ' . dbConditionInt('oh.hostid', $hostids);
     $dbActions = DBselect($sql);
     while ($dbAction = DBfetch($dbActions)) {
         $actionids[$dbAction['actionid']] = $dbAction['actionid'];
     }
     if (!empty($actionids)) {
         $update = array();
         $update[] = array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionids));
         DB::update('actions', $update);
     }
     // delete action conditions
     DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_HOST, 'value' => $hostids));
     // delete action operation commands
     $operationids = array();
     $sql = 'SELECT DISTINCT oh.operationid' . ' FROM opcommand_hst oh' . ' WHERE ' . dbConditionInt('oh.hostid', $hostids);
     $dbOperations = DBselect($sql);
     while ($dbOperation = DBfetch($dbOperations)) {
         $operationids[$dbOperation['operationid']] = $dbOperation['operationid'];
     }
     DB::delete('opcommand_hst', array('hostid' => $hostids));
     // delete empty operations
     $delOperationids = array();
     $sql = 'SELECT DISTINCT o.operationid' . ' FROM operations o' . ' WHERE ' . dbConditionInt('o.operationid', $operationids) . ' AND NOT EXISTS(SELECT oh.opcommand_hstid FROM opcommand_hst oh WHERE oh.operationid=o.operationid)';
     $dbOperations = DBselect($sql);
     while ($dbOperation = DBfetch($dbOperations)) {
         $delOperationids[$dbOperation['operationid']] = $dbOperation['operationid'];
     }
     DB::delete('operations', array('operationid' => $delOperationids));
     $hosts = API::Host()->get(array('output' => array('hostid', 'name'), 'hostids' => $hostids, 'nopermissions' => true));
     // delete host inventory
     DB::delete('host_inventory', array('hostid' => $hostids));
     // delete host applications
     DB::delete('applications', array('hostid' => $hostids));
     // delete host
     DB::delete('hosts', array('hostid' => $hostids));
     // TODO: remove info from API
     foreach ($hosts as $host) {
         info(_s('Deleted: Host "%1$s".', $host['name']));
         add_audit_ext(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_HOST, $host['hostid'], $host['name'], 'hosts', NULL, NULL);
     }
     return array('hostids' => $hostids);
 }
Example #16
0
 /**
  * Update host macros
  *
  * @param array $hostMacros an array of host macros
  *
  * @return boolean
  */
 public function update($hostMacros)
 {
     $hostMacros = zbx_toArray($hostMacros);
     $this->validateUpdate($hostMacros);
     $data = array();
     foreach ($hostMacros as $macro) {
         $hostMacroId = $macro['hostmacroid'];
         unset($macro['hostmacroid']);
         $data[] = array('values' => $macro, 'where' => array('hostmacroid' => $hostMacroId));
     }
     DB::update('hostmacro', $data);
     return array('hostmacroids' => zbx_objectValues($hostMacros, 'hostmacroid'));
 }
Example #17
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 #18
0
 /**
  * Synchronizes the templated trigger dependencies on the given hosts inherited from the given
  * templates.
  * Update dependencies, do it after all triggers that can be dependent were created/updated on
  * all child hosts/templates. Starting from highest level template triggers select triggers from
  * one level lower, then for each lower trigger look if it's parent has dependencies, if so
  * find this dependency trigger child on dependent trigger host and add new dependency.
  *
  * @param array $data
  *
  * @return void
  */
 public function syncTemplateDependencies(array $data)
 {
     $templateIds = zbx_toArray($data['templateids']);
     $hostIds = zbx_toArray($data['hostids']);
     $parentTriggers = $this->get(['output' => ['triggerid'], 'hostids' => $templateIds, 'preservekeys' => true, 'selectDependencies' => ['triggerid']]);
     if ($parentTriggers) {
         $childTriggers = $this->get(['output' => ['triggerid', 'templateid'], 'hostids' => $hostIds ? $hostIds : null, 'filter' => ['templateid' => array_keys($parentTriggers)], 'nopermissions' => true, 'preservekeys' => true, 'selectHosts' => ['hostid']]);
         if ($childTriggers) {
             $newDependencies = [];
             foreach ($childTriggers as $childTrigger) {
                 $parentDependencies = $parentTriggers[$childTrigger['templateid']]['dependencies'];
                 if ($parentDependencies) {
                     $dependencies = [];
                     foreach ($parentDependencies as $depTrigger) {
                         $dependencies[] = $depTrigger['triggerid'];
                     }
                     $host = reset($childTrigger['hosts']);
                     $dependencies = replace_template_dependencies($dependencies, $host['hostid']);
                     foreach ($dependencies as $depTriggerId) {
                         $newDependencies[] = ['triggerid' => $childTrigger['triggerid'], 'dependsOnTriggerid' => $depTriggerId];
                     }
                 }
             }
             $this->deleteDependencies($childTriggers);
             if ($newDependencies) {
                 $this->addDependencies($newDependencies);
             }
         }
     }
 }
Example #19
0
 /**
  * Update web scenario.
  *
  * @param $httpTests
  *
  * @return array
  */
 public function update($httpTests)
 {
     $httpTests = zbx_toArray($httpTests);
     if (!$httpTests) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameters.'));
     }
     $this->checkObjectIds($httpTests, 'httptestid', _('No "%1$s" given for web scenario.'), _('Empty web scenario ID.'), _('Incorrect web scenario ID.'));
     $httpTests = zbx_toHash($httpTests, 'httptestid');
     $dbHttpTests = array();
     $dbCursor = DBselect('SELECT ht.httptestid,ht.hostid,ht.templateid,ht.name,' . 'ht.ssl_cert_file,ht.ssl_key_file,ht.ssl_key_password,ht.verify_peer,ht.verify_host' . ' FROM httptest ht' . ' WHERE ' . dbConditionInt('ht.httptestid', array_keys($httpTests)));
     while ($dbHttpTest = DBfetch($dbCursor)) {
         $dbHttpTests[$dbHttpTest['httptestid']] = $dbHttpTest;
     }
     $dbCursor = DBselect('SELECT hs.httpstepid,hs.httptestid,hs.name' . ' FROM httpstep hs' . ' WHERE ' . dbConditionInt('hs.httptestid', array_keys($dbHttpTests)));
     while ($dbHttpStep = DBfetch($dbCursor)) {
         $dbHttpTests[$dbHttpStep['httptestid']]['steps'][$dbHttpStep['httpstepid']] = $dbHttpStep;
     }
     $httpTests = $this->validateUpdate($httpTests, $dbHttpTests);
     Manager::HttpTest()->persist($httpTests);
     return array('httptestids' => array_keys($httpTests));
 }
Example #20
0
 /**
  * Update value maps.
  *
  * @param array		$valuemaps								An array of value maps.
  * @param string	$valuemaps[]['valuemapid']				ID of the value map.
  * @param string	$valuemaps[]['name']					Name of the value map (optional).
  * @param array		$valuemaps[]['mappings']				Value mappings for value map (optional).
  * @param string	$valuemaps[]['mappings'][]['value']		Value mapping original value (optional).
  * @param string	$valuemaps[]['mappings'][]['newvalue']	Value to which the original value is mapped to (optional).
  *
  * @return array
  */
 public function update($valuemaps)
 {
     $valuemaps = zbx_toArray($valuemaps);
     $this->validateUpdate($valuemaps);
     $upd_valuemaps = [];
     $upd_mappings = [];
     foreach ($valuemaps as $valuemap) {
         $valuemapid = $valuemap['valuemapid'];
         if (array_key_exists('mappings', $valuemap)) {
             $upd_mappings[$valuemapid] = [];
             foreach ($valuemap['mappings'] as $mapping) {
                 $upd_mappings[$valuemapid][$mapping['value']] = $mapping['newvalue'];
             }
         }
         unset($valuemap['valuemapid'], $valuemap['mappings']);
         // Skip updating value maps, if name is not given.
         if (array_key_exists('name', $valuemap)) {
             $upd_valuemaps[$valuemapid] = $valuemap;
         }
     }
     if ($upd_valuemaps) {
         $db_valuemaps = API::getApiService()->select('valuemaps', ['output' => ['valuemapid', 'name'], 'valuemapids' => array_keys($upd_valuemaps)]);
         $update = [];
         foreach ($db_valuemaps as $db_valuemap) {
             $upd_valuemap = $upd_valuemaps[$db_valuemap['valuemapid']];
             // Skip updating value maps, if name was not changed.
             if ($upd_valuemap['name'] !== $db_valuemap['name']) {
                 $update[] = ['values' => $upd_valuemap, 'where' => ['valuemapid' => $db_valuemap['valuemapid']]];
                 add_audit_ext(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_VALUE_MAP, $db_valuemap['valuemapid'], $upd_valuemap['name'], 'valuemaps', $db_valuemap, $upd_valuemap);
             }
         }
         if ($update) {
             DB::update('valuemaps', $update);
         }
     }
     if ($upd_mappings) {
         $db_mappings = API::getApiService()->select('mappings', ['output' => ['mappingid', 'valuemapid', 'value', 'newvalue'], 'filter' => ['valuemapid' => array_keys($upd_mappings)]]);
         $insert_mapings = [];
         $update_mapings = [];
         $delete_mapingids = [];
         foreach ($db_mappings as $db_mapping) {
             if (array_key_exists($db_mapping['valuemapid'], $upd_mappings)) {
                 $upd_mapping =& $upd_mappings[$db_mapping['valuemapid']];
                 if (array_key_exists($db_mapping['value'], $upd_mapping)) {
                     if ($upd_mapping[$db_mapping['value']] !== $db_mapping['newvalue']) {
                         $update_mapings[] = ['values' => ['newvalue' => $upd_mapping[$db_mapping['value']]], 'where' => ['mappingid' => $db_mapping['mappingid']]];
                     }
                     unset($upd_mapping[$db_mapping['value']]);
                 } else {
                     $delete_mapingids[] = $db_mapping['mappingid'];
                 }
                 unset($upd_mapping);
             } else {
                 $delete_mapingids[] = $db_mapping['mappingid'];
             }
         }
         foreach ($upd_mappings as $valuemapid => $upd_mapping) {
             foreach ($upd_mapping as $value => $newvalue) {
                 $insert_mapings[] = ['valuemapid' => $valuemapid, 'value' => $value, 'newvalue' => $newvalue];
             }
         }
         if ($insert_mapings) {
             DB::insertBatch('mappings', $insert_mapings);
         }
         if ($update_mapings) {
             DB::update('mappings', $update_mapings);
         }
         if ($delete_mapingids) {
             DB::delete('mappings', ['mappingid' => $delete_mapingids]);
         }
     }
     return ['valuemapids' => zbx_objectValues($valuemaps, 'valuemapid')];
 }
Example #21
0
 /**
  * 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];
 }
 protected function updateReal($items)
 {
     $items = zbx_toArray($items);
     $data = array();
     foreach ($items as $item) {
         $data[] = array('values' => $item, 'where' => array('itemid' => $item['itemid']));
     }
     $result = DB::update('items', $data);
     if (!$result) {
         self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror');
     }
     $itemids = array();
     foreach ($items as $key => $item) {
         $itemids[] = $item['itemid'];
     }
     // TODO: REMOVE info
     $itemHosts = $this->get(array('itemids' => $itemids, 'output' => array('key_', 'name'), 'selectHosts' => array('name'), 'nopermissions' => true));
     foreach ($itemHosts as $item) {
         $host = reset($item['hosts']);
         info(_s('Updated: Discovery rule "%1$s" on "%2$s".', $item['name'], $host['name']));
     }
 }
 /**
  * Delete GraphPrototype.
  *
  * @param int|string|array $graphids
  * @param bool             $nopermissions
  *
  * @return array
  */
 public function delete($graphids, $nopermissions = false)
 {
     if (empty($graphids)) {
         self::exception(ZBX_API_ERROR_PARAMETERS, _('Empty input parameter.'));
     }
     $graphids = zbx_toArray($graphids);
     $delGraphs = $this->get(array('graphids' => $graphids, 'editable' => true, 'output' => API_OUTPUT_EXTEND, 'preservekeys' => true));
     if (!$nopermissions) {
         foreach ($graphids as $graphid) {
             if (!isset($delGraphs[$graphid])) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.'));
             }
             if ($delGraphs[$graphid]['templateid'] != 0) {
                 self::exception(ZBX_API_ERROR_PERMISSIONS, _('Cannot delete templated graphs.'));
             }
         }
     }
     $parentGraphids = $graphids;
     do {
         $dbGraphs = DBselect('SELECT g.graphid FROM graphs g WHERE ' . dbConditionInt('g.templateid', $parentGraphids));
         $parentGraphids = array();
         while ($dbGraph = DBfetch($dbGraphs)) {
             $parentGraphids[] = $dbGraph['graphid'];
             $graphids[] = $dbGraph['graphid'];
         }
     } while (!empty($parentGraphids));
     $graphids = array_unique($graphids);
     $createdGraphs = array();
     $dbGraphs = DBselect('SELECT gd.graphid FROM graph_discovery gd WHERE ' . dbConditionInt('gd.parent_graphid', $graphids));
     while ($graph = DBfetch($dbGraphs)) {
         $createdGraphs[$graph['graphid']] = $graph['graphid'];
     }
     if (!empty($createdGraphs)) {
         $result = API::Graph()->delete($createdGraphs, true);
         if (!$result) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot delete graphs created by low level discovery.'));
         }
     }
     DB::delete('graphs', array('graphid' => $graphids));
     foreach ($delGraphs as $graph) {
         info(_s('Graph prototype "%s" deleted.', $graph['name']));
     }
     return array('graphids' => $graphids);
 }
Example #24
0
                 if (is_array($newCondition['value'])) {
                     foreach ($newCondition['value'] as $key => $newValue) {
                         if ($condition['value'] == $newValue) {
                             unset($newCondition['value'][$key]);
                         }
                     }
                 } else {
                     if ($newCondition['value'] == $condition['value']) {
                         $newCondition['value'] = null;
                     }
                 }
             }
         }
         $validateConditions = $conditions;
         if (isset($newCondition['value'])) {
             $newConditionValues = zbx_toArray($newCondition['value']);
             foreach ($newConditionValues as $newValue) {
                 $condition = $newCondition;
                 $condition['value'] = $newValue;
                 $validateConditions[] = $condition;
             }
         }
         if ($validateConditions) {
             CAction::validateConditions($validateConditions);
         }
         $_REQUEST['conditions'] = $validateConditions;
     }
 } catch (APIException $e) {
     show_error_message(_('Cannot add action condition'));
     error($e->getMessage());
 }
 /**
  * Delete drules
  *
  * @param array $druleids
  * @return boolean
  */
 public function delete(array $druleids)
 {
     $druleids = zbx_toArray($druleids);
     if (self::$userData['type'] >= USER_TYPE_ZABBIX_ADMIN) {
         if (!count(get_accessible_nodes_by_user(self::$userData, PERM_READ_WRITE, PERM_RES_IDS_ARRAY))) {
             self::exception(ZBX_API_ERROR_PARAMETERS, _('No permissions to referred object or it does not exist!'));
         }
     }
     $actionids = array();
     $sql = 'SELECT DISTINCT actionid ' . ' FROM conditions ' . ' WHERE conditiontype=' . CONDITION_TYPE_DRULE . ' AND ' . dbConditionString('value', $druleids);
     $dbActions = DBselect($sql);
     while ($dbAction = DBfetch($dbActions)) {
         $actionids[] = $dbAction['actionid'];
     }
     if (!empty($actionids)) {
         DB::update('actions', array('values' => array('status' => ACTION_STATUS_DISABLED), 'where' => array('actionid' => $actionids)));
         DB::delete('conditions', array('conditiontype' => CONDITION_TYPE_DRULE, 'value' => $druleids));
     }
     DB::delete('drules', array('druleid' => $druleids));
     return array('druleids' => $druleids);
 }
Example #26
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;
 }
 public function syncTemplates($data)
 {
     $data['templateids'] = zbx_toArray($data['templateids']);
     $data['hostids'] = zbx_toArray($data['hostids']);
     $selectFields = array();
     foreach ($this->fieldRules as $key => $rules) {
         if (!isset($rules['system']) && !isset($rules['host'])) {
             $selectFields[] = $key;
         }
     }
     $items = $this->get(array('hostids' => $data['templateids'], 'preservekeys' => true, 'selectApplications' => array('applicationid'), 'output' => $selectFields));
     foreach ($items as $inum => $item) {
         $items[$inum]['applications'] = zbx_objectValues($item['applications'], 'applicationid');
     }
     $this->inherit($items, $data['hostids']);
     return true;
 }
Example #28
0
 /**
  * Delete maintenances by maintenanceids.
  *
  * @param array $maintenanceids
  *
  * @return array
  */
 public function delete(array $maintenanceids)
 {
     $maintenanceids = zbx_toArray($maintenanceids);
     if (self::$userData['type'] == USER_TYPE_ZABBIX_USER) {
         self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.'));
     }
     $options = array('maintenanceids' => $maintenanceids, 'editable' => true, 'output' => array('maintenanceid'), 'preservekeys' => true);
     $maintenances = $this->get($options);
     foreach ($maintenanceids as $maintenanceid) {
         if (!isset($maintenances[$maintenanceid])) {
             self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.'));
         }
     }
     $timeperiodids = array();
     $dbTimeperiods = DBselect('SELECT DISTINCT tp.timeperiodid' . ' FROM timeperiods tp,maintenances_windows mw' . ' WHERE ' . dbConditionInt('mw.maintenanceid', $maintenanceids) . ' AND tp.timeperiodid=mw.timeperiodid');
     while ($timeperiod = DBfetch($dbTimeperiods)) {
         $timeperiodids[] = $timeperiod['timeperiodid'];
     }
     $midCond = array('maintenanceid' => $maintenanceids);
     // remove maintenanceid from hosts table
     $options = array('real_hosts' => true, 'output' => array('hostid'), 'filter' => array('maintenanceid' => $maintenanceids));
     $hosts = API::Host()->get($options);
     if (!empty($hosts)) {
         DB::update('hosts', array('values' => array('maintenanceid' => 0), 'where' => array('hostid' => zbx_objectValues($hosts, 'hostid'))));
     }
     DB::delete('timeperiods', array('timeperiodid' => $timeperiodids));
     DB::delete('maintenances_windows', $midCond);
     DB::delete('maintenances_hosts', $midCond);
     DB::delete('maintenances_groups', $midCond);
     DB::delete('maintenances', $midCond);
     return array('maintenanceids' => $maintenanceids);
 }
Example #29
0
 /**
  * Update map.
  *
  * @param array  $maps						multidimensional array with Hosts data
  * @param string $maps['sysmapid']
  * @param string $maps['name']
  * @param array  $maps['width']
  * @param int    $maps['height']
  * @param string $maps['backgroundid']
  * @param array  $maps['label_type']
  * @param int    $maps['label_location']
  * @param int    $maps['grid_size']			size of one grid cell. 100 refers to 100x100 and so on.
  * @param int    $maps['grid_show']			does grid need to be shown. Constants: SYSMAP_GRID_SHOW_ON / SYSMAP_GRID_SHOW_OFF
  * @param int    $maps['grid_align']		do elements need to be aligned to the grid. Constants: SYSMAP_GRID_ALIGN_ON / SYSMAP_GRID_ALIGN_OFF
  *
  * @return array
  */
 public function update(array $maps)
 {
     $maps = zbx_toArray($maps);
     $sysmapIds = zbx_objectValues($maps, 'sysmapid');
     $dbMaps = $this->checkInput($maps, __FUNCTION__);
     $updateMaps = array();
     $urlIdsToDelete = $urlsToUpdate = $urlsToAdd = array();
     $selementsToDelete = $selementsToUpdate = $selementsToAdd = array();
     $linksToDelete = $linksToUpdate = $linksToAdd = array();
     foreach ($maps as $map) {
         $updateMaps[] = array('values' => $map, 'where' => array('sysmapid' => $map['sysmapid']));
         $dbMap = $dbMaps[$map['sysmapid']];
         // urls
         if (isset($map['urls'])) {
             $urlDiff = zbx_array_diff($map['urls'], $dbMap['urls'], 'name');
             foreach ($urlDiff['both'] as $updateUrl) {
                 $urlsToUpdate[] = array('values' => $updateUrl, 'where' => array('name' => $updateUrl['name'], 'sysmapid' => $map['sysmapid']));
             }
             foreach ($urlDiff['first'] as $newUrl) {
                 $newUrl['sysmapid'] = $map['sysmapid'];
                 $urlsToAdd[] = $newUrl;
             }
             $urlIdsToDelete = array_merge($urlIdsToDelete, zbx_objectValues($urlDiff['second'], 'sysmapurlid'));
         }
         // elements
         if (isset($map['selements'])) {
             $selementDiff = zbx_array_diff($map['selements'], $dbMap['selements'], 'selementid');
             // we need sysmapid for add operations
             foreach ($selementDiff['first'] as $newSelement) {
                 $newSelement['sysmapid'] = $map['sysmapid'];
                 $selementsToAdd[] = $newSelement;
             }
             $selementsToUpdate = array_merge($selementsToUpdate, $selementDiff['both']);
             $selementsToDelete = array_merge($selementsToDelete, $selementDiff['second']);
         }
         // links
         if (isset($map['links'])) {
             $linkDiff = zbx_array_diff($map['links'], $dbMap['links'], 'linkid');
             // we need sysmapId for add operations
             foreach ($linkDiff['first'] as $newLink) {
                 $newLink['sysmapid'] = $map['sysmapid'];
                 $linksToAdd[] = $newLink;
             }
             $linksToUpdate = array_merge($linksToUpdate, $linkDiff['both']);
             $linksToDelete = array_merge($linksToDelete, $linkDiff['second']);
         }
     }
     DB::update('sysmaps', $updateMaps);
     // urls
     DB::insert('sysmap_url', $urlsToAdd);
     DB::update('sysmap_url', $urlsToUpdate);
     if ($urlIdsToDelete) {
         DB::delete('sysmap_url', array('sysmapurlid' => $urlIdsToDelete));
     }
     // selements
     $newSelementIds = array('selementids' => array());
     if ($selementsToAdd) {
         $newSelementIds = $this->createSelements($selementsToAdd);
     }
     if ($selementsToUpdate) {
         $this->updateSelements($selementsToUpdate);
     }
     if ($selementsToDelete) {
         $this->deleteSelements($selementsToDelete);
     }
     // links
     if ($linksToAdd || $linksToUpdate) {
         $selementsNames = array();
         foreach ($newSelementIds['selementids'] as $key => $selementId) {
             $selementsNames[$selementsToAdd[$key]['selementid']] = $selementId;
         }
         foreach ($selementsToUpdate as $selement) {
             $selementsNames[$selement['selementid']] = $selement['selementid'];
         }
         foreach ($linksToAdd as $key => $link) {
             if (isset($selementsNames[$link['selementid1']])) {
                 $linksToAdd[$key]['selementid1'] = $selementsNames[$link['selementid1']];
             }
             if (isset($selementsNames[$link['selementid2']])) {
                 $linksToAdd[$key]['selementid2'] = $selementsNames[$link['selementid2']];
             }
         }
         foreach ($linksToUpdate as $key => $link) {
             if (isset($selementsNames[$link['selementid1']])) {
                 $linksToUpdate[$key]['selementid1'] = $selementsNames[$link['selementid1']];
             }
             if (isset($selementsNames[$link['selementid2']])) {
                 $linksToUpdate[$key]['selementid2'] = $selementsNames[$link['selementid2']];
             }
         }
         unset($selementsNames);
     }
     $newLinkIds = $updateLinkIds = array('linkids' => array());
     if ($linksToAdd) {
         $newLinkIds = $this->createLinks($linksToAdd);
     }
     if ($linksToUpdate) {
         $updateLinkIds = $this->updateLinks($linksToUpdate);
     }
     if ($linksToDelete) {
         $this->deleteLinks($linksToDelete);
     }
     // link triggers
     $linkTriggersToDelete = $linkTriggersToUpdate = $linkTriggersToAdd = array();
     foreach ($newLinkIds['linkids'] as $key => $linkId) {
         if (!isset($linksToAdd[$key]['linktriggers'])) {
             continue;
         }
         foreach ($linksToAdd[$key]['linktriggers'] as $linkTrigger) {
             $linkTrigger['linkid'] = $linkId;
             $linkTriggersToAdd[] = $linkTrigger;
         }
     }
     $dbLinks = array();
     $linkTriggerResource = DBselect('SELECT slt.* FROM sysmaps_link_triggers slt WHERE ' . dbConditionInt('slt.linkid', $updateLinkIds['linkids']));
     while ($dbLinkTrigger = DBfetch($linkTriggerResource)) {
         zbx_subarray_push($dbLinks, $dbLinkTrigger['linkid'], $dbLinkTrigger);
     }
     foreach ($updateLinkIds['linkids'] as $key => $linkId) {
         if (!isset($linksToUpdate[$key]['linktriggers'])) {
             continue;
         }
         $dbLinkTriggers = isset($dbLinks[$linkId]) ? $dbLinks[$linkId] : array();
         $dbLinkTriggersDiff = zbx_array_diff($linksToUpdate[$key]['linktriggers'], $dbLinkTriggers, 'linktriggerid');
         foreach ($dbLinkTriggersDiff['first'] as $newLinkTrigger) {
             $newLinkTrigger['linkid'] = $linkId;
             $linkTriggersToAdd[] = $newLinkTrigger;
         }
         $linkTriggersToUpdate = array_merge($linkTriggersToUpdate, $dbLinkTriggersDiff['both']);
         $linkTriggersToDelete = array_merge($linkTriggersToDelete, $dbLinkTriggersDiff['second']);
     }
     if ($linkTriggersToDelete) {
         $this->deleteLinkTriggers($linkTriggersToDelete);
     }
     if ($linkTriggersToAdd) {
         $this->createLinkTriggers($linkTriggersToAdd);
     }
     if ($linkTriggersToUpdate) {
         $this->updateLinkTriggers($linkTriggersToUpdate);
     }
     return array('sysmapids' => $sysmapIds);
 }
Example #30
0
function error($msgs)
{
    global $ZBX_MESSAGES;
    if (is_null($ZBX_MESSAGES)) {
        $ZBX_MESSAGES = array();
    }
    $msgs = zbx_toArray($msgs);
    foreach ($msgs as $msg) {
        if (isset(CWebUser::$data['debug_mode']) && !is_object($msg) && !CWebUser::$data['debug_mode']) {
            $msg = preg_replace('/^\\[.+?::.+?\\]/', '', $msg);
        }
        array_push($ZBX_MESSAGES, array('type' => 'error', 'message' => $msg));
    }
}