Location: PHPKode > projects > Php-Logging-System > phplogsys-1.1.4/includes/common_funcs.php
<?php
// Copyright (C) 2001-2004 by Michael Earls, hide@address.com
// Copyright (C) 2005 Claus Lund, hide@address.com
// Copyright (C) 2006 Clayton Dukes, hide@address.com

$REG0TO255='(2([0-4][0-9]|5[0-5])|1[0-9]?[0-9]|[1-9][0-9]?|[0-9])';
define('REGIP', $REG0TO255 . '(\\.' . $REG0TO255 . '){3}');
unset($REG0TO255);

$REGVAL='(255|254|252|248|240|224|192|128|0)';
define('REGMASK', '((255\.){3}' . $REGVAL . '|(255\.){2}' . $REGVAL . '(\.0){1}|(255\.){1}' . $REGVAL . '(\.0){2}|' . $REGVAL . '(\.0){3})');
unset($REGVAL);

define('REGCIDR', '(3[0-2]|[12][0-9]|[0-9])');

define('REGPORT', '(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[0-5][0-9]{4}|[1-9][0-9]{0,3}|0)');

error_reporting(E_ALL & ~E_NOTICE);
//------------------------------------------------------------------------
// This function returns the current microtime.
//------------------------------------------------------------------------
function get_microtime() {
	list($usec, $sec) = explode(' ', microtime());
	return ((float)$usec + (float)$sec);
}

//------------------------------------------------------------------------
// Function used to retrieve input values and if neccessary add slashes.
//------------------------------------------------------------------------
function get_input($varName){
	$value='';
	if(isset($_GET[$varName])){
		$value = $_GET[$varName];
	} elseif(isset($_POST[$varName])){
		$value = $_POST[$varName];
	}
	if($value && !get_magic_quotes_gpc()){
		if(!is_array($value)) {
			$value = addslashes($value);
		}
		else {
			foreach($value as $key => $arrValue){
				$value[$key] = addslashes($arrValue);
			}
		}
	}
	return $value;
}

//------------------------------------------------------------------------
// Function used to validate user supplied variables.
//------------------------------------------------------------------------
function validate_input($value, $regExpName) {
	global $regExpArray;

	if(!$regExpArray[$regExpName]) {
		return FALSE;
	}

	if(is_array($value)) {
		foreach($value as $arrval) {
			if(!preg_match($regExpArray[$regExpName], $arrval)) {
				return FALSE;
			}
		}
		return TRUE;
	}
	elseif(preg_match($regExpArray[$regExpName], $value)) {
		return TRUE;
	}
	else {
		return FALSE;
	}
}

//------------------------------------------------------------------------
// This function reloads the cache with data from 'MERGE*TABLE's.
//------------------------------------------------------------------------
function cachefield($link, $table, $field, $type, $where='', $regex=null, $nslookup=false){
	$sql = 'SELECT DISTINCT '.$field.' FROM ' . $table;
	$result = perform_query($sql, $link);
	$updateTime = date('Y-m-d H:i:s');
	$insert = '';
	$updates = array();
	while($row = fetch_array($result, 'ASSOC')) {
		set_time_limit(30);
		$value = $row[$field];
		if($nslookup){
			if(preg_match('/^' . REGIP . '$/', $value)){
				$oldvalue = $value;
				$value = gethostbyaddr($value);
				if($value != $oldvalue) $updates[] = 'UPDATE ' . $table . ' SET ' . $field . ' = \'' . addslashes($value) . '\' where ' . $field . ' = \'' . addslashes($oldvalue) . '\'';
			}
		}
		if(!isset($regex) || preg_match($regex, $value)){
			$add = '(\'' . $type . '\', \'' . addslashes($value) . '\', \'' . $updateTime . '\'),';
			$insert .= $add;
		}
	}
	if(strlen($insert) > 0){
		$insert = 'INSERT INTO '.CACHETABLENAME.' (type, value, updatetime) VALUES ' . rtrim($insert, ',');
		// Insert new cache values
		perform_query($insert, $link);
		// Clear memory
		unset($insert);
	}
	// Drop old cache values for 'MERGESYSLOGTABLE'
	$sql = 'DELETE FROM ' . CACHETABLENAME . ' WHERE updatetime<\'' . $updateTime . '\' AND type=\'' . $type . '\'';
	perform_query($sql, $link);
	if($nslookup && count($updates) > 0){
		set_time_limit(30);
		$admn_link = db_connect_syslog(DBADMIN, DBADMINPW);
		foreach(array_keys($updates) as $i) perform_query($sql, $admn_link);
		mysql_close($admn_link);
	}
}

