Login   Register  
PHP Classes
elePHPant
Icontem

File: bt-include/functions.php

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Classes of Michael Dale  >  Bluetrait  >  bt-include/functions.php  >  Download  
File: bt-include/functions.php
Role: Auxiliary script
Content type: text/plain
Description: Common Functions File
Class: Bluetrait
A multi-user blog system
Author: By
Last change:
Date: 2008-10-26 03:23
Size: 26,615 bytes
 

Contents

Class file image Download
<?php
/*
	Bluetrait 2.0 Core Functions
	Michael Dale Copyright 2008
*/
function bt_get_config($config_name) {
	global $bt_config;

	if (isset($bt_config[$config_name])) {
		$str = 's';
		$array = 'a';
		$integer = 'i';
		$any = '[^}]*?';
		$count = '\d+';
		$content = '"(?:\\\";|.)*?";';
		$open_tag = '\{';
		$close_tag = '\}';
		$parameter = "($str|$array|$integer|$any):($count)" . "(?:[:]($open_tag|$content)|[;])";           
		$preg = "/$parameter|($close_tag)/";
		if(!preg_match_all($preg, $bt_config[$config_name], $matches)) {           
			return $bt_config[$config_name];
		}
		else {
			return unserialize($bt_config[$config_name]);
		}
	}
	else {
		return false;
	}
}

function bt_add_config($config_name, $config_value) {
	global $bt_config, $bt_db, $bt_tb;
	
	if (!isset($bt_config[$config_name])) {
		if (is_array($config_value)) {
			$bt_config[$config_name] = serialize($config_value);
		}
		else {
			$bt_config[$config_name] = $config_value;
		}
		$stmt = $bt_db->prepare("INSERT INTO $bt_tb->site (config_value, config_name) VALUES (?, ?)");
		$stmt->bindParam(1, $bt_config[$config_name]);
		$stmt->bindParam(2, $config_name);
		try {
			$stmt->execute();
		}
		catch (Exception $e) {
			bt_die($e->getMessage());
		}
	}
	else {
		return false;
	}
}

function bt_set_config($config_name, $config_value, $update_now = TRUE) {
	global $bt_config, $bt_tb, $bt_db, $bt_hard_config;
	
	bt_run_section('set_config', array('config_name' => &$config_name, 'config_value' => &$config_value, 'update_now' => &$update_now));
	
	if (isset($bt_hard_config[$config_name])) return false;
	
	if (is_array($config_value)) {
		$bt_config[$config_name] = serialize($config_value);
	}
	else {
		$bt_config[$config_name] = $config_value;
	}

	if ($update_now) {
		$stmt = $bt_db->prepare("UPDATE $bt_tb->site SET config_value = ? WHERE config_name = ?");
		$stmt->bindParam(1, $bt_config[$config_name]);
		$stmt->bindParam(2, $config_name);
		try {
			$stmt->execute();
		}
		catch (Exception $e) {
			bt_die($e->getMessage());
		}
	}

	return true;
}

function bt_hard_set_config($config_name, $config_value) {
	global $bt_hard_config;
	
	if (is_array($config_value)) {
		$bt_hard_config[$config_name] = serialize($config_value);
	}
	else {
		$bt_hard_config[$config_name] = $config_value;
	}
	return true;
}

function bt_save_config() {
	global $bt_db, $bt_tb, $bt_config, $bt_hard_config;

	bt_run_section('save_config');
	
	foreach($bt_config as $config_name => $config_value){
		if (isset($bt_hard_config[$config_name])) continue;
		$stmt = $bt_db->prepare("UPDATE $bt_tb->site SET config_value = ? WHERE config_name = ?");
		$stmt->bindParam(1, $config_value);
		$stmt->bindParam(2, $config_name);
		try {
			$stmt->execute();
		}
		catch (Exception $e) {
			bt_die($e->getMessage());
		}
	}
	return true;
}

function bt_delete_config($config_name) {
	global $bt_db, $bt_tb, $bt_config, $bt_hard_config;
	
	if (isset($bt_hard_config[$config_name])) return false;
	
	if (isset($bt_config[$config_name])) {	
		$stmt = $bt_db->prepare("DELETE FROM $bt_tb->site WHERE config_name = ?");
		$stmt->bindParam(1, $config_name);
		try {
			$stmt->execute();
		}
		catch (Exception $e) {
			bt_die($e->getMessage());
		}
		return true;
	}
	else {
		return false;
	}

}

