$max_length) {
return substr($text, 0, $max_length) . '...';
}else{
return $text;
}
}
/* cacti_htmlspecialchars - filter dangerous specialchars but everything
@arg $value - the string to protect
@returns - the escaped string */
function cacti_htmlspecialchars($value) {
static $charset;
if ($charset == '') {
$charset = ini_get('default_charset');
}
if (strpos($value, '
name format
* @arg $cc - either a string of comma delimited email addresses, or an array of addresses in email_address => name format
* @arg $bcc - either a string of comma delimited email addresses, or an array of addresses in email_address => name format
* @arg $replyto - a string email address, or an array in array(email_address, name format)
* @arg $subject - the email subject
* @arg $body - the email body, in HTML format. If content_text is not set, the function will attempt to extract
* from the HTML format.
* @arg $body_text - the email body in TEXT format. If set, it will override the stripping tags method
* @arg $attachments - the emails attachments as an array
* @arg $headers - an array of name value pairs representing custom headers.
* @arg $html - if set to true, html is the default, otherwise text format will be used
*/
function mailer($from, $to, $cc, $bcc, $replyto, $subject, $body, $body_text = '', $attachments, $headers, $html = true) {
global $config;
include_once($config['include_path'] . '/phpmailer/PHPMailerAutoload.php');
// Set the to informaiotn
if ($to == '') {
return __('Mailer Error: No TO address set!!
If using the Test Mail link, please set the Alert e-mail setting.');
}
if (is_array($to)) {
$toText = $to[1] . ' <' . $to[0] . '>';
}else{
$toText = $to;
}
if (is_array($from)) {
$fromText = $from[1] . ' <' . $from[0] . '>';
}else{
$fromText = $from;
}
$body = str_replace('', $subject, $body);
$body = str_replace('', $toText, $body);
$body = str_replace('', $fromText, $body);
// Create the PHPMailer instance
$mail = new PHPMailer;
// Set a reasonable timeout of 5 seconds
$timeout = read_config_option('settings_smtp_timeout');
if (empty($timeout) || $timeout < 0 || $timeout > 300) {
$mail->Timeout = 5;
}else{
$mail->Timeout = $timeout;
}
// Set the subject
$mail->Subject = $subject;
$how = read_config_option('settings_how');
if ($how < 0 || $how > 2) {
$how = 0;
}
if ($how == 0) {
$mail->isMail();
} else if ($how == 1) {
$mail->Sendmail = read_config_option('settings_sendmail_path');
$mail->isSendmail();
} else if ($how == 2) {
$mail->isSMTP();
$mail->Host = read_config_option('settings_smtp_host');
$mail->Port = read_config_option('settings_smtp_port');
$mail->Username = read_config_option('settings_smtp_username');
$mail->Password = read_config_option('settings_smtp_password');
if ($mail->Username != '') {
$mail->SMTPAuth = true;
}
// Set a reasonable timeout of 5 seconds
$timeout = read_config_option('settings_smtp_timeout');
if (empty($timeout) || $timeout < 0 || $timeout > 300) {
$mail->Timeout = 5;
}else{
$mail->Timeout = $timeout;
}
$secure = read_config_option('settings_smtp_secure');
if (!empty($secure) && $secure != 'none') {
$mail->SMTPSecure = $secure;
if (substr_count($mail->Host, ':') == 0) {
$mail->Host = $secure . '://' . $mail->Host;
}
}
}
// Set the from information
if (!is_array($from)) {
$fromname = '';
if ($from == '') {
$from = read_config_option('settings_from_email');
$fromname = read_config_option('settings_from_name');
if (isset($_SERVER['HOSTNAME'])) {
$from = 'Cacti@' . $_SERVER['HOSTNAME'];
} else {
$from = 'Cacti@cacti.net';
}
if ($fromname == '') {
$fromname = 'Cacti';
}
}
$mail->setFrom($from, $fromname);
}else{
$mail->setFrom($from[0], $from[1]);
}
if (!is_array($to)) {
$to = explode(',', $to);
foreach($to as $t) {
$t = trim($t);
if ($t != '') {
$mail->addAddress($t);
}
}
}else{
foreach($to as $email => $name) {
$mail->addAddress($email, $name);
}
}
if (!is_array($cc)) {
if ($cc != '') {
$cc = explode(',', $cc);
foreach($cc as $c) {
$c = trim($c);
$mail->addCC($c);
}
}
}else{
foreach($cc as $email => $name) {
$mail->addCC($email, $name);
}
}
if (!is_array($bcc)) {
if ($bcc != '') {
$bcc = explode(',', $bcc);
foreach($bcc as $bc) {
$bc = trim($bc);
$mail->addBCC($bc);
}
}
}else{
foreach($bcc as $email => $name) {
$mail->addBCC($email, $name);
}
}
if (!is_array($replyto)) {
if ($replyto != '') {
$mail->replyTo($replyto);
}
}else{
$mail->replyTo($replyto[0], $replyto[1]);
}
// Set the wordwrap limits
$wordwrap = read_config_option('settings_wordwrap');
if ($wordwrap == '') {
$wordwrap = 76;
}elseif ($wordwrap > 9999) {
$wordwrap = 9999;
}elseif ($wordwrap < 0) {
$wordwrap = 76;
}
$mail->WordWrap = $wordwrap;
$mail->setWordWrap();
$i = 0;
// Handle Graph Attachments
if (is_array($attachments) && sizeof($attachments) && substr_count($body, '') > 0) {
foreach($attachments as $attachment) {
if ($attachment['attachment'] != '') {
/* get content id and create attachment */
$cid = getmypid() . '_' . $i . '@' . 'localhost';
/* attempt to attach */
if ($mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']) === false) {
cacti_log('ERROR: ' . $mail->ErrorInfo, false);
return $mail->ErrorInfo;
}
$body = str_replace('', "
", $body);
$i++;
} else {
$body = str_replace('' . $attachment['local_graph_id'] . '>', "
Could not open!
" . $attachment['filename'], $body);
}
}
}elseif (is_array($attachments) && sizeof($attachments) && substr_count($body, ' 0) {
foreach($attachments as $attachment) {
if ($attachment['attachment'] != '') {
/* get content id and create attachment */
$cid = getmypid() . '_' . $i . '@' . 'localhost';
/* attempt to attach */
if ($mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']) === false) {
cacti_log('ERROR: ' . $mail->ErrorInfo, false);
return $mail->ErrorInfo;
}
/* handle the body text */
switch ($attachment['inline']) {
case 'inline':
$body = str_replace('', "
", $body);
break;
case 'attachment':
$body = str_replace('', '', $body);
break;
}
$i++;
} else {
$body = str_replace('', "
Could not open!
" . $attachment['filename'], $body);
}
}
}
/* process custom headers */
if (is_array($headers) && sizeof($headers)) {
foreach($headers as $name => $value) {
$mail->addCustomHeader($name, $value);
}
}
// Set both html and non-html bodies
$text = array('text' => '', 'html' => '');
if ($body_text != '' && $html == true) {
$text['html'] = $body . '
';
$text['text'] = $body_text;
$mail->isHTML(true);
$mail->Body = $text['html'];
$mail->AltBody = $text['text'];
}elseif ($attachments == '' && $html == false) {
if ($body_text != '') {
$body = $body_text;
}else{
$body = str_replace('
', "\n", $body);
$body = str_replace('
', "\n", $body);
$body = str_replace('', "\n", $body);
}
$text['text'] = strip_tags($body);
$mail->isHTML(false);
$mail->Body = $text['text'];
$mail->AltBody = $text['text'];
} elseif ($html == false) {
$text['text'] = strip_tags($body);
$mail->isHTML(false);
$mail->Body = $text['text'];
$mail->AltBody = $text['text'];
} else {
$text['html'] = $body . '
';
$text['text'] = strip_tags(str_replace('
', "\n", $body));
$mail->isHTML(true);
$mail->Body = $text['html'];
$mail->AltBody = $text['text'];
}
if ($mail->send()) {
cacti_log("Mail Sucessfully Sent to '" . $toText . "', Subject: '" . $mail->Subject . "'", false, 'MAILER');
return '';
}else{
cacti_log("Mail Failed to '" . $toText . "', Subject: '" . $mail->Subject . "'", false, 'MAILER');
return $mail->ErrorInfo;
}
}
function ping_mail_server($host, $port, $user, $password, $timeout = 5, $secure = 'none') {
global $config;
include_once($config['include_path'] . '/phpmailer/PHPMailerAutoload.php');
//Create a new SMTP instance
$smtp = new SMTP;
if ($secure != 'tls' && $secure != 'none') {
$smtp->SMTPSecure = $secure;
if (substr_count($host, ':') == 0) {
$host = $secure . '://' . $host;
}
}
//Enable connection-level debug output
$smtp->do_debug = 0;
//$smtp->do_debug = SMTP::DEBUG_LOWLEVEL;
$results = true;
try {
//Connect to an SMTP server
if ($smtp->connect($host, $port, $timeout)) {
//Say hello
if ($smtp->hello(gethostbyname(gethostname()))) { //Put your host name in here
//Authenticate
if ($smtp->authenticate($user, $password)) {
$results = true;
} else {
throw new Exception(__('Authentication failed: %s', $smtp->getLastReply()));
}
} else {
throw new Exception(__('HELO failed: %s', $smtp->getLastReply()));
}
} else {
throw new Exception(__('Connect failed'));
}
} catch (Exception $e) {
$results = __('SMTP error: ') . $e->getMessage();
}
//Whatever happened, close the connection.
$smtp->quit(true);
return $results;
}
function email_test() {
global $config;
$message = __('This is a test message generated from Cacti. This message was sent to test the configuration of your Mail Settings.') . '
';
$message .= __('Your email settings are currently set as follows') . '
';
$message .= '' . __('Method') . ': ';
print __('Checking Configuration...
');
$ping_results = true;
$how = read_config_option('settings_how');
if ($how < 0 || $how > 2)
$how = 0;
if ($how == 0) {
$mail = __('PHP\'s Mailer Class');
} else if ($how == 1) {
$mail = __('Sendmail') . '
' . __('Sendmail Path'). ': ';
$sendmail = read_config_option('settings_sendmail_path');
$mail .= $sendmail;
} else if ($how == 2) {
print __('Method: SMTP') . '
';
$mail = __('SMTP') . '
';
$smtp_host = read_config_option('settings_smtp_host');
$smtp_port = read_config_option('settings_smtp_port');
$smtp_username = read_config_option('settings_smtp_username');
$smtp_password = read_config_option('settings_smtp_password');
$smtp_secure = read_config_option('settings_smtp_secure');
$smtp_timeout = read_config_option('settings_smtp_timeout');
$mail .= "" . __('Device') . ": $smtp_host
";
$mail .= "" . __('Port') . ": $smtp_port
";
if ($smtp_username != '' && $smtp_password != '') {
$mail .= '' . __('Authentication') . ': true
';
$mail .= '' . __('Username') . ": $smtp_username
";
$mail .= '' . __('Password') . ': (' . _('Not Shown for Security Reasons') . ')
';
$mail .= '' . __('Security') . ": $smtp_secure
";
} else {
$mail .= '' . __('Authentication') . ': false
';
}
$ping_results = ping_mail_server($smtp_host, $smtp_port, $smtp_username, $smtp_password, $smtp_timeout, $smtp_secure);
print __('Ping Results:') . ' ' . ($ping_results == 1 ? __('Success'):$ping_results) . '
';
if ($ping_results != 1) {
$mail .= '' . __('Ping Results') . ': ' . $ping_results . '
';
}else{
$mail .= '' . __('Ping Results') . ': ' . __('Success') . '
';
}
}
$message .= $mail;
$message .= '
';
$errors = '';
if ($ping_results == 1) {
print __('Creating Message Text...') . '
';
print "
";
print __('Sending Message...') . '
';
$global_alert_address = read_config_option('settings_test_email');
$errors = send_mail($global_alert_address, '', __('Cacti Test Message'), $message, '', '', true);
if ($errors == '') {
$errors = __('Success!');
}
}else{
print __('Message Not Sent due to ping failure.'). '
';
}
print "";
}
/* gethostbyaddr_wtimeout - This function provides a good method of performing
a rapid lookup of a DNS entry for a host so long as you don't have to look far.
*/
function get_dns_from_ip ($ip, $dns, $timeout = 1000) {
/* random transaction number (for routers etc to get the reply back) */
$data = rand(10, 99);
/* trim it to 2 bytes */
$data = substr($data, 0, 2);
/* create request header */
$data .= "\1\0\0\1\0\0\0\0\0\0";
/* split IP into octets */
$octets = explode('.', $ip);
/* perform a quick error check */
if (count($octets) != 4) return 'ERROR';
/* needs a byte to indicate the length of each segment of the request */
for ($x=3; $x>=0; $x--) {
switch (strlen($octets[$x])) {
case 1: // 1 byte long segment
$data .= "\1"; break;
case 2: // 2 byte long segment
$data .= "\2"; break;
case 3: // 3 byte long segment
$data .= "\3"; break;
default: // segment is too big, invalid IP
return 'ERROR';
}
/* and the segment itself */
$data .= $octets[$x];
}
/* and the final bit of the request */
$data .= "\7in-addr\4arpa\0\0\x0C\0\1";
/* create UDP socket */
$handle = @fsockopen("udp://$dns", 53);
@stream_set_timeout($handle, floor($timeout/1000), ($timeout*1000)%1000000);
@stream_set_blocking($handle, 1);
/* send our request (and store request size so we can cheat later) */
$requestsize = @fwrite($handle, $data);
/* get the response */
$response = @fread($handle, 1000);
/* check to see if it timed out */
$info = @stream_get_meta_data($handle);
/* close the socket */
@fclose($handle);
if ($info['timed_out']) {
return 'timed_out';
}
/* more error handling */
if ($response == '') { return $ip; }
/* parse the response and find the response type */
$type = @unpack('s', substr($response, $requestsize+2));
if (isset($type[1]) && $type[1] == 0x0C00) {
/* set up our variables */
$host = '';
$len = 0;
/* set our pointer at the beginning of the hostname uses the request
size from earlier rather than work it out.
*/
$position = $requestsize + 12;
/* reconstruct the hostname */
do {
/* get segment size */
$len = unpack('c', substr($response, $position));
/* null terminated string, so length 0 = finished */
if ($len[1] == 0) {
/* return the hostname, without the trailing '.' */
return strtoupper(substr($host, 0, strlen($host) -1));
}
/* add the next segment to our host */
$host .= substr($response, $position+1, $len[1]) . '.';
/* move pointer on to the next segment */
$position += $len[1] + 1;
} while ($len != 0);
/* error - return the hostname we constructed (without the . on the end) */
return strtoupper($ip);
}
/* error - return the hostname */
return strtoupper($ip);
}
function poller_maintenance () {
global $config;
$command_string = trim(read_config_option('path_php_binary'));
// If its not set, just assume its in the path
if (trim($command_string) == '') {
$command_string = 'php';
}
$extra_args = ' -q ' . $config['base_path'] . '/poller_maintenance.php';
exec_background($command_string, $extra_args);
}
function clog_admin() {
if (!isset($_SESSION['sess_clog_level'])) {
clog_authorized();
}
if ($_SESSION["sess_clog_level"] == CLOG_PERM_ADMIN) {
return true;
}else{
return false;
}
}
function clog_authorized() {
if (!isset($_SESSION['sess_clog_level'])) {
if (isset($_SESSION['sess_user_id'])) {
if (is_realm_allowed(18)) {
$_SESSION['sess_clog_level'] = CLOG_PERM_ADMIN;
}else{
if (is_realm_allowed(19)) {
$_SESSION['sess_clog_level'] = CLOG_PERM_USER;
}else {
$_SESSION['sess_clog_level'] = CLOG_PERM_NONE;
}
}
}else{
$_SESSION['sess_clog_level'] = CLOG_PERM_NONE;
}
}
if ($_SESSION['sess_clog_level'] == CLOG_PERM_USER) {
return true;
}elseif ($_SESSION['sess_clog_level'] == CLOG_PERM_ADMIN) {
return true;
}else{
return false;
}
}
function update_system_mibs($host_id) {
global $sessions;
$system_mibs = array(
'snmp_sysDescr' => '.1.3.6.1.2.1.1.1.0',
'snmp_sysObjectID' => '.1.3.6.1.2.1.1.2.0',
'snmp_sysUpTimeInstance' => '.1.3.6.1.2.1.1.3.0',
'snmp_sysContact' => '.1.3.6.1.2.1.1.4.0',
'snmp_sysName' => '.1.3.6.1.2.1.1.5.0',
'snmp_sysLocation' => '.1.3.6.1.2.1.1.6.0'
);
$h = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id));
if (sizeof($h)) {
open_snmp_session($host_id, $h);
if (isset($sessions[$host_id . '_' . $h['snmp_version']])) {
foreach($system_mibs as $name => $oid) {
$value = cacti_snmp_session_get($sessions[$host_id . '_' . $h['snmp_version']], $oid);
if (!empty($value)) {
db_execute_prepared("UPDATE host SET $name = ? WHERE id = ?",
array($value, $host_id));
}
}
}else{
cacti_log("WARNING: Unable to open session for System Mib collection for Device[$host_id]", false, 'POLLER');
}
}
}
function cacti_debug_backtrace($entry = '', $html = false) {
global $config;
$callers = debug_backtrace();
$s = '';
foreach ($callers as $c) {
if (isset($c['file'])) {
$file = str_replace($config['base_path'], '', $c['file']);
}else{
$file = '';
}
if (isset($c['line'])) {
$line = $c['line'];
}else{
$line = '';
}
$func = $c['function'];
$s = "(" . ($file != '' ? "$file: ":'') . ($line != '' ? "$line ":'') . "$func)" . $s;
}
if ($html) {
echo "\n";
}
cacti_log(trim("$entry Backtrace: $s"), false);
}
/* calculate_percentiles - Given and array of numbers, calculate the Nth percentile,
* optionally, return an array of numbers containing elements required for
* a whisker chart.
*
* @arg $data - an array of data
* @arg $percentile - the Nth percentile to calculate. By default 95th.
* #arg $whisker - if whisker is true, an array of values will be returne
* including 25th, median, 75th, and 90th perecentiles.
*
* @returns - either the Nth percentile, the elements for a whisker chart,
* or false if there is insufficient data to determine. */
function calculate_percentiles($data, $percentile = 95, $whisker = false) {
if ($percentile > 0 && $percentile < 1) {
$p = $percentile;
}elseif ($percentile > 1 && $percentile <= 100) {
$p = $percentile * .01;
}else {
return false;
}
if ($whisker) {
$tiles = array(
'25th' => 0.25,
'50th' => 0.50,
'75th' => 0.75,
'90th' => 0.90,
'95th' => 0.95,
);
}else{
$tiles = array(
'custom' => $p
);
}
$results = array();
$elements = sizeof($data);
/* sort the array to return */
sort($data);
foreach($tiles as $index => $p) {
/* calculate offsets into the array */
$allindex = ($elements - 1) * $p;
$intvalindex = intval($allindex);
$floatval = $allindex - $intvalindex;
if (!is_float($floatval)) {
$ptile = $data[$intvalindex];
} else {
if ($elements > $intvalindex + 1) {
$ptile = $floatval * ($data[$intvalindex + 1] - $data[$intvalindex]) + $data[$intvalindex];
} else {
$ptile = $data[$intvalindex];
}
}
if ($index == 'custom') {
return $ptile;
}else{
$results[$index] = $ptile;
}
}
return $result;
}
function get_timeinstate($host) {
$interval = read_config_option('poller_interval');
if ($host['status_event_count'] > 0) {
$time = $host['status_event_count'] * $interval;
}elseif (strtotime($host['status_rec_date']) > 943916400) {
$time = time() - strtotime($host['status_rec_date']);
}else{
$time = $host['snmp_sysUpTimeInstance']/100;
}
if ($time > 86400) {
$days = floor($time/86400);
$time %= 86400;
}else{
$days = 0;
}
if ($time > 3600) {
$hours = floor($time/3600);
$time %= 3600;
}else{
$hours = 0;
}
$minutes = floor($time/60);
return $days . 'd:' . $hours . 'h:' . $minutes . 'm';
}
function get_classic_tabimage($text, $down = false) {
global $config;
$images = array(
false => 'tab_template_blue.gif',
true => 'tab_template_red.gif'
);
if ($text == '') return false;
$text = strtolower($text);
$possibles = array(
array('DejaVuSans-Bold.ttf', 9, true),
array('DejaVuSansCondensed-Bold.ttf', 9, false),
array('DejaVuSans-Bold.ttf', 9, false),
array('DejaVuSansCondensed-Bold.ttf', 9, false),
array('DejaVuSans-Bold.ttf', 8, false),
array('DejaVuSansCondensed-Bold.ttf', 8, false),
array('DejaVuSans-Bold.ttf', 7, false),
array('DejaVuSansCondensed-Bold.ttf', 7, true),
);
$y = 30;
$x = 44;
$wlimit = 72;
$wrapsize = 12;
if (file_exists($config['base_path'] . '/images/' . $images[$down])) {
$originalpath = getenv('GDFONTPATH');
putenv('GDFONTPATH=' . $config['base_path'] . '/include/fonts/');
$template = imagecreatefromgif($config['base_path'] . '/images/' . $images[$down]);
$w = imagesx($template);
$h = imagesy($template);
$tab = imagecreatetruecolor($w, $h);
imagecopy($tab, $template, 0, 0, 0, 0, $w, $h);
$txcol = imagecolorat($tab, 0, 0);
imagecolortransparent($tab,$txcol);
$white = imagecolorallocate($tab, 255, 255, 255);
foreach ($possibles as $variation) {
$font = $variation[0];
$fontsize = $variation[1];
$lines = array();
// if no wrapping is requested, or no wrapping is possible...
if((!$variation[2]) || ($variation[2] && strpos($text,' ') === false)) {
$bounds = imagettfbbox($fontsize, 0, $font, $text);
$w = $bounds[4] - $bounds[0];
$h = $bounds[1] - $bounds[5];
$realx = $x - $w/2 -1;
$lines[] = array($text, $font, $fontsize, $realx, $y);
$maxw = $w;
} else {
$texts = explode("\n", wordwrap($text, $wrapsize), 2);
$line = 1;
$maxw = 0;
foreach ($texts as $txt) {
$bounds = imagettfbbox($fontsize, 0, $font, $txt);
$w = $bounds[4] - $bounds[0];
$h = $bounds[1] - $bounds[5];
$realx = $x - $w/2 -1;
$realy = $y - $h * $line + 3;
$lines[] = array($txt, $font, $fontsize, $realx, $realy);
if ($maxw < $w) {
$maxw = $w;
}
$line--;
}
}
if($maxw<$wlimit) break;
}
foreach ($lines as $line) {
imagettftext($tab, $line[2], 0, $line[3], $line[4], $white, $line[1], $line[0]);
}
putenv('GDFONTPATH=' . $originalpath);
imagetruecolortopalette($tab, true, 256);
// generate the image an return the data directly
ob_start();
imagegif($tab);
$image = ob_get_contents();
ob_end_clean();
return("data:image/gif;base64," . base64_encode($image));
}else{
return false;
}
}
function cacti_oid_numeric_format() {
if (function_exists('snmp_set_oid_output_format')) {
snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
}elseif (function_exists("snmp_set_oid_numeric_print")) {
snmp_set_oid_numeric_print(TRUE);
}
}
function IgnoreErrorHandler($message) {
global $snmp_error;
$snmp_ignore = array(
'No response from',
'noSuchName',
'No Such Object',
'Error in packet',
'This name does not exist',
'End of MIB',
);
foreach ($snmp_ignore as $i) {
if (strpos($message, $i)) {
$snmp_error = trim($message, "\\\n\t ");
return true;
}
}
$ignore = array(
'unable to read from socket' # ping.php line 387 socket refusal
);
foreach ($ignore as $i) {
if (strpos($message, $i)) {
return true;
}
}
return false;
}
function CactiErrorHandler($level, $message, $file, $line, $context) {
global $phperrors;
if (IgnoreErrorHandler($message)) {
return true;
}
preg_match("/.*\/plugins\/([\w-]*)\/.*/", $file, $output_array);
$plugin = (isset($output_array[1]) ? $output_array[1] : '');
$error = 'PHP ' . $phperrors[$level] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ": $message in file: $file on line: $line";
switch ($level) {
case E_COMPILE_ERROR:
case E_CORE_ERROR:
case E_ERROR:
case E_PARSE:
if ($plugin != '') {
api_plugin_disable_all($plugin);
cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'");
}
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR PARSE');
break;
case E_RECOVERABLE_ERROR:
case E_USER_ERROR:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
break;
case E_COMPILE_WARNING:
case E_CORE_WARNING:
case E_USER_WARNING:
case E_WARNING:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR WARNING');
break;
case E_NOTICE:
case E_USER_NOTICE:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR NOTICE');
break;
case E_STRICT:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR STRICT');
break;
default:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
}
return false;
}
function CactiShutdownHandler () {
global $phperrors;
$error = error_get_last();
if (IgnoreErrorHandler($error['message'])) {
return true;
}
switch ($error['type']) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_PARSE:
preg_match('/.*\/plugins\/([\w-]*)\/.*/', $error['file'], $output_array);
$plugin = (isset($output_array[1]) ? $output_array[1] : '' );
$message = 'PHP ' . $phperrors[$error['type']] .
($plugin != '' ? " in Plugin '$plugin'" : '') . ': ' . $error['message'] .
' in file: ' . $error['file'] . ' on line: ' . $error['line'];
cacti_log($message, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
if ($plugin != '') {
api_plugin_disable_all($plugin);
cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'");
}
}
}
/** enable_device_debug - Enables device debug for a device
* if it is disabled.
*
* @arg $host_id - the device id to search for
*
* @returns - void */
function enable_device_debug($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
if (array_search($host_id, $devices) === false) {
set_config_option('selective_device_debug', $device_debug . ',' . $host_id);
}
}else{
set_config_option('selective_device_debug', $host_id);
}
}
/** disable_device_debug - Disables device debug for a device
* if it is enabled.
*
* @arg $host_id - the device id to search for
*
* @returns - void */
function disable_device_debug($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
foreach($devices as $key => $device) {
if ($device == $host_id) {
unset($devices[$key]);
break;
}
}
set_config_option('selective_device_debug', implode(',', $devices));
}
}
/** is_device_debug_enabled - Determines if device debug is enabled
* for a device.
*
* @arg $host_id - the device id to search for
*
* @returns - boolean true or false */
function is_device_debug_enabled($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
if (array_search($host_id, $devices) !== false) {
return true;
}
}
return false;
}
/** get_url_type - Determines if remote communications are over
* http or https for remote services.
*
* @returns - http or https */
function get_url_type() {
if (read_config_option('force_https') == 'on') {
return 'https';
}else{
return 'http';
}
}
/** repair_system_data_input_methods - This utility will repair
* system data input methods when they are detected on the system
*
* @returns - null */
function repair_system_data_input_methods($step = 'import') {
$system_hashes = array(
'3eb92bb845b9660a7445cf9740726522', // Get SNMP Data
'bf566c869ac6443b0c75d1c32b5a350e', // Get SNMP Data (Indexed)
'80e9e4c4191a5da189ae26d0e237f015', // Get Script Data (Indexed)
'332111d8b54ac8ce939af87a7eac0c06', // Get Script Server Data (Indexed)
);
$good_field_hashes = array(
'3eb92bb845b9660a7445cf9740726522' => array( // Get SNMP Data (1)
'92f5906c8dc0f964b41f4253df582c38', // IP Address
'012ccb1d3687d3edb29c002ea66e72da', // SNMP Version
'32285d5bf16e56c478f5e83f32cda9ef', // SNMP Community
'fc64b99742ec417cc424dbf8c7692d36', // SNMP Port
'ad14ac90641aed388139f6ba86a2e48b', // SNMP Username
'9c55a74bd571b4f00a96fd4b793278c6', // SNMP Password
'20832ce12f099c8e54140793a091af90', // SNMP Authentication Protocol
'c60c9aac1e1b3555ea0620b8bbfd82cb', // SNMP Privacy Passphrase
'feda162701240101bc74148415ef415a', // SNMP Privacy Protocol
'4276a5ec6e3fe33995129041b1909762' // SNMP OID
),
'bf566c869ac6443b0c75d1c32b5a350e' => array( // Get SNMP Data (Indexed) (2)
'617cdc8a230615e59f06f361ef6e7728', // IP Address
'b5c23f246559df38662c255f4aa21d6b', // SNMP Version
'acb449d1451e8a2a655c2c99d31142c7', // SNMP Community
'c1f36ee60c3dc98945556d57f26e475b', // SNMP Port
'f4facc5e2ca7ebee621f09bc6d9fc792', // SNMP Username
'1cc1493a6781af2c478fa4de971531cf', // SNMP Password
'2cf7129ad3ff819a7a7ac189bee48ce8', // SNMP Authentication Protocol
'6b13ac0a0194e171d241d4b06f913158', // SNMP Privacy Passphrase
'3a33d4fc65b8329ab2ac46a36da26b72', // SNMP Privacy Protocol
'6027a919c7c7731fbe095b6f53ab127b', // Index Type
'cbbe5c1ddfb264a6e5d509ce1c78c95f', // Index Value
'e6deda7be0f391399c5130e7c4a48b28' // Output Type ID
),
'80e9e4c4191a5da189ae26d0e237f015' => array( // Get Script Data (Indexed) 11
'd39556ecad6166701bfb0e28c5a11108', // Index Type
'3b7caa46eb809fc238de6ef18b6e10d5', // Index Value
'74af2e42dc12956c4817c2ef5d9983f9', // Output Type ID
'8ae57f09f787656bf4ac541e8bd12537' // Output Value
),
'332111d8b54ac8ce939af87a7eac0c06' => array( // Get Script Server Data (Indexed) 12
'172b4b0eacee4948c6479f587b62e512', // Index Type
'30fb5d5bcf3d66bb5abe88596f357c26', // Index Value
'31112c85ae4ff821d3b288336288818c', // Output Type ID
'5be8fa85472d89c621790b43510b5043' // Output Value
)
);
foreach($good_field_hashes as $hash => $field_hashes) {
$data_input_id = db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash = ?', array($hash));
if (!empty($data_input_id)) {
$bad_hashes = db_fetch_assoc_prepared('SELECT *
FROM data_input_fields
WHERE hash NOT IN ("' . implode('","', $field_hashes) . '")
AND hash != ""
AND data_input_id = ?',
array($data_input_id));
if (sizeof($bad_hashes)) {
cacti_log(strtoupper($step) . ' NOTE: Repairing ' . sizeof($bad_hashes) . ' Damaged data_input_fields', false);
foreach($bad_hashes as $bhash) {
$good_field_id = db_fetch_cell_prepared('SELECT id
FROM data_input_fields
WHERE hash != ?
AND data_input_id = ?
AND data_name = ?',
array($bhash['hash'], $data_input_id, $bhash['data_name']));
cacti_log("Data Input ID $data_input_id Bad Field ID is " . $bhash['id'] . ", Good Field ID: " . $good_field_id, false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
cacti_log("Executing Data Input Data Check", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
// Data Input Data
$bad_mappings = db_fetch_assoc_prepared('SELECT * FROM data_input_data WHERE data_input_field_id = ?', array($bhash['id']));
if (sizeof($bad_mappings)) {
cacti_log(strtoupper($step) . ' NOTE: Found ' . sizeof($bad_mappings) . ' Damaged data_input_fields', false);
foreach($bad_mappings as $mfid) {
$good_found = db_fetch_cell_prepared('SELECT COUNT(*)
FROM data_input_data
WHERE data_input_field_id = ?
AND data_template_data_id = ?',
array($good_field_id, $mfid['data_template_data_id']));
if ($good_found) {
cacti_log("Good Found for " . $mfid['data_input_field_id'] . ", Fixing", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute("DELETE FROM data_input_data
WHERE data_input_field_id = " . $mfid['data_input_field_id'] . "
AND data_template_data_id = " . $mfid['data_template_data_id']);
}else{
cacti_log("Good NOT Found for " . $mfid['data_input_field_id'] . ", Fixing", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute("UPDATE data_input_data
SET data_input_field_id = $good_field_id
WHERE data_input_field_id = " . $mfid['data_input_field_id'] . "
AND data_template_data_id = " . $mfid['data_template_data_id']);
}
}
}else{
cacti_log("No Bad Data Input Data Records", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
// Data Template RRD
cacti_log("Executing Data Template RRD Check", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);;
$bad_mappings = db_fetch_assoc_prepared('SELECT * FROM data_template_rrd WHERE data_input_field_id = ?', array($bhash['id']));
if (sizeof($bad_mappings)) {
cacti_log(strtoupper($step) . ' NOTE: Found ' . sizeof($bad_mappings) . ' Damaged data_template_rrd', false);
foreach($bad_mappings as $mfid) {
$good_found = db_fetch_cell_prepared('SELECT COUNT(*)
FROM data_template_rrd
WHERE data_input_field_id = ?
AND id = ?',
array($good_field_id, $mfid['id']));
if ($good_found) {
cacti_log("Good Found for " . $mfid['data_input_field_id'] . ", Fixing", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute("DELETE FROM data_template_rrd
WHERE data_input_field_id = " . $mfid['data_input_field_id'] . "
AND id = " . $mfid['id']);
}else{
cacti_log("Good NOT Found for " . $mfid['data_input_field_id'] . ", Fixing", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute("UPDATE data_template_rrd
SET data_input_field_id = $good_field_id
WHERE data_input_field_id = " . $mfid['data_input_field_id'] . "
AND id = " . $mfid['id']);
}
}
}else{
cacti_log("No Bad Data Template RRD Records", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
db_execute_prepared('DELETE FROM data_input_fields WHERE hash = ?', array($bhash['hash']));
}
}
}else{
cacti_log("Could not find hash '" . $hash . "' for Data Input", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
}
}