function reload_cache($link) {
	if(defined('APACHE') && APACHE){
		cachefield($link, MERGEAPACHETABLE, 'servername', 'WEBSERVER');
		cachefield($link, MERGEAPACHETABLE, 'useragent', 'APACHEUSERAGENT');
		cachefield($link, MERGEAPACHETABLE, 'mimetype', 'APACHEMIMETYPE');
	}
	if(defined('BASH') && BASH){
		cachefield($link, MERGEBASHTABLE, 'host', 'BASHHOST', null, null, BASH_HOST_NSLOOKUP);
		cachefield($link, MERGEBASHTABLE, 'userid', 'BASHUSERID');
		cachefield($link, MERGEBASHTABLE, 'username', 'BASHUSERNAME');
	}
	if(defined('IPTABLES') && IPTABLES){
		cachefield($link, MERGEIPTABLESTABLE, 'host', 'IPTABLESHOST');
		cachefield($link, MERGEIPTABLESTABLE, 'prefix', 'IPTABLESPREFIX');
		cachefield($link, MERGEIPTABLESTABLE, 'proto', 'IPTABLESPROTO');
	}
	if(defined('SAMHAIN') && SAMHAIN){
		cachefield($link, MERGESAMHAINTABLE, 'log_host', 'SAMHAINHOST');
		cachefield($link, MERGESAMHAINTABLE, 'log_msg', 'SAMHAINMSG');
	}
	if(defined('SNORT') && SNORT){
	}
	if(defined('SQUID') && SQUID){
		cachefield($link, MERGESQUIDTABLE, 'source', 'SOURCE', null, null, SQUID_SOURCE_NSLOOKUP);
		cachefield($link, MERGESQUIDTABLE, 'useragent', 'USERAGENT', ' WHERE useragent NOT LIKE \'%AAAAA\'');
		cachefield($link, MERGESQUIDTABLE, 'mimetype', 'MIMETYPE');
	}
	if(defined('SYSLOG_NG') && SYSLOG_NG){
		cachefield($link, MERGESYSLOGTABLE, 'host', 'HOST', null, null, SYSLOG_HOST_NSLOOKUP);
		cachefield($link, MERGESYSLOGTABLE, 'facility', 'FACILITY');
		cachefield($link, MERGESYSLOGTABLE, 'program', 'PROGRAM', null, '/^[a-zA-Z]+[a-zA-Z0-9\/()._\-]+$/');
	}
}

//========================================================================
// BEGIN DATABASE FUNCTIONS
//========================================================================
//------------------------------------------------------------------------
// This function connects to the MySQL server and selects the database
// specified in the DBNAME parameter. If an error occurs then return
// FALSE.
//------------------------------------------------------------------------
function db_connect_syslog($dbUser, $dbPassword, $connType = 'P') {
	$server_string = DBHOST.':'.DBPORT;
	$link = '';
	if(function_exists('mysql_pconnect') && $connType == 'P') {
		$link = @mysql_pconnect($server_string, $dbUser, $dbPassword);
	}
	elseif(function_exists('mysql_connect')) {
		$link = @mysql_connect($server_string, $dbUser, $dbPassword);
	}
	if(!$link) {
		return FALSE;
	}

	$result = mysql_select_db(DBNAME, $link);
	if(!$result) {
		return FALSE;
	}

	return $link;
}

//------------------------------------------------------------------------
// This functions performs the SQL query and returns a result resource. If
// an error occurs then execution is halted an the MySQL error is
// displayed.
//------------------------------------------------------------------------
function perform_query($query, $link) {
	if($link) {
		$result = mysql_query($query, $link);
			if (!$result) {
				print ('Error in \'function perform_query()\' <br>Mysql_error: ' . mysql_error() . "<br>Query was: $query<br>");
				return ('Error in \'function perform_query()\' <br>Mysql_error: ' . mysql_error());
			}
	} else {
		die('Error in perform_query function<br> No DB link for query: $query<br>Mysql_error: ' . mysql_error());
	}

	return $result;
}

//------------------------------------------------------------------------
// This functions returns a result row as an array.
// The type can be BOTH, ASSOC or NUM.
//------------------------------------------------------------------------
function fetch_array($result, $type = 'BOTH') {
	if($type == 'BOTH') {
		return mysql_fetch_array($result);
	}
	elseif($type == 'ASSOC') {
		return mysql_fetch_assoc($result);
	}
	elseif($type == 'NUM') {
		return mysql_fetch_row($result);
	}
	else {
		die('Wrong type for fetch_array()');
	}
}

//------------------------------------------------------------------------
// This function checks if a particular table exists.
//------------------------------------------------------------------------
function table_exists($tableName, $link) {
	$tables = get_tables($link);
	if(array_search($tableName, $tables) !== FALSE) {
		return TRUE;
	}
	else {
		return FALSE;
	}
}

//------------------------------------------------------------------------
// This function returns an array of the names of all tables in the
// database.
//------------------------------------------------------------------------
function get_tables($link) {
	$tableList = array();
	$query = 'SHOW TABLES';
	$result = perform_query($query, $link);
	while($row = fetch_array($result)) {
		array_push($tableList, $row[0]);
	}

	return $tableList;
}

//------------------------------------------------------------------------
// This function returns an array with the names of tables with log data.
//------------------------------------------------------------------------
function get_logtables($link, $logtable=DEFAULTSYSLOGTABLE) {
	// Create an array of the column names in the default table
	$query = 'DESCRIBE `'.$logtable.'`';
	$result = perform_query($query, $link);
	$defaultFieldArray = array();
	while($row = mysql_fetch_array($result)) {
		array_push($defaultFieldArray, $row['Field']);
	}

	// Create an array with the names of all the log tables
	$logTableArray = array();
	$allTablesArray = get_tables($link);
	foreach($allTablesArray as $value) {
		// Create an array of the column names in the current table
		$query = 'DESCRIBE `'.$value.'`';
		$result = perform_query($query, $link);
		// Get the names of columns in current table
		$fieldArray = array();
		while ($row = mysql_fetch_array($result)) {
			array_push($fieldArray, $row['Field']);
		}

		// If the current array is identical to the one from the
		// DEFAULTSYSLOGTABLE then the name is added to the result
		// array.
		$diffArray = array_diff_assoc($defaultFieldArray, $fieldArray);
		if(!$diffArray) {
			array_push($logTableArray, $value);
		}
	}
	return $logTableArray;
}
//========================================================================
// END DATABASE FUNCTIONS
//========================================================================

