Index: trunk/web/punbb/include/cache.php
===================================================================
--- trunk/web/punbb/include/cache.php	(revision 10)
+++ trunk/web/punbb/include/cache.php	(revision 1)
@@ -1,9 +1,26 @@
 <?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+/***********************************************************************
+
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // Make sure no one attempts to run this script "directly"
@@ -13,4 +30,49 @@
 
 //
+// If we are running pre PHP 4.2.0, we add our own implementation of var_export
+//
+if (!function_exists('var_export'))
+{
+	function var_export()
+	{
+		$args = func_get_args();
+		$indent = (isset($args[2])) ? $args[2] : '';
+
+		if (is_array($args[0]))
+		{
+			$output = 'array ('."\n";
+
+			foreach ($args[0] as $k => $v)
+			{
+				if (is_numeric($k))
+					$output .= $indent.'  '.$k.' => ';
+				else
+					$output .= $indent.'  \''.str_replace('\'', '\\\'', str_replace('\\', '\\\\', $k)).'\' => ';
+
+				if (is_array($v))
+					$output .= var_export($v, true, $indent.'  ');
+				else
+				{
+					if (gettype($v) != 'string' && !empty($v))
+						$output .= $v.','."\n";
+					else
+						$output .= '\''.str_replace('\'', '\\\'', str_replace('\\', '\\\\', $v)).'\','."\n";
+				}
+			}
+
+			$output .= ($indent != '') ? $indent.'),'."\n" : ')';
+		}
+		else
+			$output = $args[0];
+
+		if ($args[1] == true)
+			return $output;
+		else
+			echo $output;
+	}
+}
+
+
+//
 // Generate the config cache PHP script
 //
@@ -20,19 +82,16 @@
 
 	// Get the forum config from the DB
-	$result = $db->query('SELECT * FROM '.$db->prefix.'config', true) or error('Unable to fetch forum config', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT * FROM '.$db->prefix.'config', true) or error('Impossible de retrouver la configuration des forums', __FILE__, __LINE__, $db->error());
 	while ($cur_config_item = $db->fetch_row($result))
 		$output[$cur_config_item[0]] = $cur_config_item[1];
 
 	// Output config as PHP code
-	$fh = @fopen(FORUM_CACHE_DIR.'cache_config.php', 'wb');
+	$fh = @fopen(PUN_ROOT.'cache/cache_config.php', 'wb');
 	if (!$fh)
-		error('Unable to write configuration cache file to cache directory. Please make sure PHP has write access to the directory \''.pun_htmlspecialchars(FORUM_CACHE_DIR).'\'', __FILE__, __LINE__);
+		error('Impossible d\'Ã©crire le fichier cache de configuration dans le rÃ©pertoire cache. Veuillez vous assurer que PHP a l\'accÃšs en Ã©crire au rÃ©pertoire \'cache\'', __FILE__, __LINE__);
 
 	fwrite($fh, '<?php'."\n\n".'define(\'PUN_CONFIG_LOADED\', 1);'."\n\n".'$pun_config = '.var_export($output, true).';'."\n\n".'?>');
 
 	fclose($fh);
-
-	if (function_exists('apc_delete_file'))
-		@apc_delete_file(FORUM_CACHE_DIR.'cache_config.php');
 }
 
@@ -46,5 +105,5 @@
 
 	// Get the ban list from the DB
-	$result = $db->query('SELECT * FROM '.$db->prefix.'bans', true) or error('Unable to fetch ban list', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT * FROM '.$db->prefix.'bans', true) or error('Impossible de retrouver la liste de bannissements', __FILE__, __LINE__, $db->error());
 
 	$output = array();
@@ -53,14 +112,11 @@
 
 	// Output ban list as PHP code
-	$fh = @fopen(FORUM_CACHE_DIR.'cache_bans.php', 'wb');
+	$fh = @fopen(PUN_ROOT.'cache/cache_bans.php', 'wb');
 	if (!$fh)
-		error('Unable to write bans cache file to cache directory. Please make sure PHP has write access to the directory \''.pun_htmlspecialchars(FORUM_CACHE_DIR).'\'', __FILE__, __LINE__);
+		error('Impossible d\'Ã©crire le fichier cache de bannissements dans le rÃ©pertoire cache. Veuillez vous assurer que PHP a l\'accÃšs en Ã©crire au rÃ©pertoire \'cache\'', __FILE__, __LINE__);
 
 	fwrite($fh, '<?php'."\n\n".'define(\'PUN_BANS_LOADED\', 1);'."\n\n".'$pun_bans = '.var_export($output, true).';'."\n\n".'?>');
 
 	fclose($fh);
-
-	if (function_exists('apc_delete_file'))
-		@apc_delete_file(FORUM_CACHE_DIR.'cache_bans.php');
 }
 
@@ -74,5 +130,5 @@
 
 	// Get the rank list from the DB
-	$result = $db->query('SELECT * FROM '.$db->prefix.'ranks ORDER BY min_posts', true) or error('Unable to fetch rank list', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT * FROM '.$db->prefix.'ranks ORDER BY min_posts', true) or error('Impossible de retrouver la liste des rangs utilisateurs', __FILE__, __LINE__, $db->error());
 
 	$output = array();
@@ -81,19 +137,16 @@
 
 	// Output ranks list as PHP code
-	$fh = @fopen(FORUM_CACHE_DIR.'cache_ranks.php', 'wb');
+	$fh = @fopen(PUN_ROOT.'cache/cache_ranks.php', 'wb');
 	if (!$fh)
-		error('Unable to write ranks cache file to cache directory. Please make sure PHP has write access to the directory \''.pun_htmlspecialchars(FORUM_CACHE_DIR).'\'', __FILE__, __LINE__);
+		error('Impossible d\'Ã©crire le fichier de cache de rangs utilisateurs dans le rÃ©pertoire cache. Veuillez vous assurer que PHP a l\'accÃšs en Ã©crire au rÃ©pertoire \'cache\'', __FILE__, __LINE__);
 
 	fwrite($fh, '<?php'."\n\n".'define(\'PUN_RANKS_LOADED\', 1);'."\n\n".'$pun_ranks = '.var_export($output, true).';'."\n\n".'?>');
 
 	fclose($fh);
-
-	if (function_exists('apc_delete_file'))
-		@apc_delete_file(FORUM_CACHE_DIR.'cache_ranks.php');
-}
-
-
-//
-// Generate quick jump cache PHP scripts
+}
+
+
+//
+// Generate quickjump cache PHP scripts
 //
 function generate_quickjump_cache($group_id = false)
@@ -101,183 +154,52 @@
 	global $db, $lang_common, $pun_user;
 
-	$groups = array();
-
-	// If a group_id was supplied, we generate the quick jump cache for that group only
+	// If a group_id was supplied, we generate the quickjump cache for that group only
 	if ($group_id !== false)
-	{
-		// Is this group even allowed to read forums?
-		$result = $db->query('SELECT g_read_board FROM '.$db->prefix.'groups WHERE g_id='.$group_id) or error('Unable to fetch user group read permission', __FILE__, __LINE__, $db->error());
-		$read_board = $db->result($result);
-
-		$groups[$group_id] = $read_board;
-	}
+		$groups[0] = $group_id;
 	else
 	{
-		// A group_id was not supplied, so we generate the quick jump cache for all groups
-		$result = $db->query('SELECT g_id, g_read_board FROM '.$db->prefix.'groups') or error('Unable to fetch user group list', __FILE__, __LINE__, $db->error());
+		// A group_id was now supplied, so we generate the quickjump cache for all groups
+		$result = $db->query('SELECT g_id FROM '.$db->prefix.'groups') or error('Impossible de retrouver la liste des groupes utilisateurs', __FILE__, __LINE__, $db->error());
 		$num_groups = $db->num_rows($result);
 
-		while ($row = $db->fetch_row($result))
-			$groups[$row[0]] = $row[1];
+		for ($i = 0; $i < $num_groups; ++$i)
+			$groups[] = $db->result($result, $i);
 	}
 
 	// Loop through the groups in $groups and output the cache for each of them
-	foreach ($groups as $group_id => $read_board)
+	while (list(, $group_id) = @each($groups))
 	{
-		// Output quick jump as PHP code
-		$fh = @fopen(FORUM_CACHE_DIR.'cache_quickjump_'.$group_id.'.php', 'wb');
+		// Output quickjump as PHP code
+		$fh = @fopen(PUN_ROOT.'cache/cache_quickjump_'.$group_id.'.php', 'wb');
 		if (!$fh)
-			error('Unable to write quick jump cache file to cache directory. Please make sure PHP has write access to the directory \''.pun_htmlspecialchars(FORUM_CACHE_DIR).'\'', __FILE__, __LINE__);
-
-		$output = '<?php'."\n\n".'if (!defined(\'PUN\')) exit;'."\n".'define(\'PUN_QJ_LOADED\', 1);'."\n".'$forum_id = isset($forum_id) ? $forum_id : 0;'."\n\n".'?>';
-
-		if ($read_board == '1')
+			error('Impossible d\'Ã©crire le fichier cache de saut rapide de forums dans le rÃ©pertoire cache. Veuillez vous assurer que PHP a l\'accÃšs en Ã©crire au rÃ©pertoire \'cache\'', __FILE__, __LINE__);
+
+		$output = '<?php'."\n\n".'if (!defined(\'PUN\')) exit;'."\n".'define(\'PUN_QJ_LOADED\', 1);'."\n\n".'?>';
+		$output .= "\t\t\t\t".'<form id="qjump" method="get" action="viewforum.php">'."\n\t\t\t\t\t".'<div><label><?php echo $lang_common[\'Jump to\'] ?>'."\n\n\t\t\t\t\t".'<br /><select name="id" onchange="window.location=(\'viewforum.php?id=\'+this.options[this.selectedIndex].value)">'."\n";
+
+
+		$result = $db->query('SELECT c.id AS cid, c.cat_name, f.id AS fid, f.forum_name, f.redirect_url FROM '.$db->prefix.'categories AS c INNER JOIN '.$db->prefix.'forums AS f ON c.id=f.cat_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$group_id.') WHERE fp.read_forum IS NULL OR fp.read_forum=1 ORDER BY c.disp_position, c.id, f.disp_position', true) or error('Impossible de retrouver la liste des catÃ©gories et des forums', __FILE__, __LINE__, $db->error());
+
+		$cur_category = 0;
+		while ($cur_forum = $db->fetch_assoc($result))
 		{
-			$result = $db->query('SELECT c.id AS cid, c.cat_name, f.id AS fid, f.forum_name, f.redirect_url FROM '.$db->prefix.'categories AS c INNER JOIN '.$db->prefix.'forums AS f ON c.id=f.cat_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$group_id.') WHERE fp.read_forum IS NULL OR fp.read_forum=1 ORDER BY c.disp_position, c.id, f.disp_position') or error('Unable to fetch category/forum list', __FILE__, __LINE__, $db->error());
-
-			if ($db->num_rows($result))
+			if ($cur_forum['cid'] != $cur_category)	// A new category since last iteration?
 			{
-				$output .= "\t\t\t\t".'<form id="qjump" method="get" action="viewforum.php">'."\n\t\t\t\t\t".'<div><label><span><?php echo $lang_common[\'Jump to\'] ?>'.'<br /></span>'."\n\t\t\t\t\t".'<select name="id" onchange="window.location=(\'viewforum.php?id=\'+this.options[this.selectedIndex].value)">'."\n";
-
-				$cur_category = 0;
-				while ($cur_forum = $db->fetch_assoc($result))
-				{
-					if ($cur_forum['cid'] != $cur_category) // A new category since last iteration?
-					{
-						if ($cur_category)
-							$output .= "\t\t\t\t\t\t".'</optgroup>'."\n";
-
-						$output .= "\t\t\t\t\t\t".'<optgroup label="'.pun_htmlspecialchars($cur_forum['cat_name']).'">'."\n";
-						$cur_category = $cur_forum['cid'];
-					}
-
-					$redirect_tag = ($cur_forum['redirect_url'] != '') ? ' &gt;&gt;&gt;' : '';
-					$output .= "\t\t\t\t\t\t\t".'<option value="'.$cur_forum['fid'].'"<?php echo ($forum_id == '.$cur_forum['fid'].') ? \' selected="selected"\' : \'\' ?>>'.pun_htmlspecialchars($cur_forum['forum_name']).$redirect_tag.'</option>'."\n";
-				}
-
-				$output .= "\t\t\t\t\t\t".'</optgroup>'."\n\t\t\t\t\t".'</select>'."\n\t\t\t\t\t".'<input type="submit" value="<?php echo $lang_common[\'Go\'] ?>" accesskey="g" />'."\n\t\t\t\t\t".'</label></div>'."\n\t\t\t\t".'</form>'."\n";
+				if ($cur_category)
+					$output .= "\t\t\t\t\t\t".'</optgroup>'."\n";
+
+				$output .= "\t\t\t\t\t\t".'<optgroup label="'.pun_htmlspecialchars($cur_forum['cat_name']).'">'."\n";
+				$cur_category = $cur_forum['cid'];
 			}
+
+			$redirect_tag = ($cur_forum['redirect_url'] != '') ? ' &gt;&gt;&gt;' : '';
+			$output .= "\t\t\t\t\t\t\t".'<option value="'.$cur_forum['fid'].'"<?php echo ($forum_id == '.$cur_forum['fid'].') ? \' selected="selected"\' : \'\' ?>>'.pun_htmlspecialchars($cur_forum['forum_name']).$redirect_tag.'</option>'."\n";
 		}
 
+		$output .= "\t\t\t\t\t".'</optgroup>'."\n\t\t\t\t\t".'</select>'."\n\t\t\t\t\t".'<input type="submit" value="<?php echo $lang_common[\'Go\'] ?>" accesskey="g" />'."\n\t\t\t\t\t".'</label></div>'."\n\t\t\t\t".'</form>'."\n";
+
 		fwrite($fh, $output);
 
 		fclose($fh);
-
-		if (function_exists('apc_delete_file'))
-			@apc_delete_file(FORUM_CACHE_DIR.'cache_quickjump_'.$group_id.'.php');
 	}
 }
-
-
-//
-// Generate the censoring cache PHP script
-//
-function generate_censoring_cache()
-{
-	global $db;
-
-	$result = $db->query('SELECT search_for, replace_with FROM '.$db->prefix.'censoring') or error('Unable to fetch censoring list', __FILE__, __LINE__, $db->error());
-	$num_words = $db->num_rows($result);
-
-	$search_for = $replace_with = array();
-	for ($i = 0; $i < $num_words; $i++)
-	{
-		list($search_for[$i], $replace_with[$i]) = $db->fetch_row($result);
-		$search_for[$i] = '%(?<=[^\p{L}\p{N}])('.str_replace('\*', '[\p{L}\p{N}]*?', preg_quote($search_for[$i], '%')).')(?=[^\p{L}\p{N}])%iu';
-	}
-
-	// Output censored words as PHP code
-	$fh = @fopen(FORUM_CACHE_DIR.'cache_censoring.php', 'wb');
-	if (!$fh)
-		error('Unable to write censoring cache file to cache directory. Please make sure PHP has write access to the directory \''.pun_htmlspecialchars(FORUM_CACHE_DIR).'\'', __FILE__, __LINE__);
-
-	fwrite($fh, '<?php'."\n\n".'define(\'PUN_CENSOR_LOADED\', 1);'."\n\n".'$search_for = '.var_export($search_for, true).';'."\n\n".'$replace_with = '.var_export($replace_with, true).';'."\n\n".'?>');
-
-	fclose($fh);
-
-	if (function_exists('apc_delete_file'))
-		@apc_delete_file(FORUM_CACHE_DIR.'cache_censoring.php');
-}
-
-
-//
-// Generate the stopwords cache PHP script
-//
-function generate_stopwords_cache()
-{
-	$stopwords = array();
-
-	$d = dir(PUN_ROOT.'lang');
-	while (($entry = $d->read()) !== false)
-	{
-		if ($entry{0} == '.')
-			continue;
-
-		if (is_dir(PUN_ROOT.'lang/'.$entry) && file_exists(PUN_ROOT.'lang/'.$entry.'/stopwords.txt'))
-			$stopwords = array_merge($stopwords, file(PUN_ROOT.'lang/'.$entry.'/stopwords.txt'));
-	}
-	$d->close();
-
-	// Tidy up and filter the stopwords
-	$stopwords = array_map('pun_trim', $stopwords);
-	$stopwords = array_filter($stopwords);
-
-	// Output stopwords as PHP code
-	$fh = @fopen(FORUM_CACHE_DIR.'cache_stopwords.php', 'wb');
-	if (!$fh)
-		error('Unable to write stopwords cache file to cache directory. Please make sure PHP has write access to the directory \''.pun_htmlspecialchars(FORUM_CACHE_DIR).'\'', __FILE__, __LINE__);
-
-	fwrite($fh, '<?php'."\n\n".'$cache_id = \''.generate_stopwords_cache_id().'\';'."\n".'if ($cache_id != generate_stopwords_cache_id()) return;'."\n\n".'define(\'PUN_STOPWORDS_LOADED\', 1);'."\n\n".'$stopwords = '.var_export($stopwords, true).';'."\n\n".'?>');
-
-	fclose($fh);
-
-	if (function_exists('apc_delete_file'))
-		@apc_delete_file(FORUM_CACHE_DIR.'cache_stopwords.php');
-}
-
-
-//
-// Load some information about the latest registered users
-//
-function generate_users_info_cache()
-{
-	global $db;
-
-	$stats = array();
-
-	$result = $db->query('SELECT COUNT(id)-1 FROM '.$db->prefix.'users WHERE group_id!='.PUN_UNVERIFIED) or error('Unable to fetch total user count', __FILE__, __LINE__, $db->error());
-	$stats['total_users'] = $db->result($result);
-
-	$result = $db->query('SELECT id, username FROM '.$db->prefix.'users WHERE group_id!='.PUN_UNVERIFIED.' ORDER BY registered DESC LIMIT 1') or error('Unable to fetch newest registered user', __FILE__, __LINE__, $db->error());
-	$stats['last_user'] = $db->fetch_assoc($result);
-
-	// Output users info as PHP code
-	$fh = @fopen(FORUM_CACHE_DIR.'cache_users_info.php', 'wb');
-	if (!$fh)
-		error('Unable to write users info cache file to cache directory. Please make sure PHP has write access to the directory \''.pun_htmlspecialchars(FORUM_CACHE_DIR).'\'', __FILE__, __LINE__);
-
-	fwrite($fh, '<?php'."\n\n".'define(\'PUN_USERS_INFO_LOADED\', 1);'."\n\n".'$stats = '.var_export($stats, true).';'."\n\n".'?>');
-
-	fclose($fh);
-
-	if (function_exists('apc_delete_file'))
-		@apc_delete_file(FORUM_CACHE_DIR.'cache_users_info.php');
-}
-
-
-//
-// Delete all feed caches
-//
-function clear_feed_cache()
-{
-	$d = dir(FORUM_CACHE_DIR);
-	while (($entry = $d->read()) !== false)
-	{
-		if (substr($entry, 0, 10) == 'cache_feed' && substr($entry, -4) == '.php')
-			@unlink(FORUM_CACHE_DIR.$entry);
-	}
-	$d->close();
-}
-
-
-define('FORUM_CACHE_FUNCTIONS_LOADED', true);
Index: trunk/web/punbb/include/common.php
===================================================================
--- trunk/web/punbb/include/common.php	(revision 10)
+++ trunk/web/punbb/include/common.php	(revision 1)
@@ -1,75 +1,63 @@
 <?php
 
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+/***********************************************************************
+
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
+// Activez le mode DEBUG en enlevant // du dÃ©but de la ligne ci-dessous
+//define('PUN_DEBUG', 1);
+
+// Ceci permettra d'afficher en bas de page toutes les requÃªtes exÃ©cutÃ©es
+// N'ACTIVEZ PAS cela sur un environnement de production !
+//define('PUN_SHOW_QUERIES', 1);
 
 if (!defined('PUN_ROOT'))
-	exit('The constant PUN_ROOT must be defined and point to a valid FluxBB installation root directory.');
+	exit('La constante PUN_ROOT doit Ãªtre dÃ©finie est doit pointer le repertoire racine d\'une installation fonctionnelle de PunBB.');
 
-// Define the version and database revision that this code was written for
-define('FORUM_VERSION', '1.4.7');
-
-define('FORUM_DB_REVISION', 15);
-define('FORUM_SI_REVISION', 2);
-define('FORUM_PARSER_REVISION', 2);
-
-// Block prefetch requests
-if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
-{
-	header('HTTP/1.1 403 Prefetching Forbidden');
-
-	// Send no-cache headers
-	header('Expires: Thu, 21 Jul 1977 07:30:00 GMT'); // When yours truly first set eyes on this world! :)
-	header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
-	header('Cache-Control: post-check=0, pre-check=0', false);
-	header('Pragma: no-cache'); // For HTTP/1.0 compatibility
-
-	exit;
-}
-
-// Attempt to load the configuration file config.php
-if (file_exists(PUN_ROOT.'config.php'))
-	require PUN_ROOT.'config.php';
-
-// If we have the 1.3-legacy constant defined, define the proper 1.4 constant so we don't get an incorrect "need to install" message
-if (defined('FORUM'))
-	define('PUN', FORUM);
 
 // Load the functions script
 require PUN_ROOT.'include/functions.php';
 
-// Load UTF-8 functions
-require PUN_ROOT.'include/utf8/utf8.php';
+// Reverse the effect of register_globals
+if (@ini_get('register_globals'))
+	unregister_globals();
 
-// Strip out "bad" UTF-8 characters
-forum_remove_bad_characters();
-
-// Reverse the effect of register_globals
-forum_unregister_globals();
+include PUN_ROOT.'config.php';
 
 // If PUN isn't defined, config.php is missing or corrupt
 if (!defined('PUN'))
-{
-	header('Location: install.php');
-	exit;
-}
+	exit('Le fichier "config.php" n\'existe pas ou est endommagÃ©. Veuillez lancer <a href="install.php">install.php</a> pour installer PunBB.');
+
 
 // Record the start time (will be used to calculate the generation time for the page)
-$pun_start = get_microtime();
+list($usec, $sec) = explode(' ', microtime());
+$pun_start = ((float)$usec + (float)$sec);
 
-// Make sure PHP reports all errors except E_NOTICE. FluxBB supports E_ALL, but a lot of scripts it may interact with, do not
+// Enable full error, warning and notice reporting
 error_reporting(E_ALL ^ E_NOTICE);
 
-// Force POSIX locale (to prevent functions such as strtolower() from messing up UTF-8 strings)
-setlocale(LC_CTYPE, 'C');
+// Turn off magic_quotes_runtime
+set_magic_quotes_runtime(0);
 
-// Turn off magic_quotes_runtime
-if (get_magic_quotes_runtime())
-	set_magic_quotes_runtime(0);
-
-// Strip slashes from GET/POST/COOKIE/REQUEST/FILES (if magic_quotes_gpc is enabled)
+// Strip slashes from GET/POST/COOKIE (if magic_quotes_gpc is enabled)
 if (get_magic_quotes_gpc())
 {
@@ -82,22 +70,20 @@
 	$_POST = stripslashes_array($_POST);
 	$_COOKIE = stripslashes_array($_COOKIE);
-	$_REQUEST = stripslashes_array($_REQUEST);
-	$_FILES = stripslashes_array($_FILES);
 }
 
-// If a cookie name is not specified in config.php, we use the default (pun_cookie)
+// Seed the random number generator
+mt_srand((double)microtime()*1000000);
+
+// If a cookie name is not specified in config.php, we use the default (punbb_cookie)
 if (empty($cookie_name))
-	$cookie_name = 'pun_cookie';
-
-// If the cache directory is not specified, we use the default setting
-if (!defined('FORUM_CACHE_DIR'))
-	define('FORUM_CACHE_DIR', PUN_ROOT.'cache/');
+	$cookie_name = 'punbb_cookie';
 
 // Define a few commonly used constants
-define('PUN_UNVERIFIED', 0);
+define('PUN_UNVERIFIED', 32000);
 define('PUN_ADMIN', 1);
 define('PUN_MOD', 2);
 define('PUN_GUEST', 3);
 define('PUN_MEMBER', 4);
+
 
 // Load DB abstraction layer and connect
@@ -108,31 +94,21 @@
 
 // Load cached config
-if (file_exists(FORUM_CACHE_DIR.'cache_config.php'))
-	include FORUM_CACHE_DIR.'cache_config.php';
-
+@include PUN_ROOT.'cache/cache_config.php';
 if (!defined('PUN_CONFIG_LOADED'))
 {
-	if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
-		require PUN_ROOT.'include/cache.php';
-
+	require PUN_ROOT.'include/cache.php';
 	generate_config_cache();
-	require FORUM_CACHE_DIR.'cache_config.php';
+	require PUN_ROOT.'cache/cache_config.php';
 }
 
-// Verify that we are running the proper database schema revision
-if (!isset($pun_config['o_database_revision']) || $pun_config['o_database_revision'] < FORUM_DB_REVISION ||
-	!isset($pun_config['o_searchindex_revision']) || $pun_config['o_searchindex_revision'] < FORUM_SI_REVISION ||
-	!isset($pun_config['o_parser_revision']) || $pun_config['o_parser_revision'] < FORUM_PARSER_REVISION ||
-	version_compare($pun_config['o_cur_version'], FORUM_VERSION, '<'))
-{
-	header('Location: db_update.php');
-	exit;
-}
 
 // Enable output buffering
 if (!defined('PUN_DISABLE_BUFFERING'))
 {
+	// For some very odd reason, "Norton Internet Security" unsets this
+	$_SERVER['HTTP_ACCEPT_ENCODING'] = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
+
 	// Should we use gzip output compression?
-	if ($pun_config['o_gzip'] && extension_loaded('zlib'))
+	if ($pun_config['o_gzip'] && extension_loaded('zlib') && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false || strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') !== false))
 		ob_start('ob_gzhandler');
 	else
@@ -140,7 +116,4 @@
 }
 
-// Define standard date/time formats
-$forum_time_formats = array($pun_config['o_time_format'], 'H:i:s', 'H:i', 'g:i:s a', 'g:i a');
-$forum_date_formats = array($pun_config['o_date_format'], 'Y-m-d', 'Y-d-m', 'd-m-Y', 'm-d-Y', 'M j Y', 'jS M Y');
 
 // Check/update/set cookie and fetch user info
@@ -149,8 +122,7 @@
 
 // Attempt to load the common language file
-if (file_exists(PUN_ROOT.'lang/'.$pun_user['language'].'/common.php'))
-	include PUN_ROOT.'lang/'.$pun_user['language'].'/common.php';
-else
-	error('There is no valid language pack \''.pun_htmlspecialchars($pun_user['language']).'\' installed. Please reinstall a language of that name');
+@include PUN_ROOT.'lang/'.$pun_user['language'].'/common.php';
+if (!isset($lang_common))
+	exit('Il n\'y a pas de pack de langue \''.pun_htmlspecialchars($pun_user['language']).'\' d\'installÃ©. Veuillez rÃ©-installer une langue de ce nom.');
 
 // Check if we are to display a maintenance message
@@ -158,15 +130,12 @@
 	maintenance_message();
 
+
 // Load cached bans
-if (file_exists(FORUM_CACHE_DIR.'cache_bans.php'))
-	include FORUM_CACHE_DIR.'cache_bans.php';
-
+@include PUN_ROOT.'cache/cache_bans.php';
 if (!defined('PUN_BANS_LOADED'))
 {
-	if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
-		require PUN_ROOT.'include/cache.php';
-
+	require_once PUN_ROOT.'include/cache.php';
 	generate_bans_cache();
-	require FORUM_CACHE_DIR.'cache_bans.php';
+	require PUN_ROOT.'cache/cache_bans.php';
 }
 
@@ -177,17 +146,3 @@
 update_users_online();
 
-// Check to see if we logged in without a cookie being set
-if ($pun_user['is_guest'] && isset($_GET['login']))
-	message($lang_common['No cookie']);
-
-// The maximum size of a post, in bytes, since the field is now MEDIUMTEXT this allows ~16MB but lets cap at 1MB...
-if (!defined('PUN_MAX_POSTSIZE'))
-	define('PUN_MAX_POSTSIZE', 1048576);
-
-if (!defined('PUN_SEARCH_MIN_WORD'))
-	define('PUN_SEARCH_MIN_WORD', 3);
-if (!defined('PUN_SEARCH_MAX_WORD'))
-	define('PUN_SEARCH_MAX_WORD', 20);
-
-if (!defined('FORUM_MAX_COOKIE_SIZE'))
-	define('FORUM_MAX_COOKIE_SIZE', 4048);
+?>
Index: trunk/web/punbb/include/common_admin.php
===================================================================
--- trunk/web/punbb/include/common_admin.php	(revision 10)
+++ trunk/web/punbb/include/common_admin.php	(revision 1)
@@ -1,9 +1,25 @@
 <?php
+/***********************************************************************
 
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
 
 // Make sure no one attempts to run this script "directly"
@@ -11,14 +27,4 @@
 	exit;
 
-// Make sure we have a usable language pack for admin.
-if (file_exists(PUN_ROOT.'lang/'.$pun_user['language'].'/admin_common.php'))
-	$admin_language = $pun_user['language'];
-else if (file_exists(PUN_ROOT.'lang/'.$pun_config['o_default_lang'].'/admin_common.php'))
-	$admin_language = $pun_config['o_default_lang'];
-else
-	$admin_language = 'English';
-
-// Attempt to load the admin_common language file
-require PUN_ROOT.'lang/'.$admin_language.'/admin_common.php';
 
 //
@@ -27,5 +33,5 @@
 function generate_admin_menu($page = '')
 {
-	global $pun_config, $pun_user, $lang_admin_common;
+	global $pun_config, $pun_user;
 
 	$is_admin = $pun_user['g_id'] == PUN_ADMIN ? true : false;
@@ -34,33 +40,21 @@
 <div id="adminconsole" class="block2col">
 	<div id="adminmenu" class="blockmenu">
-		<h2><span><?php echo $lang_admin_common['Moderator menu'] ?></span></h2>
+		<h2><span>Menu <?php echo ($is_admin) ? 'Admin' : 'ModÃ©rateur' ?></span></h2>
 		<div class="box">
 			<div class="inbox">
 				<ul>
-					<li<?php if ($page == 'index') echo ' class="isactive"'; ?>><a href="admin_index.php"><?php echo $lang_admin_common['Index'] ?></a></li>
-					<li<?php if ($page == 'users') echo ' class="isactive"'; ?>><a href="admin_users.php"><?php echo $lang_admin_common['Users'] ?></a></li>
-<?php if ($is_admin || $pun_user['g_mod_ban_users'] == '1'): ?>					<li<?php if ($page == 'bans') echo ' class="isactive"'; ?>><a href="admin_bans.php"><?php echo $lang_admin_common['Bans'] ?></a></li>
-<?php endif; if ($is_admin || $pun_config['o_report_method'] == '0' || $pun_config['o_report_method'] == '2'): ?>					<li<?php if ($page == 'reports') echo ' class="isactive"'; ?>><a href="admin_reports.php"><?php echo $lang_admin_common['Reports'] ?></a></li>
-<?php endif; ?>				</ul>
-			</div>
-		</div>
-<?php
-
-	if ($is_admin)
-	{
-
-?>
-		<h2 class="block2"><span><?php echo $lang_admin_common['Admin menu'] ?></span></h2>
-		<div class="box">
-			<div class="inbox">
-				<ul>
-					<li<?php if ($page == 'options') echo ' class="isactive"'; ?>><a href="admin_options.php"><?php echo $lang_admin_common['Options'] ?></a></li>
-					<li<?php if ($page == 'permissions') echo ' class="isactive"'; ?>><a href="admin_permissions.php"><?php echo $lang_admin_common['Permissions'] ?></a></li>
-					<li<?php if ($page == 'categories') echo ' class="isactive"'; ?>><a href="admin_categories.php"><?php echo $lang_admin_common['Categories'] ?></a></li>
-					<li<?php if ($page == 'forums') echo ' class="isactive"'; ?>><a href="admin_forums.php"><?php echo $lang_admin_common['Forums'] ?></a></li>
-					<li<?php if ($page == 'groups') echo ' class="isactive"'; ?>><a href="admin_groups.php"><?php echo $lang_admin_common['User groups'] ?></a></li>
-					<li<?php if ($page == 'censoring') echo ' class="isactive"'; ?>><a href="admin_censoring.php"><?php echo $lang_admin_common['Censoring'] ?></a></li>
-					<li<?php if ($page == 'ranks') echo ' class="isactive"'; ?>><a href="admin_ranks.php"><?php echo $lang_admin_common['Ranks'] ?></a></li>
-					<li<?php if ($page == 'maintenance') echo ' class="isactive"'; ?>><a href="admin_maintenance.php"><?php echo $lang_admin_common['Maintenance'] ?></a></li>
+					<li<?php if ($page == 'index') echo ' class="isactive"'; ?>><a href="admin_index.php">Index</a></li>
+<?php if ($is_admin): ?>					<li<?php if ($page == 'categories') echo ' class="isactive"'; ?>><a href="admin_categories.php">CatÃ©gories</a></li>
+<?php endif; ?><?php if ($is_admin): ?>					<li<?php if ($page == 'forums') echo ' class="isactive"'; ?>><a href="admin_forums.php">Forums</a></li>
+<?php endif; ?>					<li<?php if ($page == 'users') echo ' class="isactive"'; ?>><a href="admin_users.php">Utilisateurs</a></li>
+<?php if ($is_admin): ?>					<li<?php if ($page == 'groups') echo ' class="isactive"'; ?>><a href="admin_groups.php">Groupes</a></li>
+<?php endif; ?><?php if ($is_admin): ?>					<li<?php if ($page == 'options') echo ' class="isactive"'; ?>><a href="admin_options.php">Options</a></li>
+<?php endif; ?><?php if ($is_admin): ?>					<li<?php if ($page == 'permissions') echo ' class="isactive"'; ?>><a href="admin_permissions.php">Permissions</a></li>
+<?php endif; ?>					<li<?php if ($page == 'censoring') echo ' class="isactive"'; ?>><a href="admin_censoring.php">Mots censurÃ©s</a></li>
+<?php if ($is_admin): ?>					<li<?php if ($page == 'ranks') echo ' class="isactive"'; ?>><a href="admin_ranks.php">Rangs utilisateurs</a></li>
+<?php endif; ?><?php if ($is_admin || $pun_config['p_mod_ban_users'] == '1'): ?>					<li<?php if ($page == 'bans') echo ' class="isactive"'; ?>><a href="admin_bans.php">Bannissements</a></li>
+<?php endif; ?><?php if ($is_admin): ?>					<li<?php if ($page == 'prune') echo ' class="isactive"'; ?>><a href="admin_prune.php">Ãlaguage</a></li>
+<?php endif; ?><?php if ($is_admin): ?>					<li<?php if ($page == 'maintenance') echo ' class="isactive"'; ?>><a href="admin_maintenance.php">Maintenance</a></li>
+<?php endif; ?>					<li<?php if ($page == 'reports') echo ' class="isactive"'; ?>><a href="admin_reports.php">Signalements</a></li>
 				</ul>
 			</div>
@@ -68,8 +62,16 @@
 <?php
 
+	// See if there are any plugins
+	$plugins = array();
+	$d = dir(PUN_ROOT.'plugins');
+	while (($entry = $d->read()) !== false)
+	{
+		$prefix = substr($entry, 0, strpos($entry, '_'));
+		$suffix = substr($entry, strlen($entry) - 4);
+
+		if ($suffix == '.php' && ((!$is_admin && $prefix == 'AMP') || ($is_admin && ($prefix == 'AP' || $prefix == 'AMP'))))
+			$plugins[] = array(substr(substr($entry, strpos($entry, '_') + 1), 0, -4), $entry);
 	}
-
-	// See if there are any plugins
-	$plugins = forum_list_plugins($is_admin);
+	$d->close();
 
 	// Did we find any plugins?
@@ -78,5 +80,5 @@
 
 ?>
-		<h2 class="block2"><span><?php echo $lang_admin_common['Plugins menu'] ?></span></h2>
+		<h2 class="block2"><span>Plugins</span></h2>
 		<div class="box">
 			<div class="inbox">
@@ -84,6 +86,6 @@
 <?php
 
-		foreach ($plugins as $plugin_name => $plugin)
-			echo "\t\t\t\t\t".'<li'.(($page == $plugin_name) ? ' class="isactive"' : '').'><a href="admin_loader.php?plugin='.$plugin_name.'">'.str_replace('_', ' ', $plugin).'</a></li>'."\n";
+		while (list(, $cur_plugin) = @each($plugins))
+			echo "\t\t\t\t\t".'<li'.(($page == $cur_plugin[1]) ? ' class="isactive"' : '').'><a href="admin_loader.php?plugin='.$cur_plugin[1].'">'.str_replace('_', ' ', $cur_plugin[0]).'</a></li>'."\n";
 
 ?>
@@ -116,5 +118,5 @@
 
 	// Fetch topics to prune
-	$result = $db->query('SELECT id FROM '.$db->prefix.'topics WHERE forum_id='.$forum_id.$extra_sql, true) or error('Unable to fetch topics', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT id FROM '.$db->prefix.'topics WHERE forum_id='.$forum_id.$extra_sql, true) or error('Impossible de retrouver la liste des discussions', __FILE__, __LINE__, $db->error());
 
 	$topic_ids = '';
@@ -125,5 +127,5 @@
 	{
 		// Fetch posts to prune
-		$result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id IN('.$topic_ids.')', true) or error('Unable to fetch posts', __FILE__, __LINE__, $db->error());
+		$result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id IN('.$topic_ids.')', true) or error('Impossible de retrouver les messages', __FILE__, __LINE__, $db->error());
 
 		$post_ids = '';
@@ -134,9 +136,9 @@
 		{
 			// Delete topics
-			$db->query('DELETE FROM '.$db->prefix.'topics WHERE id IN('.$topic_ids.')') or error('Unable to prune topics', __FILE__, __LINE__, $db->error());
+			$db->query('DELETE FROM '.$db->prefix.'topics WHERE id IN('.$topic_ids.')') or error('Impossible d\'Ã©laguer les discussions', __FILE__, __LINE__, $db->error());
 			// Delete subscriptions
-			$db->query('DELETE FROM '.$db->prefix.'topic_subscriptions WHERE topic_id IN('.$topic_ids.')') or error('Unable to prune subscriptions', __FILE__, __LINE__, $db->error());
+			$db->query('DELETE FROM '.$db->prefix.'subscriptions WHERE topic_id IN('.$topic_ids.')') or error('Impossible d\'Ã©laguer les abonnements', __FILE__, __LINE__, $db->error());
 			// Delete posts
-			$db->query('DELETE FROM '.$db->prefix.'posts WHERE id IN('.$post_ids.')') or error('Unable to prune posts', __FILE__, __LINE__, $db->error());
+			$db->query('DELETE FROM '.$db->prefix.'posts WHERE id IN('.$post_ids.')') or error('Impossible d\'Ã©laguer les messages', __FILE__, __LINE__, $db->error());
 
 			// We removed a bunch of posts, so now we have to update the search index
Index: trunk/web/punbb/include/dblayer/common_db.php
===================================================================
--- trunk/web/punbb/include/dblayer/common_db.php	(revision 10)
+++ trunk/web/punbb/include/dblayer/common_db.php	(revision 1)
@@ -1,9 +1,26 @@
 <?php
+/***********************************************************************
 
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // Make sure no one attempts to run this script "directly"
@@ -12,33 +29,38 @@
 
 
+//
+// Return current timestamp (with microseconds) as a float (used in dblayer)
+//
+if (defined('PUN_SHOW_QUERIES'))
+{
+	function get_microtime()
+	{
+		list($usec, $sec) = explode(' ', microtime());
+		return ((float)$usec + (float)$sec);
+	}
+}
+
+
 // Load the appropriate DB layer class
 switch ($db_type)
 {
 	case 'mysql':
-		require_once PUN_ROOT.'include/dblayer/mysql.php';
-		break;
-
-	case 'mysql_innodb':
-		require_once PUN_ROOT.'include/dblayer/mysql_innodb.php';
+		require PUN_ROOT.'include/dblayer/mysql.php';
 		break;
 
 	case 'mysqli':
-		require_once PUN_ROOT.'include/dblayer/mysqli.php';
-		break;
-
-	case 'mysqli_innodb':
-		require_once PUN_ROOT.'include/dblayer/mysqli_innodb.php';
+		require PUN_ROOT.'include/dblayer/mysqli.php';
 		break;
 
 	case 'pgsql':
-		require_once PUN_ROOT.'include/dblayer/pgsql.php';
+		require PUN_ROOT.'include/dblayer/pgsql.php';
 		break;
 
 	case 'sqlite':
-		require_once PUN_ROOT.'include/dblayer/sqlite.php';
+		require PUN_ROOT.'include/dblayer/sqlite.php';
 		break;
 
 	default:
-		error('\''.$db_type.'\' is not a valid database type. Please check settings in config.php.', __FILE__, __LINE__);
+		error('\''.$db_type.'\' n\'est pas un type de base de donnÃ©es valable. Veuillez vÃ©rifier vos paramÃštres de configuration dans config.php', __FILE__, __LINE__);
 		break;
 }
Index: trunk/web/punbb/include/dblayer/index.html
===================================================================
--- trunk/web/punbb/include/dblayer/index.html	(revision 10)
+++ trunk/web/punbb/include/dblayer/index.html	(revision 1)
@@ -1,1 +1,8 @@
-<html><head><title>.</title></head><body>.</body></html>
+<html>
+<head>
+<title>.</title>
+</head>
+<body>
+.
+</body>
+</html>
Index: trunk/web/punbb/include/dblayer/mysql.php
===================================================================
--- trunk/web/punbb/include/dblayer/mysql.php	(revision 10)
+++ trunk/web/punbb/include/dblayer/mysql.php	(revision 1)
@@ -1,9 +1,26 @@
 <?php
+/***********************************************************************
 
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // Make sure we have built in support for MySQL
@@ -21,11 +38,4 @@
 	var $num_queries = 0;
 
-	var $error_no = false;
-	var $error_msg = 'Unknown';
-
-	var $datatype_transformations = array(
-		'%^SERIAL$%'	=>	'INT(10) UNSIGNED AUTO_INCREMENT'
-	);
-
 
 	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
@@ -40,15 +50,13 @@
 		if ($this->link_id)
 		{
-			if (!@mysql_select_db($db_name, $this->link_id))
+			if (@mysql_select_db($db_name, $this->link_id))
+			{ mysql_query("SET NAMES utf8");
+				return $this->link_id;
+		   }
+			else
 				error('Unable to select database. MySQL reported: '.mysql_error(), __FILE__, __LINE__);
 		}
 		else
 			error('Unable to connect to MySQL server. MySQL reported: '.mysql_error(), __FILE__, __LINE__);
-
-		// Setup the client-server character set (UTF-8)
-		if (!defined('FORUM_NO_SET_NAMES'))
-			$this->set_names('utf8');
-
-		return $this->link_id;
 	}
 
@@ -90,7 +98,4 @@
 				$this->saved_queries[] = array($sql, 0);
 
-			$this->error_no = @mysql_errno($this->link_id);
-			$this->error_msg = @mysql_error($this->link_id);
-
 			return false;
 		}
@@ -98,7 +103,7 @@
 
 
-	function result($query_id = 0, $row = 0, $col = 0)
+	function result($query_id = 0, $row = 0)
 	{
-		return ($query_id) ? @mysql_result($query_id, $row, $col) : false;
+		return ($query_id) ? @mysql_result($query_id, $row) : false;
 	}
 
@@ -154,7 +159,5 @@
 	function escape($str)
 	{
-		if (is_array($str))
-			return '';
-		else if (function_exists('mysql_real_escape_string'))
+		if (function_exists('mysql_real_escape_string'))
 			return mysql_real_escape_string($str, $this->link_id);
 		else
@@ -166,6 +169,6 @@
 	{
 		$result['error_sql'] = @current(@end($this->saved_queries));
-		$result['error_no'] = $this->error_no;
-		$result['error_msg'] = $this->error_msg;
+		$result['error_no'] = @mysql_errno($this->link_id);
+		$result['error_msg'] = @mysql_error($this->link_id);
 
 		return $result;
@@ -185,188 +188,3 @@
 			return false;
 	}
-
-	function get_names()
-	{
-		$result = $this->query('SHOW VARIABLES LIKE \'character_set_connection\'');
-		return $this->result($result, 0, 1);
-	}
-
-
-	function set_names($names)
-	{
-		return $this->query('SET NAMES \''.$this->escape($names).'\'');
-	}
-
-
-	function get_version()
-	{
-		$result = $this->query('SELECT VERSION()');
-
-		return array(
-			'name'		=> 'MySQL Standard',
-			'version'	=> preg_replace('%^([^-]+).*$%', '\\1', $this->result($result))
-		);
-	}
-
-
-	function table_exists($table_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW TABLES LIKE \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function field_exists($table_name, $field_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW COLUMNS FROM '.($no_prefix ? '' : $this->prefix).$table_name.' LIKE \''.$this->escape($field_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function index_exists($table_name, $index_name, $no_prefix = false)
-	{
-		$exists = false;
-
-		$result = $this->query('SHOW INDEX FROM '.($no_prefix ? '' : $this->prefix).$table_name);
-		while ($cur_index = $this->fetch_assoc($result))
-		{
-			if (strtolower($cur_index['Key_name']) == strtolower(($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name))
-			{
-				$exists = true;
-				break;
-			}
-		}
-
-		return $exists;
-	}
-
-
-	function create_table($table_name, $schema, $no_prefix = false)
-	{
-		if ($this->table_exists($table_name, $no_prefix))
-			return true;
-
-		$query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
-
-		// Go through every schema element and add it to the query
-		foreach ($schema['FIELDS'] as $field_name => $field_data)
-		{
-			$field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
-
-			$query .= $field_name.' '.$field_data['datatype'];
-
-			if (isset($field_data['collation']))
-				$query .= 'CHARACTER SET utf8 COLLATE utf8_'.$field_data['collation'];
-
-			if (!$field_data['allow_null'])
-				$query .= ' NOT NULL';
-
-			if (isset($field_data['default']))
-				$query .= ' DEFAULT '.$field_data['default'];
-
-			$query .= ",\n";
-		}
-
-		// If we have a primary key, add it
-		if (isset($schema['PRIMARY KEY']))
-			$query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
-
-		// Add unique keys
-		if (isset($schema['UNIQUE KEYS']))
-		{
-			foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
-				$query .= 'UNIQUE KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$key_name.'('.implode(',', $key_fields).'),'."\n";
-		}
-
-		// Add indexes
-		if (isset($schema['INDEXES']))
-		{
-			foreach ($schema['INDEXES'] as $index_name => $index_fields)
-				$query .= 'KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.'('.implode(',', $index_fields).'),'."\n";
-		}
-
-		// We remove the last two characters (a newline and a comma) and add on the ending
-		$query = substr($query, 0, strlen($query) - 2)."\n".') ENGINE = '.(isset($schema['ENGINE']) ? $schema['ENGINE'] : 'MyISAM').' CHARACTER SET utf8';
-
-		return $this->query($query) ? true : false;
-	}
-
-
-	function drop_table($table_name, $no_prefix = false)
-	{
-		if (!$this->table_exists($table_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-
-
-	function rename_table($old_table, $new_table, $no_prefix = false)
-	{
-		// If there new table exists and the old one doesn't, then we're happy
-		if ($this->table_exists($new_table, $no_prefix) && !$this->table_exists($old_table, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$old_table.' RENAME TO '.($no_prefix ? '' : $this->prefix).$new_table) ? true : false;
-	}
-
-
-	function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if ($this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' MODIFY '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function drop_field($table_name, $field_name, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP '.$field_name) ? true : false;
-	}
-
-
-	function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
-	{
-		if ($this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ('.implode(',', $index_fields).')') ? true : false;
-	}
-
-
-	function drop_index($table_name, $index_name, $no_prefix = false)
-	{
-		if (!$this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) ? true : false;
-	}
-
-	function truncate_table($table_name, $no_prefix = false)
-	{
-		return $this->query('TRUNCATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
 }
Index: trunk/web/punbb/include/dblayer/mysql_innodb.php
===================================================================
--- trunk/web/punbb/include/dblayer/mysql_innodb.php	(revision 10)
+++ 	(revision )
@@ -1,386 +1,0 @@
-<?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
-
-// Make sure we have built in support for MySQL
-if (!function_exists('mysql_connect'))
-	exit('This PHP environment doesn\'t have MySQL support built in. MySQL support is required if you want to use a MySQL database to run this forum. Consult the PHP documentation for further assistance.');
-
-
-class DBLayer
-{
-	var $prefix;
-	var $link_id;
-	var $query_result;
-	var $in_transaction = 0;
-
-	var $saved_queries = array();
-	var $num_queries = 0;
-
-	var $error_no = false;
-	var $error_msg = 'Unknown';
-
-	var $datatype_transformations = array(
-		'%^SERIAL$%'	=>	'INT(10) UNSIGNED AUTO_INCREMENT'
-	);
-
-
-	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
-	{
-		$this->prefix = $db_prefix;
-
-		if ($p_connect)
-			$this->link_id = @mysql_pconnect($db_host, $db_username, $db_password);
-		else
-			$this->link_id = @mysql_connect($db_host, $db_username, $db_password);
-
-		if ($this->link_id)
-		{
-			if (!@mysql_select_db($db_name, $this->link_id))
-				error('Unable to select database. MySQL reported: '.mysql_error(), __FILE__, __LINE__);
-		}
-		else
-			error('Unable to connect to MySQL server. MySQL reported: '.mysql_error(), __FILE__, __LINE__);
-
-		// Setup the client-server character set (UTF-8)
-		if (!defined('FORUM_NO_SET_NAMES'))
-			$this->set_names('utf8');
-
-		return $this->link_id;
-	}
-
-
-	function start_transaction()
-	{
-		++$this->in_transaction;
-
-		mysql_query('START TRANSACTION', $this->link_id);
-		return;
-	}
-
-
-	function end_transaction()
-	{
-		--$this->in_transaction;
-
-		mysql_query('COMMIT', $this->link_id);
-		return;
-	}
-
-
-	function query($sql, $unbuffered = false)
-	{
-		if (defined('PUN_SHOW_QUERIES'))
-			$q_start = get_microtime();
-
-		if ($unbuffered)
-			$this->query_result = @mysql_unbuffered_query($sql, $this->link_id);
-		else
-			$this->query_result = @mysql_query($sql, $this->link_id);
-
-		if ($this->query_result)
-		{
-			if (defined('PUN_SHOW_QUERIES'))
-				$this->saved_queries[] = array($sql, sprintf('%.5f', get_microtime() - $q_start));
-
-			++$this->num_queries;
-
-			return $this->query_result;
-		}
-		else
-		{
-			if (defined('PUN_SHOW_QUERIES'))
-				$this->saved_queries[] = array($sql, 0);
-
-			$this->error_no = @mysql_errno($this->link_id);
-			$this->error_msg = @mysql_error($this->link_id);
-
-			// Rollback transaction
-			if ($this->in_transaction)
-				mysql_query('ROLLBACK', $this->link_id);
-
-			--$this->in_transaction;
-
-			return false;
-		}
-	}
-
-
-	function result($query_id = 0, $row = 0, $col = 0)
-	{
-		return ($query_id) ? @mysql_result($query_id, $row, $col) : false;
-	}
-
-
-	function fetch_assoc($query_id = 0)
-	{
-		return ($query_id) ? @mysql_fetch_assoc($query_id) : false;
-	}
-
-
-	function fetch_row($query_id = 0)
-	{
-		return ($query_id) ? @mysql_fetch_row($query_id) : false;
-	}
-
-
-	function num_rows($query_id = 0)
-	{
-		return ($query_id) ? @mysql_num_rows($query_id) : false;
-	}
-
-
-	function affected_rows()
-	{
-		return ($this->link_id) ? @mysql_affected_rows($this->link_id) : false;
-	}
-
-
-	function insert_id()
-	{
-		return ($this->link_id) ? @mysql_insert_id($this->link_id) : false;
-	}
-
-
-	function get_num_queries()
-	{
-		return $this->num_queries;
-	}
-
-
-	function get_saved_queries()
-	{
-		return $this->saved_queries;
-	}
-
-
-	function free_result($query_id = false)
-	{
-		return ($query_id) ? @mysql_free_result($query_id) : false;
-	}
-
-
-	function escape($str)
-	{
-		if (is_array($str))
-			return '';
-		else if (function_exists('mysql_real_escape_string'))
-			return mysql_real_escape_string($str, $this->link_id);
-		else
-			return mysql_escape_string($str);
-	}
-
-
-	function error()
-	{
-		$result['error_sql'] = @current(@end($this->saved_queries));
-		$result['error_no'] = $this->error_no;
-		$result['error_msg'] = $this->error_msg;
-
-		return $result;
-	}
-
-
-	function close()
-	{
-		if ($this->link_id)
-		{
-			if ($this->query_result)
-				@mysql_free_result($this->query_result);
-
-			return @mysql_close($this->link_id);
-		}
-		else
-			return false;
-	}
-
-
-	function get_names()
-	{
-		$result = $this->query('SHOW VARIABLES LIKE \'character_set_connection\'');
-		return $this->result($result, 0, 1);
-	}
-
-
-	function set_names($names)
-	{
-		return $this->query('SET NAMES \''.$this->escape($names).'\'');
-	}
-
-
-	function get_version()
-	{
-		$result = $this->query('SELECT VERSION()');
-
-		return array(
-			'name'		=> 'MySQL Standard (InnoDB)',
-			'version'	=> preg_replace('%^([^-]+).*$%', '\\1', $this->result($result))
-		);
-	}
-
-
-	function table_exists($table_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW TABLES LIKE \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function field_exists($table_name, $field_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW COLUMNS FROM '.($no_prefix ? '' : $this->prefix).$table_name.' LIKE \''.$this->escape($field_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function index_exists($table_name, $index_name, $no_prefix = false)
-	{
-		$exists = false;
-
-		$result = $this->query('SHOW INDEX FROM '.($no_prefix ? '' : $this->prefix).$table_name);
-		while ($cur_index = $this->fetch_assoc($result))
-		{
-			if (strtolower($cur_index['Key_name']) == strtolower(($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name))
-			{
-				$exists = true;
-				break;
-			}
-		}
-
-		return $exists;
-	}
-
-
-	function create_table($table_name, $schema, $no_prefix = false)
-	{
-		if ($this->table_exists($table_name, $no_prefix))
-			return true;
-
-		$query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
-
-		// Go through every schema element and add it to the query
-		foreach ($schema['FIELDS'] as $field_name => $field_data)
-		{
-			$field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
-
-			$query .= $field_name.' '.$field_data['datatype'];
-
-			if (isset($field_data['collation']))
-				$query .= 'CHARACTER SET utf8 COLLATE utf8_'.$field_data['collation'];
-
-			if (!$field_data['allow_null'])
-				$query .= ' NOT NULL';
-
-			if (isset($field_data['default']))
-				$query .= ' DEFAULT '.$field_data['default'];
-
-			$query .= ",\n";
-		}
-
-		// If we have a primary key, add it
-		if (isset($schema['PRIMARY KEY']))
-			$query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
-
-		// Add unique keys
-		if (isset($schema['UNIQUE KEYS']))
-		{
-			foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
-				$query .= 'UNIQUE KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$key_name.'('.implode(',', $key_fields).'),'."\n";
-		}
-
-		// Add indexes
-		if (isset($schema['INDEXES']))
-		{
-			foreach ($schema['INDEXES'] as $index_name => $index_fields)
-				$query .= 'KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.'('.implode(',', $index_fields).'),'."\n";
-		}
-
-		// We remove the last two characters (a newline and a comma) and add on the ending
-		$query = substr($query, 0, strlen($query) - 2)."\n".') ENGINE = '.(isset($schema['ENGINE']) ? $schema['ENGINE'] : 'InnoDB').' CHARACTER SET utf8';
-
-		return $this->query($query) ? true : false;
-	}
-
-
-	function drop_table($table_name, $no_prefix = false)
-	{
-		if (!$this->table_exists($table_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-
-
-	function rename_table($old_table, $new_table, $no_prefix = false)
-	{
-		// If there new table exists and the old one doesn't, then we're happy
-		if ($this->table_exists($new_table, $no_prefix) && !$this->table_exists($old_table, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$old_table.' RENAME TO '.($no_prefix ? '' : $this->prefix).$new_table) ? true : false;
-	}
-
-
-	function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if ($this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' MODIFY '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function drop_field($table_name, $field_name, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP '.$field_name) ? true : false;
-	}
-
-
-	function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
-	{
-		if ($this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ('.implode(',', $index_fields).')') ? true : false;
-	}
-
-
-	function drop_index($table_name, $index_name, $no_prefix = false)
-	{
-		if (!$this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) ? true : false;
-	}
-
-	function truncate_table($table_name, $no_prefix = false)
-	{
-		return $this->query('TRUNCATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-}
Index: trunk/web/punbb/include/dblayer/mysqli.php
===================================================================
--- trunk/web/punbb/include/dblayer/mysqli.php	(revision 10)
+++ trunk/web/punbb/include/dblayer/mysqli.php	(revision 1)
@@ -1,9 +1,26 @@
 <?php
+/***********************************************************************
 
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // Make sure we have built in support for MySQL
@@ -21,13 +38,6 @@
 	var $num_queries = 0;
 
-	var $error_no = false;
-	var $error_msg = 'Unknown';
 
-	var $datatype_transformations = array(
-		'%^SERIAL$%'	=>	'INT(10) UNSIGNED AUTO_INCREMENT'
-	);
-
-
-	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
+	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $foo)
 	{
 		$this->prefix = $db_prefix;
@@ -37,20 +47,11 @@
 			list($db_host, $db_port) = explode(':', $db_host);
 
-		// Persistent connection in MySQLi are only available in PHP 5.3 and later releases
-		$p_connect = $p_connect && version_compare(PHP_VERSION, '5.3.0', '>=') ? 'p:' : '';
-
 		if (isset($db_port))
-			$this->link_id = @mysqli_connect($p_connect.$db_host, $db_username, $db_password, $db_name, $db_port);
+			$this->link_id = @mysqli_connect($db_host, $db_username, $db_password, $db_name, $db_port);
 		else
-			$this->link_id = @mysqli_connect($p_connect.$db_host, $db_username, $db_password, $db_name);
+			$this->link_id = @mysqli_connect($db_host, $db_username, $db_password, $db_name);
 
 		if (!$this->link_id)
 			error('Unable to connect to MySQL and select database. MySQL reported: '.mysqli_connect_error(), __FILE__, __LINE__);
-
-		// Setup the client-server character set (UTF-8)
-		if (!defined('FORUM_NO_SET_NAMES'))
-			$this->set_names('utf8');
-
-		return $this->link_id;
 	}
 
@@ -89,7 +90,4 @@
 				$this->saved_queries[] = array($sql, 0);
 
-			$this->error_no = @mysqli_errno($this->link_id);
-			$this->error_msg = @mysqli_error($this->link_id);
-
 			return false;
 		}
@@ -97,16 +95,13 @@
 
 
-	function result($query_id = 0, $row = 0, $col = 0)
+	function result($query_id = 0, $row = 0)
 	{
 		if ($query_id)
 		{
-			if ($row !== 0 && @mysqli_data_seek($query_id, $row) === false)
-				return false;
+			if ($row)
+				@mysqli_data_seek($query_id, $row);
 
 			$cur_row = @mysqli_fetch_row($query_id);
-			if ($cur_row === false)
-				return false;
-
-			return $cur_row[$col];
+			return $cur_row[0];
 		}
 		else
@@ -165,5 +160,5 @@
 	function escape($str)
 	{
-		return is_array($str) ? '' : mysqli_real_escape_string($this->link_id, $str);
+		return mysqli_real_escape_string($this->link_id, $str);
 	}
 
@@ -172,6 +167,6 @@
 	{
 		$result['error_sql'] = @current(@end($this->saved_queries));
-		$result['error_no'] = $this->error_no;
-		$result['error_msg'] = $this->error_msg;
+		$result['error_no'] = @mysqli_errno($this->link_id);
+		$result['error_msg'] = @mysqli_error($this->link_id);
 
 		return $result;
@@ -191,189 +186,3 @@
 			return false;
 	}
-
-
-	function get_names()
-	{
-		$result = $this->query('SHOW VARIABLES LIKE \'character_set_connection\'');
-		return $this->result($result, 0, 1);
-	}
-
-
-	function set_names($names)
-	{
-		return $this->query('SET NAMES \''.$this->escape($names).'\'');
-	}
-
-
-	function get_version()
-	{
-		$result = $this->query('SELECT VERSION()');
-
-		return array(
-			'name'		=> 'MySQL Improved',
-			'version'	=> preg_replace('%^([^-]+).*$%', '\\1', $this->result($result))
-		);
-	}
-
-
-	function table_exists($table_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW TABLES LIKE \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function field_exists($table_name, $field_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW COLUMNS FROM '.($no_prefix ? '' : $this->prefix).$table_name.' LIKE \''.$this->escape($field_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function index_exists($table_name, $index_name, $no_prefix = false)
-	{
-		$exists = false;
-
-		$result = $this->query('SHOW INDEX FROM '.($no_prefix ? '' : $this->prefix).$table_name);
-		while ($cur_index = $this->fetch_assoc($result))
-		{
-			if (strtolower($cur_index['Key_name']) == strtolower(($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name))
-			{
-				$exists = true;
-				break;
-			}
-		}
-
-		return $exists;
-	}
-
-
-	function create_table($table_name, $schema, $no_prefix = false)
-	{
-		if ($this->table_exists($table_name, $no_prefix))
-			return true;
-
-		$query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
-
-		// Go through every schema element and add it to the query
-		foreach ($schema['FIELDS'] as $field_name => $field_data)
-		{
-			$field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
-
-			$query .= $field_name.' '.$field_data['datatype'];
-
-			if (isset($field_data['collation']))
-				$query .= 'CHARACTER SET utf8 COLLATE utf8_'.$field_data['collation'];
-
-			if (!$field_data['allow_null'])
-				$query .= ' NOT NULL';
-
-			if (isset($field_data['default']))
-				$query .= ' DEFAULT '.$field_data['default'];
-
-			$query .= ",\n";
-		}
-
-		// If we have a primary key, add it
-		if (isset($schema['PRIMARY KEY']))
-			$query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
-
-		// Add unique keys
-		if (isset($schema['UNIQUE KEYS']))
-		{
-			foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
-				$query .= 'UNIQUE KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$key_name.'('.implode(',', $key_fields).'),'."\n";
-		}
-
-		// Add indexes
-		if (isset($schema['INDEXES']))
-		{
-			foreach ($schema['INDEXES'] as $index_name => $index_fields)
-				$query .= 'KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.'('.implode(',', $index_fields).'),'."\n";
-		}
-
-		// We remove the last two characters (a newline and a comma) and add on the ending
-		$query = substr($query, 0, strlen($query) - 2)."\n".') ENGINE = '.(isset($schema['ENGINE']) ? $schema['ENGINE'] : 'MyISAM').' CHARACTER SET utf8';
-
-		return $this->query($query) ? true : false;
-	}
-
-
-	function drop_table($table_name, $no_prefix = false)
-	{
-		if (!$this->table_exists($table_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-
-
-	function rename_table($old_table, $new_table, $no_prefix = false)
-	{
-		// If there new table exists and the old one doesn't, then we're happy
-		if ($this->table_exists($new_table, $no_prefix) && !$this->table_exists($old_table, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$old_table.' RENAME TO '.($no_prefix ? '' : $this->prefix).$new_table) ? true : false;
-	}
-
-
-	function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if ($this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' MODIFY '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function drop_field($table_name, $field_name, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP '.$field_name) ? true : false;
-	}
-
-
-	function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
-	{
-		if ($this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ('.implode(',', $index_fields).')') ? true : false;
-	}
-
-
-	function drop_index($table_name, $index_name, $no_prefix = false)
-	{
-		if (!$this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) ? true : false;
-	}
-
-	function truncate_table($table_name, $no_prefix = false)
-	{
-		return $this->query('TRUNCATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
 }
Index: trunk/web/punbb/include/dblayer/mysqli_innodb.php
===================================================================
--- trunk/web/punbb/include/dblayer/mysqli_innodb.php	(revision 10)
+++ 	(revision )
@@ -1,392 +1,0 @@
-<?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
-
-// Make sure we have built in support for MySQL
-if (!function_exists('mysqli_connect'))
-	exit('This PHP environment doesn\'t have Improved MySQL (mysqli) support built in. Improved MySQL support is required if you want to use a MySQL 4.1 (or later) database to run this forum. Consult the PHP documentation for further assistance.');
-
-
-class DBLayer
-{
-	var $prefix;
-	var $link_id;
-	var $query_result;
-
-	var $saved_queries = array();
-	var $num_queries = 0;
-	var $in_transaction = 0;
-
-	var $error_no = false;
-	var $error_msg = 'Unknown';
-
-	var $datatype_transformations = array(
-		'%^SERIAL$%'	=>	'INT(10) UNSIGNED AUTO_INCREMENT'
-	);
-
-
-	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
-	{
-		$this->prefix = $db_prefix;
-
-		// Was a custom port supplied with $db_host?
-		if (strpos($db_host, ':') !== false)
-			list($db_host, $db_port) = explode(':', $db_host);
-
-		// Persistent connection in MySQLi are only available in PHP 5.3 and later releases
-		$p_connect = $p_connect && version_compare(PHP_VERSION, '5.3.0', '>=') ? 'p:' : '';
-
-		if (isset($db_port))
-			$this->link_id = @mysqli_connect($p_connect.$db_host, $db_username, $db_password, $db_name, $db_port);
-		else
-			$this->link_id = @mysqli_connect($p_connect.$db_host, $db_username, $db_password, $db_name);
-
-		if (!$this->link_id)
-			error('Unable to connect to MySQL and select database. MySQL reported: '.mysqli_connect_error(), __FILE__, __LINE__);
-
-		// Setup the client-server character set (UTF-8)
-		if (!defined('FORUM_NO_SET_NAMES'))
-			$this->set_names('utf8');
-
-		return $this->link_id;
-	}
-
-
-	function start_transaction()
-	{
-		++$this->in_transaction;
-
-		mysqli_query($this->link_id, 'START TRANSACTION');
-		return;
-	}
-
-
-	function end_transaction()
-	{
-		--$this->in_transaction;
-
-		mysqli_query($this->link_id, 'COMMIT');
-		return;
-	}
-
-
-	function query($sql, $unbuffered = false)
-	{
-		if (defined('PUN_SHOW_QUERIES'))
-			$q_start = get_microtime();
-
-		$this->query_result = @mysqli_query($this->link_id, $sql);
-
-		if ($this->query_result)
-		{
-			if (defined('PUN_SHOW_QUERIES'))
-				$this->saved_queries[] = array($sql, sprintf('%.5f', get_microtime() - $q_start));
-
-			++$this->num_queries;
-
-			return $this->query_result;
-		}
-		else
-		{
-			if (defined('PUN_SHOW_QUERIES'))
-				$this->saved_queries[] = array($sql, 0);
-
-			$this->error_no = @mysqli_errno($this->link_id);
-			$this->error_msg = @mysqli_error($this->link_id);
-
-			// Rollback transaction
-			if ($this->in_transaction)
-				mysqli_query($this->link_id, 'ROLLBACK');
-
-			--$this->in_transaction;
-
-			return false;
-		}
-	}
-
-
-	function result($query_id = 0, $row = 0, $col = 0)
-	{
-		if ($query_id)
-		{
-			if ($row !== 0 && @mysqli_data_seek($query_id, $row) === false)
-				return false;
-
-			$cur_row = @mysqli_fetch_row($query_id);
-			if ($cur_row === false)
-				return false;
-
-			return $cur_row[$col];
-		}
-		else
-			return false;
-	}
-
-
-	function fetch_assoc($query_id = 0)
-	{
-		return ($query_id) ? @mysqli_fetch_assoc($query_id) : false;
-	}
-
-
-	function fetch_row($query_id = 0)
-	{
-		return ($query_id) ? @mysqli_fetch_row($query_id) : false;
-	}
-
-
-	function num_rows($query_id = 0)
-	{
-		return ($query_id) ? @mysqli_num_rows($query_id) : false;
-	}
-
-
-	function affected_rows()
-	{
-		return ($this->link_id) ? @mysqli_affected_rows($this->link_id) : false;
-	}
-
-
-	function insert_id()
-	{
-		return ($this->link_id) ? @mysqli_insert_id($this->link_id) : false;
-	}
-
-
-	function get_num_queries()
-	{
-		return $this->num_queries;
-	}
-
-
-	function get_saved_queries()
-	{
-		return $this->saved_queries;
-	}
-
-
-	function free_result($query_id = false)
-	{
-		return ($query_id) ? @mysqli_free_result($query_id) : false;
-	}
-
-
-	function escape($str)
-	{
-		return is_array($str) ? '' : mysqli_real_escape_string($this->link_id, $str);
-	}
-
-
-	function error()
-	{
-		$result['error_sql'] = @current(@end($this->saved_queries));
-		$result['error_no'] = $this->error_no;
-		$result['error_msg'] = $this->error_msg;
-
-		return $result;
-	}
-
-
-	function close()
-	{
-		if ($this->link_id)
-		{
-			if ($this->query_result)
-				@mysqli_free_result($this->query_result);
-
-			return @mysqli_close($this->link_id);
-		}
-		else
-			return false;
-	}
-
-
-	function get_names()
-	{
-		$result = $this->query('SHOW VARIABLES LIKE \'character_set_connection\'');
-		return $this->result($result, 0, 1);
-	}
-
-
-	function set_names($names)
-	{
-		return $this->query('SET NAMES \''.$this->escape($names).'\'');
-	}
-
-
-	function get_version()
-	{
-		$result = $this->query('SELECT VERSION()');
-
-		return array(
-			'name'		=> 'MySQL Improved (InnoDB)',
-			'version'	=> preg_replace('%^([^-]+).*$%', '\\1', $this->result($result))
-		);
-	}
-
-
-	function table_exists($table_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW TABLES LIKE \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function field_exists($table_name, $field_name, $no_prefix = false)
-	{
-		$result = $this->query('SHOW COLUMNS FROM '.($no_prefix ? '' : $this->prefix).$table_name.' LIKE \''.$this->escape($field_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function index_exists($table_name, $index_name, $no_prefix = false)
-	{
-		$exists = false;
-
-		$result = $this->query('SHOW INDEX FROM '.($no_prefix ? '' : $this->prefix).$table_name);
-		while ($cur_index = $this->fetch_assoc($result))
-		{
-			if (strtolower($cur_index['Key_name']) == strtolower(($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name))
-			{
-				$exists = true;
-				break;
-			}
-		}
-
-		return $exists;
-	}
-
-
-	function create_table($table_name, $schema, $no_prefix = false)
-	{
-		if ($this->table_exists($table_name, $no_prefix))
-			return true;
-
-		$query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
-
-		// Go through every schema element and add it to the query
-		foreach ($schema['FIELDS'] as $field_name => $field_data)
-		{
-			$field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
-
-			$query .= $field_name.' '.$field_data['datatype'];
-
-			if (isset($field_data['collation']))
-				$query .= 'CHARACTER SET utf8 COLLATE utf8_'.$field_data['collation'];
-
-			if (!$field_data['allow_null'])
-				$query .= ' NOT NULL';
-
-			if (isset($field_data['default']))
-				$query .= ' DEFAULT '.$field_data['default'];
-
-			$query .= ",\n";
-		}
-
-		// If we have a primary key, add it
-		if (isset($schema['PRIMARY KEY']))
-			$query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
-
-		// Add unique keys
-		if (isset($schema['UNIQUE KEYS']))
-		{
-			foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
-				$query .= 'UNIQUE KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$key_name.'('.implode(',', $key_fields).'),'."\n";
-		}
-
-		// Add indexes
-		if (isset($schema['INDEXES']))
-		{
-			foreach ($schema['INDEXES'] as $index_name => $index_fields)
-				$query .= 'KEY '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.'('.implode(',', $index_fields).'),'."\n";
-		}
-
-		// We remove the last two characters (a newline and a comma) and add on the ending
-		$query = substr($query, 0, strlen($query) - 2)."\n".') ENGINE = '.(isset($schema['ENGINE']) ? $schema['ENGINE'] : 'InnoDB').' CHARACTER SET utf8';
-
-		return $this->query($query) ? true : false;
-	}
-
-
-	function drop_table($table_name, $no_prefix = false)
-	{
-		if (!$this->table_exists($table_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-
-
-	function rename_table($old_table, $new_table, $no_prefix = false)
-	{
-		// If there new table exists and the old one doesn't, then we're happy
-		if ($this->table_exists($new_table, $no_prefix) && !$this->table_exists($old_table, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$old_table.' RENAME TO '.($no_prefix ? '' : $this->prefix).$new_table) ? true : false;
-	}
-
-
-	function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if ($this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		if ($default_value !== null && !is_int($default_value) && !is_float($default_value))
-			$default_value = '\''.$this->escape($default_value).'\'';
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' MODIFY '.$field_name.' '.$field_type.($allow_null ? ' ' : ' NOT NULL').($default_value !== null ? ' DEFAULT '.$default_value : ' ').($after_field != null ? ' AFTER '.$after_field : '')) ? true : false;
-	}
-
-
-	function drop_field($table_name, $field_name, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP '.$field_name) ? true : false;
-	}
-
-
-	function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
-	{
-		if ($this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ('.implode(',', $index_fields).')') ? true : false;
-	}
-
-
-	function drop_index($table_name, $index_name, $no_prefix = false)
-	{
-		if (!$this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) ? true : false;
-	}
-
-	function truncate_table($table_name, $no_prefix = false)
-	{
-		return $this->query('TRUNCATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-}
Index: trunk/web/punbb/include/dblayer/pgsql.php
===================================================================
--- trunk/web/punbb/include/dblayer/pgsql.php	(revision 10)
+++ trunk/web/punbb/include/dblayer/pgsql.php	(revision 1)
@@ -1,9 +1,26 @@
 <?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+/***********************************************************************
+
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // Make sure we have built in support for PostgreSQL
@@ -26,13 +43,4 @@
 	var $error_msg = 'Unknown';
 
-	var $datatype_transformations = array(
-		'%^(TINY|SMALL)INT( )?(\\([0-9]+\\))?( )?(UNSIGNED)?$%i'			=>	'SMALLINT',
-		'%^(MEDIUM)?INT( )?(\\([0-9]+\\))?( )?(UNSIGNED)?$%i'				=>	'INTEGER',
-		'%^BIGINT( )?(\\([0-9]+\\))?( )?(UNSIGNED)?$%i'						=>	'BIGINT',
-		'%^(TINY|MEDIUM|LONG)?TEXT$%i'										=>	'TEXT',
-		'%^DOUBLE( )?(\\([0-9,]+\\))?( )?(UNSIGNED)?$%i'					=>	'DOUBLE PRECISION',
-		'%^FLOAT( )?(\\([0-9]+\\))?( )?(UNSIGNED)?$%i'						=>	'REAL'
-	);
-
 
 	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
@@ -40,5 +48,5 @@
 		$this->prefix = $db_prefix;
 
-		if ($db_host)
+		if ($db_host != '')
 		{
 			if (strpos($db_host, ':') !== false)
@@ -48,5 +56,8 @@
 			}
 			else
-				$connect_str[] = 'host='.$db_host;
+			{
+				if ($db_host != 'localhost')
+					$connect_str[] = 'host='.$db_host;
+			}
 		}
 
@@ -54,8 +65,8 @@
 			$connect_str[] = 'dbname='.$db_name;
 
-		if ($db_username)
+		if ($db_username != '')
 			$connect_str[] = 'user='.$db_username;
 
-		if ($db_password)
+		if ($db_password != '')
 			$connect_str[] = 'password='.$db_password;
 
@@ -67,10 +78,6 @@
 		if (!$this->link_id)
 			error('Unable to connect to PostgreSQL server', __FILE__, __LINE__);
-
-		// Setup the client-server character set (UTF-8)
-		if (!defined('FORUM_NO_SET_NAMES'))
-			$this->set_names('utf8');
-
-		return $this->link_id;
+		else
+			return $this->link_id;
 	}
 
@@ -98,8 +105,8 @@
 
 
-	function query($sql, $unbuffered = false) // $unbuffered is ignored since there is no pgsql_unbuffered_query()
+	function query($sql, $unbuffered = false)	// $unbuffered is ignored since there is no pgsql_unbuffered_query()
 	{
 		if (strrpos($sql, 'LIMIT') !== false)
-			$sql = preg_replace('%LIMIT ([0-9]+),([ 0-9]+)%', 'LIMIT \\2 OFFSET \\1', $sql);
+			$sql = preg_replace('#LIMIT ([0-9]+),([ 0-9]+)#', 'LIMIT \\2 OFFSET \\1', $sql);
 
 		if (defined('PUN_SHOW_QUERIES'))
@@ -125,5 +132,4 @@
 				$this->saved_queries[] = array($sql, 0);
 
-			$this->error_no = false;
 			$this->error_msg = @pg_result_error($this->query_result);
 
@@ -138,7 +144,7 @@
 
 
-	function result($query_id = 0, $row = 0, $col = 0)
-	{
-		return ($query_id) ? @pg_fetch_result($query_id, $row, $col) : false;
+	function result($query_id = 0, $row = 0)
+	{
+		return ($query_id) ? @pg_fetch_result($query_id, $row, 0) : false;
 	}
 
@@ -174,5 +180,5 @@
 		if ($query_id && $this->last_query_text[$query_id] != '')
 		{
-			if (preg_match('%^INSERT INTO ([a-z0-9\_\-]+)%is', $this->last_query_text[$query_id], $table_name))
+			if (preg_match('/^INSERT INTO ([a-z0-9\_\-]+)/is', $this->last_query_text[$query_id], $table_name))
 			{
 				// Hack (don't ask)
@@ -212,5 +218,5 @@
 	function escape($str)
 	{
-		return is_array($str) ? '' : pg_escape_string($str);
+		return pg_escape_string($str);
 	}
 
@@ -219,5 +225,15 @@
 	{
 		$result['error_sql'] = @current(@end($this->saved_queries));
-		$result['error_no'] = $this->error_no;
+		$result['error_no'] = false;
+/*
+		if (!empty($this->query_result))
+		{
+			$result['error_msg'] = trim(@pg_result_error($this->query_result));
+			if ($result['error_msg'] != '')
+				return $result;
+		}
+
+		$result['error_msg'] = (!empty($this->link_id)) ? trim(@pg_last_error($this->link_id)) : trim(@pg_last_error());
+*/
 		$result['error_msg'] = $this->error_msg;
 