function bt_load_config() {
	global $bt_db, $bt_tb, $bt_config, $bt_hard_config;
	
	$bt_config = $bt_hard_config;
	
	try {
		foreach ($bt_db->query("SELECT config_name, config_value from $bt_tb->site", PDO::FETCH_ASSOC) as $row) {
			if (isset($bt_hard_config[$row['config_name']])) {
				$bt_config[$row['config_name']] = $bt_hard_config[$row['config_name']];
				continue;
			}
			$bt_config[$row['config_name']] = $row['config_value'];
		}
	} catch (Exception $e) {
		bt_die($e->getMessage());
	}
	
	//generate site address, used for most things
	$port_number = '';
	if ($bt_config['https']) {
		if ($bt_config['port_number'] != 443) {
			$port_number = ':'.$bt_config['port_number'];
		}
		$bt_config['address'] = 'https://' . $bt_config['domain'] . $port_number . $bt_config['script_path'];
	}
	else {
		if ($bt_config['port_number'] != 80) {
			$port_number = ':'.$bt_config['port_number'];
		}
		$bt_config['address'] = 'http://' . $bt_config['domain'] . $port_number . $bt_config['script_path'];
	}

	$bt_hard_config['address'] = $bt_config['address'];
	
	return true;
}

/*
Only use this function if a serious error has occurred.
If you want to be lazy and stop any processing use bt_stop()
*/
function bt_die($die_message = '', $display_error_message = TRUE) {
	global $bt_config;
	//mail example will be changed.
	if(BT_MAIL_NOTIFY) {
		$email_message = "You are receiving this email as an error has occured on your site at the url \"" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] . "\".\n\r";
		$email_message .= "The error is as follows:\n\r";
		$email_message .= $die_message . "\n\r";
		$email_message .= "The following information may help you diagnose the error:\n\r";
		$email_message .= "DEBUG BACKTRACE:\n";
		$email_message .= print_r(debug_backtrace(), TRUE);
		$email_message .= "\n\n------------------\nError message was triggered from the IP address: " . bt_ip_address();
		@mail(BT_MAIL_NOTIFY_EMAIL, BT_MAIL_NOTIFY_SUBJECT, $email_message, 'From: ' . BT_MAIL_NOTIFY_EMAIL . "\r\nContent-Type: text/plain; charset=utf-8\r\n");
	}
	?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
			<html xmlns="http://www.w3.org/1999/xhtml">
				<head>
					<title>Bluetrait :: Error</title>
					<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
					<style type="text/css" media="screen">@import url(<?php echo BT_REL_ROOT; ?>bt-resources/css/admin-layout.css);</style>
				</head>
		
				<body>
				<div class="header">
					<div class="headerimg"></div>
				</div>
				<div class="body">
						<div class="contain">
							<h1>Bluetrait :: Error</h1>
							<h3><?php if ($display_error_message) echo $die_message; ?></h3>
							<pre><?php if(BT_MAIL_NOTIFY) echo 'An email has been sent to the administrator of this site informing them of the error. Please try again later.'; ?></pre>
						</div>
						<br />
						<div class="copyright">
							<p>Powered by <a href="http://www.bluetrait.org/">Bluetrait</a>.</p><?php echo $_SERVER['SERVER_SIGNATURE']; ?>
						</div>
				</div>
				</body>
			</html>
	<?php
	die();
}

function bt_stop($stop_message = '') {
?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
			<html xmlns="http://www.w3.org/1999/xhtml">
				<head>
					<title>Bluetrait :: Stop</title>
					<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
					<style type="text/css" media="screen">@import url(<?php echo BT_REL_ROOT; ?>bt-resources/css/admin-layout.css);</style>
				</head>
		
				<body>
				<div class="header">
					<div class="headerimg"></div>
				</div>
				<div class="body">
						<div class="contain">
							<h1>Bluetrait :: Stop</h1>
							<h3><?php echo $stop_message; ?></h3>
							<p><a href="<?php echo bt_get_config('address'); ?>/">&laquo; Home</a> <a href="<?php echo bt_get_config('address') . BT_ADMIN; ?>/">Admin Home &raquo;</a></p>
						</div>
						<br />
						<div class="copyright">
							<p>Powered by <a href="http://www.bluetrait.org/">Bluetrait</a>.</p><?php echo $_SERVER['SERVER_SIGNATURE']; ?>
						</div>
				</div>
				</body>
			</html>
	<?php
	exit;
}