/*  Adds commas to a string of numbers
*/
function commify($str) {
	return preg_replace("/(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))/", ",", $str);
}

function rgb($val){
	switch(true){
		case $val < 64: //64
			return array(64+$val, 0, 128+($val*2)); //dp to p
		case $val < 128: //64
			return array(128-(($val-64)*2), 0, 255); //p to b
		case $val < 192: //64
			return array(0, ($val-128)*2, 255); //b to lb
		case $val < 256: //64
			return array(0, 128, 255-(($val-192)*2)); //lb to ug
		case $val < 384: //128
			return array(0, 128, 128-($val-256)); //ug to dg
		case $val < 512: //128
			return array(0, 128+($val-384), 0); //ug to g
		case $val < 640: //128
			return array(($val-512)*2, 255, 0); //g to y
		case $val < 768: //128
			return array(255, 255, 128-($val-640)); //y to o
		case $val < 1024: //256
			return array(255, 255-($val-768), 0); //o to r
		default:
			return array(255, 0, 0); //r
	}
}

function samhain_msg_code($msg){
	$regex = '/[C-][L-][D-][I-][H-][M-][U-][G-][T-][S-]/';
	if(preg_match($regex, substr($msg, -10))){
		$code = substr($msg, -10);
		$arr = array();
		foreach(str_split($code) as $char){
			switch($char){
				case 'C':
					$arr[] = 'Checksum';
					break;
				case 'L':
					$arr[] = 'soft Link';
					break;
				case 'D':
					$arr[] = 'Device number';
					break;
				case 'I':
					$arr[] = 'Inode';
					break;
				case 'H':
					$arr[] = 'number of Hardlinks';
					break;
				case 'M':
					$arr[] = 'Mode';
					break;
				case 'U':
					$arr[] = 'User owner';
					break;
				case 'G':
					$arr[] = 'Group owner';
					break;
				case 'T':
					$arr[] = 'Timestamp';
					break;
				case 'S':
					$arr[] = 'Size';
					break;
			}
			$str = implode(', ', $arr);
		}
		return preg_replace($regex, preg_replace('/, ([^,]*)$/', ', and $1', $str) . ' changed', $msg);
	}else{
		return $msg;
	}
}

function snort_references($sig_id, $sig_sid, $sig_gid, $dbLink){
	$query = <<<END
SELECT reference.ref_tag, reference_system.ref_system_name
FROM sig_reference
INNER JOIN reference ON reference.ref_id = sig_reference.ref_id
INNER JOIN reference_system ON reference.ref_system_id = reference_system.ref_system_id
WHERE sig_reference.sig_id = {$sig_id}
END;
	$return = array();
	$results = perform_query($query, $dbLink);
	while($row = fetch_array($results)){
		switch($row['ref_system_name']){
			case 'url':
				$return[] = '<a href="http://' . $row['ref_tag'] . '">url</a> ';
				break;
			case 'nessus':
				$return[] = '<a href="http://www.nessus.org/plugins/index.php?view=single&id=' . $row['ref_tag'] . '">nessus</a> ';
				break;
			case 'bugtraq':
				$return[] = '<a href="http://www.securityfocus.com/bid/' . $row['ref_tag'] . '">bugtraq</a> ';
				break;
			case 'cve':
				$return[] = '<a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=' . $row['ref_tag'] . '">cve</a> ';
				$return[] = '<a href="http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-' . $row['ref_tag'] . '">nvd</a> ';
				break;
			//Removed due to DNS Parking
			//case 'arachNIDS':
			//	$return[] = '<a href="http://www.whitehats.com/info/ids' . $row['ref_tag'] . '">arachNIDS</a> ';
			//	break;
		}
	}
	$return[] = '<a href="http://www.snort.org/pub-bin/sigs.cgi?sid=' . $sig_gid . ':' . $sig_sid . '">snort</a> ';
	return $return;
}

function snort_opts($sid, $cid, $proto, $dbLink){
	$query = 'SELECT * FROM opt WHERE sid = ' . $sid . ' AND cid = ' . $cid . ' AND opt_proto = ' . $proto;
	$return = '';
	$results = perform_query($query, $dbLink);
	while($row = fetch_array($results)){
		$return .= '<tr><td>' . $row['opt_code'] . '</td><td>' . $row['opt_len'] . '</td><td>' . $row['opt_data'] . '</td></tr>';
	}
	if($return != '') $return = '<table><tr><th>CODE</th><th>LENGTH</th><th>DATA</th></tr>' . $return . '</table>';
	return $return;
}

function hex2bin($h){
	if (!is_string($h)) return null;
	$r='';
	for ($a=0; $a<strlen($h); $a+=2) { $r.=chr(hexdec($h{$a}.$h{($a+1)})); }
	return $r;
}