@@ -246,191 +262,3 @@
 			return false;
 	}
-
-
-	function get_names()
-	{
-		$result = $this->query('SHOW client_encoding');
-		return strtolower($this->result($result)); // MySQL returns lowercase so lets be consistent
-	}
-
-
-	function set_names($names)
-	{
-		return $this->query('SET NAMES \''.$this->escape($names).'\'');
-	}
-
-
-	function get_version()
-	{
-		$result = $this->query('SELECT VERSION()');
-
-		return array(
-			'name'		=> 'PostgreSQL',
-			'version'	=> preg_replace('%^[^0-9]+([^\s,-]+).*$%', '\\1', $this->result($result))
-		);
-	}
-
-
-	function table_exists($table_name, $no_prefix = false)
-	{
-		$result = $this->query('SELECT 1 FROM pg_class WHERE relname = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function field_exists($table_name, $field_name, $no_prefix = false)
-	{
-		$result = $this->query('SELECT 1 FROM pg_class c INNER JOIN pg_attribute a ON a.attrelid = c.oid WHERE c.relname = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\' AND a.attname = \''.$this->escape($field_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function index_exists($table_name, $index_name, $no_prefix = false)
-	{
-		$result = $this->query('SELECT 1 FROM pg_index i INNER JOIN pg_class c1 ON c1.oid = i.indrelid INNER JOIN pg_class c2 ON c2.oid = i.indexrelid WHERE c1.relname = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\' AND c2.relname = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_'.$this->escape($index_name).'\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function create_table($table_name, $schema, $no_prefix = false)
-	{
-		if ($this->table_exists($table_name, $no_prefix))
-			return true;
-
-		$query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
-
-		// Go through every schema element and add it to the query
-		foreach ($schema['FIELDS'] as $field_name => $field_data)
-		{
-			$field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
-
-			$query .= $field_name.' '.$field_data['datatype'];
-
-			// The SERIAL datatype is a special case where we don't need to say not null
-			if (!$field_data['allow_null'] && $field_data['datatype'] != 'SERIAL')
-				$query .= ' NOT NULL';
-
-			if (isset($field_data['default']))
-				$query .= ' DEFAULT '.$field_data['default'];
-
-			$query .= ",\n";
-		}
-
-		// If we have a primary key, add it
-		if (isset($schema['PRIMARY KEY']))
-			$query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
-
-		// Add unique keys
-		if (isset($schema['UNIQUE KEYS']))
-		{
-			foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
-				$query .= 'UNIQUE ('.implode(',', $key_fields).'),'."\n";
-		}
-
-		// We remove the last two characters (a newline and a comma) and add on the ending
-		$query = substr($query, 0, strlen($query) - 2)."\n".')';
-
-		$result = $this->query($query) ? true : false;
-
-		// Add indexes
-		if (isset($schema['INDEXES']))
-		{
-			foreach ($schema['INDEXES'] as $index_name => $index_fields)
-				$result &= $this->add_index($table_name, $index_name, $index_fields, false, $no_prefix);
-		}
-
-		return $result;
-	}
-
-
-	function drop_table($table_name, $no_prefix = false)
-	{
-		if (!$this->table_exists($table_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-
-
-	function rename_table($old_table, $new_table, $no_prefix = false)
-	{
-		// If there new table exists and the old one doesn't, then we're happy
-		if ($this->table_exists($new_table, $no_prefix) && !$this->table_exists($old_table, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$old_table.' RENAME TO '.($no_prefix ? '' : $this->prefix).$new_table) ? true : false;
-	}
-
-
-	function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if ($this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		$result = $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ADD '.$field_name.' '.$field_type) ? true : false;
-
-		if ($default_value !== null)
-		{
-			if (!is_int($default_value) && !is_float($default_value))
-				$default_value = '\''.$this->escape($default_value).'\'';
-
-			$result &= $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ALTER '.$field_name.' SET DEFAULT '.$default_value) ? true : false;
-			$result &= $this->query('UPDATE '.($no_prefix ? '' : $this->prefix).$table_name.' SET '.$field_name.'='.$default_value) ? true : false;
-		}
-
-		if (!$allow_null)
-			$result &= $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' ALTER '.$field_name.' SET NOT NULL') ? true : false;
-
-		return $result;
-	}
-
-
-	function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = null, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-
-		$result = $this->add_field($table_name, 'tmp_'.$field_name, $field_type, $allow_null, $default_value, $after_field, $no_prefix);
-		$result &= $this->query('UPDATE '.($no_prefix ? '' : $this->prefix).$table_name.' SET tmp_'.$field_name.' = '.$field_name) ? true : false;
-		$result &= $this->drop_field($table_name, $field_name, $no_prefix);
-		$result &= $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' RENAME COLUMN tmp_'.$field_name.' TO '.$field_name) ? true : false;
-
-		return $result;
-	}
-
-
-	function drop_field($table_name, $field_name, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		return $this->query('ALTER TABLE '.($no_prefix ? '' : $this->prefix).$table_name.' DROP '.$field_name) ? true : false;
-	}
-
-
-	function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
-	{
-		if ($this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('CREATE '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ON '.($no_prefix ? '' : $this->prefix).$table_name.'('.implode(',', $index_fields).')') ? true : false;
-	}
-
-
-	function drop_index($table_name, $index_name, $no_prefix = false)
-	{
-		if (!$this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) ? true : false;
-	}
-
-	function truncate_table($table_name, $no_prefix = false)
-	{
-		return $this->query('DELETE FROM '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
 }
Index: trunk/web/punbb/include/dblayer/sqlite.php
===================================================================
--- trunk/web/punbb/include/dblayer/sqlite.php	(revision 10)
+++ trunk/web/punbb/include/dblayer/sqlite.php	(revision 1)
@@ -1,9 +1,26 @@
 <?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+/***********************************************************************
+
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // Make sure we have built in support for SQLite
@@ -25,10 +42,4 @@
 	var $error_msg = 'Unknown';
 
-	var $datatype_transformations = array(
-		'%^SERIAL$%'															=>	'INTEGER',
-		'%^(TINY|SMALL|MEDIUM|BIG)?INT( )?(\\([0-9]+\\))?( )?(UNSIGNED)?$%i'	=>	'INTEGER',
-		'%^(TINY|MEDIUM|LONG)?TEXT$%i'											=>	'TEXT'
-	);
-
 
 	function DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, $p_connect)
@@ -124,16 +135,12 @@
 
 
-	function result($query_id = 0, $row = 0, $col = 0)
+	function result($query_id = 0, $row = 0)
 	{
 		if ($query_id)
 		{
-			if ($row !== 0 && @sqlite_seek($query_id, $row) === false)
-				return false;
-
-			$cur_row = @sqlite_current($query_id);
-			if ($cur_row === false)
-				return false;
-
-			return $cur_row[$col];
+			if ($row != 0)
+				@sqlite_seek($query_id, $row);
+
+			return @current(@sqlite_current($query_id));
 		}
 		else
@@ -150,13 +157,13 @@
 			{
 				// Horrible hack to get rid of table names and table aliases from the array keys
-				foreach ($cur_row as $key => $value)
+				while (list($key, $value) = @each($cur_row))
 				{
-					$dot_spot = strpos($key, '.');
-					if ($dot_spot !== false)
-					{
-						unset($cur_row[$key]);
-						$key = substr($key, $dot_spot+1);
-						$cur_row[$key] = $value;
-					}
+				    $dot_spot = strpos($key, '.');
+				    if ($dot_spot !== false)
+				    {
+				        unset($cur_row[$key]);
+				        $key = substr($key, $dot_spot+1);
+				        $cur_row[$key] = $value;
+				    }
 				}
 			}
@@ -183,5 +190,5 @@
 	function affected_rows()
 	{
-		return ($this->link_id) ? @sqlite_changes($this->link_id) : false;
+		return ($this->query_result) ? @sqlite_changes($this->query_result) : false;
 	}
 
@@ -213,5 +220,5 @@
 	function escape($str)
 	{
-		return is_array($str) ? '' : sqlite_escape_string($str);
+		return sqlite_escape_string($str);
 	}
 
@@ -244,324 +251,3 @@
 			return false;
 	}
-
-
-	function get_names()
-	{
-		return '';
-	}
-
-
-	function set_names($names)
-	{
-		return true;
-	}
-
-
-	function get_version()
-	{
-		return array(
-			'name'		=> 'SQLite',
-			'version'	=> sqlite_libversion()
-		);
-	}
-
-
-	function table_exists($table_name, $no_prefix = false)
-	{
-		$result = $this->query('SELECT 1 FROM sqlite_master WHERE name = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\' AND type=\'table\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function field_exists($table_name, $field_name, $no_prefix = false)
-	{
-		$result = $this->query('SELECT sql FROM sqlite_master WHERE name = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\' AND type=\'table\'');
-		if (!$this->num_rows($result))
-			return false;
-
-		return preg_match('%[\r\n]'.preg_quote($field_name, '%').' %', $this->result($result));
-	}
-
-
-	function index_exists($table_name, $index_name, $no_prefix = false)
-	{
-		$result = $this->query('SELECT 1 FROM sqlite_master WHERE tbl_name = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\' AND name = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_'.$this->escape($index_name).'\' AND type=\'index\'');
-		return $this->num_rows($result) > 0;
-	}
-
-
-	function create_table($table_name, $schema, $no_prefix = false)
-	{
-		if ($this->table_exists($table_name, $no_prefix))
-			return true;
-
-		$query = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$table_name." (\n";
-
-		// Go through every schema element and add it to the query
-		foreach ($schema['FIELDS'] as $field_name => $field_data)
-		{
-			$field_data['datatype'] = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_data['datatype']);
-
-			$query .= $field_name.' '.$field_data['datatype'];
-
-			if (!$field_data['allow_null'])
-				$query .= ' NOT NULL';
-
-			if (isset($field_data['default']))
-				$query .= ' DEFAULT '.$field_data['default'];
-
-			$query .= ",\n";
-		}
-
-		// If we have a primary key, add it
-		if (isset($schema['PRIMARY KEY']))
-			$query .= 'PRIMARY KEY ('.implode(',', $schema['PRIMARY KEY']).'),'."\n";
-
-		// Add unique keys
-		if (isset($schema['UNIQUE KEYS']))
-		{
-			foreach ($schema['UNIQUE KEYS'] as $key_name => $key_fields)
-				$query .= 'UNIQUE ('.implode(',', $key_fields).'),'."\n";
-		}
-
-		// We remove the last two characters (a newline and a comma) and add on the ending
-		$query = substr($query, 0, strlen($query) - 2)."\n".')';
-
-		$result = $this->query($query) ? true : false;
-
-		// Add indexes
-		if (isset($schema['INDEXES']))
-		{
-			foreach ($schema['INDEXES'] as $index_name => $index_fields)
-				$result &= $this->add_index($table_name, $index_name, $index_fields, false, $no_prefix);
-		}
-
-		return $result;
-	}
-
-
-	function drop_table($table_name, $no_prefix = false)
-	{
-		if (!$this->table_exists($table_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP TABLE '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
-
-
-	function rename_table($old_name, $new_name, $no_prefix = false)
-	{
-		// If there new table exists and the old one doesn't, then we're happy
-		if ($this->table_exists($new_table, $no_prefix) && !$this->table_exists($old_table, $no_prefix))
-			return true;
-
-		$table = $this->get_table_info($old_name, $no_prefix);
-
-		// Create new table
-		$newtable = str_replace('CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($old_name).' (', 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($new_name).' (', $table['sql']);
-		$result = $this->query($newtable) ? true : false;
-
-		// Recreate indexes
-		if (!empty($table['indices']))
-		{
-			foreach ($table['indices'] as $cur_index)
-				$result &= $this->query($cur_index) ? true : false;
-		}
-
-		// Copy content across
-		$result &= $this->query('INSERT INTO '.($no_prefix ? '' : $this->prefix).$this->escape($new_name).' SELECT * FROM '.($no_prefix ? '' : $this->prefix).$this->escape($old_name)) ? true : false;
-
-		// Drop old table
-		$result &= $this->drop_table(($no_prefix ? '' : $this->prefix).$this->escape($table_name));
-
-		return $result;
-	}
-
-
-	function get_table_info($table_name, $no_prefix = false)
-	{
-		// Grab table info
-		$result = $this->query('SELECT sql FROM sqlite_master WHERE tbl_name = \''.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'\' ORDER BY type DESC') or error('Unable to fetch table information', __FILE__, __LINE__, $this->error());
-		$num_rows = $this->num_rows($result);
-
-		if ($num_rows == 0)
-			return;
-
-		$table = array();
-		$table['indices'] = array();
-		while ($cur_index = $this->fetch_assoc($result))
-		{
-			if (empty($cur_index['sql']))
-				continue;
-
-			if (!isset($table['sql']))
-				$table['sql'] = $cur_index['sql'];
-			else
-				$table['indices'][] = $cur_index['sql'];
-		}
-
-		// Work out the columns in the table currently
-		$table_lines = explode("\n", $table['sql']);
-		$table['columns'] = array();
-		foreach ($table_lines as $table_line)
-		{
-			$table_line = trim($table_line, " \t\n\r,"); // trim spaces, tabs, newlines, and commas
-			if (substr($table_line, 0, 12) == 'CREATE TABLE')
-				continue;
-			else if (substr($table_line, 0, 11) == 'PRIMARY KEY')
-				$table['primary_key'] = $table_line;
-			else if (substr($table_line, 0, 6) == 'UNIQUE')
-				$table['unique'] = $table_line;
-			else if (substr($table_line, 0, strpos($table_line, ' ')) != '')
-				$table['columns'][substr($table_line, 0, strpos($table_line, ' '))] = trim(substr($table_line, strpos($table_line, ' ')));
-		}
-
-		return $table;
-	}
-
-
-	function add_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = 0, $no_prefix = false)
-	{
-		if ($this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$table = $this->get_table_info($table_name, $no_prefix);
-
-		// Create temp table
-		$now = time();
-		$tmptable = str_replace('CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).' (', 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now.' (', $table['sql']);
-		$result = $this->query($tmptable) ? true : false;
-		$result &= $this->query('INSERT INTO '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now.' SELECT * FROM '.($no_prefix ? '' : $this->prefix).$this->escape($table_name)) ? true : false;
-
-		// Create new table sql
-		$field_type = preg_replace(array_keys($this->datatype_transformations), array_values($this->datatype_transformations), $field_type);
-		$query = $field_type;
-		if (!$allow_null)
-			$query .= ' NOT NULL';
-		if ($default_value === null || $default_value === '')
-			$default_value = '\'\'';
-
-		$query .= ' DEFAULT '.$default_value;
-
-		$old_columns = array_keys($table['columns']);
-		array_insert($table['columns'], $after_field, $query, $field_name);
-
-		$new_table = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).' (';
-
-		foreach ($table['columns'] as $cur_column => $column_details)
-			$new_table .= "\n".$cur_column.' '.$column_details.',';
-
-		if (isset($table['unique']))
-			$new_table .= "\n".$table['unique'].',';
-
-		if (isset($table['primary_key']))
-			$new_table .= "\n".$table['primary_key'].',';
-
-		$new_table = trim($new_table, ',')."\n".');';
-
-		// Drop old table
-		$result &= $this->drop_table(($no_prefix ? '' : $this->prefix).$this->escape($table_name));
-
-		// Create new table
-		$result &= $this->query($new_table) ? true : false;
-
-		// Recreate indexes
-		if (!empty($table['indices']))
-		{
-			foreach ($table['indices'] as $cur_index)
-				$result &= $this->query($cur_index) ? true : false;
-		}
-
-		// Copy content back
-		$result &= $this->query('INSERT INTO '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).' ('.implode(', ', $old_columns).') SELECT * FROM '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now) ? true : false;
-
-		// Drop temp table
-		$result &= $this->drop_table(($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now);
-
-		return $result;
-	}
-
-
-	function alter_field($table_name, $field_name, $field_type, $allow_null, $default_value = null, $after_field = 0, $no_prefix = false)
-	{
-		// Unneeded for SQLite
-		return true;
-	}
-
-
-	function drop_field($table_name, $field_name, $no_prefix = false)
-	{
-		if (!$this->field_exists($table_name, $field_name, $no_prefix))
-			return true;
-
-		$table = $this->get_table_info($table_name, $no_prefix);
-
-		// Create temp table
-		$now = time();
-		$tmptable = str_replace('CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).' (', 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now.' (', $table['sql']);
-		$result = $this->query($tmptable) ? true : false;
-		$result &= $this->query('INSERT INTO '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now.' SELECT * FROM '.($no_prefix ? '' : $this->prefix).$this->escape($table_name)) ? true : false;
-
-		// Work out the columns we need to keep and the sql for the new table
-		unset($table['columns'][$field_name]);
-		$new_columns = array_keys($table['columns']);
-
-		$new_table = 'CREATE TABLE '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).' (';
-
-		foreach ($table['columns'] as $cur_column => $column_details)
-			$new_table .= "\n".$cur_column.' '.$column_details.',';
-
-		if (isset($table['unique']))
-			$new_table .= "\n".$table['unique'].',';
-
-		if (isset($table['primary_key']))
-			$new_table .= "\n".$table['primary_key'].',';
-
-		$new_table = trim($new_table, ',')."\n".');';
-
-		// Drop old table
-		$result &= $this->drop_table(($no_prefix ? '' : $this->prefix).$this->escape($table_name));
-
-		// Create new table
-		$result &= $this->query($new_table) ? true : false;
-
-		// Recreate indexes
-		if (!empty($table['indices']))
-		{
-			foreach ($table['indices'] as $cur_index)
-				if (!preg_match('%\('.preg_quote($field_name, '%').'\)%', $cur_index))
-					$result &= $this->query($cur_index) ? true : false;
-		}
-
-		// Copy content back
-		$result &= $this->query('INSERT INTO '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).' SELECT '.implode(', ', $new_columns).' FROM '.($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now) ? true : false;
-
-		// Drop temp table
-		$result &= $this->drop_table(($no_prefix ? '' : $this->prefix).$this->escape($table_name).'_t'.$now);
-
-		return $result;
-	}
-
-
-	function add_index($table_name, $index_name, $index_fields, $unique = false, $no_prefix = false)
-	{
-		if ($this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('CREATE '.($unique ? 'UNIQUE ' : '').'INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name.' ON '.($no_prefix ? '' : $this->prefix).$table_name.'('.implode(',', $index_fields).')') ? true : false;
-	}
-
-
-	function drop_index($table_name, $index_name, $no_prefix = false)
-	{
-		if (!$this->index_exists($table_name, $index_name, $no_prefix))
-			return true;
-
-		return $this->query('DROP INDEX '.($no_prefix ? '' : $this->prefix).$table_name.'_'.$index_name) ? true : false;
-	}
-
-	function truncate_table($table_name, $no_prefix = false)
-	{
-		return $this->query('DELETE FROM '.($no_prefix ? '' : $this->prefix).$table_name) ? true : false;
-	}
 }
Index: trunk/web/punbb/include/email.php
===================================================================
--- trunk/web/punbb/include/email.php	(revision 10)
+++ trunk/web/punbb/include/email.php	(revision 1)
@@ -1,9 +1,26 @@
 <?php
+/***********************************************************************
 
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // Make sure no one attempts to run this script "directly"
@@ -11,15 +28,14 @@
 	exit;
 
-require PUN_ROOT.'include/utf8/utils/ascii.php';
 
 //
-// Validate an email address
+// Validate an e-mail address
 //
 function is_valid_email($email)
 {
-	if (strlen($email) > 80)
+	if (strlen($email) > 50)
 		return false;
 
-	return preg_match('%^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|("[^"]+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-zA-Z\d\-]+\.)+[a-zA-Z]{2,}))$%', $email);
+	return preg_match('/^(([^<>()[\]\\.,;:\s@"\']+(\.[^<>()[\]\\.,;:\s@"\']+)*)|("[^"\']+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-zA-Z\d\-]+\.)+[a-zA-Z]{2,}))$/', $email);
 }
 
@@ -30,5 +46,5 @@
 function is_banned_email($email)
 {
-	global $pun_bans;
+	global $db, $pun_bans;
 
 	foreach ($pun_bans as $cur_ban)
@@ -45,213 +61,34 @@
 
 //
-// Only encode with base64, if there is at least one unicode character in the string
-//
-function encode_mail_text($str)
-{
-	if (utf8_is_ascii($str))
-		return $str;
-
-	return '=?UTF-8?B?'.base64_encode($str).'?=';
-}
-
-
-//
-// Make a post email safe
-//
-function bbcode2email($text, $wrap_length = 72)
-{
-    static $base_url;
-
-    if (!isset($base_url))
-        $base_url = get_base_url();
-
-    $text = pun_trim($text, "\t\n ");
-
-    $shortcut_urls = array(
-        'topic' => '/viewtopic.php?id=$1',
-        'post' => '/viewtopic.php?pid=$1#p$1',
-        'forum' => '/viewforum.php?id=$1',
-        'user' => '/profile.php?id=$1',
-    );
-
-    // Split code blocks and text so BBcode in codeblocks won't be touched
-    list($code, $text) = extract_blocks($text, '[code]', '[/code]');
-
-    // Strip all bbcodes, except the quote, url, img, email, code and list items bbcodes
-    $text = preg_replace(array(
-        '%\[/?(?!(?:quote|url|topic|post|user|forum|img|email|code|list|\*))[a-z]+(?:=[^\]]+)?\]%i',
-        '%\n\[/?list(?:=[^\]]+)?\]%i' // A separate regex for the list tags to get rid of some whitespace
-    ), '', $text);
-
-    // Match the deepest nested bbcode
-    // An adapted example from Mastering Regular Expressions
-    $match_quote_regex = '%
-        \[(quote|\*|url|img|email|topic|post|user|forum)(?:=([^\]]+))?\]
-        (
-            (?>[^\[]*)
-            (?>
-                (?!\[/?\1(?:=[^\]]+)?\])
-                \[
-                [^\[]*
-            )*
-        )
-        \[/\1\]
-    %ix';
-
-    $url_index = 1;
-    $url_stack = array();
-    while (preg_match($match_quote_regex, $text, $matches))
-    {
-        // Quotes
-        if ($matches[1] == 'quote')
-        {
-            // Put '>' or '> ' at the start of a line
-            $replacement = preg_replace(
-                array('%^(?=\>)%m', '%^(?!\>)%m'),
-                array('>', '> '),
-                $matches[2]." said:\n".$matches[3]);
-        }
-
-        // List items
-        elseif ($matches[1] == '*')
-        {
-            $replacement = ' * '.$matches[3];
-        }
-
-        // URLs and emails
-        elseif (in_array($matches[1], array('url', 'email')))
-        {
-            if (!empty($matches[2]))
-            {
-                $replacement = '['.$matches[3].']['.$url_index.']';
-                $url_stack[$url_index] = $matches[2];
-                $url_index++;
-            }
-            else
-                $replacement = '['.$matches[3].']';
-        }
-
-        // Images
-        elseif ($matches[1] == 'img')
-        {
-            if (!empty($matches[2]))
-                $replacement = '['.$matches[2].']['.$url_index.']';
-            else
-                $replacement = '['.basename($matches[3]).']['.$url_index.']';
-
-            $url_stack[$url_index] = $matches[3];
-            $url_index++;
-        }
-
-        // Topic, post, forum and user URLs
-        elseif (in_array($matches[1], array('topic', 'post', 'forum', 'user')))
-        {
-            $url = isset($shortcut_urls[$matches[1]]) ? $base_url.$shortcut_urls[$matches[1]] : '';
-
-            if (!empty($matches[2]))
-            {
-                $replacement = '['.$matches[3].']['.$url_index.']';
-                $url_stack[$url_index] = str_replace('$1', $matches[2], $url);
-                $url_index++;
-            }
-            else
-                $replacement = '['.str_replace('$1', $matches[3], $url).']';
-        }
-
-        // Update the main text if there is a replacment
-        if (!is_null($replacement))
-        {
-            $text = str_replace($matches[0], $replacement, $text);
-            $replacement = null;
-        }
-    }
-
-    // Put code blocks and text together
-    if (isset($code))
-    {
-        $parts = explode("\1", $text);
-        $text = '';
-        foreach ($parts as $i => $part)
-        {
-            $text .= $part;
-            if (isset($code[$i]))
-                $text .= trim($code[$i], "\n\r");
-        }
-    }
-
-    // Put URLs at the bottom
-    if ($url_stack)
-    {
-        $text .= "\n\n";
-        foreach ($url_stack as $i => $url)
-            $text .= "\n".' ['.$i.']: '.$url;
-    }
-
-    // Wrap lines if $wrap_length is higher than -1
-    if ($wrap_length > -1)
-    {
-        // Split all lines and wrap them individually
-        $parts = explode("\n", $text);
-        foreach ($parts as $k => $part)
-        {
-            preg_match('%^(>+ )?(.*)%', $part, $matches);
-            $parts[$k] = wordwrap($matches[1].$matches[2], $wrap_length -
-                strlen($matches[1]), "\n".$matches[1]);
-        }
-
-        return implode("\n", $parts);
-    }
-    else
-        return $text;
-}
-
-
-//
 // Wrapper for PHP's mail()
 //
-function pun_mail($to, $subject, $message, $reply_to_email = '', $reply_to_name = '')
+function pun_mail($to, $subject, $message, $from = '')
 {
 	global $pun_config, $lang_common;
 
 	// Default sender/return address
-	$from_name = sprintf($lang_common['Mailer'], $pun_config['o_board_title']);
-	$from_email = $pun_config['o_webmaster_email'];
+	if (!$from)
+		$from = '"'.str_replace('"', '', $pun_config['o_board_title'].' '.$lang_common['Mailer']).'" <'.$pun_config['o_webmaster_email'].'>';
 
 	// Do a little spring cleaning
-	$to = pun_trim(preg_replace('%[\n\r]+%s', '', $to));
-	$subject = pun_trim(preg_replace('%[\n\r]+%s', '', $subject));
-	$from_email = pun_trim(preg_replace('%[\n\r:]+%s', '', $from_email));
-	$from_name = pun_trim(preg_replace('%[\n\r:]+%s', '', str_replace('"', '', $from_name)));
-	$reply_to_email = pun_trim(preg_replace('%[\n\r:]+%s', '', $reply_to_email));
-	$reply_to_name = pun_trim(preg_replace('%[\n\r:]+%s', '', str_replace('"', '', $reply_to_name)));
+	$to = trim(preg_replace('#[\n\r]+#s', '', $to));
+	$subject = trim(preg_replace('#[\n\r]+#s', '', $subject));
+	$from = trim(preg_replace('#[\n\r:]+#s', '', $from));
 
-	// Set up some headers to take advantage of UTF-8
-	$from = '"'.encode_mail_text($from_name).'" <'.$from_email.'>';
-	$subject = encode_mail_text($subject);
+	$headers = 'From: '.$from."\r\n".'Date: '.date('r')."\r\n".'MIME-Version: 1.0'."\r\n".'Content-transfer-encoding: 8bit'."\r\n".'Content-type: text/plain; charset='.$lang_common['lang_encoding']."\r\n".'X-Mailer: PunBB Mailer';
 
-	$headers = 'From: '.$from."\r\n".'Date: '.gmdate('r')."\r\n".'MIME-Version: 1.0'."\r\n".'Content-transfer-encoding: 8bit'."\r\n".'Content-type: text/plain; charset=utf-8'."\r\n".'X-Mailer: FluxBB Mailer';
-
-	// If we specified a reply-to email, we deal with it here
-	if (!empty($reply_to_email))
-	{
-		$reply_to = '"'.encode_mail_text($reply_to_name).'" <'.$reply_to_email.'>';
-
-		$headers .= "\r\n".'Reply-To: '.$reply_to;
-	}
-
-	// Make sure all linebreaks are LF in message (and strip out any NULL bytes)
-	$message = str_replace("\0", '', pun_linebreaks($message));
+	// Make sure all linebreaks are CRLF in message
+	$message = str_replace("\n", "\r\n", pun_linebreaks($message));
 
 	if ($pun_config['o_smtp_host'] != '')
-	{
-		// Headers should be \r\n
-		// Message should be ??
-		$message = str_replace("\n", "\r\n", $message);
 		smtp_mail($to, $subject, $message, $headers);
-	}
 	else
 	{
-		// Headers should be \r\n
-		// Message should be \n
+		// Change the linebreaks used in the headers according to OS
+		if (strtoupper(substr(PHP_OS, 0, 3)) == 'MAC')
+			$headers = str_replace("\r\n", "\r", $headers);
+		else if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN')
+			$headers = str_replace("\r\n", "\n", $headers);
+		
 		mail($to, $subject, $message, $headers);
 	}
@@ -260,6 +97,6 @@
 
 //
-// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com)
-// They deserve all the credit for writing it. I made small modifications for it to suit PunBB and it's coding standards
+// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com).
+// They deserve all the credit for writing it. I made small modifications for it to suit PunBB and it's coding standards.
 //
 function server_parse($socket, $expected_response)
@@ -269,14 +106,14 @@
 	{
 		if (!($server_response = fgets($socket, 256)))
-			error('Couldn\'t get mail server response codes. Please contact the forum administrator.', __FILE__, __LINE__);
+			error('N\'a pas pu obtenir les codes de rÃ©ponse du serveur mail. Veuillez contacter l\'administrateur de forum', __FILE__, __LINE__);
 	}
 
 	if (!(substr($server_response, 0, 3) == $expected_response))
-		error('Unable to send email. Please contact the forum administrator with the following error message reported by the SMTP server: "'.$server_response.'"', __FILE__, __LINE__);
+		error('Impossible d\'envoyer l\'e-mail. Veuillez contacter l\'administrateur des forums avec le message d\'erreur suivant rapportÃ© par le serveur SMTP : "'.$server_response.'"', __FILE__, __LINE__);
 }
 
 
 //
-// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com)
+// This function was originally a part of the phpBB Group forum software phpBB2 (http://www.phpbb.com).
 // They deserve all the credit for writing it. I made small modifications for it to suit PunBB and it's coding standards.
 //
@@ -286,8 +123,4 @@
 
 	$recipients = explode(',', $to);
-
-	// Sanitize the message
-	$message = str_replace("\r\n.", "\r\n..", $message);
-	$message = (substr($message, 0, 1) == '.' ? '.'.$message : $message);
 
 	// Are we using port 25 or a custom port?
@@ -300,9 +133,6 @@
 	}
 
-	if ($pun_config['o_smtp_ssl'] == '1')
-		$smtp_host = 'ssl://'.$smtp_host;
-
 	if (!($socket = fsockopen($smtp_host, $smtp_port, $errno, $errstr, 15)))
-		error('Could not connect to smtp host "'.$pun_config['o_smtp_host'].'" ('.$errno.') ('.$errstr.')', __FILE__, __LINE__);
+		error('Impossible de joindre l\'hÃŽte SMTP "'.$pun_config['o_smtp_host'].'" ('.$errno.') ('.$errstr.')', __FILE__, __LINE__);
 
 	server_parse($socket, '220');
@@ -331,8 +161,13 @@
 	server_parse($socket, '250');
 
-	foreach ($recipients as $email)
+	$to_header = 'To: ';
+
+	@reset($recipients);
+	while (list(, $email) = @each($recipients))
 	{
 		fwrite($socket, 'RCPT TO: <'.$email.'>'."\r\n");
 		server_parse($socket, '250');
+
+		$to_header .= '<'.$email.'>, ';
 	}
 
@@ -340,5 +175,5 @@
 	server_parse($socket, '354');
 
-	fwrite($socket, 'Subject: '.$subject."\r\n".'To: <'.implode('>, <', $recipients).'>'."\r\n".$headers."\r\n\r\n".$message."\r\n");
+	fwrite($socket, 'Subject: '.$subject."\r\n".$to_header."\r\n".$headers."\r\n\r\n".$message."\r\n");
 
 	fwrite($socket, '.'."\r\n");
Index: trunk/web/punbb/include/functions.php
===================================================================
--- trunk/web/punbb/include/functions.php	(revision 10)
+++ trunk/web/punbb/include/functions.php	(revision 1)
@@ -1,19 +1,25 @@
 <?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
-
-
-//
-// Return current timestamp (with microseconds) as a float
-//
-function get_microtime()
-{
-	list($usec, $sec) = explode(' ', microtime());
-	return ((float)$usec + (float)$sec);
-}
+/***********************************************************************
+
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
 
 //
@@ -22,27 +28,27 @@
 function check_cookie(&$pun_user)
 {
-	global $db, $db_type, $pun_config, $cookie_name, $cookie_seed;
+	global $db, $pun_config, $cookie_name, $cookie_seed;
 
 	$now = time();
-
-	// If the cookie is set and it matches the correct pattern, then read the values from it
-	if (isset($_COOKIE[$cookie_name]) && preg_match('%^(\d+)\|([0-9a-fA-F]+)\|(\d+)\|([0-9a-fA-F]+)$%', $_COOKIE[$cookie_name], $matches))
-	{
-		$cookie = array(
-			'user_id'			=> intval($matches[1]),
-			'password_hash' 	=> $matches[2],
-			'expiration_time'	=> intval($matches[3]),
-			'cookie_hash'		=> $matches[4],
-		);
-	}
-
-	// If it has a non-guest user, and hasn't expired
-	if (isset($cookie) && $cookie['user_id'] > 1 && $cookie['expiration_time'] > $now)
-	{
-		// If the cookie has been tampered with
-		if (forum_hmac($cookie['user_id'].'|'.$cookie['expiration_time'], $cookie_seed.'_cookie_hash') != $cookie['cookie_hash'])
-		{
-			$expire = $now + 31536000; // The cookie expires after a year
-			pun_setcookie(1, pun_hash(uniqid(rand(), true)), $expire);
+	$expire = $now + 31536000;	// The cookie expires after a year
+
+	// We assume it's a guest
+	$cookie = array('user_id' => 1, 'password_hash' => 'InvitÃ©');
+
+	// If a cookie is set, we get the user_id and password hash from it
+	if (isset($_COOKIE[$cookie_name]))
+		list($cookie['user_id'], $cookie['password_hash']) = @unserialize($_COOKIE[$cookie_name]);
+
+	if ($cookie['user_id'] > 1)
+	{
+		// Check if there's a user with the user ID and password hash from the cookie
+        $_query = 'SELECT u.*, g.*, o.logged, o.idle FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON u.group_id=g.g_id LEFT JOIN '.$db->prefix.'online AS o ON o.user_id=u.id WHERE u.id='.intval($cookie['user_id']);
+		$result = $db->query($_query) or error('Impossible de retrouver les informations utilisateur', __FILE__, __LINE__, $db->error());
+		$pun_user = $db->fetch_assoc($result);
+
+		// If user authorisation failed
+		if (!isset($pun_user['id']) || md5($cookie_seed.$pun_user['password']) !== $cookie['password_hash'])
+		{
+			pun_setcookie(0, random_pass(8), $expire);
 			set_default_user();
 
@@ -50,28 +56,10 @@
 		}
 
-		// Check if there's a user with the user ID and password hash from the cookie
-		$result = $db->query('SELECT u.*, g.*, o.logged, o.idle FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON u.group_id=g.g_id LEFT JOIN '.$db->prefix.'online AS o ON o.user_id=u.id WHERE u.id='.intval($cookie['user_id'])) or error('Unable to fetch user information', __FILE__, __LINE__, $db->error());
-		$pun_user = $db->fetch_assoc($result);
-
-		// If user authorisation failed
-		if (!isset($pun_user['id']) || forum_hmac($pun_user['password'], $cookie_seed.'_password_hash') !== $cookie['password_hash'])
-		{
-			$expire = $now + 31536000; // The cookie expires after a year
-			pun_setcookie(1, pun_hash(uniqid(rand(), true)), $expire);
-			set_default_user();
-
-			return;
-		}
-
-		// Send a new, updated cookie with a new expiration timestamp
-		$expire = ($cookie['expiration_time'] > $now + $pun_config['o_timeout_visit']) ? $now + 1209600 : $now + $pun_config['o_timeout_visit'];
-		pun_setcookie($pun_user['id'], $pun_user['password'], $expire);
-
 		// Set a default language if the user selected language no longer exists
-		if (!file_exists(PUN_ROOT.'lang/'.$pun_user['language']))
+		if (!$pun_user['language'] || !@file_exists(PUN_ROOT.'lang/'.$pun_user['language']))
 			$pun_user['language'] = $pun_config['o_default_lang'];
 
 		// Set a default style if the user selected style no longer exists
-		if (!file_exists(PUN_ROOT.'style/'.$pun_user['style'].'.css'))
+		if (!@file_exists(PUN_ROOT.'style/'.$pun_user['style'].'.css'))
 			$pun_user['style'] = $pun_config['o_default_style'];
 
@@ -81,4 +69,7 @@
 			$pun_user['disp_posts'] = $pun_config['o_disp_posts_default'];
 
+		if ($pun_user['save_pass'] == '0')
+			$expire = 0;
+
 		// Define this if you want this visit to affect the online list and the users last visit data
 		if (!defined('PUN_QUIET_VISIT'))
@@ -86,26 +77,5 @@
 			// Update the online list
 			if (!$pun_user['logged'])
-			{
-				$pun_user['logged'] = $now;
-
-				// With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
-				switch ($db_type)
-				{
-					case 'mysql':
-					case 'mysqli':
-					case 'mysql_innodb':
-					case 'mysqli_innodb':
-					case 'sqlite':
-						$db->query('REPLACE INTO '.$db->prefix.'online (user_id, ident, logged) VALUES('.$pun_user['id'].', \''.$db->escape($pun_user['username']).'\', '.$pun_user['logged'].')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
-						break;
-
-					default:
-						$db->query('INSERT INTO '.$db->prefix.'online (user_id, ident, logged) SELECT '.$pun_user['id'].', \''.$db->escape($pun_user['username']).'\', '.$pun_user['logged'].' WHERE NOT EXISTS (SELECT 1 FROM '.$db->prefix.'online WHERE user_id='.$pun_user['id'].')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
-						break;
-				}
-
-				// Reset tracked topics
-				set_tracked_topics(null);
-			}
+				$db->query('INSERT INTO '.$db->prefix.'online (user_id, ident, logged) VALUES('.$pun_user['id'].', \''.$db->escape($pun_user['username']).'\', '.$now.')') or error('Impossbile d\'insÃ©rer dans la liste des utilisateurs en ligne', __FILE__, __LINE__, $db->error());
 			else
 			{
@@ -113,24 +83,14 @@
 				if ($pun_user['logged'] < ($now-$pun_config['o_timeout_visit']))
 				{
-					$db->query('UPDATE '.$db->prefix.'users SET last_visit='.$pun_user['logged'].' WHERE id='.$pun_user['id']) or error('Unable to update user visit data', __FILE__, __LINE__, $db->error());
+					$db->query('UPDATE '.$db->prefix.'users SET last_visit='.$pun_user['logged'].' WHERE id='.$pun_user['id']) or error('Impossible de mettre Ã  jour les donnÃ©es de visite de l\'utilisateur', __FILE__, __LINE__, $db->error());
 					$pun_user['last_visit'] = $pun_user['logged'];
 				}
 
 				$idle_sql = ($pun_user['idle'] == '1') ? ', idle=0' : '';
-				$db->query('UPDATE '.$db->prefix.'online SET logged='.$now.$idle_sql.' WHERE user_id='.$pun_user['id']) or error('Unable to update online list', __FILE__, __LINE__, $db->error());
-
-				// Update tracked topics with the current expire time
-				if (isset($_COOKIE[$cookie_name.'_track']))
-					forum_setcookie($cookie_name.'_track', $_COOKIE[$cookie_name.'_track'], $now + $pun_config['o_timeout_visit']);
+				$db->query('UPDATE '.$db->prefix.'online SET logged='.$now.$idle_sql.' WHERE user_id='.$pun_user['id']) or error('Impossible de mettre Ã  jour la liste des utilisateurs en ligne', __FILE__, __LINE__, $db->error());
 			}
 		}
-		else
-		{
-			if (!$pun_user['logged'])
-				$pun_user['logged'] = $pun_user['last_visit'];
-		}
 
 		$pun_user['is_guest'] = false;
-		$pun_user['is_admmod'] = $pun_user['g_id'] == PUN_ADMIN || $pun_user['g_moderator'] == '1';
 	}
 	else
@@ -140,112 +100,16 @@
 
 //
-// Converts the CDATA end sequence ]]> into ]]&gt;
-//
-function escape_cdata($str)
-{
-	return str_replace(']]>', ']]&gt;', $str);
-}
-
-
-//
-// Authenticates the provided username and password against the user database
-// $user can be either a user ID (integer) or a username (string)
-// $password can be either a plaintext password or a password hash including salt ($password_is_hash must be set accordingly)
-//
-function authenticate_user($user, $password, $password_is_hash = false)
-{
-	global $db, $pun_user;
-
-	// Check if there's a user matching $user and $password
-	$result = $db->query('SELECT u.*, g.*, o.logged, o.idle FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON g.g_id=u.group_id LEFT JOIN '.$db->prefix.'online AS o ON o.user_id=u.id WHERE '.(is_int($user) ? 'u.id='.intval($user) : 'u.username=\''.$db->escape($user).'\'')) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
-	$pun_user = $db->fetch_assoc($result);
-
-	if (!isset($pun_user['id']) ||
-		($password_is_hash && $password != $pun_user['password']) ||
-		(!$password_is_hash && pun_hash($password) != $pun_user['password']))
-		set_default_user();
-	else
-		$pun_user['is_guest'] = false;
-}
-
-
-//
-// Try to determine the current URL
-//
-function get_current_url($max_length = 0)
-{
-	$protocol = get_current_protocol();
-	$port = (isset($_SERVER['SERVER_PORT']) && (($_SERVER['SERVER_PORT'] != '80' && $protocol == 'http') || ($_SERVER['SERVER_PORT'] != '443' && $protocol == 'https')) && strpos($_SERVER['HTTP_HOST'], ':') === false) ? ':'.$_SERVER['SERVER_PORT'] : '';
-
-	$url = urldecode($protocol.'://'.$_SERVER['HTTP_HOST'].$port.$_SERVER['REQUEST_URI']);
-
-	if (strlen($url) <= $max_length || $max_length == 0)
-		return $url;
-
-	// We can't find a short enough url
-	return null;
-}
-
-
-//
-// Fetch the current protocol in use - http or https
-//
-function get_current_protocol()
-{
-	$protocol = 'http';
-
-	// Check if the server is claiming to using HTTPS
-	if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off')
-		$protocol = 'https';
-
-	// If we are behind a reverse proxy try to decide which protocol it is using
-	if (defined('FORUM_BEHIND_REVERSE_PROXY'))
-	{
-		// Check if we are behind a Microsoft based reverse proxy
-		if (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) != 'off')
-			$protocol = 'https';
-
-		// Check if we're behind a "proper" reverse proxy, and what protocol it's using
-		if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']))
-			$protocol = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']);
-	}
-
-	return $protocol;
-}
-
-//
-// Fetch the base_url, optionally support HTTPS and HTTP
-//
-function get_base_url($support_https = false)
-{
-	global $pun_config;
-	static $base_url;
-
-	if (!$support_https)
-		return $pun_config['o_base_url'];
-
-	if (!isset($base_url))
-	{
-		// Make sure we are using the correct protocol
-		$base_url = str_replace(array('http://', 'https://'), get_current_protocol().'://', $pun_config['o_base_url']);
-	}
-
-	return $base_url;
-}
-
-
-//
 // Fill $pun_user with default values (for guests)
 //
 function set_default_user()
 {
-	global $db, $db_type, $pun_user, $pun_config;
+	global $db, $pun_user, $pun_config;
 
 	$remote_addr = get_remote_address();
 
 	// Fetch guest user
-	$result = $db->query('SELECT u.*, g.*, o.logged, o.last_post, o.last_search FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON u.group_id=g.g_id LEFT JOIN '.$db->prefix.'online AS o ON o.ident=\''.$remote_addr.'\' WHERE u.id=1') or error('Unable to fetch guest information', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT u.*, g.*, o.logged FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'groups AS g ON u.group_id=g.g_id LEFT JOIN '.$db->prefix.'online AS o ON o.ident=\''.$remote_addr.'\' WHERE u.id=1') or error('Impossible de retrouver les informations d\'invitÃ©', __FILE__, __LINE__, $db->error());
 	if (!$db->num_rows($result))
-		exit('Unable to fetch guest information. Your database must contain both a guest user and a guest user group.');
+		exit('Impossible de retrouver les informations invitÃ©. La table \''.$db->prefix.'users\' doit contenir une entrÃ©e avec un id = 1 qui reprÃ©sente les utilisateurs anonymes.');
 
 	$pun_user = $db->fetch_assoc($result);
@@ -253,98 +117,29 @@
 	// Update online list
 	if (!$pun_user['logged'])
-	{
-		$pun_user['logged'] = time();
-
-		// With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
-		switch ($db_type)
-		{
-			case 'mysql':
-			case 'mysqli':
-			case 'mysql_innodb':
-			case 'mysqli_innodb':
-			case 'sqlite':
-				$db->query('REPLACE INTO '.$db->prefix.'online (user_id, ident, logged) VALUES(1, \''.$db->escape($remote_addr).'\', '.$pun_user['logged'].')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
-				break;
-
-			default:
-				$db->query('INSERT INTO '.$db->prefix.'online (user_id, ident, logged) SELECT 1, \''.$db->escape($remote_addr).'\', '.$pun_user['logged'].' WHERE NOT EXISTS (SELECT 1 FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($remote_addr).'\')') or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
-				break;
-		}
-	}
+		$db->query('INSERT INTO '.$db->prefix.'online (user_id, ident, logged) VALUES(1, \''.$db->escape($remote_addr).'\', '.time().')') or error('Impossbile d\'insÃ©rer dans la liste des utilisateurs en ligne', __FILE__, __LINE__, $db->error());
 	else
-		$db->query('UPDATE '.$db->prefix.'online SET logged='.time().' WHERE ident=\''.$db->escape($remote_addr).'\'') or error('Unable to update online list', __FILE__, __LINE__, $db->error());
+		$db->query('UPDATE '.$db->prefix.'online SET logged='.time().' WHERE ident=\''.$db->escape($remote_addr).'\'') or error('Impossible de mettre Ã  jour la liste des utilisateurs en ligne', __FILE__, __LINE__, $db->error());
 
 	$pun_user['disp_topics'] = $pun_config['o_disp_topics_default'];
 	$pun_user['disp_posts'] = $pun_config['o_disp_posts_default'];
-	$pun_user['timezone'] = $pun_config['o_default_timezone'];
-	$pun_user['dst'] = $pun_config['o_default_dst'];
+	$pun_user['timezone'] = $pun_config['o_server_timezone'];
 	$pun_user['language'] = $pun_config['o_default_lang'];
 	$pun_user['style'] = $pun_config['o_default_style'];
 	$pun_user['is_guest'] = true;
-	$pun_user['is_admmod'] = false;
-}
-
-
-//
-// SHA1 HMAC with PHP 4 fallback
-//
-function forum_hmac($data, $key, $raw_output = false)
-{
-	if (function_exists('hash_hmac'))
-		return hash_hmac('sha1', $data, $key, $raw_output);
-
-	// If key size more than blocksize then we hash it once
-	if (strlen($key) > 64)
-		$key = pack('H*', sha1($key)); // we have to use raw output here to match the standard
-
-	// Ensure we're padded to exactly one block boundary
-	$key = str_pad($key, 64, chr(0x00));
-
-	$hmac_opad = str_repeat(chr(0x5C), 64);
-	$hmac_ipad = str_repeat(chr(0x36), 64);
-
-	// Do inner and outer padding
-	for ($i = 0;$i < 64;$i++) {
-		$hmac_opad[$i] = $hmac_opad[$i] ^ $key[$i];
-		$hmac_ipad[$i] = $hmac_ipad[$i] ^ $key[$i];
-	}
-
-	// Finally, calculate the HMAC
-	$hash = sha1($hmac_opad.pack('H*', sha1($hmac_ipad.$data)));
-
-	// If we want raw output then we need to pack the final result
-	if ($raw_output)
-		$hash = pack('H*', $hash);
-
-	return $hash;
-}
-
-
-//
-// Set a cookie, FluxBB style!
-// Wrapper for forum_setcookie
+
+}
+
+
+//
+// Set a cookie, PunBB style!
 //
 function pun_setcookie($user_id, $password_hash, $expire)
 {
-	global $cookie_name, $cookie_seed;
-
-	forum_setcookie($cookie_name, $user_id.'|'.forum_hmac($password_hash, $cookie_seed.'_password_hash').'|'.$expire.'|'.forum_hmac($user_id.'|'.$expire, $cookie_seed.'_cookie_hash'), $expire);
-}
-
-
-//
-// Set a cookie, FluxBB style!
-//
-function forum_setcookie($name, $value, $expire)
-{
-	global $cookie_path, $cookie_domain, $cookie_secure;
-
-	// Enable sending of a P3P header
-	header('P3P: CP="CUR ADM"');
-
-	if (version_compare(PHP_VERSION, '5.2.0', '>='))
-		setcookie($name, $value, $expire, $cookie_path, $cookie_domain, $cookie_secure, true);
-	else
-		setcookie($name, $value, $expire, $cookie_path.'; HttpOnly', $cookie_domain, $cookie_secure);
+	global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $cookie_seed;
+
+	// Enable sending of a P3P header by removing // from the following line (try this if login is failing in IE6)
+//	@header('P3P: CP="CUR ADM"');
+
+	setcookie($cookie_name, serialize(array($user_id, md5($cookie_seed.$password_hash))), $expire, $cookie_path, $cookie_domain, $cookie_secure);
 }
 
@@ -357,15 +152,11 @@
 	global $db, $pun_config, $lang_common, $pun_user, $pun_bans;
 
-	// Admins and moderators aren't affected
-	if ($pun_user['is_admmod'] || !$pun_bans)
+	// Admins aren't affected
+	if ($pun_user['g_id'] == PUN_ADMIN || !$pun_bans)
 		return;
 
-	// Add a dot or a colon (depending on IPv4/IPv6) at the end of the IP address to prevent banned address
-	// 192.168.0.5 from matching e.g. 192.168.0.50
-	$user_ip = get_remote_address();
-	$user_ip .= (strpos($user_ip, '.') !== false) ? '.' : ':';
-
+	// Add a dot at the end of the IP address to prevent banned address 192.168.0.5 from matching e.g. 192.168.0.50
+	$user_ip = get_remote_address().'.';
 	$bans_altered = false;
-	$is_banned = false;
 
 	foreach ($pun_bans as $cur_ban)
@@ -374,11 +165,14 @@
 		if ($cur_ban['expire'] != '' && $cur_ban['expire'] <= time())
 		{
-			$db->query('DELETE FROM '.$db->prefix.'bans WHERE id='.$cur_ban['id']) or error('Unable to delete expired ban', __FILE__, __LINE__, $db->error());
+			$db->query('DELETE FROM '.$db->prefix.'bans WHERE id='.$cur_ban['id']) or error('Impossible de supprimÃ© le bannissement expirÃ©', __FILE__, __LINE__, $db->error());
 			$bans_altered = true;
 			continue;
 		}
 
-		if ($cur_ban['username'] != '' && utf8_strtolower($pun_user['username']) == utf8_strtolower($cur_ban['username']))
-			$is_banned = true;
+		if ($cur_ban['username'] != '' && !strcasecmp($pun_user['username'], $cur_ban['username']))
+		{
+			$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($pun_user['username']).'\'') or error('Impossible de supprimer de la liste des utilisateur en ligne', __FILE__, __LINE__, $db->error());
+			message($lang_common['Ban message'].' '.(($cur_ban['expire'] != '') ? $lang_common['Ban message 2'].' '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? $lang_common['Ban message 3'].'<br /><br /><strong>'.pun_htmlspecialchars($cur_ban['message']).'</strong><br /><br />' : '<br /><br />').$lang_common['Ban message 4'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.', true);
+		}
 
 		if ($cur_ban['ip'] != '')
@@ -386,26 +180,15 @@
 			$cur_ban_ips = explode(' ', $cur_ban['ip']);
 
-			$num_ips = count($cur_ban_ips);
-			for ($i = 0; $i < $num_ips; ++$i)
+			for ($i = 0; $i < count($cur_ban_ips); ++$i)
 			{
-				// Add the proper ending to the ban
-				if (strpos($user_ip, '.') !== false)
-					$cur_ban_ips[$i] = $cur_ban_ips[$i].'.';
-				else
-					$cur_ban_ips[$i] = $cur_ban_ips[$i].':';
+				$cur_ban_ips[$i] = $cur_ban_ips[$i].'.';
 
 				if (substr($user_ip, 0, strlen($cur_ban_ips[$i])) == $cur_ban_ips[$i])
 				{
-					$is_banned = true;
-					break;
+					$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($pun_user['username']).'\'') or error('Impossible de supprimer de la liste des utilisateur en ligne', __FILE__, __LINE__, $db->error());
+					message($lang_common['Ban message'].' '.(($cur_ban['expire'] != '') ? $lang_common['Ban message 2'].' '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? $lang_common['Ban message 3'].'<br /><br /><strong>'.pun_htmlspecialchars($cur_ban['message']).'</strong><br /><br />' : '<br /><br />').$lang_common['Ban message 4'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.', true);
 				}
 			}
 		}
-
-		if ($is_banned)
-		{
-			$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($pun_user['username']).'\'') or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
-			message($lang_common['Ban message'].' '.(($cur_ban['expire'] != '') ? $lang_common['Ban message 2'].' '.strtolower(format_time($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? $lang_common['Ban message 3'].'<br /><br /><strong>'.pun_htmlspecialchars($cur_ban['message']).'</strong><br /><br />' : '<br /><br />').$lang_common['Ban message 4'].' <a href="mailto:'.$pun_config['o_admin_email'].'">'.$pun_config['o_admin_email'].'</a>.', true);
-		}
 	}
 
@@ -413,7 +196,5 @@
 	if ($bans_altered)
 	{
-		if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
-			require PUN_ROOT.'include/cache.php';
-
+		require_once PUN_ROOT.'include/cache.php';
 		generate_bans_cache();
 	}
@@ -422,70 +203,19 @@
 
 //
-// Check username
-//
-function check_username($username, $exclude_id = null)
-{
-	global $db, $pun_config, $errors, $lang_prof_reg, $lang_register, $lang_common, $pun_bans;
-
-	// Convert multiple whitespace characters into one (to prevent people from registering with indistinguishable usernames)
-	$username = preg_replace('%\s+%s', ' ', $username);
-
-	// Validate username
-	if (pun_strlen($username) < 2)
-		$errors[] = $lang_prof_reg['Username too short'];
-	else if (pun_strlen($username) > 25) // This usually doesn't happen since the form element only accepts 25 characters
-		$errors[] = $lang_prof_reg['Username too long'];
-	else if (!strcasecmp($username, 'Guest') || !strcasecmp($username, $lang_common['Guest']))
-		$errors[] = $lang_prof_reg['Username guest'];
-	else if (preg_match('%[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}%', $username) || preg_match('%((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))%', $username))
-		$errors[] = $lang_prof_reg['Username IP'];
-	else if ((strpos($username, '[') !== false || strpos($username, ']') !== false) && strpos($username, '\'') !== false && strpos($username, '"') !== false)
-		$errors[] = $lang_prof_reg['Username reserved chars'];
-	else if (preg_match('%(?:\[/?(?:b|u|s|ins|del|em|i|h|colou?r|quote|code|img|url|email|list|\*|topic|post|forum|user)\]|\[(?:img|url|quote|list)=)%i', $username))
-		$errors[] = $lang_prof_reg['Username BBCode'];
-
-	// Check username for any censored words
-	if ($pun_config['o_censoring'] == '1' && censor_words($username) != $username)
-		$errors[] = $lang_register['Username censor'];
-
-	// Check that the username (or a too similar username) is not already registered
-	$query = ($exclude_id) ? ' AND id!='.$exclude_id : '';
-
-	$result = $db->query('SELECT username FROM '.$db->prefix.'users WHERE (UPPER(username)=UPPER(\''.$db->escape($username).'\') OR UPPER(username)=UPPER(\''.$db->escape(ucp_preg_replace('%[^\p{L}\p{N}]%u', '', $username)).'\')) AND id>1'.$query) or error('Unable to fetch user info', __FILE__, __LINE__, $db->error());
-
-	if ($db->num_rows($result))
-	{
-		$busy = $db->result($result);
-		$errors[] = $lang_register['Username dupe 1'].' '.pun_htmlspecialchars($busy).'. '.$lang_register['Username dupe 2'];
-	}
-
-	// Check username for any banned usernames
-	foreach ($pun_bans as $cur_ban)
-	{
-		if ($cur_ban['username'] != '' && utf8_strtolower($username) == utf8_strtolower($cur_ban['username']))
-		{
-			$errors[] = $lang_prof_reg['Banned username'];
-			break;
-		}
-	}
-}
-
-
-//
 // Update "Users online"
 //
 function update_users_online()
 {
-	global $db, $pun_config;
+	global $db, $pun_config, $pun_user;
 
 	$now = time();
 
 	// Fetch all online list entries that are older than "o_timeout_online"
-	$result = $db->query('SELECT user_id, ident, logged, idle FROM '.$db->prefix.'online WHERE logged<'.($now-$pun_config['o_timeout_online'])) or error('Unable to fetch old entries from online list', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT * FROM '.$db->prefix.'online WHERE logged<'.($now-$pun_config['o_timeout_online'])) or error('Impossible de retrouver les anciennes entrÃ©es de la liste des utilisateurs', __FILE__, __LINE__, $db->error());
 	while ($cur_user = $db->fetch_assoc($result))
 	{
 		// If the entry is a guest, delete it
 		if ($cur_user['user_id'] == '1')
-			$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($cur_user['ident']).'\'') or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
+			$db->query('DELETE FROM '.$db->prefix.'online WHERE ident=\''.$db->escape($cur_user['ident']).'\'') or error('Impossible de supprimer de la liste des utilisateurs en ligne', __FILE__, __LINE__, $db->error());
 		else
 		{
@@ -493,11 +223,69 @@
 			if ($cur_user['logged'] < ($now-$pun_config['o_timeout_visit']))
 			{
-				$db->query('UPDATE '.$db->prefix.'users SET last_visit='.$cur_user['logged'].' WHERE id='.$cur_user['user_id']) or error('Unable to update user visit data', __FILE__, __LINE__, $db->error());
-				$db->query('DELETE FROM '.$db->prefix.'online WHERE user_id='.$cur_user['user_id']) or error('Unable to delete from online list', __FILE__, __LINE__, $db->error());
+				$db->query('UPDATE '.$db->prefix.'users SET last_visit='.$cur_user['logged'].' WHERE id='.$cur_user['user_id']) or error('Impossible de mettre Ã  jour les donnÃ©es de visite de l\'utilisateur', __FILE__, __LINE__, $db->error());
+				$db->query('DELETE FROM '.$db->prefix.'online WHERE user_id='.$cur_user['user_id']) or error('Impossible de supprimer de la liste des utilisateurs en ligne', __FILE__, __LINE__, $db->error());
 			}
 			else if ($cur_user['idle'] == '0')
-				$db->query('UPDATE '.$db->prefix.'online SET idle=1 WHERE user_id='.$cur_user['user_id']) or error('Unable to insert into online list', __FILE__, __LINE__, $db->error());
-		}
-	}
+				$db->query('UPDATE '.$db->prefix.'online SET idle=1 WHERE user_id='.$cur_user['user_id']) or error('Impossible d\'insÃ©rer Ã  la liste des utilisateurs en ligne', __FILE__, __LINE__, $db->error());
+		}
+	}
+}
+
+
+//
+// Generate the "navigator" that appears at the top of every page
+//
+function generate_navlinks()
+{
+	global $pun_config, $lang_common, $pun_user;
+
+	// Index and Userlist should always be displayed
+	$links[] = '<li id="navindex"><a href="index.php">'.$lang_common['Index'].'</a>';
+	$links[] = '<li id="navuserlist"><a href="userlist.php">'.$lang_common['User list'].'</a>';
+
+	if ($pun_config['o_rules'] == '1')
+		$links[] = '<li id="navrules"><a href="misc.php?action=rules">'.$lang_common['Rules'].'</a>';
+
+	if ($pun_user['is_guest'])
+	{
+		if ($pun_user['g_search'] == '1')
+			$links[] = '<li id="navsearch"><a href="search.php">'.$lang_common['Search'].'</a>';
+
+		$links[] = '<li id="navregister"><a href="register.php">'.$lang_common['Register'].'</a>';
+		$links[] = '<li id="navlogin"><a href="login.php">'.$lang_common['Login'].'</a>';
+
+		$info = $lang_common['Not logged in'];
+	}
+	else
+	{
+		if ($pun_user['g_id'] > PUN_MOD)
+		{
+			if ($pun_user['g_search'] == '1')
+				$links[] = '<li id="navsearch"><a href="search.php">'.$lang_common['Search'].'</a>';
+
+			$links[] = '<li id="navprofile"><a href="profile.php?id='.$pun_user['id'].'">'.$lang_common['Profile'].'</a>';
+			$links[] = '<li id="navlogout"><a href="login.php?action=out&amp;id='.$pun_user['id'].'">'.$lang_common['Logout'].'</a>';
+		}
+		else
+		{
+			$links[] = '<li id="navsearch"><a href="search.php">'.$lang_common['Search'].'</a>';
+			$links[] = '<li id="navprofile"><a href="profile.php?id='.$pun_user['id'].'">'.$lang_common['Profile'].'</a>';
+			$links[] = '<li id="navadmin"><a href="admin_index.php">'.$lang_common['Admin'].'</a>';
+			$links[] = '<li id="navlogout"><a href="login.php?action=out&amp;id='.$pun_user['id'].'">'.$lang_common['Logout'].'</a>';
+		}
+	}
+
+	// Are there any additional navlinks we should insert into the array before imploding it?
+	if ($pun_config['o_additional_navlinks'] != '')
+	{
+		if (preg_match_all('#([0-9]+)\s*=\s*(.*?)\n#s', $pun_config['o_additional_navlinks']."\n", $extra_links))
+		{
+			// Insert any additional links into the $links array (at the correct index)
+			for ($i = 0; $i < count($extra_links[1]); ++$i)
+				array_splice($links, $extra_links[1][$i], 0, array('<li id="navextra'.($i + 1).'">'.$extra_links[2][$i]));
+		}
+	}
+
+	return '<ul>'."\n\t\t\t\t".implode($lang_common['Link separator'].'</li>'."\n\t\t\t\t", $links).'</li>'."\n\t\t\t".'</ul>';
 }
 
@@ -520,8 +308,8 @@
 					<li<?php if ($page == 'personal') echo ' class="isactive"'; ?>><a href="profile.php?section=personal&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section personal'] ?></a></li>
 					<li<?php if ($page == 'messaging') echo ' class="isactive"'; ?>><a href="profile.php?section=messaging&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section messaging'] ?></a></li>
-<?php if ($pun_config['o_avatars'] == '1' || $pun_config['o_signatures'] == '1'): ?>					<li<?php if ($page == 'personality') echo ' class="isactive"'; ?>><a href="profile.php?section=personality&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section personality'] ?></a></li>
-<?php endif; ?>					<li<?php if ($page == 'display') echo ' class="isactive"'; ?>><a href="profile.php?section=display&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section display'] ?></a></li>
+					<li<?php if ($page == 'personality') echo ' class="isactive"'; ?>><a href="profile.php?section=personality&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section personality'] ?></a></li>
+					<li<?php if ($page == 'display') echo ' class="isactive"'; ?>><a href="profile.php?section=display&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section display'] ?></a></li>
 					<li<?php if ($page == 'privacy') echo ' class="isactive"'; ?>><a href="profile.php?section=privacy&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section privacy'] ?></a></li>
-<?php if ($pun_user['g_id'] == PUN_ADMIN || ($pun_user['g_moderator'] == '1' && $pun_user['g_mod_ban_users'] == '1')): ?>					<li<?php if ($page == 'admin') echo ' class="isactive"'; ?>><a href="profile.php?section=admin&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section admin'] ?></a></li>
+<?php if ($pun_user['g_id'] == PUN_ADMIN || ($pun_user['g_id'] == PUN_MOD && $pun_config['p_mod_ban_users'] == '1')): ?>					<li<?php if ($page == 'admin') echo ' class="isactive"'; ?>><a href="profile.php?section=admin&amp;id=<?php echo $id ?>"><?php echo $lang_profile['Section admin'] ?></a></li>
 <?php endif; ?>				</ul>
 			</div>
@@ -534,111 +322,5 @@
 
 //
-// Outputs markup to display a user's avatar
-//
-function generate_avatar_markup($user_id)
-{
-	global $pun_config;
-
-	$filetypes = array('jpg', 'gif', 'png');
-	$avatar_markup = '';
-
-	foreach ($filetypes as $cur_type)
-	{
-		$path = $pun_config['o_avatars_dir'].'/'.$user_id.'.'.$cur_type;
-
-		if (file_exists(PUN_ROOT.$path) && $img_size = getimagesize(PUN_ROOT.$path))
-		{
-			$avatar_markup = '<img src="'.pun_htmlspecialchars(get_base_url(true).'/'.$path.'?m='.filemtime(PUN_ROOT.$path)).'" '.$img_size[3].' alt="" />';
-			break;
-		}
-	}
-
-	return $avatar_markup;
-}
-
-
-//
-// Generate browser's title
-//
-function generate_page_title($page_title, $p = null)
-{
-	global $pun_config, $lang_common;
-
-	$page_title = array_reverse($page_title);
-
-	if ($p != null)
-		$page_title[0] .= ' ('.sprintf($lang_common['Page'], forum_number_format($p)).')';
-
-	$crumbs = implode($lang_common['Title separator'], $page_title);
-
-	return $crumbs;
-}
-
-
-//
-// Save array of tracked topics in cookie
-//
-function set_tracked_topics($tracked_topics)
-{
-	global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $pun_config;
-
-	$cookie_data = '';
-	if (!empty($tracked_topics))
-	{
-		// Sort the arrays (latest read first)
-		arsort($tracked_topics['topics'], SORT_NUMERIC);
-		arsort($tracked_topics['forums'], SORT_NUMERIC);
-
-		// Homebrew serialization (to avoid having to run unserialize() on cookie data)
-		foreach ($tracked_topics['topics'] as $id => $timestamp)
-			$cookie_data .= 't'.$id.'='.$timestamp.';';
-		foreach ($tracked_topics['forums'] as $id => $timestamp)
-			$cookie_data .= 'f'.$id.'='.$timestamp.';';
-
-		// Enforce a byte size limit (4096 minus some space for the cookie name - defaults to 4048)
-		if (strlen($cookie_data) > FORUM_MAX_COOKIE_SIZE)
-		{
-			$cookie_data = substr($cookie_data, 0, FORUM_MAX_COOKIE_SIZE);
-			$cookie_data = substr($cookie_data, 0, strrpos($cookie_data, ';')).';';
-		}
-	}
-
-	forum_setcookie($cookie_name.'_track', $cookie_data, time() + $pun_config['o_timeout_visit']);
-	$_COOKIE[$cookie_name.'_track'] = $cookie_data; // Set it directly in $_COOKIE as well
-}
-
-
-//
-// Extract array of tracked topics from cookie
-//
-function get_tracked_topics()
-{
-	global $cookie_name;
-
-	$cookie_data = isset($_COOKIE[$cookie_name.'_track']) ? $_COOKIE[$cookie_name.'_track'] : false;
-	if (!$cookie_data)
-		return array('topics' => array(), 'forums' => array());
-
-	if (strlen($cookie_data) > 4048)
-		return array('topics' => array(), 'forums' => array());
-
-	// Unserialize data from cookie
-	$tracked_topics = array('topics' => array(), 'forums' => array());
-	$temp = explode(';', $cookie_data);
-	foreach ($temp as $t)
-	{
-		$type = substr($t, 0, 1) == 'f' ? 'forums' : 'topics';
-		$id = intval(substr($t, 1));
-		$timestamp = intval(substr($t, strpos($t, '=') + 1));
-		if ($id > 0 && $timestamp > 0)
-			$tracked_topics[$type][$id] = $timestamp;
-	}
-
-	return $tracked_topics;
-}
-
-
-//
-// Update posts, topics, last_post, last_post_id and last_poster for a forum
+// Update posts, topics, last_post, last_post_id and last_poster for a forum (redirect topics are not included)
 //
 function update_forum($forum_id)
@@ -646,36 +328,18 @@
 	global $db;
 
-	$result = $db->query('SELECT COUNT(id), SUM(num_replies) FROM '.$db->prefix.'topics WHERE forum_id='.$forum_id) or error('Unable to fetch forum topic count', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT COUNT(id), SUM(num_replies) FROM '.$db->prefix.'topics WHERE moved_to IS NULL AND forum_id='.$forum_id) or error('Impossible de retrouver le total de discussions du forum', __FILE__, __LINE__, $db->error());
 	list($num_topics, $num_posts) = $db->fetch_row($result);
 
-	$num_posts = $num_posts + $num_topics; // $num_posts is only the sum of all replies (we have to add the topic posts)
-
-	$result = $db->query('SELECT last_post, last_post_id, last_poster FROM '.$db->prefix.'topics WHERE forum_id='.$forum_id.' AND moved_to IS NULL ORDER BY last_post DESC LIMIT 1') or error('Unable to fetch last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
-	if ($db->num_rows($result)) // There are topics in the forum
+	$num_posts = $num_posts + $num_topics;		// $num_posts is only the sum of all replies (we have to add the topic posts)
+
+	$result = $db->query('SELECT last_post, last_post_id, last_poster FROM '.$db->prefix.'topics WHERE forum_id='.$forum_id.' AND moved_to IS NULL ORDER BY last_post DESC LIMIT 1') or error('Impossible de retrouver last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
+	if ($db->num_rows($result))		// There are topics in the forum
 	{
 		list($last_post, $last_post_id, $last_poster) = $db->fetch_row($result);
 
-		$db->query('UPDATE '.$db->prefix.'forums SET num_topics='.$num_topics.', num_posts='.$num_posts.', last_post='.$last_post.', last_post_id='.$last_post_id.', last_poster=\''.$db->escape($last_poster).'\' WHERE id='.$forum_id) or error('Unable to update last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
-	}
-	else // There are no topics
-		$db->query('UPDATE '.$db->prefix.'forums SET num_topics='.$num_topics.', num_posts='.$num_posts.', last_post=NULL, last_post_id=NULL, last_poster=NULL WHERE id='.$forum_id) or error('Unable to update last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
-}
-
-
-//
-// Deletes any avatars owned by the specified user ID
-//
-function delete_avatar($user_id)
-{
-	global $pun_config;
-
-	$filetypes = array('jpg', 'gif', 'png');
-
-	// Delete user avatar
-	foreach ($filetypes as $cur_type)
-	{
-		if (file_exists(PUN_ROOT.$pun_config['o_avatars_dir'].'/'.$user_id.'.'.$cur_type))
-			@unlink(PUN_ROOT.$pun_config['o_avatars_dir'].'/'.$user_id.'.'.$cur_type);
-	}
+		$db->query('UPDATE '.$db->prefix.'forums SET num_topics='.$num_topics.', num_posts='.$num_posts.', last_post='.$last_post.', last_post_id='.$last_post_id.', last_poster=\''.$db->escape($last_poster).'\' WHERE id='.$forum_id) or error('Impossible de mettre Ã  jour last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
+	}
+	else	// There are no topics
+		$db->query('UPDATE '.$db->prefix.'forums SET num_topics=0, num_posts=0, last_post=NULL, last_post_id=NULL, last_poster=NULL WHERE id='.$forum_id) or error('Impossible de mettre Ã  jour last_post/last_post_id/last_poster', __FILE__, __LINE__, $db->error());
 }
 
@@ -689,13 +353,13 @@
 
 	// Delete the topic and any redirect topics
-	$db->query('DELETE FROM '.$db->prefix.'topics WHERE id='.$topic_id.' OR moved_to='.$topic_id) or error('Unable to delete topic', __FILE__, __LINE__, $db->error());
-
-	// Create a list of the post IDs in this topic
+	$db->query('DELETE FROM '.$db->prefix.'topics WHERE id='.$topic_id.' OR moved_to='.$topic_id) or error('Impossible de supprimer le sujet', __FILE__, __LINE__, $db->error());
+
+	// Create a list of the post ID's in this topic
 	$post_ids = '';
-	$result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to fetch posts', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Impossible de retrouver les messages', __FILE__, __LINE__, $db->error());
 	while ($row = $db->fetch_row($result))
 		$post_ids .= ($post_ids != '') ? ','.$row[0] : $row[0];
 
-	// Make sure we have a list of post IDs
+	// Make sure we have a list of post ID's
 	if ($post_ids != '')
 	{
@@ -703,9 +367,9 @@
 
 		// Delete posts in topic
-		$db->query('DELETE FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to delete posts', __FILE__, __LINE__, $db->error());
+		$db->query('DELETE FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Impossible de supprimer les messages', __FILE__, __LINE__, $db->error());
 	}
 
 	// Delete any subscriptions for this topic
-	$db->query('DELETE FROM '.$db->prefix.'topic_subscriptions WHERE topic_id='.$topic_id) or error('Unable to delete subscriptions', __FILE__, __LINE__, $db->error());
+	$db->query('DELETE FROM '.$db->prefix.'subscriptions WHERE topic_id='.$topic_id) or error('Impossible de supprimer l\'abonnement', __FILE__, __LINE__, $db->error());
 }
 
@@ -718,15 +382,15 @@
 	global $db;
 
-	$result = $db->query('SELECT id, poster, posted FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id.' ORDER BY id DESC LIMIT 2') or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT id, poster, posted FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id.' ORDER BY id DESC LIMIT 2') or error('Impossible de retrouver les informations du message', __FILE__, __LINE__, $db->error());
 	list($last_id, ,) = $db->fetch_row($result);
 	list($second_last_id, $second_poster, $second_posted) = $db->fetch_row($result);
 
 	// Delete the post
-	$db->query('DELETE FROM '.$db->prefix.'posts WHERE id='.$post_id) or error('Unable to delete post', __FILE__, __LINE__, $db->error());
+	$db->query('DELETE FROM '.$db->prefix.'posts WHERE id='.$post_id) or error('Impossible de supprimer le message', __FILE__, __LINE__, $db->error());
 
 	strip_search_index($post_id);
 
 	// Count number of replies in the topic
-	$result = $db->query('SELECT COUNT(id) FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Unable to fetch post count for topic', __FILE__, __LINE__, $db->error());
+	$result = $db->query('SELECT COUNT(id) FROM '.$db->prefix.'posts WHERE topic_id='.$topic_id) or error('Impossible de retrouver le total de messages pour la discussion', __FILE__, __LINE__, $db->error());
 	$num_replies = $db->result($result, 0) - 1;
 
@@ -736,27 +400,12 @@
 		// If there is a $second_last_id there is more than 1 reply to the topic
 		if (!empty($second_last_id))
-			$db->query('UPDATE '.$db->prefix.'topics SET last_post='.$second_posted.', last_post_id='.$second_last_id.', last_poster=\''.$db->escape($second_poster).'\', num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Unable to update topic', __FILE__, __LINE__, $db->error());
+			$db->query('UPDATE '.$db->prefix.'topics SET last_post='.$second_posted.', last_post_id='.$second_last_id.', last_poster=\''.$db->escape($second_poster).'\', num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Impossible de mettre Ã  jour la discussion', __FILE__, __LINE__, $db->error());
 		else
 			// We deleted the only reply, so now last_post/last_post_id/last_poster is posted/id/poster from the topic itself
-			$db->query('UPDATE '.$db->prefix.'topics SET last_post=posted, last_post_id=id, last_poster=poster, num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Unable to update topic', __FILE__, __LINE__, $db->error());
+			$db->query('UPDATE '.$db->prefix.'topics SET last_post=posted, last_post_id=id, last_poster=poster, num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Impossible de mettre Ã  jour la discussion', __FILE__, __LINE__, $db->error());
 	}
 	else
 		// Otherwise we just decrement the reply counter
-		$db->query('UPDATE '.$db->prefix.'topics SET num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Unable to update topic', __FILE__, __LINE__, $db->error());
-}
-
-
-//
-// Delete every .php file in the forum's cache directory
-//
-function forum_clear_cache()
-{
-	$d = dir(FORUM_CACHE_DIR);
-	while (($entry = $d->read()) !== false)
-	{
-		if (substr($entry, -4) == '.php')
-			@unlink(FORUM_CACHE_DIR.$entry);
-	}
-	$d->close();
+		$db->query('UPDATE '.$db->prefix.'topics SET num_replies='.$num_replies.' WHERE id='.$topic_id) or error('Impossible de mettre Ã  jour la discussion', __FILE__, __LINE__, $db->error());
 }
 
@@ -773,19 +422,17 @@
 	if (!isset($search_for))
 	{
-		if (file_exists(FORUM_CACHE_DIR.'cache_censoring.php'))
-			include FORUM_CACHE_DIR.'cache_censoring.php';
-
-		if (!defined('PUN_CENSOR_LOADED'))
-		{
-			if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
-				require PUN_ROOT.'include/cache.php';
-
-			generate_censoring_cache();
-			require FORUM_CACHE_DIR.'cache_censoring.php';
+		$result = $db->query('SELECT search_for, replace_with FROM '.$db->prefix.'censoring') or error('Impossible de retrouver la liste des mots Ã  censurer', __FILE__, __LINE__, $db->error());
+		$num_words = $db->num_rows($result);
+
+		$search_for = array();
+		for ($i = 0; $i < $num_words; ++$i)
+		{
+			list($search_for[$i], $replace_with[$i]) = $db->fetch_row($result);
+			$search_for[$i] = '/\b('.str_replace('\*', '\w*?', preg_quote($search_for[$i], '/')).')\b/i';
 		}
 	}
 
 	if (!empty($search_for))
-		$text = substr(ucp_preg_replace($search_for, $replace_with, ' '.$text.' '), 1, -1);
+		$text = substr(preg_replace($search_for, $replace_with, ' '.$text.' '), 1, -1);
 
 	return $text;
@@ -812,16 +459,12 @@
 
 	// If not already loaded in a previous call, load the cached ranks
-	if ($pun_config['o_ranks'] == '1' && !defined('PUN_RANKS_LOADED'))
-	{
-		if (file_exists(FORUM_CACHE_DIR.'cache_ranks.php'))
-			include FORUM_CACHE_DIR.'cache_ranks.php';
-
+	if ($pun_config['o_ranks'] == '1' && empty($pun_ranks))
+	{
+		@include PUN_ROOT.'cache/cache_ranks.php';
 		if (!defined('PUN_RANKS_LOADED'))
 		{
-			if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
-				require PUN_ROOT.'include/cache.php';
-
+			require_once PUN_ROOT.'include/cache.php';
 			generate_ranks_cache();
-			require FORUM_CACHE_DIR.'cache_ranks.php';
+			require PUN_ROOT.'cache/cache_ranks.php';
 		}
 	}
@@ -844,7 +487,8 @@
 		if ($pun_config['o_ranks'] == '1' && !empty($pun_ranks))
 		{
-			foreach ($pun_ranks as $cur_rank)
+			@reset($pun_ranks);
+			while (list(, $cur_rank) = @each($pun_ranks))
 			{
-				if ($user['num_posts'] >= $cur_rank['min_posts'])
+				if (intval($user['num_posts']) >= $cur_rank['min_posts'])
 					$user_title = pun_htmlspecialchars($cur_rank['rank']);
 			}
@@ -863,8 +507,6 @@
 // Generate a string with numbered links (for multipage scripts)
 //
-function paginate($num_pages, $cur_page, $link)
-{
-	global $lang_common;
-
+function paginate($num_pages, $cur_page, $link_to)
+{
 	$pages = array();
 	$link_to_all = false;
@@ -878,44 +520,36 @@
 
 	if ($num_pages <= 1)
-		$pages = array('<strong class="item1">1</strong>');
+		$pages = array('<strong>1</strong>');
 	else
 	{
-		// Add a previous page link
-		if ($num_pages > 1 && $cur_page > 1)
-			$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.($cur_page - 1).'">'.$lang_common['Previous'].'</a>';
-
 		if ($cur_page > 3)
 		{
-			$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p=1">1</a>';
-
-			if ($cur_page > 5)
-				$pages[] = '<span class="spacer">'.$lang_common['Spacer'].'</span>';
+			$pages[] = '<a href="'.$link_to.'&amp;p=1">1</a>';
+
+			if ($cur_page != 4)
+				$pages[] = '&hellip;';
 		}
 
 		// Don't ask me how the following works. It just does, OK? :-)
-		for ($current = ($cur_page == 5) ? $cur_page - 3 : $cur_page - 2, $stop = ($cur_page + 4 == $num_pages) ? $cur_page + 4 : $cur_page + 3; $current < $stop; ++$current)
+		for ($current = $cur_page - 2, $stop = $cur_page + 3; $current < $stop; ++$current)
 		{
 			if ($current < 1 || $current > $num_pages)
 				continue;
 			else if ($current != $cur_page || $link_to_all)
-				$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.$current.'">'.forum_number_format($current).'</a>';
+				$pages[] = '<a href="'.$link_to.'&amp;p='.$current.'">'.$current.'</a>';
 			else
-				$pages[] = '<strong'.(empty($pages) ? ' class="item1"' : '').'>'.forum_number_format($current).'</strong>';
+				$pages[] = '<strong>'.$current.'</strong>';
 		}
 
 		if ($cur_page <= ($num_pages-3))
 		{
-			if ($cur_page != ($num_pages-3) && $cur_page != ($num_pages-4))
-				$pages[] = '<span class="spacer">'.$lang_common['Spacer'].'</span>';
-
-			$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.$num_pages.'">'.forum_number_format($num_pages).'</a>';
-		}
-
-		// Add a next page link
-		if ($num_pages > 1 && !$link_to_all && $cur_page < $num_pages)
-			$pages[] = '<a'.(empty($pages) ? ' class="item1"' : '').' href="'.$link.'&amp;p='.($cur_page +1).'">'.$lang_common['Next'].'</a>';
-	}
-
-	return implode(' ', $pages);
+			if ($cur_page != ($num_pages-3))
+				$pages[] = '&hellip;';
+
+			$pages[] = '<a href="'.$link_to.'&amp;p='.$num_pages.'">'.$num_pages.'</a>';
+		}
+	}
+
+	return implode('&#160;', $pages);
 }
 
@@ -926,10 +560,12 @@
 function message($message, $no_back_link = false)
 {
-	global $db, $lang_common, $pun_config, $pun_start, $tpl_main, $pun_user;
+
+	global $db, $lang_common, $pun_config, $pun_start, $tpl_main, $env;
 
 	if (!defined('PUN_HEADER'))
 	{
-		$page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_common['Info']);
-		define('PUN_ACTIVE_PAGE', 'index');
+		global $pun_user;
+
+		$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['Info'];
 		require PUN_ROOT.'header.php';
 	}
@@ -941,6 +577,6 @@
 	<div class="box">
 		<div class="inbox">
-			<p><?php echo $message ?></p>
-<?php if (!$no_back_link): ?>			<p><a href="javascript: history.go(-1)"><?php echo $lang_common['Go back'] ?></a></p>
+		<p><?php echo $message ?></p>
+<?php if (!$no_back_link): ?>		<p><a href="javascript: history.go(-1)"><?php echo $lang_common['Go back'] ?></a></p>
 <?php endif; ?>		</div>
 	</div>
@@ -953,241 +589,148 @@
 
 //
-// Format a time string according to $time_format and time zones
-//
-function format_time($timestamp, $date_only = false, $date_format = null, $time_format = null, $time_only = false, $no_text = false)
-{
-	global $pun_config, $lang_common, $pun_user, $forum_date_formats, $forum_time_formats;
+// Format a time string according to $time_format and timezones
+//
+function format_time($timestamp, $date_only = false)
+{
+	global $pun_config, $lang_common, $pun_user;
 
 	if ($timestamp == '')
 		return $lang_common['Never'];
 
-	$diff = ($pun_user['timezone'] + $pun_user['dst']) * 3600;
+	$diff = ($pun_user['timezone'] - $pun_config['o_server_timezone']) * 3600;
 	$timestamp += $diff;
 	$now = time();
 
-	if($date_format == null)
-		$date_format = $forum_date_formats[$pun_user['date_format']];
-
-	if($time_format == null)
-		$time_format = $forum_time_formats[$pun_user['time_format']];
-
-	$date = gmdate($date_format, $timestamp);
-	$today = gmdate($date_format, $now+$diff);
-	$yesterday = gmdate($date_format, $now+$diff-86400);
-
-	if(!$no_text)
-	{
-		if ($date == $today)
-			$date = $lang_common['Today'];
-		else if ($date == $yesterday)
-			$date = $lang_common['Yesterday'];
-	}
-
-	if ($date_only)
+	$date = date($pun_config['o_date_format'], $timestamp);
+	$today = date($pun_config['o_date_format'], $now+$diff);
+	$yesterday = date($pun_config['o_date_format'], $now+$diff-86400);
+
+	if ($date == $today)
+		$date = $lang_common['Today'];
+	else if ($date == $yesterday)
+		$date = $lang_common['Yesterday'];
+
+	if (!$date_only)
+		return $date.' '.date($pun_config['o_time_format'], $timestamp);
+	else
 		return $date;
-	else if ($time_only)
-		return gmdate($time_format, $timestamp);
+}
+
+
+//
+// If we are running pre PHP 4.3.0, we add our own implementation of file_get_contents
+//
+if (!function_exists('file_get_contents'))
+{
+	function file_get_contents($filename, $use_include_path = 0)
+	{
+		$data = '';
+
+		if ($fh = fopen($filename, 'rb', $use_include_path))
+		{
+			$data = fread($fh, filesize($filename));
+			fclose($fh);
+		}
+
+		return $data;
+	}
+}
+
+
+//
+// Make sure that HTTP_REFERER matches $pun_config['o_base_url']/$script
+//
+function confirm_referrer($script)
+{
+	global $pun_config, $lang_common;
+
+	if (!preg_match('#^'.preg_quote(str_replace('www.', '', $pun_config['o_base_url']).'/'.$script, '#').'#i', str_replace('www.', '', (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''))))
+		message($lang_common['Bad referrer']);
+}
+
+
+//
+// Generate a random password of length $len
+//
+function random_pass($len)
+{
+	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+
+	$password = '';
+	for ($i = 0; $i < $len; ++$i)
+		$password .= substr($chars, (mt_rand() % strlen($chars)), 1);
+
+	return $password;
+}
+
+
+//
+// Compute a hash of $str
+// Uses sha1() if available. If not, SHA1 through mhash() if available. If not, fall back on md5().
+//
+function pun_hash($str)
+{
+	if (function_exists('sha1'))	// Only in PHP 4.3.0+
+		return sha1($str);
+	else if (function_exists('mhash'))	// Only if Mhash library is loaded
+		return bin2hex(mhash(MHASH_SHA1, $str));
 	else
-		return $date.' '.gmdate($time_format, $timestamp);
-}
-
-
-//
-// A wrapper for PHP's number_format function
-//
-function forum_number_format($number, $decimals = 0)
+		return md5($str);
+}
+
+
+//
+// Try to determine the correct remote IP-address
+//
+function get_remote_address()
+{
+	return $_SERVER['REMOTE_ADDR'];
+}
+
+
+//
+// Equivalent to htmlspecialchars(), but allows &#[0-9]+ (for unicode)
+//
+function pun_htmlspecialchars($str)
+{
+	$str = preg_replace('/&(?!#[0-9]+;)/s', '&amp;', $str);
+	$str = str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $str);
+
+	return $str;
+}
+
+
+//
+// Equivalent to strlen(), but counts &#[0-9]+ as one character (for unicode)
+//
+function pun_strlen($str)
+{
+	return strlen(preg_replace('/&#([0-9]+);/', '!', $str));
+}
+
+
+//
+// Convert \r\n and \r to \n
+//
+function pun_linebreaks($str)
+{
+	return str_replace("\r", "\n", str_replace("\r\n", "\n", $str));
+}
+
+
+//
+// A more aggressive version of trim()
+//
+function pun_trim($str)
 {
 	global $lang_common;
 
-	return is_numeric($number) ? number_format($number, $decimals, $lang_common['lang_decimal_point'], $lang_common['lang_thousands_sep']) : $number;
-}
-
-
-//
-// Generate a random key of length $len
-//
-function random_key($len, $readable = false, $hash = false)
-{
-	$key = '';
-
-	if ($hash)
-		$key = substr(pun_hash(uniqid(rand(), true)), 0, $len);
-	else if ($readable)
-	{
-		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
-
-		for ($i = 0; $i < $len; ++$i)
-			$key .= substr($chars, (mt_rand() % strlen($chars)), 1);
+	if (strpos($lang_common['lang_encoding'], '8859') !== false)
+	{
+		$fishy_chars = array(chr(0x81), chr(0x8D), chr(0x8F), chr(0x90), chr(0x9D), chr(0xA0));
+		return trim(str_replace($fishy_chars, ' ', $str));
 	}
 	else
-	{
-		for ($i = 0; $i < $len; ++$i)
-			$key .= chr(mt_rand(33, 126));
-	}
-
-	return $key;
-}
-
-
-//
-// Make sure that HTTP_REFERER matches base_url/script
-//
-function confirm_referrer($script, $error_msg = false)
-{
-	global $pun_config, $lang_common;
-
-	// There is no referrer
-	if (empty($_SERVER['HTTP_REFERER']))
-		message($error_msg ? $error_msg : $lang_common['Bad referrer']);
-
-	$referrer = parse_url(strtolower($_SERVER['HTTP_REFERER']));
-	// Remove www subdomain if it exists
-	if (strpos($referrer['host'], 'www.') === 0)
-		$referrer['host'] = substr($referrer['host'], 4);
-
-	$valid = parse_url(strtolower(get_base_url().'/'.$script));
-	// Remove www subdomain if it exists
-	if (strpos($valid['host'], 'www.') === 0)
-		$valid['host'] = substr($valid['host'], 4);
-
-	// Check the host and path match. Ignore the scheme, port, etc.
-	if ($referrer['host'] != $valid['host'] || $referrer['path'] != $valid['path'])
-		message($error_msg ? $error_msg : $lang_common['Bad referrer']);
-}
-
-
-//
-// Generate a random password of length $len
-// Compatibility wrapper for random_key
-//
-function random_pass($len)
-{
-	return random_key($len, true);
-}
-
-
-//
-// Compute a hash of $str
-//
-function pun_hash($str)
-{
-	return sha1($str);
-}
-
-
-//
-// Try to determine the correct remote IP-address
-//
-function get_remote_address()
-{
-	$remote_addr = $_SERVER['REMOTE_ADDR'];
-
-	// If we are behind a reverse proxy try to find the real users IP
-	if (defined('FORUM_BEHIND_REVERSE_PROXY'))
-	{
-		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
-		{
-			// The general format of the field is:
-			// X-Forwarded-For: client1, proxy1, proxy2
-			// where the value is a comma+space separated list of IP addresses, the left-most being the farthest downstream client,
-			// and each successive proxy that passed the request adding the IP address where it received the request from.
-			$forwarded_for = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
-			$forwarded_for = trim($forwarded_for[0]);
-
-			if (@preg_match('%^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$%', $forwarded_for) || @preg_match('%^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$%', $forwarded_for))
-				$remote_addr = $forwarded_for;
-		}
-	}
-
-	return $remote_addr;
-}
-
-
-//
-// Calls htmlspecialchars with a few options already set
-//
-function pun_htmlspecialchars($str)
-{
-	return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
-}
-
-
-//
-// Calls htmlspecialchars_decode with a few options already set
-//
-function pun_htmlspecialchars_decode($str)
-{
-	if (function_exists('htmlspecialchars_decode'))
-		return htmlspecialchars_decode($str, ENT_QUOTES);
-
-	static $translations;
-	if (!isset($translations))
-	{
-		$translations = get_html_translation_table(HTML_SPECIALCHARS, ENT_QUOTES);
-		$translations['&#039;'] = '\''; // get_html_translation_table doesn't include &#039; which is what htmlspecialchars translates ' to, but apparently that is okay?! http://bugs.php.net/bug.php?id=25927
-		$translations = array_flip($translations);
-	}
-
-	return strtr($str, $translations);
-}
-
-
-//
-// A wrapper for utf8_strlen for compatibility
-//
-function pun_strlen($str)
-{
-	return utf8_strlen($str);
-}
-
-
-//
-// Convert \r\n and \r to \n
-//
-function pun_linebreaks($str)
-{
-	return str_replace("\r", "\n", str_replace("\r\n", "\n", $str));
-}
-
-
-//
-// A wrapper for utf8_trim for compatibility
-//
-function pun_trim($str, $charlist = false)
-{
-	return utf8_trim($str, $charlist);
-}
-
-//
-// Checks if a string is in all uppercase
-//
-function is_all_uppercase($string)
-{
-	return utf8_strtoupper($string) == $string && utf8_strtolower($string) != $string;
-}
-
-
-//
-// Inserts $element into $input at $offset
-// $offset can be either a numerical offset to insert at (eg: 0 inserts at the beginning of the array)
-// or a string, which is the key that the new element should be inserted before
-// $key is optional: it's used when inserting a new key/value pair into an associative array
-//
-function array_insert(&$input, $offset, $element, $key = null)
-{
-	if ($key == null)
-		$key = $offset;
-
-	// Determine the proper offset if we're using a string
-	if (!is_int($offset))
-		$offset = array_search($offset, array_keys($input), true);
-
-	// Out of bounds checks
-	if ($offset > count($input))
-		$offset = count($input);
-	else if ($offset < 0)
-		$offset = 0;
-
-	$input = array_merge(array_slice($input, 0, $offset), array($key => $element), array_slice($input, $offset));
+		return trim($str);
 }
 
@@ -1199,13 +742,4 @@
 {
 	global $db, $pun_config, $lang_common, $pun_user;
-
-	// Send no-cache headers
-	header('Expires: Thu, 21 Jul 1977 07:30:00 GMT'); // When yours truly first set eyes on this world! :)
-	header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
-	header('Cache-Control: post-check=0, pre-check=0', false);
-	header('Pragma: no-cache'); // For HTTP/1.0 compatibility
-
-	// Send the Content-type header in case the web server is setup to send something else
-	header('Content-type: text/html; charset=utf-8');
 
 	// Deal with newlines, tabs and multiple spaces
@@ -1214,42 +748,7 @@
 	$message = str_replace($pattern, $replace, $pun_config['o_maintenance_message']);
 
-	if (file_exists(PUN_ROOT.'style/'.$pun_user['style'].'/maintenance.tpl'))
-	{
-		$tpl_file = PUN_ROOT.'style/'.$pun_user['style'].'/maintenance.tpl';
-		$tpl_inc_dir = PUN_ROOT.'style/'.$pun_user['style'].'/';
-	}
-	else
-	{
-		$tpl_file = PUN_ROOT.'include/template/maintenance.tpl';
-		$tpl_inc_dir = PUN_ROOT.'include/user/';
-	}
-
-	$tpl_maint = file_get_contents($tpl_file);
-
-	// START SUBST - <pun_include "*">
-	preg_match_all('%<pun_include "([^/\\\\]*?)\.(php[45]?|inc|html?|txt)">%i', $tpl_maint, $pun_includes, PREG_SET_ORDER);
-
-	foreach ($pun_includes as $cur_include)
-	{
-		ob_start();
-
-		// Allow for overriding user includes, too.
-		if (file_exists($tpl_inc_dir.$cur_include[1].'.'.$cur_include[2]))
-			require $tpl_inc_dir.$cur_include[1].'.'.$cur_include[2];
-		else if (file_exists(PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2]))
-			require PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2];
-		else
-			error(sprintf($lang_common['Pun include error'], htmlspecialchars($cur_include[0]), basename($tpl_file)));
-
-		$tpl_temp = ob_get_contents();
-		$tpl_maint = str_replace($cur_include[0], $tpl_temp, $tpl_maint);
-		ob_end_clean();
-	}
-	// END SUBST - <pun_include "*">
-
-
-	// START SUBST - <pun_language>
-	$tpl_maint = str_replace('<pun_language>', $lang_common['lang_identifier'], $tpl_maint);
-	// END SUBST - <pun_language>
+
+	// Load the maintenance template
+	$tpl_maint = trim(file_get_contents(PUN_ROOT.'include/template/maintenance.tpl'));
 
 
@@ -1259,11 +758,14 @@
 
 
+	// START SUBST - <pun_char_encoding>
+	$tpl_maint = str_replace('<pun_char_encoding>', $lang_common['lang_encoding'], $tpl_maint);
+	// END SUBST - <pun_char_encoding>
+
+
 	// START SUBST - <pun_head>
 	ob_start();
 
-	$page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_common['Maintenance']);
-
 ?>
-<title><?php echo generate_page_title($page_title) ?></title>
+<title><?php echo pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['Maintenance'] ?></title>
 <link rel="stylesheet" type="text/css" href="style/<?php echo $pun_user['style'].'.css' ?>" />
 <?php
@@ -1275,22 +777,12 @@
 
 
-	// START SUBST - <pun_maint_main>
-	ob_start();
-
-?>
-<div class="block">
-	<h2><?php echo $lang_common['Maintenance'] ?></h2>
-	<div class="box">
-		<div class="inbox">
-			<p><?php echo $message ?></p>
-		</div>
-	</div>
-</div>
-<?php
-
-	$tpl_temp = trim(ob_get_contents());
-	$tpl_maint = str_replace('<pun_maint_main>', $tpl_temp, $tpl_maint);
-	ob_end_clean();
-	// END SUBST - <pun_maint_main>
+	// START SUBST - <pun_maint_heading>
+	$tpl_maint = str_replace('<pun_maint_heading>', $lang_common['Maintenance'], $tpl_maint);
+	// END SUBST - <pun_maint_heading>
+
+
+	// START SUBST - <pun_maint_message>
+	$tpl_maint = str_replace('<pun_maint_message>', $message, $tpl_maint);
+	// END SUBST - <pun_maint_message>
 
 
@@ -1299,4 +791,19 @@
 
 
+	// START SUBST - <pun_include "*">
+	while (preg_match('#<pun_include "([^/\\\\]*?)">#', $tpl_maint, $cur_include))
+	{
+		if (!file_exists(PUN_ROOT.'include/user/'.$cur_include[1]))
+	 	   error('Impossible de procÃ©der Ã  l\'inclusion utilisateur &lt;pun_include "'.htmlspecialchars($cur_include[1]).'"&gt; depuis le template main.tpl. Il n\'y a pas de fichier dans le rÃ©pertoire /include/user/');
+
+		ob_start();
+		include PUN_ROOT.'include/user/'.$cur_include[1];
+		$tpl_temp = ob_get_contents();
+		$tpl_redir = str_replace($cur_include[0], $tpl_temp, $tpl_redir);
+	    ob_end_clean();
+	}
+	// END SUBST - <pun_include "*">
+
+
 	// Close the db connection (and free up any result data)
 	$db->close();
@@ -1313,10 +820,6 @@
 	global $db, $pun_config, $lang_common, $pun_user;
 
-	// Prefix with base_url (unless there's already a valid URI)
-	if (strpos($destination_url, 'http://') !== 0 && strpos($destination_url, 'https://') !== 0 && strpos($destination_url, '/') !== 0)
-		$destination_url = get_base_url(true).'/'.$destination_url;
-
-	// Do a little spring cleaning
-	$destination_url = preg_replace('%([\r\n])|(\%0[ad])|(;\s*data\s*:)%i', '', $destination_url);
+	if ($destination_url == '')
+		$destination_url = 'index.php';
 
 	// If the delay is 0 seconds, we might as well skip the redirect all together
@@ -1324,51 +827,7 @@
 		header('Location: '.str_replace('&amp;', '&', $destination_url));
 
-	// Send no-cache headers
-	header('Expires: Thu, 21 Jul 1977 07:30:00 GMT'); // When yours truly first set eyes on this world! :)
-	header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
-	header('Cache-Control: post-check=0, pre-check=0', false);
-	header('Pragma: no-cache'); // For HTTP/1.0 compatibility
-
-	// Send the Content-type header in case the web server is setup to send something else
-	header('Content-type: text/html; charset=utf-8');
-
-	if (file_exists(PUN_ROOT.'style/'.$pun_user['style'].'/redirect.tpl'))
-	{
-		$tpl_file = PUN_ROOT.'style/'.$pun_user['style'].'/redirect.tpl';
-		$tpl_inc_dir = PUN_ROOT.'style/'.$pun_user['style'].'/';
-	}
-	else
-	{
-		$tpl_file = PUN_ROOT.'include/template/redirect.tpl';
-		$tpl_inc_dir = PUN_ROOT.'include/user/';
-	}
-
-	$tpl_redir = file_get_contents($tpl_file);
-
-	// START SUBST - <pun_include "*">
-	preg_match_all('%<pun_include "([^/\\\\]*?)\.(php[45]?|inc|html?|txt)">%i', $tpl_redir, $pun_includes, PREG_SET_ORDER);
-
-	foreach ($pun_includes as $cur_include)
-	{
-		ob_start();
-
-		// Allow for overriding user includes, too.
-		if (file_exists($tpl_inc_dir.$cur_include[1].'.'.$cur_include[2]))
-			require $tpl_inc_dir.$cur_include[1].'.'.$cur_include[2];
-		else if (file_exists(PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2]))
-			require PUN_ROOT.'include/user/'.$cur_include[1].'.'.$cur_include[2];
-		else
-			error(sprintf($lang_common['Pun include error'], htmlspecialchars($cur_include[0]), basename($tpl_file)));
-
-		$tpl_temp = ob_get_contents();
-		$tpl_redir = str_replace($cur_include[0], $tpl_temp, $tpl_redir);
-		ob_end_clean();
-	}
-	// END SUBST - <pun_include "*">
-
-
-	// START SUBST - <pun_language>
-	$tpl_redir = str_replace('<pun_language>', $lang_common['lang_identifier'], $tpl_redir);
-	// END SUBST - <pun_language>
+
+	// Load the redirect template
+	$tpl_redir = trim(file_get_contents(PUN_ROOT.'include/template/redirect.tpl'));
 
 
@@ -1378,12 +837,15 @@
 
 
+	// START SUBST - <pun_char_encoding>
+	$tpl_redir = str_replace('<pun_char_encoding>', $lang_common['lang_encoding'], $tpl_redir);
+	// END SUBST - <pun_char_encoding>
+
+
 	// START SUBST - <pun_head>
 	ob_start();
 
-	$page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), $lang_common['Redirecting']);
-
 ?>
 <meta http-equiv="refresh" content="<?php echo $pun_config['o_redirect_delay'] ?>;URL=<?php echo str_replace(array('<', '>', '"'), array('&lt;', '&gt;', '&quot;'), $destination_url) ?>" />
-<title><?php echo generate_page_title($page_title) ?></title>
+<title><?php echo pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_common['Redirecting'] ?></title>
 <link rel="stylesheet" type="text/css" href="style/<?php echo $pun_user['style'].'.css' ?>" />
 <?php
@@ -1395,22 +857,13 @@
 
 
-	// START SUBST - <pun_redir_main>
-	ob_start();
-
-?>
-<div class="block">
-	<h2><?php echo $lang_common['Redirecting'] ?></h2>
-	<div class="box">
-		<div class="inbox">
-			<p><?php echo $message.'<br /><br /><a href="'.$destination_url.'">'.$lang_common['Click redirect'].'</a>' ?></p>
-		</div>
-	</div>
-</div>
-<?php
-
-	$tpl_temp = trim(ob_get_contents());
-	$tpl_redir = str_replace('<pun_redir_main>', $tpl_temp, $tpl_redir);
-	ob_end_clean();
-	// END SUBST - <pun_redir_main>
+	// START SUBST - <pun_redir_heading>
+	$tpl_redir = str_replace('<pun_redir_heading>', $lang_common['Redirecting'], $tpl_redir);
+	// END SUBST - <pun_redir_heading>
+
+
+	// START SUBST - <pun_redir_text>
+	$tpl_temp = $message.'<br /><br />'.'<a href="'.$destination_url.'">'.$lang_common['Click redirect'].'</a>';
+	$tpl_redir = str_replace('<pun_redir_text>', $tpl_temp, $tpl_redir);
+	// END SUBST - <pun_redir_text>
 
 
@@ -1431,4 +884,16 @@
 
 
+	// START SUBST - <pun_include "*">
+	while (preg_match('<pun_include "(.*?)">', $tpl_redir, $cur_include))
+	{
+		ob_start();
+		include PUN_ROOT.$cur_include[1];
+		$tpl_temp = ob_get_contents();
+		$tpl_redir = str_replace('<'.$cur_include[0].'>', $tpl_temp, $tpl_redir);
+	    ob_end_clean();
+	}
+	// END SUBST - <pun_include "*">
+
+
 	// Close the db connection (and free up any result data)
 	$db->close();
@@ -1441,49 +906,25 @@
 // Display a simple error message
 //
-function error($message, $file = null, $line = null, $db_error = false)
-{
-	global $pun_config, $lang_common;
-
-	// Set some default settings if the script failed before $pun_config could be populated
+function error($message, $file, $line, $db_error = false)
+{
+	global $pun_config;
+
+	// Set a default title if the script failed before $pun_config could be populated
 	if (empty($pun_config))
-	{
-		$pun_config = array(
-			'o_board_title'	=> 'FluxBB',
-			'o_gzip'		=> '0'
-		);
-	}
-
-	// Set some default translations if the script failed before $lang_common could be populated
-	if (empty($lang_common))
-	{
-		$lang_common = array(
-			'Title separator'	=> ' / ',
-			'Page'				=> 'Page %s'
-		);
-	}
-
-	// Empty all output buffers and stop buffering
-	while (@ob_end_clean());
+		$pun_config['o_board_title'] = 'PunBB';
+
+	// Empty output buffer and stop buffering
+	@ob_end_clean();
 
 	// "Restart" output buffering if we are using ob_gzhandler (since the gzip header is already sent)
-	if ($pun_config['o_gzip'] && extension_loaded('zlib'))
+	if (!empty($pun_config['o_gzip']) && extension_loaded('zlib') && (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false || strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate') !== false))
 		ob_start('ob_gzhandler');
-
-	// Send no-cache headers
-	header('Expires: Thu, 21 Jul 1977 07:30:00 GMT'); // When yours truly first set eyes on this world! :)
-	header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
-	header('Cache-Control: post-check=0, pre-check=0', false);
-	header('Pragma: no-cache'); // For HTTP/1.0 compatibility
-
-	// Send the Content-type header in case the web server is setup to send something else
-	header('Content-type: text/html; charset=utf-8');
 
 ?>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
+<html dir="ltr">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<?php $page_title = array(pun_htmlspecialchars($pun_config['o_board_title']), 'Error') ?>
-<title><?php echo generate_page_title($page_title) ?></title>
+<meta http-equiv="Content-Type" content="text/html; charset=<?php echo $lang_common["lang_encoding"] ?>" />
+<title><?php echo pun_htmlspecialchars($pun_config['o_board_title']) ?> / Error</title>
 <style type="text/css">
 <!--
@@ -1498,22 +939,22 @@
 
 <div id="errorbox">
-	<h2>An error was encountered</h2>
+	<h2>Une erreur s'est produite</h2>
 	<div>
 <?php
 
-	if (defined('PUN_DEBUG') && $file !== null && $line !== null)
-	{
-		echo "\t\t".'<strong>File:</strong> '.$file.'<br />'."\n\t\t".'<strong>Line:</strong> '.$line.'<br /><br />'."\n\t\t".'<strong>FluxBB reported</strong>: '.$message."\n";
+	if (defined('PUN_DEBUG'))
+	{
+		echo "\t\t".'<strong>Fichier :</strong> '.$file.'<br />'."\n\t\t".'<strong>Ligne :</strong> '.$line.'<br /><br />'."\n\t\t".'<strong>PunBB a rapportÃ© :</strong> '.$message."\n";
 
 		if ($db_error)
 		{
-			echo "\t\t".'<br /><br /><strong>Database reported:</strong> '.pun_htmlspecialchars($db_error['error_msg']).(($db_error['error_no']) ? ' (Errno: '.$db_error['error_no'].')' : '')."\n";
+			echo "\t\t".'<br /><br /><strong>La base de donnÃ©es a rapportÃ© :</strong> '.pun_htmlspecialchars($db_error['error_msg']).(($db_error['error_no']) ? ' (Errno: '.$db_error['error_no'].')' : '')."\n";
 
 			if ($db_error['error_sql'] != '')
-				echo "\t\t".'<br /><br /><strong>Failed query:</strong> '.pun_htmlspecialchars($db_error['error_sql'])."\n";
+				echo "\t\t".'<br /><br /><strong>RequÃªte Ã©chouÃ©e :</strong> '.pun_htmlspecialchars($db_error['error_sql'])."\n";
 		}
 	}
 	else
-		echo "\t\t".'Error: <strong>'.$message.'.</strong>'."\n";
+		echo "\t\t".'Erreur : <strong>'.$message.'.</strong>'."\n";
 
 ?>
@@ -1530,445 +971,4 @@
 
 	exit;
-}
-
-
-//
-// Unset any variables instantiated as a result of register_globals being enabled
-//
-function forum_unregister_globals()
-{
-	$register_globals = ini_get('register_globals');
-	if ($register_globals === '' || $register_globals === '0' || strtolower($register_globals) === 'off')
-		return;
-
-	// Prevent script.php?GLOBALS[foo]=bar
-	if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']))
-		exit('I\'ll have a steak sandwich and... a steak sandwich.');
-
-	// Variables that shouldn't be unset
-	$no_unset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
-
-	// Remove elements in $GLOBALS that are present in any of the superglobals
-	$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, $no_unset) && isset($GLOBALS[$k]))
-		{
-			unset($GLOBALS[$k]);
-			unset($GLOBALS[$k]); // Double unset to circumvent the zend_hash_del_key_or_index hole in PHP <4.4.3 and <5.1.4
-		}
-	}
-}
-
-
-//
-// Removes any "bad" characters (characters which mess with the display of a page, are invisible, etc) from user input
-//
-function forum_remove_bad_characters()
-{
-	$_GET = remove_bad_characters($_GET);
-	$_POST = remove_bad_characters($_POST);
-	$_COOKIE = remove_bad_characters($_COOKIE);
-	$_REQUEST = remove_bad_characters($_REQUEST);
-}
-
-//
-// Removes any "bad" characters (characters which mess with the display of a page, are invisible, etc) from the given string
-// See: http://kb.mozillazine.org/Network.IDN.blacklist_chars
-//
-function remove_bad_characters($array)
-{
-	static $bad_utf8_chars;
-
-	if (!isset($bad_utf8_chars))
-	{
-		$bad_utf8_chars = array(
-			"\xcc\xb7"		=> '',		// COMBINING SHORT SOLIDUS OVERLAY		0337	*
-			"\xcc\xb8"		=> '',		// COMBINING LONG SOLIDUS OVERLAY		0338	*
-			"\xe1\x85\x9F"	=> '',		// HANGUL CHOSEONG FILLER				115F	*
-			"\xe1\x85\xA0"	=> '',		// HANGUL JUNGSEONG FILLER				1160	*
-			"\xe2\x80\x8b"	=> '',		// ZERO WIDTH SPACE						200B	*
-			"\xe2\x80\x8c"	=> '',		// ZERO WIDTH NON-JOINER				200C
-			"\xe2\x80\x8d"	=> '',		// ZERO WIDTH JOINER					200D
-			"\xe2\x80\x8e"	=> '',		// LEFT-TO-RIGHT MARK					200E
-			"\xe2\x80\x8f"	=> '',		// RIGHT-TO-LEFT MARK					200F
-			"\xe2\x80\xaa"	=> '',		// LEFT-TO-RIGHT EMBEDDING				202A
-			"\xe2\x80\xab"	=> '',		// RIGHT-TO-LEFT EMBEDDING				202B
-			"\xe2\x80\xac"	=> '', 		// POP DIRECTIONAL FORMATTING			202C
-			"\xe2\x80\xad"	=> '',		// LEFT-TO-RIGHT OVERRIDE				202D
-			"\xe2\x80\xae"	=> '',		// RIGHT-TO-LEFT OVERRIDE				202E
-			"\xe2\x80\xaf"	=> '',		// NARROW NO-BREAK SPACE				202F	*
-			"\xe2\x81\x9f"	=> '',		// MEDIUM MATHEMATICAL SPACE			205F	*
-			"\xe2\x81\xa0"	=> '',		// WORD JOINER							2060
-			"\xe3\x85\xa4"	=> '',		// HANGUL FILLER						3164	*
-			"\xef\xbb\xbf"	=> '',		// ZERO WIDTH NO-BREAK SPACE			FEFF
-			"\xef\xbe\xa0"	=> '',		// HALFWIDTH HANGUL FILLER				FFA0	*
-			"\xef\xbf\xb9"	=> '',		// INTERLINEAR ANNOTATION ANCHOR		FFF9	*
-			"\xef\xbf\xba"	=> '',		// INTERLINEAR ANNOTATION SEPARATOR		FFFA	*
-			"\xef\xbf\xbb"	=> '',		// INTERLINEAR ANNOTATION TERMINATOR	FFFB	*
-			"\xef\xbf\xbc"	=> '',		// OBJECT REPLACEMENT CHARACTER			FFFC	*
-			"\xef\xbf\xbd"	=> '',		// REPLACEMENT CHARACTER				FFFD	*
-			"\xe2\x80\x80"	=> ' ',		// EN QUAD								2000	*
-			"\xe2\x80\x81"	=> ' ',		// EM QUAD								2001	*
-			"\xe2\x80\x82"	=> ' ',		// EN SPACE								2002	*
-			"\xe2\x80\x83"	=> ' ',		// EM SPACE								2003	*
-			"\xe2\x80\x84"	=> ' ',		// THREE-PER-EM SPACE					2004	*
-			"\xe2\x80\x85"	=> ' ',		// FOUR-PER-EM SPACE					2005	*
-			"\xe2\x80\x86"	=> ' ',		// SIX-PER-EM SPACE						2006	*
-			"\xe2\x80\x87"	=> ' ',		// FIGURE SPACE							2007	*
-			"\xe2\x80\x88"	=> ' ',		// PUNCTUATION SPACE					2008	*
-			"\xe2\x80\x89"	=> ' ',		// THIN SPACE							2009	*
-			"\xe2\x80\x8a"	=> ' ',		// HAIR SPACE							200A	*
-			"\xE3\x80\x80"	=> ' ',		// IDEOGRAPHIC SPACE					3000	*
-		);
-	}
-
-	if (is_array($array))
-		return array_map('remove_bad_characters', $array);
-
-	// Strip out any invalid characters
-	$array = utf8_bad_strip($array);
-
-	// Remove control characters
-	$array = preg_replace('%[\x{00}-\x{08}\x{0b}-\x{0c}\x{0e}-\x{1f}]%', '', $array);
-
-	// Replace some "bad" characters
-	$array = str_replace(array_keys($bad_utf8_chars), array_values($bad_utf8_chars), $array);
-
-	return $array;
-}
-
-
-//
-// Converts the file size in bytes to a human readable file size
-//
-function file_size($size)
-{
-	global $lang_common;
-
-	$units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB');
-
-	for ($i = 0; $size > 1024; $i++)
-		$size /= 1024;
-
-	return sprintf($lang_common['Size unit '.$units[$i]], round($size, 2));;
-}
-
-
-//
-// Fetch a list of available styles
-//
-function forum_list_styles()
-{
-	$styles = array();
-
-	$d = dir(PUN_ROOT.'style');
-	while (($entry = $d->read()) !== false)
-	{
-		if ($entry{0} == '.')
-			continue;
-
-		if (substr($entry, -4) == '.css')
-			$styles[] = substr($entry, 0, -4);
-	}
-	$d->close();
-
-	natcasesort($styles);
-
-	return $styles;
-}
-
-
-//
-// Fetch a list of available language packs
-//
-function forum_list_langs()
-{
-	$languages = array();
-
-	$d = dir(PUN_ROOT.'lang');
-	while (($entry = $d->read()) !== false)
-	{
-		if ($entry{0} == '.')
-			continue;
-
-		if (is_dir(PUN_ROOT.'lang/'.$entry) && file_exists(PUN_ROOT.'lang/'.$entry.'/common.php'))
-			$languages[] = $entry;
-	}
-	$d->close();
-
-	natcasesort($languages);
-
-	return $languages;
-}
-
-
-//
-// Generate a cache ID based on the last modification time for all stopwords files
-//
-function generate_stopwords_cache_id()
-{
-	$files = glob(PUN_ROOT.'lang/*/stopwords.txt');
-	if ($files === false)
-		return 'cache_id_error';
-
-	$hash = array();
-
-	foreach ($files as $file)
-	{
-		$hash[] = $file;
-		$hash[] = filemtime($file);
-	}
-
-	return sha1(implode('|', $hash));
-}
-
-
-//
-// Fetch a list of available admin plugins
-//
-function forum_list_plugins($is_admin)
-{
-	$plugins = array();
-
-	$d = dir(PUN_ROOT.'plugins');
-	while (($entry = $d->read()) !== false)
-	{
-		if ($entry{0} == '.')
-			continue;
-
-		$prefix = substr($entry, 0, strpos($entry, '_'));
-		$suffix = substr($entry, strlen($entry) - 4);
-
-		if ($suffix == '.php' && ((!$is_admin && $prefix == 'AMP') || ($is_admin && ($prefix == 'AP' || $prefix == 'AMP'))))
-			$plugins[$entry] = substr($entry, strpos($entry, '_') + 1, -4);
-	}
-	$d->close();
-
-	natcasesort($plugins);
-
-	return $plugins;
-}
-
-
-//
-// Split text into chunks ($inside contains all text inside $start and $end, and $outside contains all text outside)
-//
-function split_text($text, $start, $end, &$errors, $retab = true)
-{
-	global $pun_config, $lang_common;
-
-	$result = array(0 => array(), 1 => array()); // 0 = inside, 1 = outside
-
-	// split the text into parts
-	$parts = preg_split('%'.preg_quote($start, '%').'(.*)'.preg_quote($end, '%').'%Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
-	$num_parts = count($parts);
-
-	// preg_split results in outside parts having even indices, inside parts having odd
-	for ($i = 0;$i < $num_parts;$i++)
-		$result[1 - ($i % 2)][] = $parts[$i];
-
-	if ($pun_config['o_indent_num_spaces'] != 8 && $retab)
-	{
-		$spaces = str_repeat(' ', $pun_config['o_indent_num_spaces']);
-		$result[1] = str_replace("\t", $spaces, $result[1]);
-	}
-
-	return $result;
-}
-
-
-//
-// Extract blocks from a text with a starting and ending string
-// This function always matches the most outer block so nesting is possible
-//
-function extract_blocks($text, $start, $end, &$errors = array(), $retab = true)
-{
-	global $pun_config;
-
-	$code = array();
-	$start_len = strlen($start);
-	$end_len = strlen($end);
-	$regex = '%(?:'.preg_quote($start, '%').'|'.preg_quote($end, '%').')%';
-	$matches = array();
-
-	if (preg_match_all($regex, $text, $matches))
-	{
-		$counter = $offset = 0;
-		$start_pos = $end_pos = false;
-
-		foreach ($matches[0] as $match)
-		{
-			if ($match == $start)
-			{
-				if ($counter == 0)
-					$start_pos = strpos($text, $start);
-				$counter++;
-			}
-			elseif ($match == $end)
-			{
-				$counter--;
-				if ($counter == 0)
-					$end_pos = strpos($text, $end, $offset + 1);
-				$offset = strpos($text, $end, $offset + 1);
-			}
-
-			if ($start_pos !== false && $end_pos !== false)
-			{
-				$code[] = substr($text, $start_pos + $start_len,
-					$end_pos - $start_pos - $start_len);
-				$text = substr_replace($text, "\1", $start_pos,
-					$end_pos - $start_pos + $end_len);
-				$start_pos = $end_pos = false;
-				$offset = 0;
-			}
-		}
-	}
-
-	if ($pun_config['o_indent_num_spaces'] != 8 && $retab)
-	{
-		$spaces = str_repeat(' ', $pun_config['o_indent_num_spaces']);
-		$text = str_replace("\t", $spaces, $text);
-	}
-
-	return array($code, $text);
-}
-
-
-//
-// function url_valid($url) {
-//
-// Return associative array of valid URI components, or FALSE if $url is not
-// RFC-3986 compliant. If the passed URL begins with: "www." or "ftp.", then
-// "http://" or "ftp://" is prepended and the corrected full-url is stored in
-// the return array with a key name "url". This value should be used by the caller.
-//
-// Return value: FALSE if $url is not valid, otherwise array of URI components:
-// e.g.
-// Given: "http://www.jmrware.com:80/articles?height=10&width=75#fragone"
-// Array(
-//	  [scheme] => http
-//	  [authority] => www.jmrware.com:80
-//	  [userinfo] =>
-//	  [host] => www.jmrware.com
-//	  [IP_literal] =>
-//	  [IPV6address] =>
-//	  [ls32] =>
-//	  [IPvFuture] =>
-//	  [IPv4address] =>
-//	  [regname] => www.jmrware.com
-//	  [port] => 80
-//	  [path_abempty] => /articles
-//	  [query] => height=10&width=75
-//	  [fragment] => fragone
-//	  [url] => http://www.jmrware.com:80/articles?height=10&width=75#fragone
-// )
-function url_valid($url)
-{
-	if (strpos($url, 'www.') === 0) $url = 'http://'. $url;
-	if (strpos($url, 'ftp.') === 0) $url = 'ftp://'. $url;
-	if (!preg_match('/# Valid absolute URI having a non-empty, valid DNS host.
-		^
-		(?P<scheme>[A-Za-z][A-Za-z0-9+\-.]*):\/\/
-		(?P<authority>
-		  (?:(?P<userinfo>(?:[A-Za-z0-9\-._~!$&\'()*+,;=:]|%[0-9A-Fa-f]{2})*)@)?
-		  (?P<host>
-			(?P<IP_literal>
-			  \[
-			  (?:
-				(?P<IPV6address>
-				  (?:												 (?:[0-9A-Fa-f]{1,4}:){6}
-				  |												   ::(?:[0-9A-Fa-f]{1,4}:){5}
-				  | (?:							 [0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){4}
-				  | (?:(?:[0-9A-Fa-f]{1,4}:){0,1}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){3}
-				  | (?:(?:[0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})?::(?:[0-9A-Fa-f]{1,4}:){2}
-				  | (?:(?:[0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})?::	[0-9A-Fa-f]{1,4}:
-				  | (?:(?:[0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})?::
-				  )
-				  (?P<ls32>[0-9A-Fa-f]{1,4}:[0-9A-Fa-f]{1,4}
-				  | (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
-					   (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
-				  )
-				|	(?:(?:[0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})?::	[0-9A-Fa-f]{1,4}
-				|	(?:(?:[0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})?::
-				)
-			  | (?P<IPvFuture>[Vv][0-9A-Fa-f]+\.[A-Za-z0-9\-._~!$&\'()*+,;=:]+)
-			  )
-			  \]
-			)
-		  | (?P<IPv4address>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}
-							   (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
-		  | (?P<regname>(?:[A-Za-z0-9\-._~!$&\'()*+,;=]|%[0-9A-Fa-f]{2})+)
-		  )
-		  (?::(?P<port>[0-9]*))?
-		)
-		(?P<path_abempty>(?:\/(?:[A-Za-z0-9\-._~!$&\'()*+,;=:@]|%[0-9A-Fa-f]{2})*)*)
-		(?:\?(?P<query>		  (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
-		(?:\#(?P<fragment>	  (?:[A-Za-z0-9\-._~!$&\'()*+,;=:@\\/?]|%[0-9A-Fa-f]{2})*))?
-		$
-		/mx', $url, $m)) return FALSE;
-	switch ($m['scheme'])
-	{
-	case 'https':
-	case 'http':
-		if ($m['userinfo']) return FALSE; // HTTP scheme does not allow userinfo.
-		break;
-	case 'ftps':
-	case 'ftp':
-		break;
-	default:
-		return FALSE;	// Unrecognised URI scheme. Default to FALSE.
-	}
-	// Validate host name conforms to DNS "dot-separated-parts".
-	if ($m{'regname'}) // If host regname specified, check for DNS conformance.
-	{
-		if (!preg_match('/# HTTP DNS host name.
-			^					   # Anchor to beginning of string.
-			(?!.{256})			   # Overall host length is less than 256 chars.
-			(?:					   # Group dot separated host part alternatives.
-			  [0-9A-Za-z]\.		   # Either a single alphanum followed by dot
-			|					   # or... part has more than one char (63 chars max).
-			  [0-9A-Za-z]		   # Part first char is alphanum (no dash).
-			  [\-0-9A-Za-z]{0,61}  # Internal chars are alphanum plus dash.
-			  [0-9A-Za-z]		   # Part last char is alphanum (no dash).
-			  \.				   # Each part followed by literal dot.
-			)*					   # One or more parts before top level domain.
-			(?:					   # Explicitly specify top level domains.
-			  com|edu|gov|int|mil|net|org|biz|
-			  info|name|pro|aero|coop|museum|
-			  asia|cat|jobs|mobi|tel|travel|
-			  [A-Za-z]{2})		   # Country codes are exqactly two alpha chars.
-			$					   # Anchor to end of string.
-			/ix', $m['host'])) return FALSE;
-	}
-	$m['url'] = $url;
-	for ($i = 0; isset($m[$i]); ++$i) unset($m[$i]);
-	return $m; // return TRUE == array of useful named $matches plus the valid $url.
-}
-
-//
-// Replace string matching regular expression
-//
-// This function takes care of possibly disabled unicode properties in PCRE builds
-//
-function ucp_preg_replace($pattern, $replace, $subject)
-{
-	$replaced = preg_replace($pattern, $replace, $subject);
-
-	// If preg_replace() returns false, this probably means unicode support is not built-in, so we need to modify the pattern a little
-	if ($replaced === false)
-	{
-		if (is_array($pattern))
-		{
-			foreach ($pattern as $cur_key => $cur_pattern)
-				$pattern[$cur_key] = str_replace('\p{L}\p{N}', '\w', $cur_pattern);
-
-			$replaced = preg_replace($pattern, $replace, $subject);
-		}
-		else
-			$replaced = preg_replace(str_replace('\p{L}\p{N}', '\w', $pattern), $replace, $subject);
-	}
-
-	return $replaced;
 }
 
@@ -1994,6 +994,6 @@
 			<thead>
 				<tr>
-					<th class="tcl" scope="col"><?php echo $lang_common['Query times'] ?></th>
-					<th class="tcr" scope="col"><?php echo $lang_common['Query'] ?></th>
+					<th class="tcl" scope="col">Temps (s)</th>
+					<th class="tcr" scope="col">RequÃªte</th>
 				</tr>
 			</thead>
@@ -2002,5 +1002,5 @@
 
 	$query_time_total = 0.0;
-	foreach ($saved_queries as $cur_query)
+	while (list(, $cur_query) = @each($saved_queries))
 	{
 		$query_time_total += $cur_query[1];
@@ -2017,5 +1017,5 @@
 ?>
 				<tr>
-					<td class="tcl" colspan="2"><?php printf($lang_common['Total query time'], $query_time_total.' s') ?></td>
+					<td class="tcl" colspan="2">Temps total requÃªte : <?php echo $query_time_total ?> s</td>
 				</tr>
 			</tbody>
@@ -2030,4 +1030,26 @@
 
 //
+// Unset any variables instantiated as a result of register_globals being enabled
+//
+function unregister_globals()
+{
+	// Prevent script.php?GLOBALS[foo]=bar
+	if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']))
+		exit('I\'ll have a steak sandwich and... a steak sandwich.');
+	
+	// Variables that shouldn't be unset
+	$no_unset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
+	
+	// Remove elements in $GLOBALS that are present in any of the superglobals
+	$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, $no_unset) && isset($GLOBALS[$k]))
+			unset($GLOBALS[$k]);
+	}
+}
+
+
+//
 // Dump contents of variable(s)
 //
Index: trunk/web/punbb/include/index.html
===================================================================
--- trunk/web/punbb/include/index.html	(revision 10)
+++ 	(revision )
@@ -1,1 +1,0 @@
-<html><head><title>.</title></head><body>.</body></html>
Index: trunk/web/punbb/include/parser.php
===================================================================
--- trunk/web/punbb/include/parser.php	(revision 10)
+++ trunk/web/punbb/include/parser.php	(revision 1)
@@ -1,9 +1,25 @@
 <?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+/***********************************************************************
+
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
 
 // Make sure no one attempts to run this script "directly"
@@ -11,52 +27,14 @@
 	exit;
 
-// Global variables
-/* regular expression to match nested BBCode LIST tags
-'%
-\[list                # match opening bracket and tag name of outermost LIST tag
-(?:=([1a*]))?+        # optional attribute capture in group 1
-\]                    # closing bracket of outermost opening LIST tag
-(                     # capture contents of LIST tag in group 2
-  (?:                 # non capture group for either contents or whole nested LIST
-	[^\[]*+           # unroll the loop! consume everything up to next [ (normal *)
-	(?:               # (See "Mastering Regular Expressions" chapter 6 for details)
-	  (?!             # negative lookahead ensures we are NOT on [LIST*] or [/LIST]
-		\[list        # opening LIST tag
-		(?:=[1a*])?+  # with optional attribute
-		\]            # closing bracket of opening LIST tag
-		|             # or...
-		\[/list\]     # a closing LIST tag
-	  )               # end negative lookahead assertion (we are not on a LIST tag)
-	  \[              # match the [ which is NOT the start of LIST tag (special)
-	  [^\[]*+         # consume everything up to next [ (normal *)
-	)*+               # finish up "unrolling the loop" technique (special (normal*))*
-  |                   # or...
-	(?R)              # recursively match a whole nested LIST element
-  )*                  # as many times as necessary until deepest nested LIST tag grabbed
-)                     # end capturing contents of LIST tag into group 2
-\[/list\]             # match outermost closing LIST tag
-%iex' */
-$re_list = '%\[list(?:=([1a*]))?+\]((?:[^\[]*+(?:(?!\[list(?:=[1a*])?+\]|\[/list\])\[[^\[]*+)*+|(?R))*)\[/list\]%ie';
-
-// Here you can add additional smilies if you like (please note that you must escape single quote and backslash)
-$smilies = array(
-	':)' => 'smile.png',
-	'=)' => 'smile.png',
-	':|' => 'neutral.png',
-	'=|' => 'neutral.png',
-	':(' => 'sad.png',
-	'=(' => 'sad.png',
-	':D' => 'big_smile.png',
-	'=D' => 'big_smile.png',
-	':o' => 'yikes.png',
-	':O' => 'yikes.png',
-	';)' => 'wink.png',
-	':/' => 'hmm.png',
-	':P' => 'tongue.png',
-	':p' => 'tongue.png',
-	':lol:' => 'lol.png',
-	':mad:' => 'mad.png',
-	':rolleyes:' => 'roll.png',
-	':cool:' => 'cool.png');
+
+// Load cache smiley
+@include_once PUN_ROOT.'cache/cache_smilies.php';
+if (!defined('PUN_CACHE_SMILEY'))
+{
+	require_once PUN_ROOT.'include/cache_smilies.php';
+	generate_smiley_cache();
+	require PUN_ROOT.'cache/cache_smilies.php';
+}
+
 
 //
@@ -65,800 +43,384 @@
 function preparse_bbcode($text, &$errors, $is_signature = false)
 {
-	global $pun_config, $lang_common, $lang_post, $re_list;
-
-	if ($is_signature)
-	{
-		global $lang_profile;
-
-		if (preg_match('%\[/?(?:quote|code|list|h)\b[^\]]*\]%i', $text))
-			$errors[] = $lang_profile['Signature quote/code/list/h'];
-	}
+	// Change all simple BBCodes to lower case
+	$a = array('[B]', '[I]', '[U]', '[/B]', '[/I]', '[/U]');
+	$b = array('[b]', '[i]', '[u]', '[/b]', '[/i]', '[/u]');
+	$text = str_replace($a, $b, $text);
+
+	// Do the more complex BBCodes (also strip excessive whitespace and useless quotes)
+	$a = array( '#\[url=("|\'|)(.*?)\\1\]\s*#i',
+				'#\[url\]\s*#i',
+				'#\s*\[/url\]#i',
+				'#\[email=("|\'|)(.*?)\\1\]\s*#i',
+				'#\[email\]\s*#i',
+				'#\s*\[/email\]#i',
+				'#\[img\]\s*(.*?)\s*\[/img\]#is',
+				'#\[colou?r=("|\'|)(.*?)\\1\](.*?)\[/colou?r\]#is');
+
+	$b = array(	'[url=$2]',
+				'[url]',
+				'[/url]',
+				'[email=$2]',
+				'[email]',
+				'[/email]',
+				'[img]$1[/img]',
+				'[color=$2]$3[/color]');
+
+	if (!$is_signature)
+	{
+		// For non-signatures, we have to do the quote and code tags as well
+		$a[] = '#\[quote=(&quot;|"|\'|)(.*?)\\1\]\s*#i';
+		$a[] = '#\[quote\]\s*#i';
+		$a[] = '#\s*\[/quote\]\s*#i';
+		$a[] = '#\[code\][\r\n]*(.*?)\s*\[/code\]\s*#is';
+
+		$b[] = '[quote=$1$2$1]';
+		$b[] = '[quote]';
+		$b[] = '[/quote]'."\n";
+		$b[] = '[code]$1[/code]'."\n";
+	}
+
+	// Run this baby!
+	$text = preg_replace($a, $b, $text);
+
+	if (!$is_signature)
+	{
+		$overflow = check_tag_order($text, $error);
+
+		if ($error)
+			// A BBCode error was spotted in check_tag_order()
+			$errors[] = $error;
+		else if ($overflow)
+			// The quote depth level was too high, so we strip out the inner most quote(s)
+			$text = substr($text, 0, $overflow[0]).substr($text, $overflow[1], (strlen($text) - $overflow[0]));
+	}
+	else
+	{
+		global $lang_prof_reg;
+
+		if (preg_match('#\[quote=(&quot;|"|\'|)(.*)\\1\]|\[quote\]|\[/quote\]|\[code\]|\[/code\]#i', $text))
+			message($lang_prof_reg['Signature quote/code']);
+	}
+
+	return trim($text);
+}
+
+
+//
+// Parse text and make sure that [code] and [quote] syntax is correct
+//
+function check_tag_order($text, &$error)
+{
+	global $lang_common;
+
+	// The maximum allowed quote depth
+	$max_depth = 3;
+
+	$cur_index = 0;
+	$q_depth = 0;
+
+	while (true)
+	{
+		// Look for regular code and quote tags
+		$c_start = strpos($text, '[code]');
+		$c_end = strpos($text, '[/code]');
+		$q_start = strpos($text, '[quote]');
+		$q_end = strpos($text, '[/quote]');
+
+		// Look for [quote=username] style quote tags
+		if (preg_match('#\[quote=(&quot;|"|\'|)(.*)\\1\]#sU', $text, $matches))
+			$q2_start = strpos($text, $matches[0]);
+		else
+			$q2_start = 65536;
+
+		// Deal with strpos() returning false when the string is not found
+		// (65536 is one byte longer than the maximum post length)
+		if ($c_start === false) $c_start = 65536;
+		if ($c_end === false) $c_end = 65536;
+		if ($q_start === false) $q_start = 65536;
+		if ($q_end === false) $q_end = 65536;
+
+		// If none of the strings were found
+		if (min($c_start, $c_end, $q_start, $q_end, $q2_start) == 65536)
+			break;
+
+		// We are interested in the first quote (regardless of the type of quote)
+		$q3_start = ($q_start < $q2_start) ? $q_start : $q2_start;
+
+		// We found a [quote] or a [quote=username]
+		if ($q3_start < min($q_end, $c_start, $c_end))
+		{
+			$step = ($q_start < $q2_start) ? 7 : strlen($matches[0]);
+
+			$cur_index += $q3_start + $step;
+
+			// Did we reach $max_depth?
+			if ($q_depth == $max_depth)
+				$overflow_begin = $cur_index - $step;
+
+			++$q_depth;
+			$text = substr($text, $q3_start + $step);
+		}
+
+		// We found a [/quote]
+		else if ($q_end < min($q_start, $c_start, $c_end))
+		{
+			if ($q_depth == 0)
+			{
+				$error = $lang_common['BBCode error'].' '.$lang_common['BBCode error 1'];
+				return;
+			}
+
+			$q_depth--;
+			$cur_index += $q_end+8;
+
+			// Did we reach $max_depth?
+			if ($q_depth == $max_depth)
+				$overflow_end = $cur_index;
+
+			$text = substr($text, $q_end+8);
+		}
+
+		// We found a [code]
+		else if ($c_start < min($c_end, $q_start, $q_end))
+		{
+			// Make sure there's a [/code] and that any new [code] doesn't occur before the end tag
+			$tmp = strpos($text, '[/code]');
+			$tmp2 = strpos(substr($text, $c_start+6), '[code]');
+			if ($tmp2 !== false)
+				$tmp2 += $c_start+6;
+				
+			if ($tmp === false || ($tmp2 !== false && $tmp2 < $tmp))
+			{
+				$error = $lang_common['BBCode error'].' '.$lang_common['BBCode error 2'];
+				return;
+			}
+			else
+				$text = substr($text, $tmp+7);
+
+			$cur_index += $tmp+7;
+		}
+
+		// We found a [/code] (this shouldn't happen since we handle both start and end tag in the if clause above)
+		else if ($c_end < min($c_start, $q_start, $q_end))
+		{
+			$error = $lang_common['BBCode error'].' '.$lang_common['BBCode error 3'];
+			return;
+		}
+	}
+
+	// If $q_depth <> 0 something is wrong with the quote syntax
+	if ($q_depth)
+	{
+		$error = $lang_common['BBCode error'].' '.$lang_common['BBCode error 4'];
+		return;
+	}
+	else if ($q_depth < 0)
+	{
+		$error = $lang_common['BBCode error'].' '.$lang_common['BBCode error 5'];
+		return;
+	}
+
+	// If the quote depth level was higher than $max_depth we return the index for the
+	// beginning and end of the part we should strip out
+	if (isset($overflow_begin))
+		return array($overflow_begin, $overflow_end);
+	else
+		return null;
+}
+
+
+//
+// Split text into chunks ($inside contains all text inside $start and $end, and $outside contains all text outside)
+//
+function split_text($text, $start, $end)
+{
+	global $pun_config;
+
+	$tokens = explode($start, $text);
+
+	$outside[] = $tokens[0];
+
+	$num_tokens = count($tokens);
+	for ($i = 1; $i < $num_tokens; ++$i)
+	{
+		$temp = explode($end, $tokens[$i]);
+		$inside[] = $temp[0];
+		$outside[] = $temp[1];
+	}
+
+	if ($pun_config['o_indent_num_spaces'] != 8 && $start == '[code]')
+	{
+		$spaces = str_repeat(' ', $pun_config['o_indent_num_spaces']);
+		$inside = str_replace("\t", $spaces, $inside);
+	}
+
+	return array($inside, $outside);
+}
+
+
+//
+// Truncate URL if longer than 55 characters (add http:// or ftp:// if missing)
+//
+function handle_url_tag($url, $link = '')
+{
+	global $pun_user;
+
+	$full_url = str_replace(array(' ', '\'', '`'), array('%20', '', ''), $url);
+	if (strpos($url, 'www.') === 0)			// If it starts with www, we add http://
+		$full_url = 'http://'.$full_url;
+	else if (strpos($url, 'ftp.') === 0)	// Else if it starts with ftp, we add ftp://
+		$full_url = 'ftp://'.$full_url;
+	else if (!preg_match('#^([a-z0-9]{3,6})://#', $url, $bah)) 	// Else if it doesn't start with abcdef://, we add http://
+		$full_url = 'http://'.$full_url;
+
+	// Ok, not very pretty :-)
+	$link = ($link == '' || $link == $url) ? ((strlen($url) > 55) ? substr($url, 0 , 39).' &hellip; '.substr($url, -10) : $url) : stripslashes($link);
+
+	return '<a href="'.$full_url.'" target=\"_blank\">'.$link.'</a>';
+}
+
+
+//
+// Turns an URL from the [img] tag into an <img> tag or a <a href...> tag
+//
+function handle_img_tag($url, $is_signature = false)
+{
+	global $lang_common, $pun_config, $pun_user;
+
+	$img_tag = '<a href="'.$url.'">&lt;'.$lang_common['Image link'].'&gt;</a>';
+
+	if ($is_signature && $pun_user['show_img_sig'] != '0')
+		$img_tag = '<img class="sigimage" src="'.$url.'" alt="'.htmlspecialchars($url).'" />';
+	else if (!$is_signature && $pun_user['show_img'] != '0')
+		$img_tag = '<img class="postimg" src="'.$url.'" alt="'.htmlspecialchars($url).'" />';
+
+	return $img_tag;
+}
+
+
+//
+// Convert BBCodes to their HTML equivalent
+//
+function do_bbcode($text)
+{
+	global $lang_common, $pun_user;
+
+	if (strpos($text, 'quote') !== false)
+	{
+		$text = str_replace('[quote]', '</p><blockquote><div class="incqbox"><p>', $text);
+		$text = preg_replace('#\[quote=(&quot;|"|\'|)(.*)\\1\]#seU', '"</p><blockquote><div class=\"incqbox\"><h4>".str_replace(array(\'[\', \'\\"\'), array(\'&#91;\', \'"\'), \'$2\')." ".$lang_common[\'wrote\'].":</h4><p>"', $text);
+		$text = preg_replace('#\[\/quote\]\s*#', '</p></div></blockquote><p>', $text);
+	}
+	
+	$pattern = array('#\[b\](.*?)\[/b\]#s',
+					 '#\[i\](.*?)\[/i\]#s',
+					 '#\[u\](.*?)\[/u\]#s',
+					 '#\[url\]([^\[]*?)\[/url\]#e',
+					 '#\[url=([^\[]*?)\](.*?)\[/url\]#e',
+					 '#\[email\]([^\[]*?)\[/email\]#',
+					 '#\[email=([^\[]*?)\](.*?)\[/email\]#',
+					 '#\[color=([a-zA-Z]*|\#?[0-9a-fA-F]{6})](.*?)\[/color\]#s',
+					 '#\[font=(.*?)](.*?)\[/font\]#s',
+					 '#\[align=(.*?)\](.*?)\[/align\]#s',
+					 '#\[hr /\]#',
+					 '#\[hr\]#',
+					 '#\[s\](.*?)\[/s\]#s',
+					 '#\[h\](.*?)\[/h\]#s',
+                               '#\[size=([0-9]{1,2})](.*?)\[/size\]#s');
+
+	$replace = array('<strong>$1</strong>',
+					 '<em>$1</em>',
+					 '<span class="bbu">$1</span>',
+					 'handle_url_tag(\'$1\')',
+					 'handle_url_tag(\'$1\', \'$2\')',
+					 '<a href="mailto:$1">$1</a>',
+					 '<a href="mailto:$1">$2</a>',
+					 '<span style="color: $1">$2</span>',
+					 '<span style="font-family: $1">$2</span>',
+					 '<div align="$1">$2</div>',
+					 '<hr />',
+					 '<hr />',
+					 '<del>$1</del>',
+					 '<span style="background-color: #FFFF00; color: #000000">$1</span>',
+                               '<span style="font-size: $1pt;">$2</span>');
+
+	// This thing takes a while! :)
+	$text = preg_replace($pattern, $replace, $text);
+
+	return $text;
+}
+
+
+//
+// Make hyperlinks clickable
+//
+function do_clickable($text)
+{
+	global $pun_user;
+
+	$text = ' '.$text;
+
+	$text = preg_replace('#([\s\(\)])(https?|ftp|news){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^"\s\(\)<\[]*)?)#ie', '\'$1\'.handle_url_tag(\'$2://$3\')', $text);
+	$text = preg_replace('#([\s\(\)])(www|ftp)\.(([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^"\s\(\)<\[]*)?)#ie', '\'$1\'.handle_url_tag(\'$2.$3\', \'$2.$3\')', $text);
+
+	return substr($text, 1);
+}
+
+
+//
+// Convert a series of smilies to images
+//
+function do_smilies($text)
+{
+	global $smiley_text, $smiley_img;
+
+	$text = ' '.$text.' ';
+
+	$num_smilies = count($smiley_text);
+	for ($i = 0; $i < $num_smilies; ++$i)
+		$text = preg_replace("#(?<=.\W|\W.|^\W)".preg_quote($smiley_text[$i], '#')."(?=.\W|\W.|\W$)#m", '$1<img src="'.PUN_ROOT.'img/smilies/'.$smiley_img[$i].'" alt="'.substr($smiley_img[$i], 0, strrpos($smiley_img[$i], '.')).'" />$2', $text);
+
+	return substr($text, 1, -1);
+}
+
+
+//
+// Parse message text
+//
+function parse_message($text, $hide_smilies)
+{
+	global $pun_config, $lang_common, $pun_user;
+
+	if ($pun_config['o_censoring'] == '1')
+		$text = censor_words($text);
+
+	// Convert applicable characters to HTML entities
+	$text = pun_htmlspecialchars($text);
 
 	// If the message contains a code tag we have to split it up (text within [code][/code] shouldn't be touched)
 	if (strpos($text, '[code]') !== false && strpos($text, '[/code]') !== false)
-		list($inside, $text) = extract_blocks($text, '[code]', '[/code]', $errors);
-
-	// Tidy up lists
-	$temp = preg_replace($re_list, 'preparse_list_tag(\'$2\', \'$1\', $errors)', $text);
-
-	// If the regex failed
-	if ($temp === null)
-		$errors[] = $lang_common['BBCode list size error'];
-	else
-		$text = str_replace('*'."\0".']', '*]', $temp);
+	{
+		list($inside, $outside) = split_text($text, '[code]', '[/code]');
+		$outside = array_map('ltrim', $outside);
+		$text = implode('<">', $outside);
+	}
 
 	if ($pun_config['o_make_links'] == '1')
 		$text = do_clickable($text);
 
-	// If we split up the message before we have to concatenate it together again (code tags)
-	if (isset($inside))
-	{
-		$outside = explode("\1", $text);
-		$text = '';
-
-		$num_tokens = count($outside);
-		for ($i = 0; $i < $num_tokens; ++$i)
-		{
-			$text .= $outside[$i];
-			if (isset($inside[$i]))
-				$text .= '[code]'.$inside[$i].'[/code]';
-		}
-
-		unset($inside);
-	}
-
-	$temp_text = false;
-	if (empty($errors))
-		$temp_text = preparse_tags($text, $errors, $is_signature);
-
-	if ($temp_text !== false)
-		$text = $temp_text;
-
-	// Remove empty tags
-	while (($new_text = strip_empty_bbcode($text, $errors)) !== false)
-	{
-		if ($new_text != $text)
-		{
-			$text = $new_text;
-			if ($new_text == '')
-			{
-				$errors[] = $lang_post['Empty after strip'];
-				break;
-			}
-		}
-		else
-			break;
-	}
-
-	return pun_trim($text);
-}
-
-
-//
-// Strip empty bbcode tags from some text
-//
-function strip_empty_bbcode($text, &$errors)
-{
-	// If the message contains a code tag we have to split it up (empty tags within [code][/code] are fine)
-	if (strpos($text, '[code]') !== false && strpos($text, '[/code]') !== false)
-		list($inside, $text) = extract_blocks($text, '[code]', '[/code]', $errors);
-
-	// Remove empty tags
-	while (($new_text = preg_replace('%\[(b|u|s|ins|del|em|i|h|colou?r|quote|img|url|email|list|topic|post|forum|user)(?:\=[^\]]*)?\]\s*\[/\1\]%', '', $text)) !== NULL)
-	{
-		if ($new_text != $text)
-			$text = $new_text;
-		else
-			break;
-	}
-
-	// If we split up the message before we have to concatenate it together again (code tags)
-    if (isset($inside)) {
-        $parts = explode("\1", $text);
-        $text = '';
-        foreach ($parts as $i => $part)
-        {
-            $text .= $part;
-            if (isset($inside[$i]))
-                $text .= '[code]'.$inside[$i].'[/code]';
-        }
-    }
-
-	// Remove empty code tags
-	while (($new_text = preg_replace('%\[(code)\]\s*\[/\1\]%', '', $text)) !== NULL)
-	{
-		if ($new_text != $text)
-			$text = $new_text;
-		else
-			break;
-	}
-
-	return $text;
-}
-
-
-//
-// Check the structure of bbcode tags and fix simple mistakes where possible
-//
-function preparse_tags($text, &$errors, $is_signature = false)
-{
-	global $lang_common, $pun_config;
-
-	// Start off by making some arrays of bbcode tags and what we need to do with each one
-
-	// List of all the tags
-	$tags = array('quote', 'code', 'b', 'i', 'u', 's', 'ins', 'del', 'em', 'color', 'colour', 'url', 'email', 'img', 'list', '*', 'h', 'topic', 'post', 'forum', 'user');
-	// List of tags that we need to check are open (You could not put b,i,u in here then illegal nesting like [b][i][/b][/i] would be allowed)
-	$tags_opened = $tags;
-	// and tags we need to check are closed (the same as above, added it just in case)
-	$tags_closed = $tags;
-	// Tags we can nest and the depth they can be nested to
-	$tags_nested = array('quote' => $pun_config['o_quote_depth'], 'list' => 5, '*' => 5);
-	// Tags to ignore the contents of completely (just code)
-	$tags_ignore = array('code');
-	// Block tags, block tags can only go within another block tag, they cannot be in a normal tag
-	$tags_block = array('quote', 'code', 'list', 'h', '*');
-	// Inline tags, we do not allow new lines in these
-	$tags_inline = array('b', 'i', 'u', 's', 'ins', 'del', 'em', 'color', 'colour', 'h', 'topic', 'post', 'forum', 'user');
-	// Tags we trim interior space
-	$tags_trim = array('img');
-	// Tags we remove quotes from the argument
-	$tags_quotes = array('url', 'email', 'img', 'topic', 'post', 'forum', 'user');
-	// Tags we limit bbcode in
-	$tags_limit_bbcode = array(
-		'*' 	=> array('b', 'i', 'u', 's', 'ins', 'del', 'em', 'color', 'colour', 'url', 'email', 'list', 'img', 'code', 'topic', 'post', 'forum', 'user'),
-		'list' 	=> array('*'),
-		'url' 	=> array('img'),
-		'email' => array('img'),
-		'topic' => array('img'),
-		'post'  => array('img'),
-		'forum' => array('img'),
-		'user'  => array('img'),
-		'img' 	=> array(),
-		'h'		=> array('b', 'i', 'u', 's', 'ins', 'del', 'em', 'color', 'colour', 'url', 'email', 'topic', 'post', 'forum', 'user'),
-	);
-	// Tags we can automatically fix bad nesting
-	$tags_fix = array('quote', 'b', 'i', 'u', 's', 'ins', 'del', 'em', 'color', 'colour', 'url', 'email', 'h', 'topic', 'post', 'forum', 'user');
-
-	$split_text = preg_split('%(\[[\*a-zA-Z0-9-/]*?(?:=.*?)?\])%', $text, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
-
-	$open_tags = array('fluxbb-bbcode');
-	$open_args = array('');
-	$opened_tag = 0;
-	$new_text = '';
-	$current_ignore = '';
-	$current_nest = '';
-	$current_depth = array();
-	$limit_bbcode = $tags;
-	$count_ignored = array();
-
-	foreach ($split_text as $current)
-	{
-		if ($current == '')
-			continue;
-
-		// Are we dealing with a tag?
-		if (substr($current, 0, 1) != '[' || substr($current, -1, 1) != ']')
-		{
-			// It's not a bbcode tag so we put it on the end and continue
-			// If we are nested too deeply don't add to the end
-			if ($current_nest)
-				continue;
-
-			$current = str_replace("\r\n", "\n", $current);
-			$current = str_replace("\r", "\n", $current);
-			if (in_array($open_tags[$opened_tag], $tags_inline) && strpos($current, "\n") !== false)
-			{
-				// Deal with new lines
-				$split_current = preg_split('%(\n\n+)%', $current, -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
-				$current = '';
-
-				if (!pun_trim($split_current[0], "\n")) // The first part is a linebreak so we need to handle any open tags first
-					array_unshift($split_current, '');
-
-				for ($i = 1; $i < count($split_current); $i += 2)
-				{
-					$temp_opened = array();
-					$temp_opened_arg = array();
-					$temp = $split_current[$i - 1];
-					while (!empty($open_tags))
-					{
-						$temp_tag = array_pop($open_tags);
-						$temp_arg = array_pop($open_args);
-
-						if (in_array($temp_tag , $tags_inline))
-						{
-							array_push($temp_opened, $temp_tag);
-							array_push($temp_opened_arg, $temp_arg);
-							$temp .= '[/'.$temp_tag.']';
-						}
-						else
-						{
-							array_push($open_tags, $temp_tag);
-							array_push($open_args, $temp_arg);
-							break;
-						}
-					}
-					$current .= $temp.$split_current[$i];
-					$temp = '';
-					while (!empty($temp_opened))
-					{
-						$temp_tag = array_pop($temp_opened);
-						$temp_arg = array_pop($temp_opened_arg);
-						if (empty($temp_arg))
-							$temp .= '['.$temp_tag.']';
-						else
-							$temp .= '['.$temp_tag.'='.$temp_arg.']';
-						array_push($open_tags, $temp_tag);
-						array_push($open_args, $temp_arg);
-					}
-					$current .= $temp;
-				}
-
-				if (array_key_exists($i - 1, $split_current))
-					$current .= $split_current[$i - 1];
-			}
-
-			if (in_array($open_tags[$opened_tag], $tags_trim))
-				$new_text .= pun_trim($current);
-			else
-				$new_text .= $current;
-
-			continue;
-		}
-
-		// Get the name of the tag
-		$current_arg = '';
-		if (strpos($current, '/') === 1)
-		{
-			$current_tag = substr($current, 2, -1);
-		}
-		else if (strpos($current, '=') === false)
-		{
-			$current_tag = substr($current, 1, -1);
-		}
-		else
-		{
-			$current_tag = substr($current, 1, strpos($current, '=')-1);
-			$current_arg = substr($current, strpos($current, '=')+1, -1);
-		}
-		$current_tag = strtolower($current_tag);
-
-		// Is the tag defined?
-		if (!in_array($current_tag, $tags))
-		{
-			// It's not a bbcode tag so we put it on the end and continue
-			if (!$current_nest)
-				$new_text .= $current;
-
-			continue;
-		}
-
-		// We definitely have a bbcode tag
-
-		// Make the tag string lower case
-		if ($equalpos = strpos($current,'='))
-		{
-			// We have an argument for the tag which we don't want to make lowercase
-			if (strlen(substr($current, $equalpos)) == 2)
-			{
-				// Empty tag argument
-				$errors[] = sprintf($lang_common['BBCode error empty attribute'], $current_tag);
-				return false;
-			}
-			$current = strtolower(substr($current, 0, $equalpos)).substr($current, $equalpos);
-		}
-		else
-			$current = strtolower($current);
-
-		// This is if we are currently in a tag which escapes other bbcode such as code
-		// We keep a cound of ignored bbcodes (code tags) so we can nest them, but
-		// only balanced sets of tags can be nested
-		if ($current_ignore)
-		{
-			// Increase the current ignored tags counter
-			if ('['.$current_ignore.']' == $current)
-			{
-				if (!isset($count_ignored[$current_tag]))
-					$count_ignored[$current_tag] = 2;
-				else
-					$count_ignored[$current_tag]++;
-			}
-
-			// Decrease the current ignored tags counter
-			if ('[/'.$current_ignore.']' == $current)
-				$count_ignored[$current_tag]--;
-
-			if ('[/'.$current_ignore.']' == $current && $count_ignored[$current_tag] == 0)
-			{
-				// We've finished the ignored section
-				$current = '[/'.$current_tag.']';
-				$current_ignore = '';
-				$count_ignored = array();
-			}
-
-			$new_text .= $current;
-
-			continue;
-		}
-
-		if ($current_nest)
-		{
-			// We are currently too deeply nested so lets see if we are closing the tag or not
-			if ($current_tag != $current_nest)
-				continue;
-
-			if (substr($current, 1, 1) == '/')
-				$current_depth[$current_nest]--;
-			else
-				$current_depth[$current_nest]++;
-
-			if ($current_depth[$current_nest] <= $tags_nested[$current_nest])
-				$current_nest = '';
-
-			continue;
-		}
-
-		// Check the current tag is allowed here
-		if (!in_array($current_tag, $limit_bbcode) && $current_tag != $open_tags[$opened_tag])
-		{
-			$errors[] = sprintf($lang_common['BBCode error invalid nesting'], $current_tag, $open_tags[$opened_tag]);
-			return false;
-		}
-
-		if (substr($current, 1, 1) == '/')
-		{
-			// This is if we are closing a tag
-			if ($opened_tag == 0 || !in_array($current_tag, $open_tags))
-			{
-				// We tried to close a tag which is not open
-				if (in_array($current_tag, $tags_opened))
-				{
-					$errors[] = sprintf($lang_common['BBCode error no opening tag'], $current_tag);
-					return false;
-				}
-			}
-			else
-			{
-				// Check nesting
-				while (true)
-				{
-					// Nesting is ok
-					if ($open_tags[$opened_tag] == $current_tag)
-					{
-						array_pop($open_tags);
-						array_pop($open_args);
-						$opened_tag--;
-						break;
-					}
-
-					// Nesting isn't ok, try to fix it
-					if (in_array($open_tags[$opened_tag], $tags_closed) && in_array($current_tag, $tags_closed))
-					{
-						if (in_array($current_tag, $open_tags))
-						{
-							$temp_opened = array();
-							$temp_opened_arg = array();
-							$temp = '';
-							while (!empty($open_tags))
-							{
-								$temp_tag = array_pop($open_tags);
-								$temp_arg = array_pop($open_args);
-
-								if (!in_array($temp_tag, $tags_fix))
-								{
-									// We couldn't fix nesting
-									$errors[] = sprintf($lang_common['BBCode error no closing tag'], array_pop($temp_opened));
-									return false;
-								}
-								array_push($temp_opened, $temp_tag);
-								array_push($temp_opened_arg, $temp_arg);
-
-								if ($temp_tag == $current_tag)
-									break;
-								else
-									$temp .= '[/'.$temp_tag.']';
-							}
-							$current = $temp.$current;
-							$temp = '';
-							array_pop($temp_opened);
-							array_pop($temp_opened_arg);
-
-							while (!empty($temp_opened))
-							{
-								$temp_tag = array_pop($temp_opened);
-								$temp_arg = array_pop($temp_opened_arg);
-								if (empty($temp_arg))
-									$temp .= '['.$temp_tag.']';
-								else
-									$temp .= '['.$temp_tag.'='.$temp_arg.']';
-								array_push($open_tags, $temp_tag);
-								array_push($open_args, $temp_arg);
-							}
-							$current .= $temp;
-							$opened_tag--;
-							break;
-						}
-						else
-						{
-							// We couldn't fix nesting
-							$errors[] = sprintf($lang_common['BBCode error no opening tag'], $current_tag);
-							return false;
-						}
-					}
-					else if (in_array($open_tags[$opened_tag], $tags_closed))
-						break;
-					else
-					{
-						array_pop($open_tags);
-						array_pop($open_args);
-						$opened_tag--;
-					}
-				}
-			}
-
-			if (in_array($current_tag, array_keys($tags_nested)))
-			{
-				if (isset($current_depth[$current_tag]))
-					$current_depth[$current_tag]--;
-			}
-
-			if (in_array($open_tags[$opened_tag], array_keys($tags_limit_bbcode)))
-				$limit_bbcode = $tags_limit_bbcode[$open_tags[$opened_tag]];
-			else
-				$limit_bbcode = $tags;
-
-			$new_text .= $current;
-
-			continue;
-		}
-		else
-		{
-			// We are opening a tag
-			if (in_array($current_tag, array_keys($tags_limit_bbcode)))
-				$limit_bbcode = $tags_limit_bbcode[$current_tag];
-			else
-				$limit_bbcode = $tags;
-
-			if (in_array($current_tag, $tags_block) && !in_array($open_tags[$opened_tag], $tags_block) && $opened_tag != 0)
-			{
-				// We tried to open a block tag within a non-block tag
-				$errors[] = sprintf($lang_common['BBCode error invalid nesting'], $current_tag, $open_tags[$opened_tag]);
-				return false;
-			}
-
-			if (in_array($current_tag, $tags_ignore))
-			{
-				// It's an ignore tag so we don't need to worry about what's inside it
-				$current_ignore = $current_tag;
-				$new_text .= $current;
-				continue;
-			}
-
-			// Deal with nested tags
-			if (in_array($current_tag, $open_tags) && !in_array($current_tag, array_keys($tags_nested)))
-			{
-				// We nested a tag we shouldn't
-				$errors[] = sprintf($lang_common['BBCode error invalid self-nesting'], $current_tag);
-				return false;
-			}
-			else if (in_array($current_tag, array_keys($tags_nested)))
-			{
-				// We are allowed to nest this tag
-
-				if (isset($current_depth[$current_tag]))
-					$current_depth[$current_tag]++;
-				else
-					$current_depth[$current_tag] = 1;
-
-				// See if we are nested too deep
-				if ($current_depth[$current_tag] > $tags_nested[$current_tag])
-				{
-					$current_nest = $current_tag;
-					continue;
-				}
-			}
-
-			// Remove quotes from arguments for certain tags
-			if (strpos($current, '=') !== false && in_array($current_tag, $tags_quotes))
-			{
-				$current = preg_replace('%\['.$current_tag.'=("|\'|)(.*?)\\1\]\s*%i', '['.$current_tag.'=$2]', $current);
-			}
-
-			if (in_array($current_tag, array_keys($tags_limit_bbcode)))
-				$limit_bbcode = $tags_limit_bbcode[$current_tag];
-
-			$open_tags[] = $current_tag;
-			$open_args[] = $current_arg;
-			$opened_tag++;
-			$new_text .= $current;
-			continue;
-		}
-	}
-
-	// Check we closed all the tags we needed to
-	foreach ($tags_closed as $check)
-	{
-		if (in_array($check, $open_tags))
-		{
-			// We left an important tag open
-			$errors[] = sprintf($lang_common['BBCode error no closing tag'], $check);
-			return false;
-		}
-	}
-
-	if ($current_ignore)
-	{
-		// We left an ignore tag open
-		$errors[] = sprintf($lang_common['BBCode error no closing tag'], $current_ignore);
-		return false;
-	}
-
-	return $new_text;
-}
-
-
-//
-// Preparse the contents of [list] bbcode
-//
-function preparse_list_tag($content, $type = '*', &$errors)
-{
-	global $lang_common, $re_list;
-
-	if (strlen($type) != 1)
-		$type = '*';
-
-	if (strpos($content,'[list') !== false)
-	{
-		$content = preg_replace($re_list, 'preparse_list_tag(\'$2\', \'$1\', $errors)', $content);
-	}
-
-	$items = explode('[*]', str_replace('\"', '"', $content));
-
-	$content = '';
-	foreach ($items as $item)
-	{
-		if (pun_trim($item) != '')
-			$content .= '[*'."\0".']'.str_replace('[/*]', '', pun_trim($item)).'[/*'."\0".']'."\n";
-	}
-
-	return '[list='.$type.']'."\n".$content.'[/list]';
-}
-
-
-//
-// Truncate URL if longer than 55 characters (add http:// or ftp:// if missing)
-//
-function handle_url_tag($url, $link = '', $bbcode = false)
-{
-	$url = pun_trim($url);
-	$full_url = str_replace(array(' ', '\'', '`', '"'), array('%20', '', '', ''), $url);
-	if (strpos($url, 'www.') === 0) // If it starts with www, we add http://
-		$full_url = 'http://'.$full_url;
-	else if (strpos($url, 'ftp.') === 0) // Else if it starts with ftp, we add ftp://
-		$full_url = 'ftp://'.$full_url;
-	else if (strpos($url, '/') === 0) // Allow for relative URLs that start with a slash
-		$full_url = get_base_url(true).$full_url;
-	else if (!preg_match('#^([a-z0-9]{3,6})://#', $url)) // Else if it doesn't start with abcdef://, we add http://
-		$full_url = 'http://'.$full_url;
-
-	// Ok, not very pretty :-)
-	if ($bbcode)
-	{
-		if ($full_url == $link)
-			return '[url]'.$link.'[/url]';
-		else
-			return '[url='.$full_url.']'.$link.'[/url]';
-	}
-	else
-	{
-		if ($link == '' || $link == $url)
-		{
-			$url = pun_htmlspecialchars_decode($url);
-			$link = utf8_strlen($url) > 55 ? utf8_substr($url, 0 , 39).' âŠ '.utf8_substr($url, -10) : $url;
-			$link = pun_htmlspecialchars($link);
-		}
-		else
-			$link = stripslashes($link);
-
-		return '<a href="'.$full_url.'">'.$link.'</a>';
-	}
-}
-
-
-//
-// Turns an URL from the [img] tag into an <img> tag or a <a href...> tag
-//
-function handle_img_tag($url, $is_signature = false, $alt = null)
-{
-	global $lang_common, $pun_user;
-
-	if ($alt == null)
-		$alt = basename($url);
-
-	$img_tag = '<a href="'.$url.'">&lt;'.$lang_common['Image link'].' - '.$alt.'&gt;</a>';
-
-	if ($is_signature && $pun_user['show_img_sig'] != '0')
-		$img_tag = '<img class="sigimage" src="'.$url.'" alt="'.$alt.'" />';
-	else if (!$is_signature && $pun_user['show_img'] != '0')
-		$img_tag = '<span class="postimg"><img src="'.$url.'" alt="'.$alt.'" /></span>';
-
-	return $img_tag;
-}
-
-
-//
-// Parse the contents of [list] bbcode
-//
-function handle_list_tag($content, $type = '*')
-{
-	global $re_list;
-
-	if (strlen($type) != 1)
-		$type = '*';
-
-	if (strpos($content,'[list') !== false)
-	{
-		$content = preg_replace($re_list, 'handle_list_tag(\'$2\', \'$1\')', $content);
-	}
-
-	$content = preg_replace('#\s*\[\*\](.*?)\[/\*\]\s*#s', '<li><p>$1</p></li>', pun_trim($content));
-
-	if ($type == '*')
-		$content = '<ul>'.$content.'</ul>';
-	else
-		if ($type == 'a')
-			$content = '<ol class="alpha">'.$content.'</ol>';
-		else
-			$content = '<ol class="decimal">'.$content.'</ol>';
-
-	return '</p>'.$content.'<p>';
-}
-
-
-//
-// Convert BBCodes to their HTML equivalent
-//
-function do_bbcode($text, $is_signature = false)
-{
-	global $lang_common, $pun_user, $pun_config, $re_list;
-
-	if (strpos($text, '[quote') !== false)
-	{
-		$text = preg_replace('%\[quote\]\s*%', '</p><div class="quotebox"><blockquote><div><p>', $text);
-		$text = preg_replace('%\[quote=(&quot;|&\#039;|"|\'|)(.*?)\\1\]%se', '"</p><div class=\"quotebox\"><cite>".str_replace(array(\'[\', \'\\"\'), array(\'&#91;\', \'"\'), \'$2\')." ".$lang_common[\'wrote\']."</cite><blockquote><div><p>"', $text);
-		$text = preg_replace('%\s*\[\/quote\]%S', '</p></div></blockquote></div><p>', $text);
-	}
-
-	if (!$is_signature)
-	{
-		$pattern[] = $re_list;
-		$replace[] = 'handle_list_tag(\'$2\', \'$1\')';
-	}
-
-	$pattern[] = '%\[b\](.*?)\[/b\]%ms';
-	$pattern[] = '%\[i\](.*?)\[/i\]%ms';
-	$pattern[] = '%\[u\](.*?)\[/u\]%ms';
-	$pattern[] = '%\[s\](.*?)\[/s\]%ms';
-	$pattern[] = '%\[del\](.*?)\[/del\]%ms';
-	$pattern[] = '%\[ins\](.*?)\[/ins\]%ms';
-	$pattern[] = '%\[em\](.*?)\[/em\]%ms';
-	$pattern[] = '%\[colou?r=([a-zA-Z]{3,20}|\#[0-9a-fA-F]{6}|\#[0-9a-fA-F]{3})](.*?)\[/colou?r\]%ms';
-	$pattern[] = '%\[h\](.*?)\[/h\]%ms';
-
-	$replace[] = '<strong>$1</strong>';
-	$replace[] = '<em>$1</em>';
-	$replace[] = '<span class="bbu">$1</span>';
-	$replace[] = '<span class="bbs">$1</span>';
-	$replace[] = '<del>$1</del>';
-	$replace[] = '<ins>$1</ins>';
-	$replace[] = '<em>$1</em>';
-	$replace[] = '<span style="color: $1">$2</span>';
-	$replace[] = '</p><h5>$1</h5><p>';
-
-	if (($is_signature && $pun_config['p_sig_img_tag'] == '1') || (!$is_signature && $pun_config['p_message_img_tag'] == '1'))
-	{
-		$pattern[] = '%\[img\]((ht|f)tps?://)([^\s<"]*?)\[/img\]%e';
-		$pattern[] = '%\[img=([^\[]*?)\]((ht|f)tps?://)([^\s<"]*?)\[/img\]%e';
-		if ($is_signature)
-		{
-			$replace[] = 'handle_img_tag(\'$1$3\', true)';
-			$replace[] = 'handle_img_tag(\'$2$4\', true, \'$1\')';
-		}
-		else
-		{
-			$replace[] = 'handle_img_tag(\'$1$3\', false)';
-			$replace[] = 'handle_img_tag(\'$2$4\', false, \'$1\')';
-		}
-	}
-
-	$pattern[] = '%\[url\]([^\[]*?)\[/url\]%e';
-	$pattern[] = '%\[url=([^\[]+?)\](.*?)\[/url\]%e';
-	$pattern[] = '%\[email\]([^\[]*?)\[/email\]%';
-	$pattern[] = '%\[email=([^\[]+?)\](.*?)\[/email\]%';
-	$pattern[] = '%\[topic\]([^\[]*?)\[/topic\]%e';
-	$pattern[] = '%\[topic=([^\[]+?)\](.*?)\[/topic\]%e';
-	$pattern[] = '%\[post\]([^\[]*?)\[/post\]%e';
-	$pattern[] = '%\[post=([^\[]+?)\](.*?)\[/post\]%e';
-	$pattern[] = '%\[forum\]([^\[]*?)\[/forum\]%e';
-	$pattern[] = '%\[forum=([^\[]+?)\](.*?)\[/forum\]%e';
-	$pattern[] = '%\[user\]([^\[]*?)\[/user\]%e';
-	$pattern[] = '%\[user=([^\[]+?)\](.*?)\[/user\]%e';
-
-	$replace[] = 'handle_url_tag(\'$1\')';
-	$replace[] = 'handle_url_tag(\'$1\', \'$2\')';
-	$replace[] = '<a href="mailto:$1">$1</a>';
-	$replace[] = '<a href="mailto:$1">$2</a>';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/viewtopic.php?id=$1\')';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/viewtopic.php?id=$1\', \'$2\')';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/viewtopic.php?pid=$1#p$1\')';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/viewtopic.php?pid=$1#p$1\', \'$2\')';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/viewforum.php?id=$1\')';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/viewforum.php?id=$1\', \'$2\')';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/profile.php?id=$1\')';
-	$replace[] = 'handle_url_tag(\''.get_base_url(true).'/profile.php?id=$1\', \'$2\')';
-
-	// This thing takes a while! :)
-	$text = preg_replace($pattern, $replace, $text);
-
-	return $text;
-}
-
-
-//
-// Make hyperlinks clickable
-//
-function do_clickable($text)
-{
-	$text = ' '.$text;
-
-	$text = ucp_preg_replace('%(?<=[\s\]\)])(<)?(\[)?(\()?([\'"]?)(https?|ftp|news){1}://([\p{L}\p{N}\-]+\.([\p{L}\p{N}\-]+\.)*[\p{L}\p{N}]+(:[0-9]+)?(/[^\s\[]*[^\s.,?!\[;:-])?)\4(?(3)(\)))(?(2)(\]))(?(1)(>))(?![^\s]*\[/(?:url|img)\])%uie', 'stripslashes(\'$1$2$3$4\').handle_url_tag(\'$5://$6\', \'$5://$6\', true).stripslashes(\'$4$10$11$12\')', $text);
-	$text = ucp_preg_replace('%(?<=[\s\]\)])(<)?(\[)?(\()?([\'"]?)(www|ftp)\.(([\p{L}\p{N}\-]+\.)*[\p{L}\p{N}]+(:[0-9]+)?(/[^\s\[]*[^\s.,?!\[;:-])?)\4(?(3)(\)))(?(2)(\]))(?(1)(>))(?![^\s]*\[/(?:url|img)\])%uie', 'stripslashes(\'$1$2$3$4\').handle_url_tag(\'$5.$6\', \'$5.$6\', true).stripslashes(\'$4$10$11$12\')', $text);
-
-	return substr($text, 1);
-}
-
-
-//
-// Convert a series of smilies to images
-//
-function do_smilies($text)
-{
-	global $pun_config, $smilies;
-
-	$text = ' '.$text.' ';
-
-	foreach ($smilies as $smiley_text => $smiley_img)
-	{
-		if (strpos($text, $smiley_text) !== false)
-			$text = ucp_preg_replace('%(?<=[>\s])'.preg_quote($smiley_text, '%').'(?=[^\p{L}\p{N}])%um', '<img src="'.pun_htmlspecialchars(get_base_url(true).'/img/smilies/'.$smiley_img).'" width="15" height="15" alt="'.substr($smiley_img, 0, strrpos($smiley_img, '.')).'" />', $text);
-	}
-
-	return substr($text, 1, -1);
-}
-
-
-//
-// Parse message text
-//
-function parse_message($text, $hide_smilies)
-{
-	global $pun_config, $lang_common, $pun_user;
-
-	if ($pun_config['o_censoring'] == '1')
-		$text = censor_words($text);
-
-	// Convert applicable characters to HTML entities
-	$text = pun_htmlspecialchars($text);
-
-	// If the message contains a code tag we have to split it up (text within [code][/code] shouldn't be touched)
-	if (strpos($text, '[code]') !== false && strpos($text, '[/code]') !== false)
-		list($inside, $text) = extract_blocks($text, '[code]', '[/code]', $errors);
-
-	if ($pun_config['p_message_bbcode'] == '1' && strpos($text, '[') !== false && strpos($text, ']') !== false)
-		$text = do_bbcode($text);
-
 	if ($pun_config['o_smilies'] == '1' && $pun_user['show_smilies'] == '1' && $hide_smilies == '0')
 		$text = do_smilies($text);
+
+	if ($pun_config['p_message_bbcode'] == '1' && strpos($text, '[') !== false && strpos($text, ']') !== false)
+	{
+		$text = do_bbcode($text);
+
+		if ($pun_config['p_message_img_tag'] == '1')
+		{
+//			$text = preg_replace('#\[img\]((ht|f)tps?://)([^\s<"]*?)\.(jpg|jpeg|png|gif)\[/img\]#e', 'handle_img_tag(\'$1$3.$4\')', $text);
+			$text = preg_replace('#\[img\]((ht|f)tps?://)([^\s<"]*?)\[/img\]#e', 'handle_img_tag(\'$1$3\')', $text);
+		}
+	}
 
 	// Deal with newlines, tabs and multiple spaces
@@ -868,22 +430,35 @@
 
 	// If we split up the message before we have to concatenate it together again (code tags)
-    if (isset($inside)) {
-        $parts = explode("\1", $text);
-        $text = '';
-        foreach ($parts as $i => $part)
-        {
-            $text .= $part;
-            if (isset($inside[$i]))
-            {
-                $num_lines = (substr_count($inside[$i], "\n"));
-                $text .= '</p><div class="codebox"><pre'.(($num_lines > 28) ? ' class="vscroll"' : '').'><code>'.pun_trim($inside[$i], "\n\r").'</code></pre></div><p>';
-            }
-        }
-    }
+	if (isset($inside))
+	{
+		$outside = explode('<">', $text);
+		$text = '';
+
+		$num_tokens = count($outside);
+
+		for ($i = 0; $i < $num_tokens; ++$i)
+		{
+			$text .= $outside[$i];
+			if (isset($inside[$i]))
+			{
+				$num_lines = ((substr_count($inside[$i], "\n")) + 3) * 1.5;
+				$height_str = ($num_lines > 35) ? '35em' : $num_lines.'em';
+				$text .= '</p><div class="codebox"><div class="incqbox"><h4>'.$lang_common['Code'].':</h4><div class="scrollbox" style="height: '.$height_str.'"><pre>'.$inside[$i].'</pre></div></div></div><p>';
+			}
+		}
+	}
 
 	// Add paragraph tag around post, but make sure there are no empty paragraphs
-	$text = preg_replace('%<br />\s*?<br />((\s*<br />)*)%i', "</p>$1<p>", $text);
-	$text = str_replace('<p><br />', '<p>', $text);
 	$text = str_replace('<p></p>', '', '<p>'.$text.'</p>');
+
+	// Mod: Flash MP3 Player (8 nouvelles lignes suivent)
+	$player_url     = 'dewplayer-multi.swf';
+	$player_bgcolor = 'ffffff';
+	$player_width   = 240;
+	$player_height  = 20;
+	$player_param   = '?bgcolor='.$player_bgcolor.'&amp;mp3=$1';  // Pour plus d'options: http://www.alsacreations.fr/?dewplayer
+	$player_alternative = '<strong>Flash non dÃ©tÃ©ctÃ©</strong>';
+	$player_code = "\n\t\t\t\t\t<object type=\"application/x-shockwave-flash\" data=\"".$player_url.$player_param."\" width=\"".$player_width."\" height=\"".$player_height."\">\n\t\t\t\t\t  <param name=\"movie\" value=\"".$player_url.$player_param."\" />\n\t\t\t\t\t  <param name=\"bgcolor\" value=\"#".$player_bgcolor."\" />\n\t\t\t\t\t  ".$player_alternative."\n\t\t\t\t\t</object>\n\t\t\t\t\t";
+	$text = preg_replace("/\[mp3 url=([^ ]+)\]/", $player_code, $text);
 
 	return $text;
@@ -901,13 +476,22 @@
 		$text = censor_words($text);
 
-	// Convert applicable characters to HTML entities
 	$text = pun_htmlspecialchars($text);
 
+	if ($pun_config['o_make_links'] == '1')
+		$text = do_clickable($text);
+
+	if ($pun_config['o_smilies_sig'] == '1' && $pun_user['show_smilies'] != '0')
+		$text = do_smilies($text);
+
 	if ($pun_config['p_sig_bbcode'] == '1' && strpos($text, '[') !== false && strpos($text, ']') !== false)
-		$text = do_bbcode($text, true);
-
-	if ($pun_config['o_smilies_sig'] == '1' && $pun_user['show_smilies'] == '1')
-		$text = do_smilies($text);
-
+	{
+		$text = do_bbcode($text);
+
+		if ($pun_config['p_sig_img_tag'] == '1')
+		{
+//			$text = preg_replace('#\[img\]((ht|f)tps?://)([^\s<"]*?)\.(jpg|jpeg|png|gif)\[/img\]#e', 'handle_img_tag(\'$1$3.$4\', true)', $text);
+			$text = preg_replace('#\[img\]((ht|f)tps?://)([^\s<"]*?)\[/img\]#e', 'handle_img_tag(\'$1$3\', true)', $text);
+		}
+	}
 
 	// Deal with newlines, tabs and multiple spaces
@@ -916,9 +500,5 @@
 	$text = str_replace($pattern, $replace, $text);
 
-	// Add paragraph tag around post, but make sure there are no empty paragraphs
-	$text = preg_replace('%<br />\s*?<br />((\s*<br />)*)%i', "</p>$1<p>", $text);
-	$text = str_replace('<p><br />', '<p>', $text);
-	$text = str_replace('<p></p>', '', '<p>'.$text.'</p>');
-
 	return $text;
 }
+?>
Index: trunk/web/punbb/include/search_idx.php
===================================================================
--- trunk/web/punbb/include/search_idx.php	(revision 10)
+++ trunk/web/punbb/include/search_idx.php	(revision 1)
@@ -1,12 +1,29 @@
 <?php
-
-/**
- * Copyright (C) 2008-2011 FluxBB
- * based on code by Rickard Andersson copyright (C) 2002-2008 PunBB
- * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
- */
+/***********************************************************************
+
+  Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
+
+  This file is part of PunBB.
+
+  PunBB 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.
+
+  PunBB 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
+
+************************************************************************/
+
 
 // The contents of this file are very much inspired by the file functions_search.php
-// from the phpBB Group forum software phpBB2 (http://www.phpbb.com)
+// from the phpBB Group forum software phpBB2 (http://www.phpbb.com). 
 
 
@@ -16,138 +33,50 @@
 
 
-// Make a regex that will match CJK or Hangul characters
-define('PUN_CJK_HANGUL_REGEX', '['.
-	'\x{1100}-\x{11FF}'.		// Hangul Jamo							1100-11FF		(http://www.fileformat.info/info/unicode/block/hangul_jamo/index.htm)
-	'\x{3130}-\x{318F}'.		// Hangul Compatibility Jamo			3130-318F		(http://www.fileformat.info/info/unicode/block/hangul_compatibility_jamo/index.htm)
-	'\x{AC00}-\x{D7AF}'.		// Hangul Syllables						AC00-D7AF		(http://www.fileformat.info/info/unicode/block/hangul_syllables/index.htm)
-
-	// Hiragana
-	'\x{3040}-\x{309F}'.		// Hiragana								3040-309F		(http://www.fileformat.info/info/unicode/block/hiragana/index.htm)
-
-	// Katakana
-	'\x{30A0}-\x{30FF}'.		// Katakana								30A0-30FF		(http://www.fileformat.info/info/unicode/block/katakana/index.htm)
-	'\x{31F0}-\x{31FF}'.		// Katakana Phonetic Extensions			31F0-31FF		(http://www.fileformat.info/info/unicode/block/katakana_phonetic_extensions/index.htm)
-
-	// CJK Unified Ideographs	(http://en.wikipedia.org/wiki/CJK_Unified_Ideographs)
-	'\x{2E80}-\x{2EFF}'.		// CJK Radicals Supplement				2E80-2EFF		(http://www.fileformat.info/info/unicode/block/cjk_radicals_supplement/index.htm)
-	'\x{2F00}-\x{2FDF}'.		// Kangxi Radicals						2F00-2FDF		(http://www.fileformat.info/info/unicode/block/kangxi_radicals/index.htm)
-	'\x{2FF0}-\x{2FFF}'.		// Ideographic Description Characters	2FF0-2FFF		(http://www.fileformat.info/info/unicode/block/ideographic_description_characters/index.htm)
-	'\x{3000}-\x{303F}'.		// CJK Symbols and Punctuation			3000-303F		(http://www.fileformat.info/info/unicode/block/cjk_symbols_and_punctuation/index.htm)
-	'\x{31C0}-\x{31EF}'.		// CJK Strokes							31C0-31EF		(http://www.fileformat.info/info/unicode/block/cjk_strokes/index.htm)
-	'\x{3200}-\x{32FF}'.		// Enclosed CJK Letters and Months		3200-32FF		(http://www.fileformat.info/info/unicode/block/enclosed_cjk_letters_and_months/index.htm)
-	'\x{3400}-\x{4DBF}'.		// CJK Unified Ideographs Extension A	3400-4DBF		(http://www.fileformat.info/info/unicode/block/cjk_unified_ideographs_extension_a/index.htm)
-	'\x{4E00}-\x{9FFF}'.		// CJK Unified Ideographs				4E00-9FFF		(http://www.fileformat.info/info/unicode/block/cjk_unified_ideographs/index.htm)
-	'\x{20000}-\x{2A6DF}'.		// CJK Unified Ideographs Extension B	20000-2A6DF		(http://www.fileformat.info/info/unicode/block/cjk_unified_ideographs_extension_b/index.htm)
-']');
-
-
 //
 // "Cleans up" a text string and returns an array of unique words
 // This function depends on the current locale setting
 //
-function split_words($text, $idx)
+function split_words($text)
 {
-	// Remove BBCode
-	$text = preg_replace('%\[/?(b|u|s|ins|del|em|i|h|colou?r|quote|code|img|url|email|list)(?:\=[^\]]*)?\]%', ' ', $text);
-
-	// Remove any apostrophes or dashes which aren't part of words
-	$text = substr(ucp_preg_replace('%((?<=[^\p{L}\p{N}])[\'\-]|[\'\-](?=[^\p{L}\p{N}]))%u', '', ' '.$text.' '), 1, -1);
-
-	// Remove punctuation and symbols (actually anything that isn't a letter or number), allow apostrophes and dashes (and % * if we aren't indexing)
-	$text = ucp_preg_replace('%(?![\'\-'.($idx ? '' : '\%\*').'])[^\p{L}\p{N}]+%u', ' ', $text);
-
-	// Replace multiple whitespace or dashes
-	$text = preg_replace('%(\s){2,}%u', '\1', $text);
+	global $pun_user;
+	static $noise_match, $noise_replace, $stopwords;
+
+	if (empty($noise_match))
+	{
+		$noise_match = array('[quote', '[code', '[url', '[img', '[email', '[color', '[colour', 'quote]', 'code]', 'url]', 'img]', 'email]', 'color]', 'colour]', '^', '$', '&', '(', ')', '<', '>', '`', '\'', '"', '|', ',', '@', '_', '?', '%', '~', '+', '[', ']', '{', '}', ':', '\\', '/', '=', '#', ';', '!', '*');
+		$noise_replace = array('',       '',      '',     '',     '',       '',       '',        '',       '',      '',     '',     '',       '',       '',        ' ', ' ', ' ', ' ', ' ', ' ', ' ', '',  '',   ' ', ' ', ' ', ' ', '',  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '' ,  ' ', ' ', ' ', ' ', ' ', ' ');
+
+		$stopwords = (array)@file(PUN_ROOT.'lang/'.$pun_user['language'].'/stopwords.txt');
+		$stopwords = array_map('trim', $stopwords);
+	}
+
+	// Clean up
+	$patterns[] = '#&[\#a-z0-9]+?;#i';
+	$patterns[] = '#\b[\w]+:\/\/[a-z0-9\.\-]+(\/[a-z0-9\?\.%_\-\+=&\/~]+)?#';
+	$patterns[] = '#\[\/?[a-z\*=\+\-]+(\:?[0-9a-z]+)?:[a-z0-9]{10,}(\:[a-z0-9]+)?=?.*?\]#';
+	$text = preg_replace($patterns, ' ', ' '.strtolower($text).' ');
+
+	// Filter out junk
+	$text = str_replace($noise_match, $noise_replace, $text);
+
+	// Strip out extra whitespace between words
+	$text = trim(preg_replace('#\s+#', ' ', $text));
 
 	// Fill an array with all the words
-	$words = array_unique(explode(' ', $text));
-
-	// Remove any words that should not be indexed
-	foreach ($words as $key => $value)
-	{
-		// If the word shouldn't be indexed, remove it
-		if (!validate_search_word($value, $idx))
-			unset($words[$key]);
-	}
-
-	return $words;
-}
-
-
-//
-// Checks if a word is a valid searchable word
-//
-function validate_search_word($word, $idx)
-{
-	static $stopwords;
-
-	// If the word is a keyword we don't want to index it, but we do want to be allowed to search it
-	if (is_keyword($word))
-		return !$idx;
-
-	if (!isset($stopwords))
-	{
-		if (file_exists(FORUM_CACHE_DIR.'cache_stopwords.php'))
-			include FORUM_CACHE_DIR.'cache_stopwords.php';
-
-		if (!defined('PUN_STOPWORDS_LOADED'))
-		{
-			if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
-				require PUN_ROOT.'include/cache.php';
-
-			generate_stopwords_cache();
-			require FORUM_CACHE_DIR.'cache_stopwords.php';
-		}
-	}
-
-	// If it is a stopword it isn't valid
-	if (in_array($word, $stopwords))
-		return false;
-
-	// If the word if CJK we don't want to index it, but we do want to be allowed to search it
-	if (is_cjk($word))
-		return !$idx;
-
-	// Check the word is within the min/max length
-	$num_chars = pun_strlen($word);
-	return $num_chars >= PUN_SEARCH_MIN_WORD && $num_chars <= PUN_SEARCH_MAX_WORD;
-}
-
-
-//
-// Check a given word is a search keyword.
-//
-function is_keyword($word)
-{
-	return $word == 'and' || $word == 'or' || $word == 'not';
-}
-
-
-//
-// Check if a given word is CJK or Hangul.
-//
-function is_cjk($word)
-{
-	return preg_match('%^'.PUN_CJK_HANGUL_REGEX.'+$%u', $word) ? true : false;
-}
-
-
-//
-// Strip [img] [url] and [email] out of the message so we don't index their contents
-//
-function strip_bbcode($text)
-{
-	static $patterns;
-
-	if (!isset($patterns))
-	{
-		$patterns = array(
-			'%\[img=([^\]]*+)\]([^[]*+)\[/img\]%'									=>	'$2 $1',	// Keep the url and description
-			'%\[(url|email)=([^\]]*+)\]([^[]*+(?:(?!\[/\1\])\[[^[]*+)*)\[/\1\]%'	=>	'$2 $3',	// Keep the url and text
-			'%\[(img|url|email)\]([^[]*+(?:(?!\[/\1\])\[[^[]*+)*)\[/\1\]%'			=>	'$2',		// Keep the url
-		);
-	}
-
-	return preg_replace(array_keys($patterns), array_values($patterns), $text);
+	$words = explode(' ', $text);
+
+	if (!empty($words))
+	{
+		while (list($i, $word) = @each($words))
+		{
+			$words[$i] = trim($word, '.');
+			$num_chars = pun_strlen($word);
+
+			if ($num_chars < 3 || $num_chars > 20 || in_array($word, $stopwords))
+				unset($words[$i]);
+		}
+	}
+
+	return array_unique($words);
 }
 
@@ -160,17 +89,11 @@
 	global $db_type, $db;
 
-	$message = utf8_strtolower($message);
-	$subject = utf8_strtolower($subject);
-
-	// Remove any bbcode that we shouldn't index
-	$message = strip_bbcode($message);
-
 	// Split old and new post/subject to obtain array of 'words'
-	$words_message = split_words($message, true);
-	$words_subject = ($subject) ? split_words($subject, true) : array();
+	$words_message = split_words($message);
+	$words_subject = ($subject) ? split_words($subject) : array();
 
 	if ($mode == 'edit')
 	{
-		$result = $db->query('SELECT w.id, w.word, m.subject_match FROM '.$db->prefix.'search_words AS w INNER JOIN '.$db->prefix.'search_matches AS m ON w.id=m.word_id WHERE m.post_id='.$post_id, true) or error('Unable to fetch search index words', __FILE__, __LINE__, $db->error());
+		$result = $db->query('SELECT w.id, w.word, m.subject_match FROM '.$db->prefix.'search_words AS w INNER JOIN '.$db->prefix.'search_matches AS m ON w.id=m.word_id WHERE m.post_id='.$post_id, true) or error('Impossible de retrouver les mots index de recherches', __FILE__, __LINE__, $db->error());
 
 		// Declare here to stop array_keys() and array_diff() from complaining if not set
@@ -207,5 +130,5 @@
 	if (!empty($unique_words))
 	{
-		$result = $db->query('SELECT id, word FROM '.$db->prefix.'search_words WHERE word IN(\''.implode('\',\'', array_map(array($db, 'escape'), $unique_words)).'\')', true) or error('Unable to fetch search index words', __FILE__, __LINE__, $db->error());
+		$result = $db->query('SELECT id, word FROM '.$db->prefix.'search_words WHERE word IN('.implode(',', preg_replace('#^(.*)$#', '\'\1\'', $unique_words)).')', true) or error('Impossible de retrouver les mots index de recherches', __FILE__, __LINE__, $db->error());
 
 		$word_ids = array();
@@ -224,12 +147,10 @@
 				case 'mysql':
 				case 'mysqli':
-				case 'mysql_innodb':
-				case 'mysqli_innodb':
-					$db->query('INSERT INTO '.$db->prefix.'search_words (word) VALUES(\''.implode('\'),(\'', array_map(array($db, 'escape'), $new_words)).'\')');
+					$db->query('INSERT INTO '.$db->prefix.'search_words (word) VALUES'.implode(',', preg_replace('#^(.*)$#', '(\'\1\')', $new_words))) or error('Impossible d\'ajouter les mots index de recherche', __FILE__, __LINE__, $db->error());
 					break;
 
 				default:
-					foreach ($new_words as $word)
-						$db->query('INSERT INTO '.$db->prefix.'search_words (word) VALUES(\''.$db->escape($word).'\')');
+					while (list(, $word) = @each($new_words))
+						$db->query('INSERT INTO '.$db->prefix.'search_words (word) VALUES(\''.$word.'\')') or error('Impossible d\'ajouter les mots index de recherche', __FILE__, __LINE__, $db->error());
 					break;
 			}
@@ -240,5 +161,5 @@
 
 	// Delete matches (only if editing a post)
-	foreach ($words['del'] as $match_in => $wordlist)
+	while (list($match_in, $wordlist) = @each($words['del']))
 	{
 		$subject_match = ($match_in == 'subject') ? 1 : 0;
@@ -247,18 +168,18 @@
 		{
 			$sql = '';
-			foreach ($wordlist as $word)
+			while (list(, $word) = @each($wordlist))
 				$sql .= (($sql != '') ? ',' : '').$cur_words[$match_in][$word];
 
-			$db->query('DELETE FROM '.$db->prefix.'search_matches WHERE word_id IN('.$sql.') AND post_id='.$post_id.' AND subject_match='.$subject_match) or error('Unable to delete search index word matches', __FILE__, __LINE__, $db->error());
+			$db->query('DELETE FROM '.$db->prefix.'search_matches WHERE word_id IN('.$sql.') AND post_id='.$post_id.' AND subject_match='.$subject_match) or error('Impossible de supprimer des mots index de recherche', __FILE__, __LINE__, $db->error());
 		}
 	}
 
 	// Add new matches
-	foreach ($words['add'] as $match_in => $wordlist)
+	while (list($match_in, $wordlist) = @each($words['add']))
 	{
 		$subject_match = ($match_in == 'subject') ? 1 : 0;
 
 		if (!empty($wordlist))
-			$db->query('INSERT INTO '.$db->prefix.'search_matches (post_id, word_id, subject_match) SELECT '.$post_id.', id, '.$subject_match.' FROM '.$db->prefix.'search_words WHERE word IN(\''.implode('\',\'', array_map(array($db, 'escape'), $wordlist)).'\')') or error('Unable to insert search index word matches', __FILE__, __LINE__, $db->error());
+			$db->query('INSERT INTO '.$db->prefix.'search_matches (post_id, word_id, subject_match) SELECT '.$post_id.', id, '.$subject_match.' FROM '.$db->prefix.'search_words WHERE word IN('.implode(',', preg_replace('#^(.*)$#', '\'\1\'', $wordlist)).')') or error('Impossible d\'ajouter les correspondances index de recherche', __FILE__, __LINE__, $db->error());
 	}
 
@@ -278,8 +199,6 @@
 		case 'mysql':
 		case 'mysqli':
-		case 'mysql_innodb':
-		case 'mysqli_innodb':
-		{
-			$result = $db->query('SELECT word_id FROM '.$db->prefix.'search_matches WHERE post_id IN('.$post_ids.') GROUP BY word_id') or error('Unable to fetch search index word match', __FILE__, __LINE__, $db->error());
+		{
+			$result = $db->query('SELECT word_id FROM '.$db->prefix.'search_matches WHERE post_id IN('.$post_ids.') GROUP BY word_id') or error('Impossible de retrouver les correspondances de mots index de recherche', __FILE__, __LINE__, $db->error());
 
 			if ($db->num_rows($result))
@@ -289,5 +208,5 @@
 					$word_ids .= ($word_ids != '') ? ','.$row[0] : $row[0];
 
-				$result = $db->query('SELECT word_id FROM '.$db->prefix.'search_matches WHERE word_id IN('.$word_ids.') GROUP BY word_id HAVING COUNT(word_id)=1') or error('Unable to fetch search index word match', __FILE__, __LINE__, $db->error());
+				$result = $db->query('SELECT word_id FROM '.$db->prefix.'search_matches WHERE word_id IN('.$word_ids.') GROUP BY word_id HAVING COUNT(word_id)=1') or error('Impossible de retrouver les correspondances de mots index de recherche', __FILE__, __LINE__, $db->error());
 
 				if ($db->num_rows($result))
@@ -297,5 +216,5 @@
 						$word_ids .= ($word_ids != '') ? ','.$row[0] : $row[0];
 
-					$db->query('DELETE FROM '.$db->prefix.'search_words WHERE id IN('.$word_ids.')') or error('Unable to delete search index word', __FILE__, __LINE__, $db->error());
+					$db->query('DELETE FROM '.$db->prefix.'search_words WHERE id IN('.$word_ids.')') or error('Impossible de supprimer des mots index de recherche', __FILE__, __LINE__, $db->error());
 				}
 			}
@@ -305,8 +224,8 @@
 
 		default:
-			$db->query('DELETE FROM '.$db->prefix.'search_words WHERE id IN(SELECT word_id FROM '.$db->prefix.'search_matches WHERE word_id IN(SELECT word_id FROM '.$db->prefix.'search_matches WHERE post_id IN('.$post_ids.') GROUP BY word_id) GROUP BY word_id HAVING COUNT(word_id)=1)') or error('Unable to delete from search index', __FILE__, __LINE__, $db->error());
+			$db->query('DELETE FROM '.$db->prefix.'search_words WHERE id IN(SELECT word_id FROM '.$db->prefix.'search_matches WHERE word_id IN(SELECT word_id FROM '.$db->prefix.'search_matches WHERE post_id IN('.$post_ids.') GROUP BY word_id) GROUP BY word_id HAVING COUNT(word_id)=1)') or error('Impossible de supprimer depuis l\'index de recherche', __FILE__, __LINE__, $db->error());
 			break;
 	}
 
-	$db->query('DELETE FROM '.$db->prefix.'search_matches WHERE post_id IN('.$post_ids.')') or error('Unable to delete search index word match', __FILE__, __LINE__, $db->error());
+	$db->query('DELETE FROM '.$db->prefix.'search_matches WHERE post_id IN('.$post_ids.')') or error('Impossible de supprimer des correspondances de mots index de recherche', __FILE__, __LINE__, $db->error());
 }
Index: trunk/web/punbb/include/template/admin.tpl
===================================================================
--- trunk/web/punbb/include/template/admin.tpl	(revision 10)
+++ trunk/web/punbb/include/template/admin.tpl	(revision 1)
@@ -1,14 +1,13 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<pun_language>" lang="<pun_language>" dir="<pun_content_direction>">
+
+<html dir="<pun_content_direction>">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta http-equiv="Content-Type" content="text/html; charset=<pun_char_encoding>" />
 <pun_head>
 </head>
-
 <body>
 
+<div id="punwrap">
 <div id="punadmin" class="pun">
-<div class="top-box"><div><!-- Top Corners --></div></div>
-<div class="punwrap">
 
 <div id="brdheader" class="block">
@@ -25,12 +24,9 @@
 <pun_announcement>
 
-<div id="brdmain">
 <pun_main>
-</div>
 
 <pun_footer>
 
 </div>
-<div class="end-box"><div><!-- Bottom Corners --></div></div>
 </div>
 
Index: trunk/web/punbb/include/template/help.tpl
===================================================================
--- trunk/web/punbb/include/template/help.tpl	(revision 10)
+++ trunk/web/punbb/include/template/help.tpl	(revision 1)
@@ -1,21 +1,17 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<pun_language>" lang="<pun_language>" dir="<pun_content_direction>">
+
+<html dir="<pun_content_direction>">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta http-equiv="Content-Type" content="text/html; charset=<pun_char_encoding>" />
 <pun_head>
 </head>
-
 <body>
 
-<div id="punhelp" class="pun">
-<div class="top-box"><div><!-- Top Corners --></div></div>
-<div class="punwrap">
+<div id="punwrap">
+<div id="helpfile" class="pun">
 
-<div id="brdmain">
 <pun_main>
-</div>
 
 </div>
-<div class="end-box"><div><!-- Bottom Corners --></div></div>
 </div>
 
Index: trunk/web/punbb/include/template/index.html
===================================================================
--- trunk/web/punbb/include/template/index.html	(revision 10)
+++ trunk/web/punbb/include/template/index.html	(revision 1)
@@ -1,1 +1,8 @@
-<html><head><title>.</title></head><body>.</body></html>
+<html>
+<head>
+<title>.</title>
+</head>
+<body>
+.
+</body>
+</html>
Index: trunk/web/punbb/include/template/main.tpl
===================================================================
--- trunk/web/punbb/include/template/main.tpl	(revision 10)
+++ trunk/web/punbb/include/template/main.tpl	(revision 1)
@@ -1,19 +1,15 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<pun_language>" lang="<pun_language>" dir="<pun_content_direction>">
+
+<html dir="<pun_content_direction>">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta http-equiv="Content-Type" content="text/html; charset=<pun_char_encoding>" />
 <pun_head>
 </head>
-
 <body>
-
+<div id="punwrap">
 <div id="pun<pun_page>" class="pun">
-<div class="top-box"><div><!-- Top Corners --></div></div>
-<div class="punwrap">
-
-<div id="brdheader" class="block">
+  <div id="brdheader" class="block">
 	<div class="box">
 		<div id="brdtitle" class="inbox">
-			<pun_title>
 			<pun_desc>
 		</div>
@@ -21,16 +17,13 @@
 		<pun_status>
 	</div>
-</div>
+  </div>
 
 <pun_announcement>
 
-<div id="brdmain">
 <pun_main>
-</div>
 
 <pun_footer>
 
 </div>
-<div class="end-box"><div><!-- Bottom corners --></div></div>
 </div>
 
Index: trunk/web/punbb/include/template/maintenance.tpl
===================================================================
--- trunk/web/punbb/include/template/maintenance.tpl	(revision 10)
+++ trunk/web/punbb/include/template/maintenance.tpl	(revision 1)
@@ -1,21 +1,24 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<pun_language>" lang="<pun_language>" dir="<pun_content_direction>">
+
+<html dir="<pun_content_direction>">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta http-equiv="Content-Type" content="text/html; charset=<pun_char_encoding>" />
 <pun_head>
 </head>
-
 <body>
 
+<div id="punwrap">
 <div id="punmaint" class="pun">
-<div class="top-box"><div><!-- Top Corners --></div></div>
-<div class="punwrap">
 
-<div id="brdmain">
-<pun_maint_main>
+<div class="block">
+	<h2><pun_maint_heading></h2>
+	<div class="box">
+		<div class="inbox">
+			<p><pun_maint_message></p>
+		</div>
+	</div>
 </div>
 
 </div>
-<div class="end-box"><div><!-- Bottom Corners --></div></div>
 </div>
 
Index: trunk/web/punbb/include/template/redirect.tpl
===================================================================
--- trunk/web/punbb/include/template/redirect.tpl	(revision 10)
+++ trunk/web/punbb/include/template/redirect.tpl	(revision 1)
@@ -1,17 +1,21 @@
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<pun_language>" lang="<pun_language>" dir="<pun_content_direction>">
+
+<html dir="<pun_content_direction>">
 <head>
-<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta http-equiv="Content-Type" content="text/html; charset=<pun_char_encoding>" />
 <pun_head>
 </head>
-
 <body>
 
+<div id="punwrap">
 <div id="punredirect" class="pun">
-<div class="top-box"><div><!-- Top Corners --></div></div>
-<div class="punwrap">
 
-<div id="brdmain">
-<pun_redir_main>
+<div class="block">
+	<h2><pun_redir_heading></h2>
+	<div class="box">
+		<div class="inbox">
+			<p><pun_redir_text></p>
+		</div>
+	</div>
 </div>
 
@@ -19,5 +23,4 @@
 
 </div>
-<div class="end-box"><div><!-- Bottom Corners --></div></div>
 </div>
 