// register_globals off
function bt_unregister_globals() {
	if (!ini_get('register_globals')) {
		return true;
	}

	// Might want to change this perhaps to a nicer error
	if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
		bt_die('GLOBALS overwrite attempt detected.');
	}

	// Variables that shouldn't be unset
	$noUnset = array('GLOBALS',  '_GET',
		'_POST',    '_COOKIE',
		'_REQUEST', '_SERVER',
		'_ENV',    '_FILES');

	$input = array_merge($_GET,    $_POST,
	$_COOKIE, $_SERVER,
	$_ENV,    $_FILES,
	
	isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());

	foreach ($input as $k => $v) {
		if (!in_array($k, $noUnset) && isset($GLOBALS[$k])) {
			unset($GLOBALS[$k]);
		}
	}

	return true;
}

function bt_shutdown_function() {
	global $bt_db;
	
	bt_run_section('shutdown');

	$bt_db = null;
}

//start the timer, works out page generation time
function bt_start_timer() {
	global $bt_tstart;
	
	$starttime = explode(' ', microtime());
	$bt_tstart = $starttime[1] + $starttime[0];
	
	return true;	
}

//stops the timer and returns the time it took for generation. Level of accuracy can be changed
function bt_stop_timer($accuracy = 4) {
	global $bt_tstart;
	
	$starttime = explode(' ', microtime());
	$tend = $starttime[1] + $starttime[0];
	$totaltime = number_format($tend - $bt_tstart, $accuracy);
	
	return $totaltime;
}

function bt_htmlentities($string) {

	return htmlentities($string, ENT_QUOTES, 'utf-8');
}

//set a header to be sent later
function bt_set_header($header) {
	global $bt_headers;
	
	$bt_headers[] = $header;
}

//sends HTTP headers
function bt_send_headers() {
	global $bt_headers;

	if (is_array($bt_headers)) {
		foreach ($bt_headers as $header) {
			header($header);
		}
	}

	return true;
}

//from phpbb3 beta 3
function bt_memory_usage() {
	
	if (function_exists('memory_get_usage')) {
		$total_memory = ini_get('memory_limit');
		$memory_usage = memory_get_usage();
		$memory_usage = ($memory_usage >= 1048576) ? round((round($memory_usage / 1048576 * 100) / 100), 2) . ' ' . 'MB' : (($memory_usage >= 1024) ? round((round($memory_usage / 1024 * 100) / 100), 2) . ' ' . 'KB' : $memory_usage . ' ' . 'BYTES');
		return $memory_usage;
	}
	else {
		return false;
	}
}

function bt_datetime($add_seconds = 0) {

	$base_time = time() + (int) $add_seconds + 3600 * bt_get_config('time_zone');

	return gmdate('Y-m-d H:i:s', $base_time);
}

function bt_datetime_utc($add_seconds = 0) {

	$base_time = time() + (int) $add_seconds;

	return gmdate('Y-m-d H:i:s', $base_time);
}

function bt_datetime_utc_from_datetime($datetime) {

	$date_utc = strtotime($datetime);
	$date_utc = strtotime('-' . bt_get_config('time_zone') . ' hours', $date_utc);
	return date('Y-m-d H:i:s', $date_utc);

}

function bt_datetime_user() {

}

function bt_ip_address() {

	return $_SERVER['REMOTE_ADDR'];
}

