function update_node_profile($nodeids) { DBstart(); DBexecute('DELETE FROM profiles WHERE userid=' . CWebUser::$data['userid'] . ' AND idx=' . zbx_dbstr('web.nodes.selected')); foreach ($nodeids as $nodeid) { DBexecute('INSERT INTO profiles (profileid,userid,idx,value_id,type)' . ' VALUES (' . get_dbid('profiles', 'profileid') . ',' . CWebUser::$data['userid'] . ',' . zbx_dbstr('web.nodes.selected') . ',' . $nodeid . ',4)'); } DBend(); }
function add_script($name, $command, $usrgrpid, $groupid, $access) { $scriptid = get_dbid('scripts', 'scriptid'); $sql = 'INSERT INTO scripts (scriptid,name,command,usrgrpid,groupid,host_access) ' . " VALUES ({$scriptid}," . zbx_dbstr($name) . ',' . zbx_dbstr($command) . ",{$usrgrpid},{$groupid},{$access})"; $result = DBexecute($sql); if ($result) { $result = $scriptid; } return $result; }
function add_expression($regexpid, $expression = array()) { $db_fields = array('expression' => null, 'expression_type' => null, 'case_sensitive' => 0, 'exp_delimiter' => ','); if (!check_db_fields($db_fields, $expression)) { error(S_INCORRECT_ARGUMENTS_PASSED_TO_FUNCTION . ' [add_expression]'); return false; } $expressionid = get_dbid('expressions', 'expressionid'); $result = DBexecute('INSERT INTO expressions (expressionid,regexpid,expression,expression_type,case_sensitive,exp_delimiter) ' . ' VALUES (' . $expressionid . ',' . $regexpid . ',' . zbx_dbstr($expression['expression']) . ',' . $expression['expression_type'] . ',' . $expression['case_sensitive'] . ',' . zbx_dbstr($expression['exp_delimiter']) . ')'); return $result ? $expressionid : false; }
function add_expression($regexpid, $expression = array()) { $db_fields = array('expression' => null, 'expression_type' => null, 'case_sensitive' => 0, 'exp_delimiter' => ','); if (!check_db_fields($db_fields, $expression)) { error('Incorrect arguments pasted to function [add_expression]'); return false; } $expressionid = get_dbid('expressions', 'expressionid'); $result = DBexecute('INSERT INTO expressions (expressionid,regexpid,expression,expression_type,case_sensitive,exp_delimiter) ' . ' VALUES (' . $expressionid . ',' . $regexpid . ',' . zbx_dbstr($expression['expression']) . ',' . $expression['expression_type'] . ',' . $expression['case_sensitive'] . ',' . zbx_dbstr($expression['exp_delimiter']) . ')'); return $result ? $expressionid : false; }
function add_user_to_group($userid, $usrgrpid) { $result = false; if (granted2move_user($userid, $usrgrpid)) { DBexecute('DELETE FROM users_groups WHERE userid=' . zbx_dbstr($userid) . ' AND usrgrpid=' . zbx_dbstr($usrgrpid)); $users_groups_id = get_dbid('users_groups', 'id'); $result = DBexecute('INSERT INTO users_groups (id,usrgrpid,userid) VALUES (' . $users_groups_id . ',' . zbx_dbstr($usrgrpid) . ',' . zbx_dbstr($userid) . ')'); } else { error(_('User cannot change status of himself.')); } return $result; }
function add_image($name, $imagetype, $file) { if (!is_null($file)) { if ($file["error"] != 0 || $file["size"] == 0) { error("Incorrect Image"); } else { if ($file["size"] < 1024 * 1024) { global $DB; $imageid = get_dbid("images", "imageid"); $image = fread(fopen($file["tmp_name"], "r"), filesize($file["tmp_name"])); if ($DB['TYPE'] == "ORACLE") { DBstart(); $lobimage = OCINewDescriptor($DB['DB'], OCI_D_LOB); $stid = OCIParse($DB['DB'], "insert into images (imageid,name,imagetype,image)" . " values ({$imageid}," . zbx_dbstr($name) . "," . $imagetype . ",EMPTY_BLOB())" . " return image into :image"); if (!$stid) { $e = ocierror($stid); error("Parse SQL error [" . $e["message"] . "] in [" . $e["sqltext"] . "]"); return false; } OCIBindByName($stid, ':image', $lobimage, -1, OCI_B_BLOB); if (!OCIExecute($stid, OCI_DEFAULT)) { $e = ocierror($stid); error("Execute SQL error [" . $e["message"] . "] in [" . $e["sqltext"] . "]"); return false; } $result = DBend($lobimage->save($image)); if (!$result) { error("Couldn't save image!\n"); return false; } $lobimage->free(); OCIFreeStatement($stid); return $stid; } else { if ($DB['TYPE'] == "POSTGRESQL") { $image = pg_escape_bytea($image); } else { if ($DB['TYPE'] == "SQLITE3") { $image = bin2hex($image); } } } return DBexecute("insert into images (imageid,name,imagetype,image)" . " values ({$imageid}," . zbx_dbstr($name) . "," . $imagetype . "," . zbx_dbstr($image) . ")"); } else { error("Image size must be less than 1Mb"); } } } else { error("Select image to download"); } return false; }
function add_acknowledge_coment($eventid, $userid, $message) { $result = set_event_acnowledged($eventid); if (!$result) { return $result; } $acknowledgeid = get_dbid("acknowledges", "acknowledgeid"); $result = DBexecute("insert into acknowledges (acknowledgeid,userid,eventid,clock,message)" . " values ({$acknowledgeid},{$userid},{$eventid}," . time() . "," . zbx_dbstr($message) . ")"); if (!$result) { return $result; } return $acknowledgeid; }
function update_node_profile($nodeids) { global $USER_DETAILS; DBstart(); $sql = 'DELETE FROM profiles WHERE userid=' . $USER_DETAILS['userid'] . ' AND idx=' . zbx_dbstr('web.nodes.selected'); DBexecute($sql); foreach ($nodeids as $nodeid) { $profileid = get_dbid('profiles', 'profileid'); $sql = 'INSERT INTO profiles (profileid, userid, idx, value_id, type)' . ' VALUES (' . $profileid . ',' . $USER_DETAILS['userid'] . ', ' . zbx_dbstr('web.nodes.selected') . ',' . $nodeid . ', 4)'; DBexecute($sql); } DBend(); }
/** * Adds favorite value to DB. * * @param string $idx identifier of favorite value group * @param int $favid value id * @param string $favobj source object * * @return bool did SQL INSERT succeeded */ public static function add($idx, $favid, $favobj = null) { if (self::exists($idx, $favid, $favobj)) { return true; } // add to cache only if cache is created if (isset(self::$cache[$idx])) { self::$cache[$idx][] = array('value' => $favid, 'source' => $favobj); } $values = array('profileid' => get_dbid('profiles', 'profileid'), 'userid' => CWebUser::$data['userid'], 'idx' => zbx_dbstr($idx), 'value_id' => zbx_dbstr($favid), 'type' => PROFILE_TYPE_ID); if (!is_null($favobj)) { $values['source'] = zbx_dbstr($favobj); } return DBexecute('INSERT INTO profiles (' . implode(', ', array_keys($values)) . ')' . ' VALUES (' . implode(', ', $values) . ')'); }
function add_valuemap($name, $mappings) { if (!is_array($mappings)) { return FALSE; } $valuemapid = get_dbid("valuemaps", "valuemapid"); $result = DBexecute("insert into valuemaps (valuemapid,name) values ({$valuemapid}," . zbx_dbstr($name) . ")"); if (!$result) { return $result; } $result = add_mapping_to_valuemap($valuemapid, $mappings); if (!$result) { delete_valuemap($valuemapid); } else { $result = $valuemapid; } return $result; }
function add_service_alarm($serviceid, $status, $clock) { if (latest_service_alarm($serviceid, $status)) { return true; } $result = DBexecute('INSERT INTO service_alarms (servicealarmid,serviceid,clock,value) VALUES (' . get_dbid('service_alarms', 'servicealarmid') . ',' . $serviceid . ',' . $clock . ',' . $status . ')'); return $result; }
function update_slideshow($slideshowid, $name, $delay, $slides) { // validate slides if (empty($slides)) { error(_('Slide show must contain slides.')); return false; } // validate screens $screenids = zbx_objectValues($slides, 'screenid'); $screens = API::Screen()->get(array('screenids' => $screenids, 'output' => array('screenid'))); $screens = ZBX_toHash($screens, 'screenid'); foreach ($screenids as $screenid) { if (!isset($screens[$screenid])) { error(_('Incorrect screen provided for slide show.')); return false; } } // validate slide name $db_slideshow = DBfetch(DBselect('SELECT s.slideshowid' . ' FROM slideshows s' . ' WHERE s.name=' . zbx_dbstr($name) . ' AND s.slideshowid<>' . zbx_dbstr($slideshowid) . ' ' . andDbNode('s.slideshowid'))); if (!empty($db_slideshow)) { error(_s('Slide show "%s" already exists.', $name)); return false; } $db_slideshow = DBfetchArray(DBselect('SELECT * FROM slideshows WHERE slideshowid=' . zbx_dbstr($slideshowid))); $db_slideshow = $db_slideshow[0]; $changed = false; $slideshow = array('name' => $name, 'delay' => $delay); foreach ($slideshow as $key => $val) { if ($db_slideshow[$key] != $val) { $changed = true; break; } } if ($changed) { if (!($result = DBexecute('UPDATE slideshows SET name=' . zbx_dbstr($name) . ',delay=' . zbx_dbstr($delay) . ' WHERE slideshowid=' . zbx_dbstr($slideshowid)))) { return false; } } // get slides $db_slides = DBfetchArrayAssoc(DBselect('SELECT s.* FROM slides s WHERE s.slideshowid=' . zbx_dbstr($slideshowid)), 'slideid'); $slidesToDel = zbx_objectValues($db_slides, 'slideid'); $slidesToDel = zbx_toHash($slidesToDel); $step = 0; foreach ($slides as $slide) { $slide['delay'] = $slide['delay'] ? $slide['delay'] : 0; if (isset($db_slides[$slide['slideid']])) { // update slide if ($db_slides[$slide['slideid']]['delay'] != $slide['delay'] || $db_slides[$slide['slideid']]['step'] != $step) { $result = DBexecute('UPDATE slides SET step=' . zbx_dbstr($step) . ', delay=' . zbx_dbstr($slide['delay']) . ' WHERE slideid=' . zbx_dbstr($slide['slideid'])); } else { $result = true; } unset($slidesToDel[$slide['slideid']]); } else { $slideid = get_dbid('slides', 'slideid'); $result = DBexecute('INSERT INTO slides (slideid,slideshowid,screenid,step,delay)' . ' VALUES (' . zbx_dbstr($slideid) . ',' . zbx_dbstr($slideshowid) . ',' . zbx_dbstr($slide['screenid']) . ',' . zbx_dbstr($step) . ',' . zbx_dbstr($slide['delay']) . ')'); } $step++; if (!$result) { return false; } } // delete unnecessary slides if (!empty($slidesToDel)) { DBexecute('DELETE FROM slides WHERE slideid IN(' . implode(',', $slidesToDel) . ')'); } return true; }
function insert_dependency($triggerid_down, $triggerid_up) { $triggerdepid = get_dbid("trigger_depends", "triggerdepid"); $result = DBexecute("insert into trigger_depends (triggerdepid,triggerid_down,triggerid_up)" . " values ({$triggerdepid},{$triggerid_down},{$triggerid_up})"); if (!$result) { return $result; } return DBexecute("update triggers set dep_level=dep_level+1 where triggerid={$triggerid_up}"); }
/** * Add images. * * @param array $images ['name' => string, 'image' => string, 'imagetype' => int] * * @return array */ public function create($images) { global $DB; $images = zbx_toArray($images); $this->validateCreate($images); $imageids = array(); foreach ($images as $image) { // decode BASE64 $image['image'] = base64_decode($image['image']); // validate image (size and format) $this->checkImage($image['image']); $imageid = get_dbid('images', 'imageid'); $values = array('imageid' => $imageid, 'name' => zbx_dbstr($image['name']), 'imagetype' => zbx_dbstr($image['imagetype'])); switch ($DB['TYPE']) { case ZBX_DB_ORACLE: $values['image'] = 'EMPTY_BLOB()'; $lob = oci_new_descriptor($DB['DB'], OCI_D_LOB); $sql = 'INSERT INTO images (' . implode(' ,', array_keys($values)) . ') VALUES (' . implode(',', $values) . ')' . ' returning image into :imgdata'; $stmt = oci_parse($DB['DB'], $sql); if (!$stmt) { $e = oci_error($DB['DB']); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Parse SQL error [%1$s] in [%2$s].', $e['message'], $e['sqltext'])); } oci_bind_by_name($stmt, ':imgdata', $lob, -1, OCI_B_BLOB); if (!oci_execute($stmt, OCI_DEFAULT)) { $e = oci_error($stmt); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Execute SQL error [%1$s] in [%2$s].', $e['message'], $e['sqltext'])); } if (!$lob->save($image['image'])) { $e = oci_error($stmt); self::exception(ZBX_API_ERROR_PARAMETERS, _s('Image load error [%1$s] in [%2$s].', $e['message'], $e['sqltext'])); } $lob->free(); oci_free_statement($stmt); break; case ZBX_DB_DB2: $stmt = db2_prepare($DB['DB'], 'INSERT INTO images (' . implode(' ,', array_keys($values)) . ',image)' . ' VALUES (' . implode(',', $values) . ', ?)'); if (!$stmt) { self::exception(ZBX_API_ERROR_PARAMETERS, db2_conn_errormsg($DB['DB'])); } $variable = $image['image']; if (!db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN, DB2_BINARY)) { self::exception(ZBX_API_ERROR_PARAMETERS, db2_conn_errormsg($DB['DB'])); } if (!db2_execute($stmt)) { self::exception(ZBX_API_ERROR_PARAMETERS, db2_conn_errormsg($DB['DB'])); } break; case ZBX_DB_SQLITE3: $values['image'] = zbx_dbstr(bin2hex($image['image'])); $sql = 'INSERT INTO images (' . implode(', ', array_keys($values)) . ') VALUES (' . implode(', ', $values) . ')'; if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror'); } break; case ZBX_DB_MYSQL: $values['image'] = zbx_dbstr($image['image']); $sql = 'INSERT INTO images (' . implode(', ', array_keys($values)) . ') VALUES (' . implode(', ', $values) . ')'; if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror'); } break; case ZBX_DB_POSTGRESQL: $values['image'] = "'" . pg_escape_bytea($image['image']) . "'"; $sql = 'INSERT INTO images (' . implode(', ', array_keys($values)) . ') VALUES (' . implode(', ', $values) . ')'; if (!DBexecute($sql)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror'); } break; } $imageids[] = $imageid; } return array('imageids' => $imageids); }
function add_action($name, $eventsource, $esc_period, $def_shortdata, $def_longdata, $recovery_msg, $r_shortdata, $r_longdata, $evaltype, $status, $conditions, $operations) { if (!is_array($conditions) || count($conditions) == 0) { /* error(S_NO_CONDITIONS_DEFINED); return false; */ } else { if (!check_permission_for_action_conditions($conditions)) { return false; } foreach ($conditions as $condition) { if (!validate_condition($condition['type'], $condition['value'])) { return false; } } } if (!is_array($operations) || count($operations) == 0) { error(S_NO_OPERATIONS_DEFINED); return false; } foreach ($operations as $operation) { if (!validate_operation($operation)) { return false; } } $actionid = get_dbid('actions', 'actionid'); $result = DBexecute('INSERT INTO actions (actionid,name,eventsource,esc_period,def_shortdata,def_longdata,recovery_msg,r_shortdata,r_longdata,evaltype,status)' . ' VALUES (' . $actionid . ',' . zbx_dbstr($name) . ',' . $eventsource . ',' . $esc_period . ',' . zbx_dbstr($def_shortdata) . ',' . zbx_dbstr($def_longdata) . ',' . $recovery_msg . ',' . zbx_dbstr($r_shortdata) . ',' . zbx_dbstr($r_longdata) . ',' . $evaltype . ',' . $status . ')'); if (!$result) { return $result; } foreach ($operations as $operation) { if (!($result = add_action_operation($actionid, $operation))) { break; } } if ($result) { foreach ($conditions as $condition) { if (!($result = add_action_condition($actionid, $condition))) { break; } } } return $actionid; }
/** * Add Template * * @param array $templates multidimensional array with templates data * @param string $templates['host'] * @return boolean */ public function create($templates) { $templates = zbx_toArray($templates); $templateids = array(); // CHECK IF HOSTS HAVE AT LEAST 1 GROUP {{{ foreach ($templates as $tnum => $template) { if (empty($template['groups'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('No groups for template [ %s ]', $template['host'])); } $templates[$tnum]['groups'] = zbx_toArray($templates[$tnum]['groups']); foreach ($templates[$tnum]['groups'] as $gnum => $group) { $groupids[$group['groupid']] = $group['groupid']; } } // }}} CHECK IF HOSTS HAVE AT LEAST 1 GROUP // PERMISSIONS {{{ $options = array('groupids' => $groupids, 'editable' => 1, 'preservekeys' => 1); $updGroups = API::HostGroup()->get($options); foreach ($groupids as $gnum => $groupid) { if (!isset($updGroups[$groupid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, _('You do not have permission to perform this operation.')); } } // }}} PERMISSIONS foreach ($templates as $tnum => $template) { // If visible name is not given or empty it should be set to host name if (!isset($template['name']) || isset($template['name']) && zbx_empty(trim($template['name']))) { if (isset($template['host'])) { $template['name'] = $template['host']; } } $templateDbFields = array('host' => null); if (!check_db_fields($templateDbFields, $template)) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Field "host" is mandatory')); } if (!preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/', $template['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Incorrect characters used for Template name [ %1$s ]', $template['host'])); } if (isset($template['host'])) { if ($this->exists(array('host' => $template['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template "%s" already exists.', $template['host'])); } if (API::Host()->exists(array('host' => $template['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host "%s" already exists.', $template['host'])); } } if (isset($template['name'])) { if ($this->exists(array('name' => $template['name']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Template with the same visible name "%s" already exists.', $template['name'])); } if (API::Host()->exists(array('name' => $template['name']))) { self::exception(ZBX_API_ERROR_PARAMETERS, _s('Host with the same visible name "%s" already exists.', $template['name'])); } } $templateid = DB::insert('hosts', array(array('host' => $template['host'], 'name' => $template['name'], 'status' => HOST_STATUS_TEMPLATE))); $templateids[] = $templateid = reset($templateid); foreach ($template['groups'] as $group) { $hostgroupid = get_dbid('hosts_groups', 'hostgroupid'); $result = DBexecute('INSERT INTO hosts_groups (hostgroupid,hostid,groupid) VALUES (' . zbx_dbstr($hostgroupid) . ',' . zbx_dbstr($templateid) . ',' . zbx_dbstr($group['groupid']) . ')'); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror'); } } $template['templateid'] = $templateid; $options = array(); $options['templates'] = $template; if (isset($template['templates']) && !is_null($template['templates'])) { $options['templates_link'] = $template['templates']; } if (isset($template['macros']) && !is_null($template['macros'])) { $options['macros'] = $template['macros']; } if (isset($template['hosts']) && !is_null($template['hosts'])) { $options['hosts'] = $template['hosts']; } $result = $this->massAdd($options); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS); } } return array('templateids' => $templateids); }
function add_discovery_rule($proxy_hostid, $name, $iprange, $delay, $status, $dchecks) { if (!validate_ip_range($iprange)) { error('Incorrect IP range.'); return false; } $druleid = get_dbid('drules', 'druleid'); $result = DBexecute('insert into drules (druleid,proxy_hostid,name,iprange,delay,status) ' . ' values (' . $druleid . ',' . $proxy_hostid . ',' . zbx_dbstr($name) . ',' . zbx_dbstr($iprange) . ',' . $delay . ',' . $status . ')'); if ($result) { if (isset($dchecks)) { foreach ($dchecks as $val) { add_discovery_check($druleid, $val['type'], $val['ports'], $val['key'], $val['snmp_community'], $val['snmpv3_securityname'], $val['snmpv3_securitylevel'], $val['snmpv3_authpassphrase'], $val['snmpv3_privpassphrase']); } } $result = $druleid; } return $result; }
/** * Add alerts * * @param _array $alerts multidimensional array with alerts data * @param array $alerts[0,...]['expression'] * @param array $alerts[0,...]['description'] * @param array $alerts[0,...]['type'] OPTIONAL * @param array $alerts[0,...]['priority'] OPTIONAL * @param array $alerts[0,...]['status'] OPTIONAL * @param array $alerts[0,...]['comments'] OPTIONAL * @param array $alerts[0,...]['url'] OPTIONAL * @return boolean */ public static function create($alerts) { $alerts = zbx_toArray($alerts); $alertids = array(); $result = false; self::BeginTransaction(__METHOD__); foreach ($alerts as $anum => $alert) { $alert_db_fields = array('actionid' => null, 'eventid' => null, 'userid' => null, 'clock' => time(), 'mediatypeid' => 0, 'sendto' => null, 'subject' => '', 'message' => '', 'status' => ALERT_STATUS_NOT_SENT, 'retries' => 0, 'error' => '', 'nextcheck' => null, 'esc_step' => 0, 'alerttype' => ALERT_TYPE_MESSAGE); if (!check_db_fields($alert_db_fields, $alert)) { $result = false; break; } $alertid = get_dbid('alerts', 'alertid'); $sql = 'INSERT INTO alerts ' . '(alertid, actionid, eventid, userid, mediatypeid, clock, sendto, subject, message, status, retries, error, nextcheck, esc_step, alerttype) ' . ' VALUES (' . $alertid . ',' . $alert['actionid'] . ',' . $alert['eventid'] . ',' . $alert['userid'] . ',' . $alert['mediatypeid'] . ',' . $alert['clock'] . ',' . zbx_dbstr($alert['sendto']) . ',' . zbx_dbstr($alert['subject']) . ',' . zbx_dbstr($alert['message']) . ',' . $alert['status'] . ',' . $alert['retries'] . ',' . zbx_dbstr($alert['error']) . ',' . $alert['nextcheck'] . ',' . $alert['esc_step'] . ',' . $alert['alerttype'] . ' )'; $result = DBexecute($sql); if (!$result) { break; } $alertids[] = $alertid; } $result = self::EndTransaction($result, __METHOD__); if ($result) { return array('alertids' => $alertids); } else { self::$error[] = array('error' => ZBX_API_ERROR_INTERNAL, 'data' => 'Internal Zabbix error'); return false; } }
function addUserHistory($title, $url) { $userId = CWebUser::$data['userid']; $history5 = DBfetch(DBSelect('SELECT uh.title5,uh.url5' . ' FROM user_history uh' . ' WHERE uh.userid=' . $userId)); if ($history5) { if ($history5['title5'] === $title) { if ($history5['url5'] === $url) { return true; } else { $sql = 'UPDATE user_history SET url5=' . zbx_dbstr($url) . ' WHERE userid=' . $userId; } } else { $sql = 'UPDATE user_history' . ' SET title1=title2,' . ' url1=url2,' . ' title2=title3,' . ' url2=url3,' . ' title3=title4,' . ' url3=url4,' . ' title4=title5,' . ' url4=url5,' . ' title5=' . zbx_dbstr($title) . ',' . ' url5=' . zbx_dbstr($url) . ' WHERE userid=' . $userId; } } else { $userHistoryId = get_dbid('user_history', 'userhistoryid'); $sql = 'INSERT INTO user_history (userhistoryid, userid, title5, url5)' . ' VALUES(' . $userHistoryId . ', ' . $userId . ', ' . zbx_dbstr($title) . ', ' . zbx_dbstr($url) . ')'; } return DBexecute($sql); }
/** * Add template. * * @param array $templates * * @return array */ public function create(array $templates) { $templates = zbx_toArray($templates); $this->validateCreate($templates); $templateIds = array(); foreach ($templates as $key => $template) { $templates[$key]['groups'] = zbx_toArray($template['groups']); } foreach ($templates as $template) { // if visible name is not given or empty it should be set to host name if ((!isset($template['name']) || zbx_empty(trim($template['name']))) && isset($template['host'])) { $template['name'] = $template['host']; } $newTemplateIds = DB::insert('hosts', array(array('host' => $template['host'], 'name' => $template['name'], 'description' => isset($template['description']) ? $template['description'] : null, 'status' => HOST_STATUS_TEMPLATE))); $templateId = reset($newTemplateIds); $templateIds[] = $templateId; foreach ($template['groups'] as $group) { $hostGroupId = get_dbid('hosts_groups', 'hostgroupid'); $result = DBexecute('INSERT INTO hosts_groups (hostgroupid,hostid,groupid)' . ' VALUES (' . zbx_dbstr($hostGroupId) . ',' . zbx_dbstr($templateId) . ',' . zbx_dbstr($group['groupid']) . ')'); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot add group.')); } } $template['templateid'] = $templateId; $result = $this->massAdd(array('templates' => $template, 'templates_link' => isset($template['templates']) ? $template['templates'] : null, 'macros' => isset($template['macros']) ? $template['macros'] : null, 'hosts' => isset($template['hosts']) ? $template['hosts'] : null)); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot create template.')); } } return array('templateids' => $templateIds); }
function add_audit_ext($action, $resourcetype, $resourceid, $resourcename, $table_name, $values_old, $values_new) { global $USER_DETAILS; if (!isset($USER_DETAILS["userid"])) { check_authorisation(); } if ($action == AUDIT_ACTION_UPDATE) { $values_diff = array(); foreach ($values_new as $id => $value) { if ($values_old[$id] !== $value) { array_push($values_diff, $id); } } if (0 == count($values_diff)) { return true; } } $auditid = get_dbid('auditlog', 'auditid'); if (zbx_strlen($resourcename) > 255) { $details = substr($resourcename, 0, 252) . '...'; } $ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']; /*SDI( 'INSERT INTO auditlog (auditid,userid,clock,ip,action,resourcetype,resourceid,resourcename)'. ' values ('.$auditid.','.$USER_DETAILS['userid'].','.time().','.zbx_dbstr($ip). ','.$action.','.$resourcetype.','.$resourceid.','.zbx_dbstr($resourcename).')');*/ $result = DBexecute('INSERT INTO auditlog (auditid,userid,clock,ip,action,resourcetype,resourceid,resourcename)' . ' values (' . $auditid . ',' . $USER_DETAILS['userid'] . ',' . time() . ',' . zbx_dbstr($ip) . ',' . $action . ',' . $resourcetype . ',' . $resourceid . ',' . zbx_dbstr($resourcename) . ')'); if ($result && $action == AUDIT_ACTION_UPDATE) { foreach ($values_diff as $id) { $auditdetailid = get_dbid('auditlog_details', 'auditdetailid'); $result &= DBexecute('insert into auditlog_details (auditdetailid,auditid,table_name,field_name,oldvalue,newvalue)' . ' values (' . $auditdetailid . ',' . $auditid . ',' . zbx_dbstr($table_name) . ',' . zbx_dbstr($id) . ',' . zbx_dbstr($values_old[$id]) . ',' . zbx_dbstr($values_new[$id]) . ')'); } } if ($result) { $result = $auditid; } return $result; }
function update_user_group($usrgrpid, $name, $users_status, $gui_access, $api_access, $debug_mode, $users = array(), $rights = array()) { global $USER_DETAILS; $sql = 'SELECT * ' . ' FROM usrgrp ' . ' WHERE name=' . zbx_dbstr($name) . ' AND usrgrpid<>' . $usrgrpid . ' AND ' . DBin_node('usrgrpid', get_current_nodeid(false)); if (DBfetch(DBselect($sql))) { error("Group '{$name}' already exists"); return 0; } $result = DBexecute('UPDATE usrgrp SET name=' . zbx_dbstr($name) . ' WHERE usrgrpid=' . $usrgrpid); if (!$result) { return $result; } // must come before adding user to group $result &= change_group_status($usrgrpid, $users_status); $result &= change_group_gui_access($usrgrpid, $gui_access); $result &= change_group_api_access($usrgrpid, $api_access); $result &= change_group_debug_mode($usrgrpid, $debug_mode); if (!$result) { return $result; } //------- $grant = true; if ($gui_access == GROUP_GUI_ACCESS_DISABLED || $users_status == GROUP_STATUS_DISABLED) { $grant = !uint_in_array($USER_DETAILS['userid'], $users); } if ($grant) { $result = DBexecute('DELETE FROM users_groups WHERE usrgrpid=' . $usrgrpid); foreach ($users as $userid => $name) { $result = add_user_to_group($userid, $usrgrpid); if (!$result) { return $result; } } } else { error(S_USER_CANNOT_DISABLE_ITSELF); return false; } $result = DBexecute('DELETE FROM rights WHERE groupid=' . $usrgrpid); foreach ($rights as $right) { $id = get_dbid('rights', 'rightid'); $result = DBexecute('INSERT INTO rights (rightid,groupid,permission,id)' . ' VALUES (' . $id . ',' . $usrgrpid . ',' . $right['permission'] . ',' . $right['id'] . ')'); if (!$result) { return $result; } } return $result; }
function db_save_application($name, $hostid, $applicationid = null, $templateid = 0) { if (!is_string($name)) { error('Incorrect parameters for "db_save_application"'); return false; } $host = get_host_by_hostid($hostid); $hostids = array(); $db_hosts = get_hosts_by_templateid($host['hostid']); while ($db_host = DBfetch($db_hosts)) { $hostids[] = $db_host['hostid']; } $sql = 'SELECT applicationid FROM applications WHERE name=' . zbx_dbstr($name) . ' AND ' . DBcondition('hostid', $hostids); $lower_app = DBfetch(DBselect($sql)); if ($lower_app) { error(S_APPLICATION . SPACE . "'{$name}'" . SPACE . S_ALREADY_EXISTS_IN_LINKED_HOSTS_SMALL); return false; } $sql = 'SELECT applicationid FROM applications WHERE name=' . zbx_dbstr($name) . ' AND hostid=' . $hostid; if (!is_null($applicationid)) { $sql .= ' AND applicationid<>' . $applicationid; } $db_app = DBfetch(DBselect($sql)); if ($db_app && $templateid == 0) { error(S_APPLICATION . SPACE . "'{$name}'" . SPACE . S_ALREADY_EXISTS_SMALL); return false; } if ($db_app && !is_null($applicationid)) { // delete old application with same name delete_application($db_app['applicationid']); } if ($db_app && is_null($applicationid)) { // if found application with same name update them, adding not needed $applicationid = $db_app['applicationid']; } if (is_null($applicationid)) { $applicationid_new = get_dbid('applications', 'applicationid'); $sql = 'INSERT INTO applications (applicationid, name, hostid, templateid) ' . " VALUES ({$applicationid_new}, " . zbx_dbstr($name) . ", {$hostid}, {$templateid})"; if ($result = DBexecute($sql)) { info(S_ADDED_NEW_APPLICATION . SPACE . $host['host'] . ':' . $name); } } else { $old_app = get_application_by_applicationid($applicationid); $result = DBexecute('UPDATE applications SET name=' . zbx_dbstr($name) . ', hostid=' . $hostid . ', templateid=' . $templateid . ' WHERE applicationid=' . $applicationid); if ($result) { info(S_UPDATED_APPLICATION . SPACE . $host['host'] . ':' . $old_app['name']); } } if (!$result) { return $result; } if (is_null($applicationid)) { // create application for childs $applicationid = $applicationid_new; $db_childs = get_hosts_by_templateid($hostid); while ($db_child = DBfetch($db_childs)) { // recursion $result = add_application($name, $db_child['hostid'], $applicationid); if (!$result) { break; } } } else { $db_applications = get_applications_by_templateid($applicationid); while ($db_app = DBfetch($db_applications)) { // recursion $result = update_application($db_app['applicationid'], $name, $db_app['hostid'], $applicationid); if (!$result) { break; } } } if ($result) { return $applicationid; } if ($templateid == 0) { delete_application($applicationid); } return false; }
/** * Add Medias for User * * {@source} * @access public * @static * @since 1.8 * @version 1 * * @param array $media_data * @param string $media_data['userid'] * @param string $media_data['medias']['mediatypeid'] * @param string $media_data['medias']['address'] * @param int $media_data['medias']['severity'] * @param int $media_data['medias']['active'] * @param string $media_data['medias']['period'] * @return boolean */ public static function addMedia($media_data) { global $USER_DETAILS; $result = true; $medias = zbx_toArray($media_data['medias']); $users = zbx_toArray($media_data['users']); $userids = array(); if ($USER_DETAILS['type'] < USER_TYPE_ZABBIX_ADMIN) { self::setError(__METHOD__, ZBX_API_ERROR_PERMISSIONS, S_CUSER_ERROR_ONLY_ADMIN_CAN_ADD_USER_MEDIAS); return false; } foreach ($users as $unum => $user) { $userids[] = $user['userid']; foreach ($medias as $mnum => $media) { if (!validate_period($media['period'])) { self::setError(__METHOD__, ZBX_API_ERROR_PARAMETERS, S_CUSER_ERROR_INCORRECT_TIME_PERIOD); return false; } $mediaid = get_dbid('media', 'mediaid'); $sql = 'INSERT INTO media (mediaid,userid,mediatypeid,sendto,active,severity,period) ' . ' VALUES (' . $mediaid . ',' . $user['userid'] . ',' . $media['mediatypeid'] . ',' . zbx_dbstr($media['sendto']) . ',' . $media['active'] . ',' . $media['severity'] . ',' . zbx_dbstr($media['period']) . ')'; $result = DBexecute($sql); if (!$result) { break 2; } } } if ($result) { return array('userids' => $userids); } else { self::$error[] = array('error' => ZBX_API_ERROR_INTERNAL, 'data' => S_CUSER_ERROR_INTERNAL_ZABBIX_ERROR); return false; } }
function add_item_to_graph($graphid, $itemid, $color, $drawtype, $sortorder, $yaxisside, $calc_fnc, $type, $periods_cnt) { $gitemid = get_dbid('graphs_items', 'gitemid'); $result = DBexecute('insert into graphs_items' . ' (gitemid,graphid,itemid,color,drawtype,sortorder,yaxisside,calc_fnc,type,periods_cnt)' . ' values (' . $gitemid . ',' . $graphid . ',' . $itemid . ',' . zbx_dbstr($color) . ',' . $drawtype . ',' . $sortorder . ',' . $yaxisside . ',' . $calc_fnc . ',' . $type . ',' . $periods_cnt . ')'); return $result ? $gitemid : $result; }
/** * Add events ( without alerts ) * * {@source} * @access public * @static * @since 1.8 * @version 1 * * @param _array $events multidimensional array with events data * @param array $events[0,...]['source'] * @param array $events[0,...]['object'] * @param array $events[0,...]['objectid'] * @param array $events[0,...]['clock'] OPTIONAL * @param array $events[0,...]['value'] OPTIONAL * @param array $events[0,...]['acknowledged'] OPTIONAL * @return boolean */ public static function create($events) { $events = zbx_toArray($events); $eventids = array(); $result = true; $options = array('triggerids' => zbx_objectValues($events, 'objectid'), 'output' => API_OUTPUT_EXTEND, 'preservekeys' => 1); $triggers = CTrigger::get($options); foreach ($events as $num => $event) { if ($event['object'] != EVENT_OBJECT_TRIGGER) { continue; } if (isset($triggers[$event['objectid']])) { $trigger = $triggers[$event['objectid']]; if ($event['value'] != $trigger['value'] || $event['value'] == TRIGGER_VALUE_TRUE && $trigger['type'] == TRIGGER_MULT_EVENT_ENABLED) { continue; } } unset($events[$num]); } self::BeginTransaction(__METHOD__); foreach ($events as $num => $event) { $event_db_fields = array('source' => null, 'object' => null, 'objectid' => null, 'clock' => time(), 'value' => 0, 'acknowledged' => 0); if (!check_db_fields($event_db_fields, $event)) { $result = false; break; } $eventid = get_dbid('events', 'eventid'); $sql = 'INSERT INTO events (eventid, source, object, objectid, clock, value, acknowledged) ' . ' VALUES (' . $eventid . ',' . $event['source'] . ',' . $event['object'] . ',' . $event['objectid'] . ',' . $event['clock'] . ',' . $event['value'] . ',' . $event['acknowledged'] . ')'; $result = DBexecute($sql); if (!$result) { break; } // $triggers[] = array('triggerid' => $event['objectid'], 'value'=> $event['value'], 'lastchange'=> $event['clock']); $eventids[$eventid] = $eventid; } if ($result) { // This will create looping (Trigger->Event->Trigger->Event) // $result = CTrigger::update($triggers); } $result = self::EndTransaction($result, __METHOD__); if ($result) { return $eventids; } else { self::$error[] = array('error' => ZBX_API_ERROR_INTERNAL, 'data' => 'Internal Zabbix error'); return false; } }
function insert_profile($idx, $value, $type, $idx2, $source) { global $USER_DETAILS; $profileid = get_dbid('profiles', 'profileid'); $value_type = profile_field_by_type($type); $val['value_id'] = 0; $val['value_int'] = 0; $val['value_str'] = ''; $val[$value_type] = $value; $idx2 = zbx_numeric($idx2) ? $idx2 : 0; $src = is_null($source) ? '' : $source; if (is_array($value)) { $val[$value_type] = isset($value['value']) ? $value['value'] : ''; $src = isset($value['source']) ? $value['source'] : $src; } if (is_null($val[$value_type])) { return false; } $sql = 'INSERT INTO profiles (profileid,userid,idx,idx2,value_id,value_int,value_str,source,type)' . ' VALUES (' . $profileid . ',' . $USER_DETAILS['userid'] . ',' . zbx_dbstr($idx) . ',' . $idx2 . ',' . $val['value_id'] . ',' . $val['value_int'] . ',' . zbx_dbstr($val['value_str']) . ',' . zbx_dbstr($src) . ',' . $type . ')'; $result = DBexecute($sql); return $result; }
private static function insertDB($idx, $value, $type, $idx2) { $value_type = self::getFieldByType($type); $values = array('profileid' => get_dbid('profiles', 'profileid'), 'userid' => self::$userDetails['userid'], 'idx' => zbx_dbstr($idx), $value_type => zbx_dbstr($value), 'type' => $type, 'idx2' => $idx2); return DBexecute('INSERT INTO profiles (' . implode(', ', array_keys($values)) . ') VALUES (' . implode(', ', $values) . ')'); }
/** * Add Host * * @param _array $hosts multidimensional array with Hosts data * @param string $hosts['host'] Host name. * @param array $hosts['groups'] array of HostGroup objects with IDs add Host to. * @param int $hosts['port'] Port. OPTIONAL * @param int $hosts['status'] Host Status. OPTIONAL * @param int $hosts['useip'] Use IP. OPTIONAL * @param string $hosts['dns'] DNS. OPTIONAL * @param string $hosts['ip'] IP. OPTIONAL * @param int $hosts['proxy_hostid'] Proxy Host ID. OPTIONAL * @param int $hosts['useipmi'] Use IPMI. OPTIONAL * @param string $hosts['ipmi_ip'] IPMAI IP. OPTIONAL * @param int $hosts['ipmi_port'] IPMI port. OPTIONAL * @param int $hosts['ipmi_authtype'] IPMI authentication type. OPTIONAL * @param int $hosts['ipmi_privilege'] IPMI privilege. OPTIONAL * @param string $hosts['ipmi_username'] IPMI username. OPTIONAL * @param string $hosts['ipmi_password'] IPMI password. OPTIONAL * @return boolean */ public static function create($hosts) { $hosts = zbx_toArray($hosts); $hostids = array(); $groupids = array(); try { self::BeginTransaction(__METHOD__); // BASIC VALIDATION {{{ foreach ($hosts as $hnum => $host) { // CHECK IF HOSTS HAVE AT LEAST 1 GROUP if (empty($host['groups'])) { self::exception(ZBX_API_ERROR_PARAMETERS, sprintf(S_NO_GROUPS_FOR_HOST, $host['host'])); } // Check if host name isn't longer then 64 chars if (zbx_strlen($host['host']) > 64) { self::exception(ZBX_API_ERROR_PARAMETERS, sprintf(S_HOST_NAME_MUST_BE_LONGER, 64, $host['host'], zbx_strlen($host['host']))); } $hosts[$hnum]['groups'] = zbx_toArray($hosts[$hnum]['groups']); foreach ($hosts[$hnum]['groups'] as $gnum => $group) { $groupids[$group['groupid']] = $group['groupid']; } } // }}} // PERMISSIONS {{{ $upd_groups = CHostGroup::get(array('groupids' => $groupids, 'editable' => 1, 'preservekeys' => 1)); foreach ($groupids as $gnum => $groupid) { if (!isset($upd_groups[$groupid])) { self::exception(ZBX_API_ERROR_PERMISSIONS, S_NO_PERMISSIONS); } } // }}} PERMISSIONS foreach ($hosts as $num => $host) { $host_db_fields = array('host' => null, 'port' => 0, 'status' => 0, 'useip' => 0, 'dns' => '', 'ip' => '0.0.0.0', 'proxy_hostid' => 0, 'useipmi' => 0, 'ipmi_ip' => '', 'ipmi_port' => 623, 'ipmi_authtype' => 0, 'ipmi_privilege' => 0, 'ipmi_username' => '', 'ipmi_password' => ''); if (!check_db_fields($host_db_fields, $host)) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Wrong fields for host [ ' . $host['host'] . ' ]'); } if (!preg_match('/^' . ZBX_PREG_HOST_FORMAT . '$/i', $host['host'])) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for Hostname [ ' . $host['host'] . ' ]'); } if (!empty($host['dns']) && !preg_match('/^' . ZBX_PREG_DNS_FORMAT . '$/i', $host['dns'])) { self::exception(ZBX_API_ERROR_PARAMETERS, 'Incorrect characters used for DNS [ ' . $host['dns'] . ' ]'); } if (self::exists(array('host' => $host['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, S_HOST . ' [ ' . $host['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL); } if (CTemplate::exists(array('host' => $host['host']))) { self::exception(ZBX_API_ERROR_PARAMETERS, S_TEMPLATE . ' [ ' . $host['host'] . ' ] ' . S_ALREADY_EXISTS_SMALL); } $hostid = get_dbid('hosts', 'hostid'); $hostids[] = $hostid; $result = DBexecute('INSERT INTO hosts (hostid, proxy_hostid, host, port, status, useip, dns, ip, disable_until, available,' . 'useipmi,ipmi_port,ipmi_authtype,ipmi_privilege,ipmi_username,ipmi_password,ipmi_ip) VALUES (' . $hostid . ',' . $host['proxy_hostid'] . ',' . zbx_dbstr($host['host']) . ',' . $host['port'] . ',' . $host['status'] . ',' . $host['useip'] . ',' . zbx_dbstr($host['dns']) . ',' . zbx_dbstr($host['ip']) . ',0,' . HOST_AVAILABLE_UNKNOWN . ',' . $host['useipmi'] . ',' . $host['ipmi_port'] . ',' . $host['ipmi_authtype'] . ',' . $host['ipmi_privilege'] . ',' . zbx_dbstr($host['ipmi_username']) . ',' . zbx_dbstr($host['ipmi_password']) . ',' . zbx_dbstr($host['ipmi_ip']) . ')'); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror'); } foreach ($host['groups'] as $group) { $hostgroupid = get_dbid('hosts_groups', 'hostgroupid'); $result = DBexecute("INSERT INTO hosts_groups (hostgroupid, hostid, groupid) VALUES ({$hostgroupid}, {$hostid}, {$group['groupid']})"); if (!$result) { self::exception(ZBX_API_ERROR_PARAMETERS, 'DBerror'); } } $host['hostid'] = $hostid; $options = array(); $options['hosts'] = $host; if (isset($host['templates']) && !is_null($host['templates'])) { $options['templates'] = $host['templates']; } if (isset($host['macros']) && !is_null($host['macros'])) { $options['macros'] = $host['macros']; } $result = CHost::massAdd($options); if (!$result) { self::exception(); } if (isset($host['profile']) && !empty($host['extendedProfile'])) { $fields = array_keys($host['profile']); $fields = implode(', ', $fields); $values = array_map('zbx_dbstr', $host['profile']); $values = implode(', ', $values); DBexecute('INSERT INTO hosts_profiles (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')'); } if (isset($host['extendedProfile']) && !empty($host['extendedProfile'])) { $fields = array_keys($host['extendedProfile']); $fields = implode(', ', $fields); $values = array_map('zbx_dbstr', $host['extendedProfile']); $values = implode(', ', $values); DBexecute('INSERT INTO hosts_profiles_ext (hostid, ' . $fields . ') VALUES (' . $hostid . ', ' . $values . ')'); } } 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; } }
function add_service_alarm($serviceid, $status, $clock) { if (latest_service_alarm($serviceid, $status)) { return true; } return DBexecute('INSERT INTO service_alarms (servicealarmid,serviceid,clock,value) VALUES (' . get_dbid('service_alarms', 'servicealarmid') . ',' . zbx_dbstr($serviceid) . ',' . zbx_dbstr($clock) . ',' . zbx_dbstr($status) . ')'); }