function inputgroup($name, $descr, $options=null, $blnsearch=true, $blnregex=true, $blnselect=true){
	if(!isset($options)) $blnselect = false;
	if($blnselect){
		$return = '<td><b>' . strtoupper($descr) . ': ' . count($options) . '</b>';
	}else{
		$return = '<td><b>' . strtoupper($descr) . ':</b>';
	}
	$return .= '<table align="center" class="formentry">' .
		'<tr><td>Include</td><td><input name="exclude' . $name . '" id="exclude' . $name . '_0" value="0" type="radio"></td></tr>' .
		'<tr><td>Exclude</td><td><input name="exclude' . $name . '" id="exclude' . $name . '_1" value="1" type="radio" checked></td></tr>';
	if($blnsearch){
		if($blnregex){
			$return .= '<tr><td>RegExp Matching?</td><td><input name="regexp' . $name . '" id="regexp' . $name . '" value="1" type="checkbox"></td></tr>';
		}
		$return .= '<tr><td>' . ucwords($descr) . ' match</td><td><input type="text" name="' . $name . '2" id="' . $name . '2" size="20"></td></tr>';
		if($blnselect) $return .= '<tr><td valign="top">=====AND=====<br><a href="javascript:expandselect(\'' . $name . '\', \'15em\');">expand/contract</a></td><td>';
	}else{
		if($blnselect) $return .= '<tr><td colspan=2>';
	}
	if($blnselect) $return .= '<select name="' . $name . '[]" id="' . $name . '" multiple size="10" style="max-width: 15em;">' . implode($options) . '</select></td></tr>';
	$return .= '</table></td>';
	return $return;
}

function parseinput($name, $validate, $blnsearch, $blnregex){
	global $inputValError;

	$GLOBALS[$name] = get_input($name);
	if(isset($GLOBALS[$name]) && !validate_input($GLOBALS[$name], $validate)) array_push($inputValError, $name . '1');
	$GLOBALS['exclude' . $name] = get_input('exclude' . $name);
	if(isset($GLOBALS['exclude' . $name]) && !validate_input($GLOBALS['exclude' . $name], 'excludeX')) array_push($inputValError, 'exclude' . $name);
	if($blnregex){
		$GLOBALS['regexp' . $name] = get_input('regexp' . $name);
		if($GLOBALS['regexp' . $name] && !validate_input($GLOBALS['regexp' . $name], 'regexpX')) array_push($inputValError, 'regexp' . $name);
	}
	if($blnsearch){
		$GLOBALS[$name . '2'] = get_input($name . '2');
		if(isset($GLOBALS[$name . '2']) && ((!$GLOBALS['regexp' . $name] && !validate_input($GLOBALS[$name . '2'], $validate)) || ($GLOBALS['regexp' . $name] && !validate_input($GLOBALS[$name . '2'], $validate . 'RegExp')))) array_push($inputValError, $name . '2');
	}
}

function msginputgroup($title){
	$return = '<td><b>' . strtoupper($title) . ':</b>&nbsp;&nbsp;<input type="button" onclick="addmsg()" value="More">' .
		'<br><table id="msgentry" class="msgentry"><tbody><tr><td>Exclude <input type="checkbox" name="ExcludeMsg1" id="ExcludeMsg1" value="1" /></td>' .
		'<td>RegExp <input type="checkbox" name="RegExpMsg1" id="RegExpMsg1" value="1" /></td><td><input type=text name="msg1" id="msg1" size="75%" /></td>' .
		'<td>&nbsp;</td></tr></tbody></table></td>';
	return $return;
}

function parsemsginput(){
	global $inputValError;
	$msgvarnum=1;
	$msgvarname='msg'.$msgvarnum;
	$excmsgvarname='ExcludeMsg'.$msgvarnum;
	$regexpmsgvarname='RegExpMsg'.$msgvarnum;

	while(get_input($msgvarname)){
		$GLOBALS[$msgvarname] = get_input($msgvarname);
		$GLOBALS[$excmsgvarname] = get_input($excmsgvarname);
		$GLOBALS[$regexpmsgvarname] = get_input($regexpmsgvarname);

		if(isset($GLOBALS[$msgvarname]) && !validate_input($GLOBALS[$msgvarname], 'msg')) array_push($inputValError, $msgvarname);
		if(isset($GLOBALS[$excmsgvarname]) && !validate_input($GLOBALS[$excmsgvarname], 'excludeX')) array_push($inputValError, $excmsgvarname);
		if(isset($GLOBALS[$regexpmsgvarname]) && !validate_input($GLOBALS[$regexpmsgvarname], 'regexpX')) array_push($inputValError, $regexpmsgvarname);

		$msgvarnum++;
		$msgvarname='msg'.$msgvarnum;
		$excmsgvarname='ExcludeMsg'.$msgvarnum;
		$regexpmsgvarname='RegExpMsg'.$msgvarnum;
	}
}

