Location: PHPKode > projects > raSMP > rasmp/common/functions.php
<?php

/*******************************************************************

 Name		: raSMP 2.0
 Copyright	: 2002, Adam Alkins
 Website	: http://www.rasmp.com
 email		: hide@address.com

 $Id: functions.php,v 1.44 2003/03/22 00:53:35 rasadam Exp $: 

*******************************************************************/

/*******************************************************************

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the 
Free Software Foundation Inc., 59 Temple Place, Suite 330,
Boston, MA  02111-1307  USA

*******************************************************************/

/*

Common Functions

*/

if ( !defined('RASMP') )
{
	die('Unauthorised Access Denied');
}

//
// This error is usually used when nothing has been displayed on the screen
// as yet. It will kill the script and display a nice little error to boot
// if needed.
//
function fatal_error($errormsg, $sql_error, $query, $die = 1)
{
    echo "Fatal Error: $errormsg<br />";
	
	if($sql_error != '')
	{
		echo "$sql_error<br />";
	}
	
	if($query != '')
	{
		echo strip_tags($query)."<br />";
	}
	
	if($die == 1)
	{
		die;
	}
}

//
// Store visitor information (You should mention in your privacy policy what information you store (!)
//
function record_hit($page_id = -1)
{
	$query = "INSERT INTO ".HITS_TABLE." (page_id, date, ip, php_self, referrer, language, server_name, comp_details) VALUES(".$page_id.", ".date("U").", '".format_ipv6($_SERVER['REMOTE_ADDR'])."', '".$_SERVER['PHP_SELF']."','".$_SERVER['HTTP_REFERER']."','".$_SERVER['HTTP_ACCEPT_LANGUAGE']."','".$_SERVER['SERVER_NAME']."','".$_SERVER['HTTP_USER_AGENT']."')";
	db_query($query, 'Could not insert row into Hits table');
}

//
// Checks if the user is banned or not and does appropriate. You can customise
// how the ban screen looks here also.
//
function check_banned($ip,$page)
{
	global $ban_message;

	if(!check_ban_ip($ip))
	{
		return false;
	}
	else
	{
		$ban_data = check_ban_ip($ip,1);
		
		if(is_ipv4($ip))
		{
			$ip = format_ipv6($ip);
		}
		
		$query = "INSERT INTO ".BAN_ATTEMPTS_TABLE." (ban_id, ip, date, page_id) VALUES(".$ban_data['ban_id'].", '".$ip."', ".date("U").", $page)";
		db_query($query, 'Could not insert ban attempt information');
		
		$ban_message = stripslashes($ban_data['comment']);
		
		return true;
	}
}

// Displays a message in a big grayscale screen
function display_message($message,$die = 1)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $message; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>

<body bgcolor="#999999" link="#FFFFFF" vlink="#FFFFFF" alink="#FFFFFF">
<table width="100%" height="75%" border="1" cellpadding="20" cellspacing="0" bordercolor="#FFFFFF" bgcolor="#CCCCCC">
  <tr>
    <td align="center" valign="middle"><div align="center"><strong><font color="#000000" size="3" face="Times New Roman, Times, serif"><?php echo $message; ?></font></strong></div></td>
  </tr>
</table>
<div align="center"><font size="2" color="#FFFFFF">Powered by <a href="http://www.rasmp.com">raSMP</a> 
  <?php echo RASMP_VERSION; ?></font></div>
</body>
</html>
<?php
	if($die == 1)
	{
		die;
	}
}

// clean strings that have no need for these characters
function clean($string)
{
	$string = str_replace("'","",$string);
	$string = str_replace("\"","",$string);
	$string = str_replace(",","",$string);
	$string = str_replace("(","",$string);
	$string = str_replace(")","",$string);
	$string = str_replace("NUL","\NUL",$string);
	return $string;
}