function bt_get_content_identifier() {
	global $bt_content_type;
	
	$bt_content_identifier['year'] = '';
	$bt_content_identifier['month'] = '';
	$bt_content_identifier['day'] = '';
	$bt_content_identifier['x_title'] = '';
	//blog, cms, rss etc
	$bt_content_identifier['type'] = 'blog';
	//send the user to a 404 unless the content type is picked up
	$bt_content_identifier['theme_type'] = '404';
	$bt_content_identifier['id'] = '';
	$bt_content_identifier['page'] = '';
	$bt_content_identifier['category'] = '';
	
	bt_run_section_ref('content_identifier_defaults', $bt_content_identifier);

	if (isset($_GET['bt_year'])) $bt_content_identifier['year'] = (int) $_GET['bt_year'];
	if (isset($_GET['bt_month'])) $bt_content_identifier['month'] = (int) $_GET['bt_month'];
	if (isset($_GET['bt_day'])) $bt_content_identifier['day'] = (int) $_GET['bt_day'];
	if (isset($_GET['bt_x_title'])) $bt_content_identifier['x_title'] = strtolower($_GET['bt_x_title']);
	if (isset($_GET['bt_type'])) $bt_content_identifier['type'] = strtolower($_GET['bt_type']);
	if (isset($_GET['bt_id'])) $bt_content_identifier['id'] = (int) $_GET['bt_id'];
	if (isset($_GET['bt_page'])) $bt_content_identifier['page'] = (int) $_GET['bt_page'];
	if (isset($_GET['bt_category'])) $bt_content_identifier['category'] = $_GET['bt_category'];

	if (empty($_GET['bt_year']) && empty($_GET['bt_month']) && empty($_GET['bt_day']) && empty($_GET['bt_x_title'])
	&& empty($_GET['bt_id']) && empty($_GET['bt_page']) && empty($_GET['bt_category'])) {
		$bt_content_identifier['empty'] = 1;
	}
	else {
		$bt_content_identifier['empty'] = 0;	
	}
	
	$bt_content_identifier['year']  = substr($bt_content_identifier['year'], 0, 4);
	$bt_content_identifier['month'] = substr($bt_content_identifier['month'], 0, 2);
	$bt_content_identifier['day'] = substr($bt_content_identifier['day'], 0, 2);
	
	if (isset($bt_content_type)) {
		$bt_content_identifier['type'] = strtolower($bt_content_type);
	}
	$bt_content_identifier['type'] = preg_replace('([^0-9a-z_\/])', '', $bt_content_identifier['type']);

	bt_run_section_ref('content_identifier', $bt_content_identifier);
	
	return $bt_content_identifier;

}
//makes title into one that works nicely in a url
function bt_x_title($title) {
	$title = strtolower($title);
	$title = str_replace(' ', '-', $title);
	$title = preg_replace('/&.+?;/', '', $title); // kill entities
	$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
	$title = preg_replace('/\s+/', '-', $title);
	//following line was having issues on ipod touch, need to look into it.
	//$title = preg_replace('|-+|', '-', $title);
	return $title;
}

//adds slashes to a value. This will add slashes to an array too.
function bt_add_magic_quotes($array) {

	foreach ($array as $key => $value) {
		if (is_array($value)) {
			$array[$key] = bt_add_magic_quotes($value);
		}
		else {
			$array[$key] = addslashes($value);
		}
	}

	return $array;
}

//removes slashes from a value. This will remove slashes from an array too.
function bt_remove_magic_quotes($array) {

	foreach ($array as $key => $value) {
		if (is_array($value)) {
			$array[$key] = bt_remove_magic_quotes($value);
		}
		else {
			$array[$key] = stripslashes($value);
		}
	}

	return $array;
} 

//serialize an array and put it into a cookie
function bt_set_cookie_array($array, $seconds = 31536000) {

	if (bt_get_config('domain') == 'localhost' || bt_get_config('domain') == '127.0.0.1') {
		$domain = '';
	}
	else {
		$domain = bt_get_config('domain');
	}
	if (setcookie(bt_get_config('cookie_name') . '_data', serialize($array), time() + $seconds, bt_get_config('script_path') . '/', $domain)) {
		return true;
	}
	else {
		return false;
	}
}
//return the array from the cookie
function bt_get_cookie_array() {

	if (isset($_COOKIE[bt_get_config('cookie_name') . '_data'])) {
		return bt_add_magic_quotes(unserialize(stripslashes($_COOKIE[bt_get_config('cookie_name') . '_data'])));
	}
	else {
		return false;
	}
}