function ipinputgroup($name, $descr){
	global $default_ips;
	$iplist = '';
	if(isset($default_ips)) $iplist = '<option>' . implode('</option><option>', $default_ips) . '</option>';
	$return = '<td><b>' . strtoupper($descr) . ':</b><table align="center" class="formentry">' .
		'<tr><td>Include</td><td><input name="exclude' . $name . '" id="exclude' . $name . '_0" value="0" type="radio"></td></tr>' .
		'<tr><td>Exclude</td><td><input name="exclude' . $name . '" id="exclude' . $name . '_1" value="1" type="radio" checked></td></tr>' .
		'<tr><td>' . ucwords($descr) . ' match</td>' .
		'<td nowrap><input type="text" size="3" maxlength="3" name="' . $name . 'oct1" id="' . $name . 'oct1"> . ' .
		'<input type="text" size="3" maxlength="3" name="' . $name . 'oct2" id="' . $name . 'oct2"> . ' .
		'<input type="text" size="3" maxlength="3" name="' . $name . 'oct3" id="' . $name . 'oct3"> . ' .
		'<input type="text" size="3" maxlength="3" name="' . $name . 'oct4" id="' . $name . 'oct4"></td></tr>' .
		'<tr><td valign="top">=====AND=====<br><a href="javascript:expandselect(\'' . $name . '\', \'15em\');">expand/contract</a></td>' .
		'<td><input type="text" name="add' . $name . '" id="add' . $name . '" value="" size="20" onmouseover="return overlib(\'' .
		'<table border=1 cellspacing=0 cellpadding=0 width=100%><tr><td class=tooltip>Enter an ip address or range, and then click the Add to List button.<br>' .
		'Valid entries can be in any of the following formats:<br>Single IP: 192.168.0.1<br>IP Range: 192.168.0.1-192.168.255.255<br>IP with Netmask: 192.168.0.1/255.255.0.0<br>IP with CIDR: 192.168.0.1/16</TD></TR></TABLE>\')" ' .
		' onmouseout="nd()">&nbsp;<input type="button" value="Add To List" onclick="addOption(\'add' . $name . '\', \'' . $name . '\')"><br>' .
		'<select name="' . $name . '[]" id="' . $name . '" multiple size="10" style="max-width: 15em;">' . $iplist . '</select></td></tr></table></td>';
	return $return;
}

function parseipinput($name){
	global $inputValError;
	$GLOBALS[$name] = get_input($name);
	if(isset($GLOBALS[$name]) && !validate_input($GLOBALS[$name], 'ipaddr')) array_push($inputValError, $name . '1');
	$GLOBALS['exclude' . $name] = get_input('exclude' . $name);
	if(isset($GLOBALS['exclude' . $name]) && !validate_input($GLOBALS['exclude' . $name], 'excludeX')) array_push($inputValError, 'exclude' . $name);
	for($x=1;$x<5;$x++){
		$GLOBALS[$name . 'oct' . $x] = get_input($name . 'oct' . $x);
		if(isset($GLOBALS[$name . 'oct' . $x]) && !validate_input($GLOBALS[$name . 'oct' . $x], 'ipoctet')) array_push($inputValError, $name . 'oct' . $x);
	}
}

function portinputgroup($name, $descr){
	global $default_ports;
	$portlist = '';
	if(isset($default_ports)) $portlist = '<option>' . implode('</option><option>', $default_ports) . '</option>';
	$return = '<td><b>' . strtoupper($descr) . ':</b><table align="center" class="formentry">' .
		'<tr><td>Include</td><td><input name="exclude' . $name . '" id="exclude' . $name . '_0" value="0" type="radio"></td></tr>' .
		'<tr><td>Exclude</td><td><input name="exclude' . $name . '" id="exclude' . $name . '_1" value="1" type="radio" checked></td></tr>' .
		'<tr><td valign="top">&nbsp;<br><a href="javascript:expandselect(\'' . $name . '\', \'15em\');">expand/contract</a></td>' .
		'<td><input type="text" name="add' . $name . '" id="add' . $name . '" value="" size="12" onmouseover="return overlib(\'' .
		'<table border=1 cellspacing=0 cellpadding=0 width=100%><tr><td class=tooltip>Enter a port range, and then click the Add to List button.<br>' .
		'Valid entries can be in any of the following formats:<br>Single Port: 1433<br>Port Range: 1-1024<br>Port List: 20,21,80,8080</TD></TR></TABLE>\')" ' .
		' onmouseout="nd()">&nbsp;<input type="button" value="Add To List" onclick="addOption(\'add' . $name . '\', \'' . $name . '\')"><br>' .
		'<select name="' . $name . '[]" id="' . $name . '" multiple size="10" style="max-width: 15em;">' . $portlist . '</select></td></tr></table></td>';
	return $return;
}

function parseportinput($name){
	global $inputValError;
	$GLOBALS[$name] = get_input($name);
	if(isset($GLOBALS[$name]) && !validate_input($GLOBALS[$name], 'port')) array_push($inputValError, $name . '1');
	$GLOBALS['exclude' . $name] = get_input('exclude' . $name);
	if(isset($GLOBALS['exclude' . $name]) && !validate_input($GLOBALS['exclude' . $name], 'excludeX')) array_push($inputValError, 'exclude' . $name);
}

