function delete_note($noteid) { $db = new DbConn(); $result = $db->fetch('select userid from notes where id = ?'); if ($result) { $db->exec('delete from notes where id = ?', $noteid); log_event(LOG_NOTE_DELETED, $result->userid, $noteid); } }
function run_sql($query) { global $dblog; log_event($query, $dblog); $tmp = mysql_query($query) or die("Error in query:" . $query . " " . mysql_error()); return $tmp; }
function update() { $this->load->helper('html2text'); $id = $this->input->post('id'); $subject = $this->input->post('subject'); $htmlbody = $this->input->post('htmlbody'); $textbody = html_to_plaintext($htmlbody); $attachments = $this->input->post('attachment'); $db = new DbConn(); if (!$id) { // New template $db->exec('insert into mail_templates () values ()'); $id = $db->last_insert_id(); } $rows = $db->exec('insert into mail_template_versions (templateid, subject, html, plaintext, datecreated, creator) values (?, ?, ?, ?, ?, ?)', (int) $id, $subject, $htmlbody, $textbody, date_create(), $this->admin->id()); if ($rows != 1) { throw new RuntimeException("Insertion failed!"); } $newId = $db->last_insert_id(); // process attachments if ($attachments) { foreach ($attachments as $attachId) { $attachId = (int) $attachId; $db->exec('insert into templatevers_to_attachments (templateverid, attachmentid) values (?, ?)', $newId, $attachId); } } $template = get_mail_template($id); $role = $template ? $template->role : '(unknown)'; log_event(LOG_MAIL_TEMPLATE_EDITED, NULL, $role); redirect("admin/emails/index/{$id}"); }
/** * Script finished with errors */ function exitFail($error, $exit) { echo "1;" . $error; log_event("ERROR", $error); if ($exit) { exit; } }
function discover_service($device, $service) { if (!dbFetchCell('SELECT COUNT(service_id) FROM `services` WHERE `service_type`= ? AND `device_id` = ?', array($service, $device['device_id']))) { add_service($device, $service, "(Auto discovered) {$service}"); log_event('Autodiscovered service: type ' . mres($service), $device, 'service'); echo '+'; } echo "{$service} "; }
/** * Observium * * This file is part of Observium. * * @package observium * @subpackage poller * @copyright (C) 2006-2014 Adam Armstrong * */ function discover_service($device, $service) { if (!dbFetchCell("SELECT COUNT(service_id) FROM `services` WHERE `service_type`= ? AND `device_id` = ?", array($service, $device['device_id']))) { add_service($device, $service, "(自动发现) {$service}"); log_event("自动发现服务: 类型 {$service}", $device, 'service'); echo "+"; } echo "{$service} "; }
function login() { $this->_logout(); $email = $this->input->post('login_email'); $password = $this->input->post('login_password'); $user = FALSE; if (!($email === FALSE || $password === FALSE)) { $user = get_user_by_credentials($email, $password); } if (!$user) { $errmsg = 'Sorry, unrecognized e-mail or incorrect password.'; $this->load->view('header'); $this->load->view('index', array('login_error' => $errmsg)); $this->load->view('footer'); } else { log_event(LOG_USER_LOGIN, $user->id); $this->session->set_userdata('userid', $user->id); // TODO: Pick up where user left off, not on page 1 redirect('welcome/dispatch'); } }
function log_action($op, $user, $agg, $slice = NULL, $rspec = NULL, $slice_id = NULL) { $log_url = get_first_service_of_type(SR_SERVICE_TYPE::LOGGING_SERVICE); $user_id = $user->account_id; if (!is_array($agg)) { $aggs[] = $agg; } else { $aggs = $agg; } foreach ($aggs as $am) { $attributes['aggregate'] = $am; $msg = "{$op} at {$am}"; if ($slice) { $msg .= " on {$slice}"; $slice_attributes = get_attribute_for_context(CS_CONTEXT_TYPE::SLICE, $slice_id); $attributes = array_merge($attributes, $slice_attributes); } if ($rspec) { $attributes['rspec'] = $rspec; } $result = log_event($log_url, $user, $msg, $attributes); } }
} elseif (isset($data['ipNetToMediaPhysAddress'])) { $raw_mac = $data['ipNetToMediaPhysAddress']; list($if, $ip) = explode('.', $ip, 2); $ipv = 'ipv4'; } $interface = get_port_by_index_cache($device['device_id'], $if); $port_id = $interface['port_id']; if (!empty($ip) && $ipv === 'ipv4' && $raw_mac != '0:0:0:0:0:0' && !isset($arp_table[$port_id][$ip])) { $mac = implode(array_map('zeropad', explode(':', $raw_mac))); $arp_table[$port_id][$ip] = $mac; $index = array_search($ip, $ipv4_addresses); if ($index !== false) { $old_mac = $existing_data[$index]['mac_address']; if ($mac != $old_mac && $mac != '') { d_echo("Changed mac address for {$ip} from {$old_mac} to {$mac}\n"); log_event("MAC change: {$ip} : " . mac_clean_to_readable($old_mac) . ' -> ' . mac_clean_to_readable($mac), $device, 'interface', $port_id); dbUpdate(array('mac_address' => $mac), 'ipv4_mac', 'port_id=? AND ipv4_address=? AND context_name=?', array($port_id, $ip, $context)); } d_echo(null, '.'); } elseif (isset($interface['port_id'])) { d_echo(null, '+'); $insert_data[] = array('port_id' => $port_id, 'mac_address' => $mac, 'ipv4_address' => $ip, 'context_name' => $context); } } } // add new entries if (!empty($insert_data)) { dbBulkInsert($insert_data, 'ipv4_mac'); } // remove stale entries foreach ($existing_data as $entry) {
function renamehost($id, $new, $source = 'console') { global $config; // FIXME does not check if destination exists! $host = dbFetchCell("SELECT `hostname` FROM `devices` WHERE `device_id` = ?", array($id)); if (rename($config['rrd_dir'] . "/{$host}", $config['rrd_dir'] . "/{$new}") === TRUE) { dbUpdate(array('hostname' => $new), 'devices', 'device_id=?', array($id)); log_event("Hostname changed -> {$new} ({$source})", $id, 'system'); } else { echo "Renaming of {$host} failed\n"; log_event("Renaming of {$host} failed", $id, 'system'); } }
} else { del_dev_attrib($device, 'override_sysLocation_bool'); } if (isset($override_sysLocation_string)) { set_dev_attrib($device, 'override_sysLocation_string', $override_sysLocation_string); } # FIXME needs more sanity checking! and better feedback # FIXME -- update location too? Need to trigger geolocation! $param = array('purpose' => $vars['descr'], 'type' => $vars['type'], 'ignore' => $vars['ignore'], 'disabled' => $vars['disabled']); $rows_updated = dbUpdate($param, 'devices', '`device_id` = ?', array($device['device_id'])); if ($rows_updated > 0 || $updated) { if ((bool) $vars['ignore'] != (bool) $device['ignore']) { log_event('设备 ' . ((bool) $vars['ignore'] ? 'ignored' : 'attended') . ': ' . $device['hostname'], $device['device_id'], 'device', $device['device_id'], 5); } if ((bool) $vars['disabled'] != (bool) $device['disabled']) { log_event('设备 ' . ((bool) $vars['disabled'] ? 'disabled' : 'enabled') . ': ' . $device['hostname'], $device['device_id'], 'device'); } $update_message = "设备更新的记录."; if ($updated == 2) { $update_message .= " 请注意, 最新的系统位置字符串将在轮询后可见."; } $updated = 1; $device = dbFetchRow("SELECT * FROM `devices` WHERE `device_id` = ?", array($device['device_id'])); } elseif ($rows_updated = '-1') { $update_message = "装置记录不变. 没有更新的必要."; $updated = -1; } else { $update_message = "装置的记录更新错误."; } } else { include "includes/error-no-perm.inc.php";
$stp['rootBridge'] = '0'; } d_echo($stp); if ($stp_raw[0]['version'] == '3') { echo "RSTP "; } else { echo "STP "; } if (!$stp_db['bridgeAddress'] && $stp['bridgeAddress']) { dbInsert($stp, 'stp'); log_event('STP added, bridge address: ' . $stp['bridgeAddress'], $device, 'stp'); echo '+'; } if ($stp_db['bridgeAddress'] && !$stp['bridgeAddress']) { dbDelete('stp', 'device_id = ?', array($device['device_id'])); log_event('STP removed', $device, 'stp'); echo '-'; } // STP port related stuff foreach ($stp_raw as $port => $value) { if ($port) { // $stp_raw[0] ist not port related so we skip this one $stp_port = array('priority' => $stp_raw[$port]['dot1dStpPortPriority'], 'state' => $stp_raw[$port]['dot1dStpPortState'], 'enable' => $stp_raw[$port]['dot1dStpPortEnable'], 'pathCost' => $stp_raw[$port]['dot1dStpPortPathCost'], 'designatedCost' => $stp_raw[$port]['dot1dStpPortDesignatedCost'], 'designatedPort' => $stp_raw[$port]['dot1dStpPortDesignatedPort'], 'forwardTransitions' => $stp_raw[$port]['dot1dStpPortForwardTransitions']); // set device binding $stp_port['device_id'] = $device['device_id']; // set port binding $stp_port['port_id'] = dbFetchCell('SELECT port_id FROM `ports` WHERE `device_id` = ? AND `ifIndex` = ?', array($device['device_id'], $stp_raw[$port]['dot1dStpPort'])); $dr = str_replace(array(' ', ':', '-'), '', strtolower($stp_raw[$port]['dot1dStpPortDesignatedRoot'])); $dr = substr($dr, -12); //remove first two octets $stp_port['designatedRoot'] = $dr;
function poll_device($device, $options) { global $config, $device, $polled_devices, $db_stats, $memcache; $attribs = get_dev_attribs($device['device_id']); $status = 0; unset($array); $device_start = utime(); // Start counting device poll time echo $device['hostname'] . ' ' . $device['device_id'] . ' ' . $device['os'] . ' '; if ($config['os'][$device['os']]['group']) { $device['os_group'] = $config['os'][$device['os']]['group']; echo '(' . $device['os_group'] . ')'; } echo "\n"; unset($poll_update); unset($poll_update_query); unset($poll_separator); $poll_update_array = array(); $update_array = array(); $host_rrd = $config['rrd_dir'] . '/' . $device['hostname']; if (!is_dir($host_rrd)) { mkdir($host_rrd); echo "Created directory : {$host_rrd}\n"; } $address_family = snmpTransportToAddressFamily($device['transport']); $ping_response = isPingable($device['hostname'], $address_family, $attribs); $device_perf = $ping_response['db']; $device_perf['device_id'] = $device['device_id']; $device_perf['timestamp'] = array('NOW()'); if (can_ping_device($attribs) === true && is_array($device_perf)) { dbInsert($device_perf, 'device_perf'); } $device['pingable'] = $ping_response['result']; $ping_time = $ping_response['last_ping_timetaken']; $response = array(); $status_reason = ''; if ($device['pingable']) { $device['snmpable'] = isSNMPable($device); if ($device['snmpable']) { $status = '1'; $response['status_reason'] = ''; } else { echo 'SNMP Unreachable'; $status = '0'; $response['status_reason'] = 'snmp'; } } else { echo 'Unpingable'; $status = '0'; $response['status_reason'] = 'icmp'; } if ($device['status'] != $status) { $poll_update .= $poll_separator . "`status` = '{$status}'"; $poll_separator = ', '; dbUpdate(array('status' => $status, 'status_reason' => $response['status_reason']), 'devices', 'device_id=?', array($device['device_id'])); dbInsert(array('importance' => '0', 'device_id' => $device['device_id'], 'message' => 'Device is ' . ($status == '1' ? 'up' : 'down')), 'alerts'); log_event('Device status changed to ' . ($status == '1' ? 'Up' : 'Down'), $device, $status == '1' ? 'up' : 'down'); } if ($status == '1') { $graphs = array(); $oldgraphs = array(); if ($options['m']) { foreach (explode(',', $options['m']) as $module) { if (is_file('includes/polling/' . $module . '.inc.php')) { include 'includes/polling/' . $module . '.inc.php'; } } } else { foreach ($config['poller_modules'] as $module => $module_status) { if ($attribs['poll_' . $module] || $module_status && !isset($attribs['poll_' . $module])) { // TODO per-module polling stats include 'includes/polling/' . $module . '.inc.php'; } else { if (isset($attribs['poll_' . $module]) && $attribs['poll_' . $module] == '0') { echo "Module [ {$module} ] disabled on host.\n"; } else { echo "Module [ {$module} ] disabled globally.\n"; } } } } //end if if (!$options['m']) { // FIXME EVENTLOGGING -- MAKE IT SO WE DO THIS PER-MODULE? // This code cycles through the graphs already known in the database and the ones we've defined as being polled here // If there any don't match, they're added/deleted from the database. // Ideally we should hold graphs for xx days/weeks/polls so that we don't needlessly hide information. foreach (dbFetch('SELECT `graph` FROM `device_graphs` WHERE `device_id` = ?', array($device['device_id'])) as $graph) { if (isset($graphs[$graph['graph']])) { $oldgraphs[$graph['graph']] = true; } else { dbDelete('device_graphs', '`device_id` = ? AND `graph` = ?', array($device['device_id'], $graph['graph'])); } } foreach ($graphs as $graph => $value) { if (!isset($oldgraphs[$graph])) { echo '+'; dbInsert(array('device_id' => $device['device_id'], 'graph' => $graph), 'device_graphs'); } echo $graph . ' '; } } //end if $device_end = utime(); $device_run = $device_end - $device_start; $device_time = substr($device_run, 0, 5); // TODO: These should be easy converts to rrd_create_update() // Poller performance rrd $poller_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/poller-perf.rrd'; if (!is_file($poller_rrd)) { rrdtool_create($poller_rrd, 'DS:poller:GAUGE:600:0:U ' . $config['rrd_rra']); } if (!empty($device_time)) { $fields = array('poller' => $device_time); rrdtool_update($poller_rrd, $fields); } // Ping response rrd if (can_ping_device($attribs) === true) { $ping_rrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/ping-perf.rrd'; if (!is_file($ping_rrd)) { rrdtool_create($ping_rrd, 'DS:ping:GAUGE:600:0:65535 ' . $config['rrd_rra']); } if (!empty($ping_time)) { $fields = array('ping' => $ping_time); rrdtool_update($ping_rrd, $fields); } $update_array['last_ping'] = array('NOW()'); $update_array['last_ping_timetaken'] = $ping_time; } $update_array['last_polled'] = array('NOW()'); $update_array['last_polled_timetaken'] = $device_time; // echo("$device_end - $device_start; $device_time $device_run"); echo "Polled in {$device_time} seconds\n"; d_echo('Updating ' . $device['hostname'] . "\n"); d_echo($update_array); $updated = dbUpdate($update_array, 'devices', '`device_id` = ?', array($device['device_id'])); if ($updated) { echo "UPDATED!\n"; } unset($storage_cache); // Clear cache of hrStorage ** MAYBE FIXME? ** unset($cache); // Clear cache (unify all things here?) } //end if }
print_cli_data("Asset", $asset_tag ?: "%b<empty>%n"); echo PHP_EOL; foreach ($os_additional_info as $header => $entries) { print_cli_heading($header, 3); foreach ($entries as $field => $entry) { print_cli_data($field, $entry, 3); } echo PHP_EOL; } // Fields notified in event log $update_fields = array('version', 'features', 'hardware', 'serial', 'kernel', 'distro', 'distro_ver', 'arch', 'asset_tag'); // Log changed variables foreach ($update_fields as $field) { if (isset(${$field})) { ${$field} = snmp_fix_string(${$field}); } // Fix unprintable chars if ((isset(${$field}) || strlen($device[$field])) && ${$field} != $device[$field]) { $update_array[$field] = ${$field}; log_event(nicecase($field) . " -> " . $update_array[$field], $device, 'device', $device['device_id']); } } // Here additional fields, change only if not set already foreach (array('type', 'icon') as $field) { if (isset(${$field}) && ($device[$field] == "unknown" || $device[$field] == '' || !isset($device[$field]) || !strlen($device[$field]))) { $update_array[$field] = ${$field}; log_event(nicecase($field) . " -> " . $update_array[$field], $device, 'device', $device['device_id']); } } unset($entPhysical, $oids, $hw, $os_additional_info); // EOF
/** * @param $userid * @param $headers * @param $table_csv * @param array $fields * @param $parent_chkd_flds * @param $export_file_name * @param $debug * @param null $comment * @param array $to */ public static function do_sendit($userid, $headers, $table_csv, $fields = array(), $parent_chkd_flds, $export_file_name, $comment = null, $to = array(), $debug) { global $project_id, $user_rights, $app_title, $lang, $redcap_version; // we could use the global $userid, but we need control of it for setting the user as [CRON], so this is passed in args. $return_val = false; $export_type = 0; // this puts all files generated here in the Data Export category in the File Repository $today = date("Y-m-d_Hi"); //get today for filename $projTitleShort = substr(str_replace(" ", "", ucwords(preg_replace("/[^a-zA-Z0-9 ]/", "", html_entity_decode($app_title, ENT_QUOTES)))), 0, 20); // shortened project title for filename $originalFilename = $projTitleShort . "_" . $export_file_name . "_DATA_" . $today . ".csv"; // name the file for storage $today = date("Y-m-d-H-i-s"); // get today for comment, subsequent processing as needed $docs_comment_WH = $export_type ? "Data export file created by $userid on $today" : fix_case($export_file_name) . " file created by $userid on $today. $comment"; // unused, but I keep it around just in case /** * setup vars for value export logging */ $chkd_fields = implode(',', $fields); /** * turn on/off exporting per user rights */ if (($user_rights['data_export_tool'] || $userid == '[CRON]') && !$debug) { $table_csv = addBOMtoUTF8($headers . $table_csv); /** * Store the file in the file system and log the activity, handle if error */ if (!DataExport::storeExportFile($originalFilename, $table_csv, true)) { log_event("", "redcap_data", "data_export", "", str_replace("'", "", $chkd_fields) . (($parent_chkd_flds == "") ? "" : ", " . str_replace("'", "", $parent_chkd_flds)), "Data Export Failed"); } else { log_event("", "redcap_data", "data_export", "", str_replace("'", "", $chkd_fields) . (($parent_chkd_flds == "") ? "" : ", " . str_replace("'", "", $parent_chkd_flds)), "Export data for SendIt"); /** * email file link and download password in two separate emails via REDCap SendIt */ $file_info_sql = db_query("SELECT docs_id, docs_size, docs_type FROM redcap_docs WHERE project_id = $project_id ORDER BY docs_id DESC LIMIT 1"); // get required info about the file we just created if ($file_info_sql) { $docs_id = db_result($file_info_sql, 0, 'docs_id'); $docs_size = db_result($file_info_sql, 0, 'docs_size'); $docs_type = db_result($file_info_sql, 0, 'docs_type'); } $yourName = 'PRIORITIZE REDCap'; $expireDays = 3; // set the SendIt to expire in this many days /** * $file_location: * 1 = ephemeral, will be deleted on $expireDate * 2 = export file, visible only to rights in file repository */ $file_location = 2; $send = 1; // always send download confirmation $expireDate = date('Y-m-d H:i:s', strtotime("+$expireDays days")); $expireYear = substr($expireDate, 0, 4); $expireMonth = substr($expireDate, 5, 2); $expireDay = substr($expireDate, 8, 2); $expireHour = substr($expireDate, 11, 2); $expireMin = substr($expireDate, 14, 2); // Add entry to sendit_docs table $query = "INSERT INTO redcap_sendit_docs (doc_name, doc_orig_name, doc_type, doc_size, send_confirmation, expire_date, username, location, docs_id, date_added) VALUES ('$originalFilename', '" . prep($originalFilename) . "', '$docs_type', '$docs_size', $send, '$expireDate', '" . prep($userid) . "', $file_location, $docs_id, '" . NOW . "')"; db_query($query); $newId = db_insert_id(); $logDescrip = "Send file from file repository (Send-It)"; log_event($query, "redcap_sendit_docs", "MANAGE", $newId, "document_id = $newId", $logDescrip); // Set email subject $subject = "[PRIORITIZE] " . $comment; $subject = html_entity_decode($subject, ENT_QUOTES); // Set email From address $from = array('Ken Bergquist' => '*****@*****.**'); // Begin set up of email to send to recipients $email = new Message(); foreach ($from as $name => $address) { $email->setFrom($address); $email->setFromName($name); } $email->setSubject($subject); // Loop through each recipient and send email foreach ($to as $name => $address) { // If a non-blank email address if (trim($address) != '') { // create key for unique url $key = strtoupper(substr(uniqid(md5(mt_rand())), 0, 25)); // create password $pwd = generateRandomHash(8, false, true); $query = "INSERT INTO redcap_sendit_recipients (email_address, sent_confirmation, download_date, download_count, document_id, guid, pwd) VALUES ('$address', 0, NULL, 0, $newId, '$key', '" . md5($pwd) . "')"; $q = db_query($query); // Download URL $url = APP_PATH_WEBROOT_FULL . 'redcap_v' . $redcap_version . '/SendIt/download.php?' . $key; // Message from sender $note = "$comment for $today"; // Get YMD timestamp of the file's expiration time $expireTimestamp = date('Y-m-d H:i:s', mktime($expireHour, $expireMin, 0, $expireMonth, $expireDay, $expireYear)); // Email body $body = "<html><body style=\"font-family:Arial;font-size:10pt;\"> $yourName {$lang['sendit_51']} \"$originalFilename\" {$lang['sendit_52']} " . date('l', mktime($expireHour, $expireMin, 0, $expireMonth, $expireDay, $expireYear)) . ", " . DateTimeRC::format_ts_from_ymd($expireTimestamp) . "{$lang['period']} {$lang['sendit_53']}<br><br> {$lang['sendit_54']}<br> <a href=\"$url\">$url</a><br><br> $note <br>-----------------------------------------------<br> {$lang['sendit_55']} " . CONSORTIUM_WEBSITE_DOMAIN . ". </body></html>"; // Construct email and send $email->setTo($address); $email->setToName($name); $email->setBody($body); if ($email->send()) { // Now send follow-up email containing password $bodypass = "******"font-family:Arial;font-size:10pt;\"> {$lang['sendit_50']}<br><br> $pwd<br><br> </body></html>"; $email->setSubject("Re: $subject"); $email->setBody($bodypass); sleep(2); // Hold for a second so that second email somehow doesn't reach the user first $email->send(); } else { error_log("ERROR: pid=$project_id: Email to $name <$address> NOT SENT"); } } } } unset($table_csv); } }
print "<script type='text/javascript'>\n\t\t\t\twindow.opener.location.reload();\n\t\t\t\tsetTimeout(function(){self.close();},2500);\n\t\t\t\t</script>"; //Query failed } else { print "<p><b>{$lang['global_01']}{$lang['colon']}</b> {$lang['calendar_popup_28']}</p>"; if (SUPER_USER) { print db_error() . "<br>QUERY:<br>{$sql}"; } } /** * DISPLAY CONFIRMATION THAT CALENDAR EVENT WAS DELETED */ } elseif (isset($_GET['cal_id']) && is_numeric($_GET['cal_id']) && !empty($_POST) && isset($_POST['deleteCalEv'])) { //Query to delete calendar event $sql = "delete from redcap_events_calendar where cal_id = " . $_GET['cal_id']; //Logging log_event($sql, "redcap_events_calendar", "MANAGE", $_GET['cal_id'], calLogChange($_GET['cal_id']), "Delete calendar event"); //Run query after logging because values will be deleted db_query($sql); //Show confirmation print "<div style='color:red;padding:30px 0 0 15px;margin-bottom:10px;font-weight:bold;font-size:16px;'>\n\t\t\t\t{$lang['calendar_popup_29']}<br><br><br>\n\t\t\t</div>"; //Render javascript to refresh calendar underneath and close pop-up print "<script type='text/javascript'>\n\t\t\twindow.opener.location.reload();\n\t\t\tsetTimeout(function(){self.close();},2500);\n\t\t\t</script>"; } /** * PAGE FOOTER */ callJSfile('Calendar.js'); $_GET['width'] = isset($_GET['width']) && is_numeric($_GET['width']) && $_GET['width'] < 1200 ? $_GET['width'] : 800; print "</div>\n\t\t<script type='text/javascript'>\n\t\t\$(function(){\n\t\t\t// Resize window to fit contents\n\t\t\tvar maxh = window.screen.height - 100;\n\t\t\tvar divh = document.getElementById('bodydiv').offsetHeight + 130;\n\t\t\tvar newh = (divh > maxh) ? maxh : divh;\n\t\t\twindow.resizeTo({$_GET['width']},newh);\n\t\t\t// Load calendar pop-up\n\t\t\t\$('#newdate').datepicker({buttonText: 'Click to select a date',yearRange: '-100:+10',changeMonth: true, changeYear: true, dateFormat: user_date_format_jquery});\t\t\t\t\t\t\n\t\t\t// Pop-up time-select initialization\n\t\t\t\$('.time').timepicker({hour: currentTime('h'), minute: currentTime('m'), timeFormat: 'hh:mm'});\n\t\t});\n\t\t</script>"; ?> </body>
*/ if (preg_match("/^([0-9]+) .*\$/", $vm_info["vmwVmMemSize"], $matches)) { $vm_info["vmwVmMemSize"] = $matches[1]; } /* * If VMware Tools is not running then don't overwrite the GuesOS with the error * message, but just leave it as it currently is. */ if (stristr($vm_info["vmwVmGuestOS"], 'tools not running') !== FALSE) { $vm_info["vmwVmGuestOS"] = $db_info["vmwVmGuestOS"]; } /* * Process all the VMware Virtual Machine properties. */ foreach ($vm_info as $property => $value) { /* * Check the property for any modifications. */ if ($vm_info[$property] != $db_info[$property]) { echo $vm_info[$property] . "!=" . $db_info[$property] . PHP_EOL; // FIXME - this should loop building a query and then run the query after the loop (bad geert!) dbUpdate(array($property => $vm_info[$property]), 'vminfo', '`id` = ?', array($db_info["id"])); log_event($db_info["vmwVmDisplayName"] . " (" . preg_replace("/^vmwVm/", "", $property) . ") -> " . $vm_info[$property], $device, 'vm'); } } } /* * Finished discovering VMware information. */ echo PHP_EOL; // EOF
if (!isset($p_list[$peer_ip][$peer_as]) && is_bgp_peer_valid($peer, $device)) { $p_list[$peer_ip][$peer_as] = 1; $peerlist[] = $peer; print_debug("Found peer IP: {$peer_ip} (AS{$peer_as}, LocalIP: {$local_ip})"); } } } else { $vendor_mib = FALSE; // Unset vendor_mib since not found on device } } # Vendors } else { echo "No BGP on host"; if (is_numeric($device['bgpLocalAs'])) { log_event('BGP ASN removed: AS' . $device['bgpLocalAs'], $device, 'bgp'); dbUpdate(array('bgpLocalAs' => array('NULL')), 'devices', 'device_id = ?', array($device['device_id'])); print_message('Removed ASN (' . $device['bgpLocalAs'] . ')'); } # End if } # End if // Process discovered peers $table_rows = array(); if (OBS_DEBUG > 1) { print_vars($peerlist); } if (isset($peerlist)) { // Walk vendor oids if ($vendor_mib) { if (!isset($vendor_use_index[$vendor_PeerRemoteAddrType])) {
} //end if $poll_device['sysLocation'] = str_replace('"', '', $poll_device['sysLocation']); // Remove leading & trailing backslashes added by VyOS/Vyatta/EdgeOS $poll_device['sysLocation'] = trim($poll_device['sysLocation'], '\\'); // Rewrite sysLocation if there is a mapping array (database too?) if (!empty($poll_device['sysLocation']) && (is_array($config['location_map']) || is_array($config['location_map_regex']))) { $poll_device['sysLocation'] = rewrite_location($poll_device['sysLocation']); } $poll_device['sysContact'] = str_replace('"', '', $poll_device['sysContact']); // Remove leading & trailing backslashes added by VyOS/Vyatta/EdgeOS $poll_device['sysContact'] = trim($poll_device['sysContact'], '\\'); foreach (array('sysLocation', 'sysContact') as $elem) { if ($poll_device[$elem] == 'not set') { $poll_device[$elem] = ''; } } // Save results of various polled values to the database foreach (array('sysContact', 'sysObjectID', 'sysName', 'sysDescr') as $elem) { if ($poll_device[$elem] && $poll_device[$elem] != $device[$elem]) { $update_array[$elem] = $poll_device[$elem]; log_event("{$elem} -> " . $poll_device[$elem], $device, 'system'); } } if ($poll_device['sysLocation'] && $device['location'] != $poll_device['sysLocation'] && $device['override_sysLocation'] == 0) { $update_array['location'] = $poll_device['sysLocation']; log_event('Location -> ' . $poll_device['sysLocation'], $device, 'system'); } if ($config['geoloc']['latlng'] === true) { location_to_latlng($device); }
$r->close(); break; } $r->close(); // Create user $q = "INSERT INTO users SET username='******', password='******', dt_lastlogin=NOW()"; if (@$m->query($q) === FALSE) { $page_error = "Sorry, an internal database error occured. Your account was NOT created. Wait a while and try again."; break; } // Add membership to the public group $q = "INSERT INTO group_members SET group_id=1, user_id='" . $m->escape_string($m->insert_id) . "'"; @$m->query($q); // Login user $q = "SELECT * FROM users WHERE username='******'"; $r = @$m->query($q); $row = $r->fetch_object(); $r->close(); $_SESSION["loggedin"] = TRUE; $_SESSION["u"] = $row; $_SESSION["groups"] = array(); $q = "SELECT groups.*, group_admin FROM group_members LEFT JOIN groups ON group_id=groups.id WHERE user_id='" . $m->escape_string($row->id) . "'"; if (($r = @$m->query($q)) !== FALSE) { while ($row = $r->fetch_object()) { $_SESSION["groups"][$row->id] = array("group" => $row->groupname, "admin" => $row->group_admin); } $r->close(); } log_event("User " . $_SESSION["u"]->username . " (id " . $_SESSION["u"]->id . ") registered"); header("Location: {$root_url}"); } while (0);
$_SESSION["groups"][$row->id] = array("group" => $row->groupname, "admin" => $row->group_admin, "dt_created" => $row->dt_created, "invite_code" => $row->invite_code); $r->close(); } else log_event("Login groups database error: $m->error. SQL: $q"); */ // Extract saved session cache, used for storing number of cracked hashes // for jobs for example $q = "SELECT * FROM sessioncache WHERE user_id='" . $m->escape_string($_SESSION["u"]->id) . "'"; if (($r = @$m->query($q)) !== FALSE) { if ($r->num_rows == 0) { $q = "INSERT INTO sessioncache SET user_id='" . $m->escape_string($_SESSION["u"]->id) . "', session='" . $m->escape_string(serialize(array())) . "'"; @$m->query($q); $_SESSION["c"] = array(); } else { $row = $r->fetch_object(); $_SESSION["c"] = unserialize($row->session); } $r->close(); } log_event("Login succeeded for user '" . $_POST["u"] . "'"); header("Location: {$root_url}"); } else { $page_error = "Oops, login failed. Make sure you typed in the right username and password."; log_event("Login failed for user '" . $_POST["u"] . "'"); } } else { log_event("Login database error: {$m->error}. SQL: {$q}"); $page_error = "Sorry, an internal database error occured. Try again in a bit!"; } }
if (count($update_array)) { dbUpdate($update_array, 'sensors', '`sensor_id` = ?', array($sensor['sensor_id'])); $msg = 'Sensor Limits updated (custom): ' . mres($sensor['sensor_class']) . ' ' . mres($sensor['sensor_type']) . ' ' . mres($sensor['sensor_id']) . ' ' . mres($sensor['sensor_descr']) . ' '; if ($update_array['sensor_limit_low']) { $msg .= '[L: ' . $update_array['sensor_limit_low'] . ']'; } if ($update_array['sensor_limit_low_warn']) { $msg .= '[Lw: ' . $update_array['sensor_limit_low_warn'] . ']'; } if ($update_array['sensor_limit_warn']) { $msg .= '[Hw: ' . $update_array['sensor_limit_warn'] . ']'; } if ($update_array['sensor_limit']) { $msg .= '[H: ' . $update_array['sensor_limit'] . ']'; } log_event($msg, $device, 'sensor', $sensor['sensor_id']); $did_update = TRUE; } unset($update_array); } // Query updated sensors array if ($did_update) { $sensors = dbFetchRows($query, array($device['device_id'])); } } //print_vars($_POST); ?> <form id='update-sensors' name='update-sensors' method='post' action=''> <fieldset> <legend>Sensor Properties</legend>
/** * print the platform field * @return void */ function print_filter_platform() { global $g_select_modifier, $g_filter; ?> <!-- Platform --> <select<?php echo $g_select_modifier; ?> name="<?php echo FILTER_PROPERTY_PLATFORM; ?> []"> <option value="<?php echo META_FILTER_ANY; ?> "<?php check_selected($g_filter[FILTER_PROPERTY_PLATFORM], (string) META_FILTER_ANY); ?> >[<?php echo lang_get('any'); ?> ]</option> <?php log_event(LOG_FILTERING, 'Platform = ' . var_export($g_filter[FILTER_PROPERTY_PLATFORM], true)); print_platform_option_list($g_filter[FILTER_PROPERTY_PLATFORM]); ?> </select> <?php }
} else { echo '.'; } } // Save the discovered Virtual Machine. $libvirt_vmlist[] = $dom_id; } //end if } //end foreach } //end if // If we found VMs, don't cycle the other protocols anymore. if (count($libvirt_vmlist)) { break; } } //end foreach // Get a list of all the known Virtual Machines for this host. $sql = "SELECT id, vmwVmVMID, vmwVmDisplayName FROM vminfo WHERE device_id = '" . $device['device_id'] . "' AND vm_type='libvirt'"; foreach (dbFetchRows($sql) as $db_vm) { // Delete the Virtual Machines that are removed from the host. if (!in_array($db_vm['vmwVmVMID'], $libvirt_vmlist)) { dbDelete('vminfo', '`id` = ?', array($db_vm['id'])); echo '-'; log_event('Virtual Machine removed: ' . $db_vm['vmwVmDisplayName'], $device, 'vm', $db_vm['id']); } } echo "\n"; } //end if
/** * execute query, requires connection to be opened * An error will be triggered if there is a problem executing the query. * @global array of previous executed queries for profiling * @global adodb database connection object * @global boolean indicating whether queries array is populated * @param string $p_query Parameterlised Query string to execute * @param array $arr_parms Array of parameters matching $p_query * @param int $p_limit Number of results to return * @param int $p_offset offset query results for paging * @return ADORecordSet|bool adodb result set or false if the query failed. */ function db_query_bound($p_query, $arr_parms = null, $p_limit = -1, $p_offset = -1) { global $g_queries_array, $g_db, $g_db_log_queries, $g_db_param_count; $t_db_type = config_get_global('db_type'); static $s_check_params; if ($s_check_params === null) { $s_check_params = db_is_pgsql() || $t_db_type == 'odbc_mssql' || $t_db_type == 'mssqlnative'; } if (ON == $g_db_log_queries) { $t_start = microtime(true); $t_backtrace = debug_backtrace(); $t_caller = basename($t_backtrace[0]['file']); $t_caller .= ":" . $t_backtrace[0]['line']; # Is this called from another function? if (isset($t_backtrace[1])) { $t_caller .= ' ' . $t_backtrace[1]['function'] . '()'; } else { # or from a script directly? $t_caller .= ' - '; } } if ($arr_parms != null && $s_check_params) { $params = count($arr_parms); for ($i = 0; $i < $params; $i++) { if ($arr_parms[$i] === false) { $arr_parms[$i] = 0; } elseif ($arr_parms[$i] === true && $t_db_type == 'mssqlnative') { $arr_parms[$i] = 1; } } } if ($p_limit != -1 || $p_offset != -1) { $t_result = $g_db->SelectLimit($p_query, $p_limit, $p_offset, $arr_parms); } else { $t_result = $g_db->Execute($p_query, $arr_parms); } if (ON == $g_db_log_queries) { $t_elapsed = number_format(microtime(true) - $t_start, 4); $lastoffset = 0; $i = 0; if (!(is_null($arr_parms) || empty($arr_parms))) { while (preg_match('/\\?/', $p_query, $matches, PREG_OFFSET_CAPTURE, $lastoffset)) { $matches = $matches[0]; # Realign the offset returned by preg_match as it is byte-based, # which causes issues with UTF-8 characters in the query string # (e.g. from custom fields names) $t_utf8_offset = utf8_strlen(substr($p_query, 0, $matches[1]), mb_internal_encoding()); if ($i <= count($arr_parms)) { if (is_null($arr_parms[$i])) { $replace = 'NULL'; } else { if (is_string($arr_parms[$i])) { $replace = "'" . $arr_parms[$i] . "'"; } else { if (is_integer($arr_parms[$i]) || is_float($arr_parms[$i])) { $replace = (double) $arr_parms[$i]; } else { if (is_bool($arr_parms[$i])) { switch ($t_db_type) { case 'pgsql': $replace = "'" . $arr_parms[$i] . "'"; break; default: $replace = $arr_parms[$i]; break; } } else { echo "Invalid argument type passed to query_bound(): " . $i + 1; exit(1); } } } } $p_query = utf8_substr($p_query, 0, $t_utf8_offset) . $replace . utf8_substr($p_query, $t_utf8_offset + utf8_strlen($matches[0])); $lastoffset = $matches[1] + strlen($replace) + 1; } else { $lastoffset = $matches[1] + 1; } $i++; } } log_event(LOG_DATABASE, var_export(array($p_query, $t_elapsed, $t_caller), true)); array_push($g_queries_array, array($p_query, $t_elapsed, $t_caller)); } else { array_push($g_queries_array, 1); } # We can't reset the counter because we have queries being built # and executed while building bigger queries in filter_api. -jreese # $g_db_param_count = 0; if (!$t_result) { db_error($p_query); trigger_error(ERROR_DB_QUERY_FAILED, ERROR); return false; } else { return $t_result; } }
echo '+'; // FIXME eventlog } else { echo '.'; } /* * Save the discovered Virtual Machine. */ $vmw_vmlist[] = $index; } /* * Get a list of all the known Virtual Machines for this host. */ $sql = "SELECT id, vmwVmVMID, vmwVmDisplayName FROM vminfo WHERE device_id = '" . $device['device_id'] . "' AND vm_type='vmware'"; foreach (dbFetchRows($sql) as $db_vm) { /* * Delete the Virtual Machines that are removed from the host. */ if (!in_array($db_vm['vmwVmVMID'], $vmw_vmlist)) { dbDelete('vminfo', '`id` = ?', array($db_vm['id'])); log_event(mres($db_vm['vmwVmDisplayName']) . ' Removed', $device, 'system', $db_vm['vmwVmVMID']); echo '-'; // FIXME eventlog } } /* * Finished discovering VMware information. */ echo "\n"; } //end if
} } } //end if } //end if if ($bgpPeerFsmEstablishedTime) { if (!(is_array($config['alerts']['bgp']['whitelist']) && !in_array($peer['bgpPeerRemoteAs'], $config['alerts']['bgp']['whitelist'])) && ($bgpPeerFsmEstablishedTime < $peer['bgpPeerFsmEstablishedTime'] || $bgpPeerState != $peer['bgpPeerState'])) { if ($peer['bgpPeerState'] == $bgpPeerState) { log_event('BGP Session Flap: ' . $peer['bgpPeerIdentifier'] . ' (AS' . $peer['bgpPeerRemoteAs'] . ')', $device, 'bgpPeer', $bgpPeer_id); } else { if ($bgpPeerState == 'established') { log_event('BGP Session Up: ' . $peer['bgpPeerIdentifier'] . ' (AS' . $peer['bgpPeerRemoteAs'] . ')', $device, 'bgpPeer', $bgpPeer_id); } else { if ($peer['bgpPeerState'] == 'established') { log_event('BGP Session Down: ' . $peer['bgpPeerIdentifier'] . ' (AS' . $peer['bgpPeerRemoteAs'] . ')', $device, 'bgpPeer', $bgpPeer_id); } } } } } $peerrrd = $config['rrd_dir'] . '/' . $device['hostname'] . '/' . safename('bgp-' . $peer['bgpPeerIdentifier'] . '.rrd'); if (!is_file($peerrrd)) { $create_rrd = 'DS:bgpPeerOutUpdates:COUNTER:600:U:100000000000 DS:bgpPeerInUpdates:COUNTER:600:U:100000000000 DS:bgpPeerOutTotal:COUNTER:600:U:100000000000 DS:bgpPeerInTotal:COUNTER:600:U:100000000000 DS:bgpPeerEstablished:GAUGE:600:0:U ' . $config['rrd_rra']; rrdtool_create($peerrrd, $create_rrd); } $fields = array('bgpPeerOutUpdates' => $bgpPeerOutUpdates, 'bgpPeerInUpdates' => $bgpPeerInUpdates, 'bgpPeerOutTotal' => $bgpPeerOutTotalMessages, 'bgpPeerInTotal' => $bgpPeerInTotalMessages, 'bgpPeerEstablished' => $bgpPeerFsmEstablishedTime);
function createHost($hostname, $snmp_community = NULL, $snmp_version, $snmp_port = 161, $snmp_transport = 'udp', $snmp_v3 = array()) { $hostname = trim(strtolower($hostname)); $device = array('hostname' => $hostname, 'sysName' => $hostname, 'status' => '1', 'snmp_community' => $snmp_community, 'snmp_port' => $snmp_port, 'snmp_transport' => $snmp_transport, 'snmp_version' => $snmp_version); // Add snmp v3 auth params foreach (array('authlevel', 'authname', 'authpass', 'authalgo', 'cryptopass', 'cryptoalgo') as $v3_key) { if (isset($snmp_v3['snmp_' . $v3_key])) { // Or $snmp_v3['snmp_authlevel'] $device['snmp_' . $v3_key] = $snmp_v3['snmp_' . $v3_key]; } else { if (isset($snmp_v3[$v3_key])) { // Or $snmp_v3['authlevel'] $device['snmp_' . $v3_key] = $snmp_v3[$v3_key]; } } } // This is compatibility code after refactor in r6306, for keep devices up before DB updated if (get_db_version() < 189) { // FIXME. Remove this in r7000 $device['snmpver'] = $device['snmp_version']; unset($device['snmp_version']); foreach (array('transport', 'port', 'timeout', 'retries', 'community', 'authlevel', 'authname', 'authpass', 'authalgo', 'cryptopass', 'cryptoalgo') as $old_key) { if (isset($device['snmp_' . $old_key])) { // Convert to old device snmp keys $device[$old_key] = $device['snmp_' . $old_key]; unset($device['snmp_' . $old_key]); } } } $device['os'] = get_device_os($device); $device['snmpEngineID'] = snmp_cache_snmpEngineID($device); $device['sysName'] = snmp_get($device, "sysName.0", "-Oqv", "SNMPv2-MIB", mib_dirs()); $device['location'] = snmp_get($device, "sysLocation.0", "-Oqv", "SNMPv2-MIB", mib_dirs()); $device['sysContact'] = snmp_get($device, "sysContact.0", "-Oqv", "SNMPv2-MIB", mib_dirs()); if ($device['os']) { $device_id = dbInsert($device, 'devices'); if ($device_id) { log_event("设备添加: {$hostname}", $device_id, 'device', $device_id, 5); // severity 5, for logging user/console info if (is_cli()) { print_success("正在使用自动发现功能 " . $device['hostname'] . " (id = " . $device_id . ")"); $device['device_id'] = $device_id; // Discover things we need when linking this to other hosts. discover_device($device, $options = array('m' => 'ports')); discover_device($device, $options = array('m' => 'ipv4-addresses')); discover_device($device, $options = array('m' => 'ipv6-addresses')); log_event("snmpEngineID -> " . $device['snmpEngineID'], $device, 'device', $device['device_id']); // Reset `last_discovered` for full rediscover device by cron dbUpdate(array('last_discovered' => 'NULL'), 'devices', '`device_id` = ?', array($device_id)); array_push($GLOBALS['devices'], $device_id); } return $device_id; } else { return FALSE; } } else { return FALSE; } }
function calc_accts() { global $DB, $error_ar; echo "Billing accounts ...\n"; $start_time = microtime(1); //$n = 0; $account_result = $DB->make_select('Accounts'); //$account_result = $DB->make_select('Accounts', '', "`status`='Open'"); for ($n = 0; $account_row = $DB->row($account_result); $n++) { $status = $account_row['status']; $amount = $account_row['amount']; $bonustime = $account_row['bonustime']; //$statusinfo = $account_row['statusinfo']; $NOW = date('Y-m-d H:i:s'); $now = strtotime($NOW); //$now = time(); $addsql = array(); if ($status == 'Active') { $account = new Account(); $account->load($account_row); list($amount, $bonustime, $closetime) = $account->getBalance(); $ostperiod = $closetime - $now; $ostdays = round($ostperiod / iDAY, 0); $addsql['closetime'] = date('Y-m-d H:i:s', $closetime); if ($ostperiod + iDAY * $account->billing_opts['credit_days'] <= 0) { echo "Suspend account {$account->domain} (id={$account->id})\n"; if (ACTION) { if ($account->suspend(false)) { } $account->mail_send(3); } } elseif ($ostdays == 7 || $ostdays == 3 || $ostdays <= 1) { echo "Send mail to account {$account->domain} ({$account->contact->Email}) with '{$status}' status about close date in {$ostdays} days\n"; if (ACTION) { $account->mail_send(2); } } unset($account); $addsql['amount'] = $amount; $addsql['bonustime'] = $bonustime; } elseif ($status == 'Open') { $account = new Account(); $account->load($account_row); //$amount = 0; $bonustime = 0; $period_live = $now - strtotime($account_row['opentime']); $days_live = round($period_live / iDAY, 0); if ($days_live == 25) { if (ACTION) { $account->mail_send(2); } echo "Send mail to account {$account->domain} ({$account->contact->Email}) with '{$status}' status about close date in {$ostdays} days\n"; } elseif ($days_live >= 30) { echo "Close account {$account->domain} (id={$account->id})\n"; if (ACTION) { if ($account->suspend(false)) { } $account->mail_send(3); } } unset($account); //$addsql['amount'] = $amount; //$addsql['bonustime'] = $bonustime; } elseif ($status == 'Suspend') { $account = new Account(); $account->load($account_row); $period = $now - strtotime($account_row['closetime']); if ($period >= 60 * iDAY) { echo "Delete account {$account_row['domain']} (id={$account_row['AccountID']})\n"; if (ACTION) { log_event('delete account', 'notice', '', $account_row['AccountID'], $account_row['ResellerID']); $whm = new WhmAPI($account->ServerID); $result = $whm->killacct($account); if ($result) { //echo nl2br($whm->xml->rawout); } else { echo $whm->geterrmsg(); } } $addsql['status'] = 'Deleted'; //$addsql['statusinfo'] = "$statusinfo\nautomatic deleted $NOW"; } } elseif ($status == 'Deleted') { $addsql['lastproc'] = 0; // pack and archive account if closetime > 6 * iMON } elseif ($status == 'Staff') { // our accounts } else { $error_ar[] = "Unknown Status for account {$account_row['domain']} (id={$account_row['AccountID']})\n"; } if (ACTION) { $addsql['lastproc'] = $NOW; $result = $DB->make_update('Accounts', '`AccountID`=' . $account_row['AccountID'], $addsql); } //$n++; } echo "Finished Step. {$n} account calculated. Time " . intval((microtime(1) - $start_time) * 1000) . "ms.\n\n"; }
<?php if (isset($_GET["cancel"])) { ?> <h1>Upgrade canceled</h1> <p>You canceled the payment.</p> <?php } else { log_event("User paid for the services"); $q = "UPDATE users SET user_flags = user_flags | " . USER_FLAG_PREMIUM . " WHERE id='" . $m->escape_string($_SESSION["u"]->id) . "'"; if (@$m->query($q) === FALSE) { log_event("Failed to reflect payment in users-table: {$m->error}\nSQL: {$q}"); } $_SESSION["u"]->user_flags |= USER_FLAG_PREMIUM; ?> <h1>Your account has been upgraded</h1> <p>Thank you for your payment. Your transaction has been completed, and a receipt for your purchase has been emailed to you. You may log into your account at <a href="https://www.paypal.com/row" target="_blank">www.paypal.com/row</a> to view details of this transaction.</p> <?php } ?> <p><a href="/">Continue to the frontpage</a></p>