// clean a string that is going to be used publicly in urls
function clean_public($string)
{
	$string = str_replace(" ","",$string);
	$string = str_replace("\"","",$string);
	$string = str_replace("'","",$string);
	$string = str_replace("\\","",$string);
	$string = str_replace("/","",$string);
	$string = str_replace("(","",$string);
	$string = str_replace(")","",$string);
	$string = str_replace("*","",$string);
	$string = str_replace("#","",$string);
	$string = str_replace("^","",$string);
	$string = str_replace("?","",$string);
	$string = str_replace("=","",$string);
	return $string;
}

// Format an ipv4 string to an ipv6
function format_ipv6($ip, $long = 0)
{
	if(!strstr($ip,":"))
	{
		if($long == 0)
		{
			return "::".$ip;
		}
		else
		{
			return "0000:0000:0000:0000:0000:0000:".$ip;
		}
	}
	
	return $ip;
}

// this function will look for obvious invalid email addresses
// Note: Will not check for dotted domains because if used on an intranet,
// a dotted domain isn't neccessary
function validate_email($email)
{
	return preg_match("/^[-a-zA-Z0-9_.]+@[-a-zA-Z0-9_.]+$/",$email);
}

// Format an ipv4 string (in ipv6 form) to an ipv4 string
function format_ipv4($ip, $long = 0)
{
	$ip = str_replace(":","",$ip);
	
	if($long == 1)
	{
		return ip2long($ip);
	}
		
	return $ip;
}
	
// Check an IP to see if its IPv4 (Checks for both in regular IPv4 format or in IPv6 format (long or short))
function is_ipv4($ip)
{
	return preg_match("/^(::|0000:0000:0000:0000:0000:0000:)?([0-9]{1,2}|[0-2][0-9]{0,2})(\.([0-9]{1,2}|[0-2][0-9]{0,2})){3}$/",$ip);
}

// checks if IP exists
function check_ban_ip($ip, $return = 0)
{
	if(!strstr($ip,":"))
	{	
		$split_ip = explode(".",$ip);
		$query = "SELECT ban_id,comment FROM ".BANS_TABLE." WHERE ip IN( '::".$ip."', '::".$split_ip[0].".".$split_ip[1].".".$split_ip[2]."', '::".$split_ip[0].".".$split_ip[1]."', '::".$split_ip[0]."' ) AND ipv6 = 0";
	}
	else if(strstr($ip,"."))
	{
		$ip = format_ipv4($ip);

		$split_ip = explode(".",$ip);
		$query = "SELECT ban_id,comment FROM ".BANS_TABLE." WHERE ip IN( '::".$ip."', '::".$split_ip[0].".".$split_ip[1].".".$split_ip[2]."', '::".$split_ip[0].".".$split_ip[1]."', '::".$split_ip[0]."' ) AND ipv6 = 0";
	}
	else
	{
		$query = "SELECT ban_id,comment FROM ".BANS_TABLE." WHERE ip = '".$ip."' AND ipv6 = 1";
	}
	
	$result = db_query($query, 'Could not query Ban Table');
	if(db_numrows($result)==0)
	{
		return false;
	}
		
	if($return == 1)
	{
		$row_data = db_fetchassoc($result);
		return $row_data;
	}
	else
	{
		return true;
	}
}

// see if ip exists (works a bit differently from check_ban_ip)
function ip_exists($ip, $table = BANS_TABLE, $ipcolumn = 'ip', $select = 'ip', $args = '', $return = 0)
{
	if(strstr($ip,"."))
	{	
		$ip = format_ipv4($ip);

		$split_ip = explode(".",$ip);
		$num = count($split_ip);
		
		if($num == 2)
		{
			$query = "SELECT $select FROM $table WHERE $ipcolumn IN( '::".$ip."', '::".$split_ip[0]."' )".$args;
		}
		else if($num == 3)
		{
			$query = "SELECT $select FROM $table WHERE $ipcolumn IN( '::".$ip."', '::".$split_ip[0].".".$split_ip[1]."', '::".$split_ip[0]."' )".$args;
		}
		else if($num == 4)
		{
			$query = "SELECT $select FROM $table WHERE $ipcolumn IN( '::".$ip."', '::".$split_ip[0].".".$split_ip[1].".".$split_ip[2]."', '::".$split_ip[0].".".$split_ip[1]."', '::".$split_ip[0]."' )".$args;
		}
		else
		{
			$query = "SELECT $select FROM $table WHERE $ipcolumn = '::".$ip."'".$args;
		}
	}
	else
	{
		$query = "SELECT $select FROM $table WHERE $ipcolumn = '".$ip."'".$args;
	}
	
	$result = db_query($query, 'Could not query ip information');
	if(db_numrows($result)==0)
	{
		return false;
	}
	else
	{
		if($return == 1)
		{
			$row_data = db_fetchrows($result);
			return $row_data;
		}
		else
		{
			return true;
		}
	}
}