function inputdb($name, $dbfield, $dbsearchfield, $blnsearch, $blnregex){
	global $where;
	global $ParamsGET;

	if($blnsearch){
		if($GLOBALS[$name . '2']){
			if($where!='') $where .= ' AND ';
			$clause = '';
			if($blnregex && $GLOBALS['regexp' . $name]==1){
				$clause = $dbsearchfield . ' RLIKE \''.$GLOBALS[$name . '2'].'\'';
				$ParamsGET=$ParamsGET.$name.'2='.$GLOBALS[$name . '2'].'&exclude'.$name.'='.$GLOBALS['exclude' . $name].'&regexp'.$name.'='.$GLOBALS['regexp' . $name].'&';
			}else{
				$parts = preg_split('/\s*[,;]+\s*/', $GLOBALS[$name . '2']);
				foreach ($parts as $part){
					if (empty($part)) continue;
					$clause .= ($clause!='') ? ' OR ' : '';
					$clause .= $dbsearchfield . ' LIKE \'%' . $part . '%\'';
				}
				$ParamsGET=$ParamsGET.$name.'2='.$GLOBALS[$name . '2'].'&exclude'.$name.'='.$GLOBALS['exclude' . $name].'&';
			}
			$where .= (($GLOBALS['exclude' . $name]==1) ? 'NOT ' : '')."($clause)";
		}
	}
	if(isset($GLOBALS[$name]) && is_array($GLOBALS[$name])){
		$GET=implode('&'.$name.'[]=',$GLOBALS[$name]);
		$SQL=implode('\',\'',$GLOBALS[$name]);
		if($where!='') $where .= ' AND ';
		if($GLOBALS['exclude' . $name]==1){
			$where = $where.' ' . $dbfield . ' NOT IN (\''.$SQL.'\') ';
		}else{
			$where = $where.' ' . $dbfield . ' IN (\''.$SQL.'\') ';
		}
		$ParamsGET=$ParamsGET.$name.'[]='.$GET.'&exclude'.$name.'='.$GLOBALS['exclude' . $name].'&';
	}
}

function ipinputdb($name, $dbfield, $blnStoredAsInt){
	global $where;
	global $ParamsGET;
	$ipWhere = '';

	if(isset($GLOBALS[$name]) && is_array($GLOBALS[$name])){
		$ipGET=implode('&'.$name.'[]=',$GLOBALS[$name]);
		$ipSQL = '';
		foreach($GLOBALS[$name] as $sip){
			//ip notation
			if(preg_match('/^' . REGIP . '$/', $sip)){
				$ipSQL .= ',\'' . $sip . '\'';
				continue;
			}
			if(isset($firstip)) unset($firstip);
			if(isset($lastip)) unset($lastip);
			//ip-ip notation
			if(preg_match('/^' . REGIP . '-' . REGIP . '$/', $sip)){
				list($firstip, $lastip) = explode('-', $sip);
				$firstip = ip2long($firstip);
				$lastip = ip2long($lastip);
			}else{
				//ip/mask notation
				if(preg_match('/^' . REGIP . '\/' . REGMASK . '$/', $sip)){
					list($ip, $mask) = explode('/', $sip);
					//convert this to cidr notation and handle it below
					$sip = $ip . '/' . strlen(preg_replace('/0/', '', decbin(ip2long($mask))));
				}
				//ip/cidr notation
				if(preg_match('/^' . REGIP . '\/' . REGCIDR . '$/', $sip)){
					list($ip, $cidr) = explode('/', $sip);
					$netbits = 32-intval($cidr);
					$firstip = (ip2long($ip) >> $netbits) << $netbits;
					$lastip = $firstip + bindec(str_repeat('1', $netbits));
				}
			}
			if(isset($firstip) && isset($lastip)){
				if($GLOBALS['exclude' . $name]==1){
					if($ipWhere!='') $ipWhere = $ipWhere.' AND ';
					if($blnStoredAsInt){
						$ipWhere = $ipWhere.' ' . $dbfield . ' NOT BETWEEN ' . sprintf('%u', $firstip) . ' AND ' . sprintf('%u', $lastip) . ' ';
					}else{
						$ipWhere = $ipWhere.' INET_ATON(' . $dbfield . ') NOT BETWEEN ' . sprintf('%u', $firstip) . ' AND ' . sprintf('%u', $lastip) . ' ';
					}
				}else{
					if($ipWhere!='') $ipWhere = $ipWhere.' OR ';
					if($blnStoredAsInt){
						$ipWhere = $ipWhere.' ' . $dbfield . ' BETWEEN ' . sprintf('%u', $firstip) . ' AND ' . sprintf('%u', $lastip) . ' ';
					}else{
						$ipWhere = $ipWhere.' INET_ATON(' . $dbfield . ') BETWEEN ' . sprintf('%u', $firstip) . ' AND ' . sprintf('%u', $lastip) . ' ';
					}
				}
				continue;
			}
		}
		if($ipSQL != ''){
			if($GLOBALS['exclude' . $name]==1){
				if($ipWhere!='') $ipWhere = $ipWhere.' AND ';
				if($blnStoredAsInt){
					$ipWhere = $ipWhere.' INET_NTOA(' . $dbfield . ') NOT IN ('.substr($ipSQL, 1).') ';
				}else{
					$ipWhere = $ipWhere.' ' . $dbfield . ' NOT IN ('.substr($ipSQL, 1).') ';
				}
			}else{
				if($ipWhere!='') $ipWhere = $ipWhere.' OR ';
				if($blnStoredAsInt){
					$ipWhere = $ipWhere.' INET_NTOA(' . $dbfield . ') IN ('.substr($ipSQL, 1).') ';
				}else{
					$ipWhere = $ipWhere.' ' . $dbfield . ' IN ('.substr($ipSQL, 1).') ';
				}
			}
		}
	}
	$iplike = '';
	if($GLOBALS[$name . 'oct1']) $iplike .= $GLOBALS[$name . 'oct1'] . '.'; else $iplike .= '%.';
	if($GLOBALS[$name . 'oct2']) $iplike .= $GLOBALS[$name . 'oct2'] . '.'; else $iplike .= '%.';
	if($GLOBALS[$name . 'oct3']) $iplike .= $GLOBALS[$name . 'oct3'] . '.'; else $iplike .= '%.';
	if($GLOBALS[$name . 'oct4']) $iplike .= $GLOBALS[$name . 'oct4']; else $iplike .= '%';
	if($iplike != '%.%.%.%'){
		if($ipWhere != '') $ipWhere = $ipWhere.' AND ';
		if($GLOBALS['exclude' . $name]==1){
			if($blnStoredAsInt){
				$ipWhere .= ' INET_NTOA(' . $dbfield . ') NOT LIKE \'' . $iplike . '\'';
			}else{
				$ipWhere .= ' ' . $dbfield . ' NOT LIKE \'' . $iplike . '\'';
			}
		}else{
			if($blnStoredAsInt){
				$ipWhere .= ' INET_NTOA(' . $dbfield . ') LIKE \'' . $iplike . '\'';
			}else{
				$ipWhere .= ' ' . $dbfield . ' LIKE \'' . $iplike . '\'';
			}
		}
	}
	if($ipWhere != ''){
		if($where != '') $where .= ' AND ';
		$where .= '(' . $ipWhere . ') ';
	}
	$ParamsGET .= $name.'[]='.$ipGET.'&exclude'.$name.'='.$GLOBALS['exclude' . $name].'&';
	for($x=1;$x<5;$x++) $ParamsGET .= $name . 'oct' . $x . '=' . $GLOBALS[$name . 'oct' . $x] . '&';
}