//deletes a cookie
function bt_clear_cookie($seconds = 31536000) {

	if (bt_get_config('domain') == 'localhost' || bt_get_config('domain') == '127.0.0.1') {
		$domain = '';
	}
	else {
		$domain = bt_get_config('domain');
	}

	if (setcookie(bt_get_config('cookie_name') . '_data', '', time() - $seconds, bt_get_config('script_path') . '/', $domain)) {
		return true;
	}
	else {
		return false;
	}
}

//clears and deletes current session.
function bt_clear_session() {
	global $bt_session;

	$bt_session->destroy(session_id());
	
	return true;
	
}

function bt_load_user_data() {
	global $bt_db, $bt_tb;
	
	if (isset($_SESSION['bt_user_data']['user_id'])) {
		$user_id = (int) $_SESSION['bt_user_data']['user_id'];
		$query = "SELECT * FROM $bt_tb->users WHERE user_id = ? AND active = 1 LIMIT 1";
		$stmt = $bt_db->prepare($query);
		$stmt->bindParam(1, $user_id);
		
		try {
			$stmt->execute();
		}
		catch (Exception $e) {
			bt_die($e->getMessage());
		}
		$user_details = $stmt->fetch(PDO::FETCH_ASSOC);
		if ($user_details) {
			$user_array = array(
				'user_id' => $user_details['user_id'],
				'user_name' => $user_details['user_name'],
				'display_name' => $user_details['display_name'],
				'website' => $user_details['website'],
				'email' => $user_details['email'],
				'group_id' => $user_details['group_id'],
				'joined' => $user_details['joined'],
				'contact' => $user_details['contact'],
				'gui_editor' => $user_details['gui_editor']
			);
			$_SESSION['bt_user_data'] = $user_array;
			return true;
		}
		else {
			$_SESSION['bt_user_data'] = array();
			return false;
		}
	}
	else {
		return false;
	}

}