//
// Gets raSMP config values
//
function get_config_values($columns = '*', $where = '')
{
	$query = "SELECT ".$columns." FROM ".CONFIG_TABLE.$where;
	$result = db_query($query,'Could not fetch config values');
	
	for($i = 0; $i < db_numrows($result);$i++)
	{
		$row_data = db_fetchassoc($result);
		$config_array[$row_data['config_name']] = $row_data['config_value'];
	}
	
	return $config_array;
}

//
// Direct from phpBB
//
function split_sql_file($sql, $delimiter)
{
	// Split up our string into "possible" SQL statements.
	$tokens = explode($delimiter, $sql);

	// try to save mem.
	$sql = "";
	$output = array();
	
	// we don't actually care about the matches preg gives us.
	$matches = array();
	
	// this is faster than calling count($oktens) every time thru the loop.
	$token_count = count($tokens);
	for ($i = 0; $i < $token_count; $i++)
	{
		// Don't wanna add an empty string as the last thing in the array.
		if (($i != ($token_count - 1)) || (strlen($tokens[$i] > 0)))
		{
			// This is the total number of single quotes in the token.
			$total_quotes = preg_match_all("/'/", $tokens[$i], $matches);
			// Counts single quotes that are preceded by an odd number of backslashes, 
			// which means they're escaped quotes.
			$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$i], $matches);
			
			$unescaped_quotes = $total_quotes - $escaped_quotes;
			
			// If the number of unescaped quotes is even, then the delimiter did NOT occur inside a string literal.
			if (($unescaped_quotes % 2) == 0)
			{
				// It's a complete sql statement.
				$output[] = $tokens[$i];
				// save memory.
				$tokens[$i] = "";
			}
			else
			{
				// incomplete sql statement. keep adding tokens until we have a complete one.
				// $temp will hold what we have so far.
				$temp = $tokens[$i] . $delimiter;
				// save memory..
				$tokens[$i] = "";
				
				// Do we have a complete statement yet? 
				$complete_stmt = false;
				
				for ($j = $i + 1; (!$complete_stmt && ($j < $token_count)); $j++)
				{
					// This is the total number of single quotes in the token.
					$total_quotes = preg_match_all("/'/", $tokens[$j], $matches);
					// Counts single quotes that are preceded by an odd number of backslashes, 
					// which means they're escaped quotes.
					$escaped_quotes = preg_match_all("/(?<!\\\\)(\\\\\\\\)*\\\\'/", $tokens[$j], $matches);
			
					$unescaped_quotes = $total_quotes - $escaped_quotes;
					
					if (($unescaped_quotes % 2) == 1)
					{
						// odd number of unescaped quotes. In combination with the previous incomplete
						// statement(s), we now have a complete statement. (2 odds always make an even)
						$output[] = $temp . $tokens[$j];

						// save memory.
						$tokens[$j] = "";
						$temp = "";
						
						// exit the loop.
						$complete_stmt = true;
						// make sure the outer loop continues at the right point.
						$i = $j;
					}
					else
					{
						// even number of unescaped quotes. We still don't have a complete statement. 
						// (1 odd and 1 even always make an odd)
						$temp .= $tokens[$j] . $delimiter;
						// save memory.
						$tokens[$j] = "";
					}
					
				} // for..
			} // else
		}
	}

	return $output;
}

?>
Return current item: raSMP