function portinputdb($name, $dbfield){
	global $where;
	global $ParamsGET;
	$portWhere = '';

	if(isset($GLOBALS[$name]) && is_array($GLOBALS[$name])){
		$portGET=implode('&'.$name.'[]=',$GLOBALS[$name]);
		$portSQL = '';
		foreach($GLOBALS[$name] as $sport){
			//port-port notation
			if(preg_match('/-/', $sport)){
				list($firstport, $lastport) = explode('-', $sport);
				if($GLOBALS['exclude' . $name]==1){
					if($portWhere!='') $portWhere = $portWhere.' AND ';
					$portWhere = $portWhere.' ' . $dbfield . ' NOT BETWEEN ' . sprintf('%u', $firstport) . ' AND ' . sprintf('%u', $lastport) . ' ';
				}else{
					if($portWhere!='') $portWhere = $portWhere.' OR ';
					$portWhere = $portWhere.' ' . $dbfield . ' BETWEEN ' . sprintf('%u', $firstport) . ' AND ' . sprintf('%u', $lastport) . ' ';
				}
				continue;
			}
			//port notation
			$portSQL .= ',' . $sport;
		}
		if($portSQL != ''){
			if($GLOBALS['exclude' . $name]==1){
				if($portWhere!='') $portWhere = $portWhere.' AND ';
				$portWhere = $portWhere.' ' . $dbfield . ' NOT IN ('.substr($portSQL, 1).') ';
			}else{
				if($portWhere!='') $portWhere = $portWhere.' OR ';
				$portWhere = $portWhere.' ' . $dbfield . ' IN ('.substr($portSQL, 1).') ';
			}
		}
		$ParamsGET .= $name.'[]='.$portGET;
	}
	if($portWhere != ''){
		if($where != '') $where .= ' AND ';
		$where .= '(' . $portWhere . ') ';
	}
	$ParamsGET .= '&exclude'.$name.'='.$GLOBALS['exclude' . $name].'&';
}

function timestampdb($dbfield, $format){
	global $date;
	global $time;
	global $date2;
	global $time2;

	global $where;
	global $ParamsGET;

	$timestamp = '';
	$timestamp2 = '';

	if($date){
		$ParamsGET=$ParamsGET.'date='.$date.'&time='.$time.'&';
		if(strcasecmp($date, 'now') == 0 || strcasecmp($date, 'today') == 0){
			$date = date('Y-m-d');
		}elseif(strcasecmp($date, 'yesterday') == 0){
			$date = date('Y-m-d', mktime(0, 0, 0, date('m')  , date('d')-1, date('Y')));
		}
		if(!$time){
			$time = '00:00:00';
		}elseif(strcasecmp($time, 'now') == 0){
			$time = date('H:i:s');
		}
		$timestamp = strtotime($date.' '.$time);
	}
	if($date2){
		$ParamsGET=$ParamsGET.'date2='.$date2.'&time2='.$time2.'&';
		if(strcasecmp($date2, 'now') == 0 || strcasecmp($date2, 'today') == 0){
			$date2 = date('Y-m-d');
		}elseif(strcasecmp($date2, 'yesterday') == 0){
			$date2 = date('Y-m-d', mktime(0, 0, 0, date('m')  , date('d')-1, date('Y')));
		}
		if(!$time2){
			$time2 = '23:59:59';
		}elseif(strcasecmp($time2, 'now') == 0){
			$time2 = date('H:i:s');
		}
		$timestamp2 = strtotime($date2.' '.$time2);
	}

	if($timestamp && $timestamp2){
		if($where != '') $where = $where.' AND ';
		if(isset($format)){
			$where = $where.' ' . $dbfield . ' between \''.date($format, $timestamp).'\' AND \''.date($format, $timestamp2).'\' ';
		}else{
			$where = $where.' ' . $dbfield . ' between ' . $timestamp . ' AND ' . $timestamp2 . ' ';
		}
	}elseif($timestamp){
		if($where != '') $where = $where.' AND ';
		if(isset($format)){
			$where = $where.' ' . $dbfield . ' > \''.date($format, $timestamp).'\' ';
		}else{
			$where = $where.' ' . $dbfield . ' > ' . $timestamp . ' ';
		}
	}elseif($timestamp2){
		if($where != '') $where = $where.' AND ';
		if(isset($format)){
			$where = $where.' ' . $dbfield . ' < \''.date($format, $timestamp2).'\' ';
		}else{
			$where = $where.' ' . $dbfield . ' < ' . $timestamp2 . ' ';
		}
	}
}