function bt_get_user_data($index_name) {
	
	if (isset($_SESSION['bt_user_data']) && !empty($_SESSION['bt_user_data'])) {
		$array = $_SESSION['bt_user_data'];
		
		if (isset($array[$index_name])) {
			return $array[$index_name];
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}

}

function bt_set_user_data($index_name, $value) {
	global $bt_db, $bt_tb;

	if (isset($_SESSION['bt_user_data']) && !empty($_SESSION['bt_user_data'])) {
		$user_id = (int) bt_get_user_data('user_id');
		if (array_key_exists($index_name, $_SESSION['bt_user_data']) && $user_id != 0) {
			switch ($index_name) {
				case 'gui_editor':
					$value = (int) $value;
					$query = "UPDATE $bt_tb->users SET gui_editor = :gui_editor WHERE user_id = :user_id";
					$stmt = $bt_db->prepare($query);
					$stmt->bindParam(':user_id', $user_id);
					$stmt->bindParam(':gui_editor', $value);
					try {
						$stmt->execute();
					}
					catch (Exception $e) {
						bt_die($e->getMessage());
					}
					$_SESSION['bt_user_data'][$index_name] = $value;
				break;
				
				case 'contact':
					$value = (int) $value;
					$query = "UPDATE $bt_tb->users SET contact = :contact WHERE user_id = :user_id";
					$stmt = $bt_db->prepare($query);
					$stmt->bindParam(':user_id', $user_id);
					$stmt->bindParam(':contact', $value);
					try {
						$stmt->execute();
					}
					catch (Exception $e) {
						bt_die($e->getMessage());
					}
					$_SESSION['bt_user_data'][$index_name] = $value;
				
				break;
				
				case 'email':
					$query = "UPDATE $bt_tb->users SET email = :email WHERE user_id = :user_id";
					$stmt = $bt_db->prepare($query);
					$stmt->bindParam(':user_id', $user_id);
					$stmt->bindParam(':email', $value);
					try {
						$stmt->execute();
					}
					catch (Exception $e) {
						bt_die($e->getMessage());
					}
					$_SESSION['bt_user_data'][$index_name] = $value;
				
				break;
				
				case 'website':
					$query = "UPDATE $bt_tb->users SET website = :website WHERE user_id = :user_id";
					$stmt = $bt_db->prepare($query);
					$stmt->bindParam(':user_id', $user_id);
					$stmt->bindParam(':website', $value);
					try {
						$stmt->execute();
					}
					catch (Exception $e) {
						bt_die($e->getMessage());
					}
					$_SESSION['bt_user_data'][$index_name] = $value;
				
				break;
				
				case 'display_name':
					$query = "UPDATE $bt_tb->users SET display_name = :display_name WHERE user_id = :user_id";
					$stmt = $bt_db->prepare($query);
					$stmt->bindParam(':user_id', $user_id);
					$stmt->bindParam(':display_name', $value);
					try {
						$stmt->execute();
					}
					catch (Exception $e) {
						bt_die($e->getMessage());
					}
					$_SESSION['bt_user_data'][$index_name] = $value;
				
				break;
			
			}
			return true;
		}
		else {
			return false;
		}
	}
	else {
		return false;
	}

}

function bt_is_logged_in() {

	if (bt_get_user_data('user_name')) {
		return true;
	}
	else {
		return false;
	}

}

function bt_feed_comments_setup() {
	global $bt_comment_array;

	$bt_content_identifier['limit'] = 10;
	$bt_content_identifier['order'] = 1;
	$bt_content_identifier['get_posts'] = true;
	
	$bt_comments = new bt_comments();
	$bt_comment_array = $bt_comments->get_comments($bt_content_identifier);

}
function bt_trigger_error($error_number, $error_string, $error_file, $error_line, $error_context = '') {
		bt_error_report($error_number, $error_string, $error_file, $error_line, $error_context);
}
function bt_error_report($error_number, $error_string, $error_file, $error_line, $error_context) {
		global $bt_db, $bt_tb;

		if (BT_DEBUG) {
			echo '<br />' . $error_number . ': ' . $error_string .  ' in <b>' . $error_file . '</b> on line <b>' . $error_line . '</b>';
		}

		$user_id = (int) bt_get_user_data('user_id');
		
		switch ($error_number) {	
		  case E_USER_ERROR:

				$type = 'ERROR';
				
				/*
				Get the backtrace here
				*/
				ob_start();
				debug_print_backtrace();
				$trace = ob_get_contents();
				ob_end_clean();
				
		  		$stmt = $bt_db->prepare("INSERT INTO $bt_tb->events 
				(user_id, event_date, event_date_utc, file, file_line, type, ip_address, event_no, description, trace) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
				$stmt->bindParam(1, $user_id);
				$stmt->bindParam(2, bt_datetime());
				$stmt->bindParam(3, bt_datetime_utc());
				$stmt->bindParam(4, $error_file);
				$stmt->bindParam(5, $error_line);
				$stmt->bindParam(6, $type);
				$stmt->bindParam(7, bt_ip_address());
				$stmt->bindParam(8, $error_number);
				$stmt->bindParam(9, $error_string);
				$stmt->bindParam(10, $trace);
				
				try {
					$stmt->execute();
				}
				catch (Exception $e) {
					bt_die($e->getMessage());
				}
	
		   break;
		  case E_USER_WARNING:
		  
		  		$type = 'WARNING';
		  		
				$stmt = $bt_db->prepare("INSERT INTO $bt_tb->events 
				(user_id, event_date, event_date_utc, file, file_line, type, ip_address, event_no, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
				$stmt->bindParam(1, $user_id);
				$stmt->bindParam(2, bt_datetime());
				$stmt->bindParam(3, bt_datetime_utc());
				$stmt->bindParam(4, $error_file);
				$stmt->bindParam(5, $error_line);
				$stmt->bindParam(6, $type);
				$stmt->bindParam(7, bt_ip_address());
				$stmt->bindParam(8, $error_number);
				$stmt->bindParam(9, $error_string);

				try {
					$stmt->execute();
				}
				catch (Exception $e) {
					bt_die($e->getMessage());
				}
		   
			break;
		  case E_USER_NOTICE:
		  
				$type = 'NOTICE';
				
		  		$stmt = $bt_db->prepare("INSERT INTO $bt_tb->events 
				(user_id, event_date, event_date_utc, file, file_line, type, ip_address, event_no, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
				$stmt->bindParam(1, $user_id);
				$stmt->bindParam(2, bt_datetime());
				$stmt->bindParam(3, bt_datetime_utc());
				$stmt->bindParam(4, $error_file);
				$stmt->bindParam(5, $error_line);
				$stmt->bindParam(6, $type);
				$stmt->bindParam(7, bt_ip_address());
				$stmt->bindParam(8, $error_number);
				$stmt->bindParam(9, $error_string);
				
				try {
					$stmt->execute();
				}
				catch (Exception $e) {
					bt_die($e->getMessage());
				}

			break;
		  default:
		  		if(BT_LOG_ALL) {
				}
		   break;
		}
		
}
function bt_uuid()
/* Copyright 2006 Maciej Strzelecki

   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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA 
 */
{
   // version 4 UUID
   return sprintf(
       '%08x-%04x-%04x-%02x%02x-%012x',
       mt_rand(),
       mt_rand(0, 65535),
       bindec(substr_replace(
           sprintf('%016b', mt_rand(0, 65535)), '0100', 11, 4)
       ),
       bindec(substr_replace(sprintf('%08b', mt_rand(0, 255)), '01', 5, 2)),
       mt_rand(0, 255),
       mt_rand()
   );
}

function bt_check_time($time) {
	$pass = true;
	
	$time = explode(':', $time);
	
	if ($time[0] >= 0 && $time[0] <= 24 && $time[1] >= 0 && $time[1] <= 59 && $time[2] >= 0 && $time[2] <= 59) {
	}
	else {
		$pass = false;
	}
	if (array_key_exists(3, $time)) $pass = false;
	
	return $pass;
}

function bt_check_date($date) {
	
	$date = explode('-', $date);
	if (!isset($date[0]) || !isset($date[1]) || !isset($date[2])) return false;
	if (!checkdate($date[1], $date[2], $date[0])) return false;
	if (array_key_exists(3, $date)) return false;
	
	return true;
}

function bt_check_datetime($datetime) {

	$pass = true;
	$array = explode(' ', $datetime);
	
	if (!bt_check_date($array[0])) $pass = false;
	if(array_key_exists(1, $array)) {
		if (!bt_check_time($array[1])) $pass = false;
	}
	if (array_key_exists(2, $array)) $pass = false;

	return $pass;
}

function bt_gzip() {

	if (BT_OUTPUT_BUFFERING) {
		if (bt_get_config('gzip') && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && extension_loaded('zlib')) {
			ob_start('ob_gzhandler');
			bt_set_header('Content-Encoding: gzip');
			return true;
		}
		else {
			ob_start();
			return false;
		}
	}
	else {
		return false;
	}
}

function bt_remove_end_slash($script_path) {
		
	if(substr($script_path, -1) == '/') {	
		$script_path = substr($script_path, 0, strlen($script_path) - 1);
		$script_path = bt_remove_end_slash($script_path);
	}
	return $script_path;
}

function bt_check_email_address($email) {

	$email_pattern = '/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i';
	
	if (preg_match($email_pattern, $email)) {
		return true;
	}
	else {
		return false;
	}
}

function bt_check_email_address_taken($user_id, $email) {
	global $bt_db, $bt_tb;
	$user_id = (int) $user_id;
	$query = "SELECT count(*) FROM $bt_tb->users WHERE email = :email AND user_id != :user_id";
	$stmt = $bt_db->prepare($query);
	$stmt->bindParam(':user_id', $user_id);
	$stmt->bindParam(':email', $email);
	try {
		$stmt->execute();
	}
	catch (Exception $e) {
		bt_die($e->getMessage());
	}

	$count = $stmt->fetch(PDO::FETCH_ASSOC);
	if ($count['count(*)'] != 0) {
		//already in list
		return true;
	}
	else {
		return false;
	}

}
function bt_sanitize_user_name($user_name) {

		//converts username to lowercase.
		$user_name = strtolower($user_name);
		
		//only allow a-z, 0-9 - and _ characters.
		$user_name = preg_replace('([^a-z0-9_-])', '', $user_name);
		
		return $user_name;

}
?>