Index: branches/rsr.v5.1.dev/web/punbb/include/dblayer/sqlite.php
===================================================================
--- branches/rsr.v5.1.dev/web/punbb/include/dblayer/sqlite.php	(revision 1)
+++ branches/rsr.v5.1.dev/web/punbb/include/dblayer/sqlite.php	(revision 3)
@@ -1,26 +1,9 @@
 <?php
-/***********************************************************************
-
-  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
-
-************************************************************************/
-
+
+/**
+ * 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 SQLite
@@ -42,4 +25,10 @@
 	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)
@@ -135,12 +124,16 @@
 
 
-	function result($query_id = 0, $row = 0)
+	function result($query_id = 0, $row = 0, $col = 0)
 	{
 		if ($query_id)
 		{
-			if ($row != 0)
-				@sqlite_seek($query_id, $row);
-
-			return @current(@sqlite_current($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];
 		}
 		else
@@ -157,13 +150,13 @@
 			{
 				// Horrible hack to get rid of table names and table aliases from the array keys
-				while (list($key, $value) = @each($cur_row))
+				foreach ($cur_row as $key => $value)
 				{
-				    $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;
+					}
 				}
 			}
@@ -190,5 +183,5 @@
 	function affected_rows()
 	{
-		return ($this->query_result) ? @sqlite_changes($this->query_result) : false;
+		return ($this->link_id) ? @sqlite_changes($this->link_id) : false;
 	}
 
@@ -220,5 +213,5 @@
 	function escape($str)
 	{
-		return sqlite_escape_string($str);
+		return is_array($str) ? '' : sqlite_escape_string($str);
 	}
 
@@ -251,3 +244,324 @@
 			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;
+	}
 }