function msginputdb($dbfield){
	global $where;
	global $ParamsGET;

	$msgvarnum=1;
	$msgvarname='msg'.$msgvarnum;
	$excmsgvarname='ExcludeMsg'.$msgvarnum;
	$regexpmsgvarname='RegExpMsg'.$msgvarnum;

	while(isset($GLOBALS[$msgvarname])){
		if($where !=''){
			$where = $where.' AND ';
		}
		$where .= $dbfield;
		if($GLOBALS[$excmsgvarname] == '1'){
			$where .= ' NOT ';
			$ParamsGET .= $excmsgvarname.'='.$GLOBALS[$excmsgvarname].'&';
		}
		if($GLOBALS[$regexpmsgvarname] == '1'){
			$where .= ' RLIKE \''.$GLOBALS[$msgvarname].'\' ';
			$ParamsGET .= $regexpmsgvarname.'='.$GLOBALS[$regexpmsgvarname].'&';
		} else{
			$where .= ' LIKE \'%'.$GLOBALS[$msgvarname].'%\' ';
		}
		$ParamsGET .= $msgvarname.'='.$GLOBALS[$msgvarname].'&';

		$msgvarnum++;
		$msgvarname='msg'.$msgvarnum;
		$excmsgvarname='ExcludeMsg'.$msgvarnum;
		$regexpmsgvarname = 'RegExpMsg'.$msgvarnum;
	}
}

function dateinputgroup(){
	$caltoday = date('Y-m-d');

	return <<<END
<td><table align="center" class="formentry">
	<tr><td>&nbsp;</td>
		<td>DATE</td>
		<td>TIME</td>
	</tr>
	<tr><td><b>From:</b></td>
		<td><div id="myDatePickerDiv" width="100">
				<input type="text" id="date" name="date" onMouseover="return overlib('<TABLE border=1 cellspacing=0 cellpadding=0 width=100%><TR><TD class=tooltip>Click on the Calendar to SELECT the date.<br>The date format is YYYY-MM-DD and the time format is HH:MM:SS.<br>Yesterday, today and now are also valid dates and now is also valid as a time.<br>If you do not get a calendar popup, then manually enter the date as<br>YYYY-MM-DD<br>eg: {$caltoday}</TD></TR></TABLE>');" onMouseout="nd();" size="12">
				<img src="cal/buttons/bs_calendar.gif" id="fromdate_trigger">
				<script type="text/javascript">Calendar.setup({inputField:"date", ifFormat:"%Y-%m-%d", button:"fromdate_trigger", singleClick:true, weekNumbers:false, align:"Br"});</script>
			</div>
		</td>
		<td><input type="text" size=8 maxlength=8 name="time" id="time"></td>
	</tr>
	<tr><td><b>To:</b></td>
		<td><div id="myDatePickerDivR">
				<input type="text" id="date2" name="date2" onMouseover="return overlib('<TABLE border=1 cellspacing=0 cellpadding=0 width=100%><TR><TD class=tooltip>Click on the Calendar to SELECT the date.<br>The date format is YYYY-MM-DD and the time format is HH:MM:SS.<br>Yesterday, today and now are also valid dates and now is also valid as a time.<br>If you do not get a calendar popup, then manually enter the date as<br>YYYY-MM-DD<br>eg: {$caltoday}</TD></TR></TABLE>');" onMouseout="nd();" size="12">
				<img src="cal/buttons/bs_calendar.gif" id="todate_trigger">
				<script type="text/javascript">Calendar.setup({inputField:"date2", ifFormat:"%Y-%m-%d", button:"todate_trigger", singleClick:true, weekNumbers:false, align:"Br"});</script>
			</div>
		</td>
		<td><input type="text" size=8 maxlength=8 name="time2" id="time2"></td>
	</tr>
	<tr><td>&nbsp;</td>
		<td colspan="2">
			<input type="button" value="Today" onclick="set_today()">
			<input type="button" value="Yesterday" onclick="set_yesterday()">
			<input type="button" value="This Week" onclick="set_thisweek()">
		</td>
	</tr>
	</table>
</td>
END;
}
?>
Return current item: Php-Logging-System