All pastes #368314 Raw Edit

Mine

public php v1 · immutable
#368314 ·published 2007-02-22 23:52 UTC
rendered paste body
<?php/** * ShuttleBB DBAL - *  * This database abstaction layer was written, benchmarked, and tested by Dean Newman; * it is designed and optimized for maximum performance and security. *  * The purpose of this package is to provide support to many different databases without * the need of seperate releases and/or increased lines of code. *  * This package depends on a couple of vital includes from the shuttlebb core including * but not limited to: Caching, Constants, Configuration and The Error Handler. *  * You are permitted to use this system in your own projects for personal use only, * however the ShuttleBB Development Team will not be responcible for support, security * or any other issues that may occur. *  * The main interface class also contains a number of small methods to make sql queries * and database interface much easier and cleaner; these include field management, simple * updating, simple inserts and many other useful methods and functions. *  * $Id: class_dbal.php 66 2006-12-03 13:45:51Z afterlife69 $ * $Date: 2006-12-04 00:45:51 +1100 (Mon, 04 Dec 2006) $ * $Rev: 66 $ *//** * @todo Caching Object(s) <<< *  * The new caching object should include seperate subclasses for different handling of caching, * the main object will be just a shell. *  * The following are used in this API: * 	- cache::cache_sql::store($cache_name); * 	- cache::cache_sql::load($cache_name); *  * >>> *//** * Prevent include errors */if ( class_exists ( 'dbal' ) ){	return;}/** * Secure the class */if ( ! defined ( 'IN_SBB' ) ){	trigger_error('Error_Security_Include');	exit;}/** * Database Abstraction Layer *  * This wrapper handles all the caching and debugging jobs, * while interfacing with a specific database layer. *  * @package		shuttlebb * @subpackage	dbal * @author		Dean Newman * @copyright	&copy; 2006, ShuttleBB Development Team * @access		Public */class dbal{	var $layer;	var $error;	var $cache;	var $stats;	/**	 * Constructor	 *	 * @param	string	$db_type	The name of the db layer to use	 * @return	dbal	 */	function dbal ( $db_type = DB_LAYER )	{		// Typecast the DB layer for error prevention		$db_type	= (string) $db_type;		$db_layer	= (string) 'dbal_' . $db_type;				// Ensure the file exists		if ( ! file_exists ( INC_PATH . 'dbal/' . $db_layer . PHPEX ) )		{			// If not, die			trigger_error('Error_DB_Include');			exit;		}				// Include layer and ensure file is secure		include ( INC_PATH . 'dbal/' . $db_layer . PHPEX );		if ( ! class_exists ( $db_layer ) )		{			// If not, die			trigger_error('Error_DB_Include,Error_DB_Security_Include');			exit;		}				// Init the object as a subclass		$this->layer = new $db_layer();				// Fill some values		$this->stats = array(			'queries'	=> 0,			'cached'	=> 0,		);		$this->cache = array();		$this->error = array();	}		/**	 * Connects to the database server	 *	 * @param	string	$db_user		Username for db server	 * @param	string	$db_pass		Password for db server	 * @param	string	$db_name		Name of the database	 * @param	string	$db_server		The db server to connect to	 * @param	boolean	$db_persistant	Use a persistant connection?	 * @return	boolean	 */	function sql_connect($db_user, $db_pass, $db_name, $db_server, $db_persistant)	{		// Attempt to the connection		$connection = $this->layer->sql_connect($db_user, $db_pass, $db_name, $db_server, $db_persistant);				// Check if it connected		if ( ! $connection )		{			// If not, error.			trigger_error('Error_DB_Connect');		}				// Return connection identifier		return $connection;	}		/**	 * Close the database connection	 *	 * @return	boolean	 */	function sql_close()	{		// Close the db connection		return $this->layer->sql_close();	}		/**	 * Execute an sql query, Cache the result if needed, Load the result	 * if available.	 *	 * @global	object	$cache		Cache object included for sql caching	 * @param	string	$sql		The sql query to be executed	 * @param	string	$cache_name	The cache handle for this query	 * @return	mixed	 */	function sql_query($sql, $cache_name = false)	{		global $cache;				// Increment the query counter.		$this->stats['queries']++;				// Check for caching		if ( $cache_name != false && class_exists ( 'cache_handler' ) )		{			// Allow the query to be cached without a handle			if ( gettype($cache_name) == 'boolean' )			{				// The handle becomes an md5 string of the sql				$cache_name = md5($sql);			}						// If not, execute and handle bad results.			if ( ! $result = $this->layer->sql_query($sql) )			{				// Report a query error.				trigger_error('Error_DB_Query');			}						// Attempt to load cache			if ( ! $this->cache[$cache_name] = $cache->sql->load($cache_name) )			{				// If load fails, free var				$this->sql_freeresult($result);			}						// Only execute if not already set			if ( ! isset ( $this->cache[$cache_name] ) )			{				// Handle caching if needed				$cache[$cache_name] = $this->sql_fetchrowset($result, 'assoc');				$cache->sql->store($cache_name, $cache[$cache_name]);								// Free the result				$this->sql_freeresult($result);			}						// Return as cache handle			$result = $cache_name;						// Increment cached queries			$this->stats['cached']++;		}				// Check if cache loaded		if ( ! isset ( $result ) )		{			// If not, execute and handle bad results.			if ( ! $result = $this->layer->sql_query($sql) )			{				// Report a query error.				trigger_error('Error_DB_Query(' . $this->layer->sql_error($result) . ',' . $sql . ')');			}		}				// Return Identifier		return $result;	}		/**	 * Get a database result row	 *	 * @param	mixed	$resource	Either the query resource identifier or the cache handle	 * @param	string	$type		The type of output to return (assoc, object or index)	 * @return	mixed	 */	function sql_fetchrow($result, $type = 'assoc')	{		if ( is_string($result) && isset ( $this->cache[$result] ) && is_array ( $this->cache[$result] ) )		{			$row = current($this->cache[$result]);			next($this->cache[$result]);						$typecast = '';			switch ($type)			{				default:				case 'assoc':					$typecast = 'array';					break;				case 'object':					$typecast = 'object';					break;				case 'index':					$row = array_values($row);					$typecast = 'array';			}						return $row;		}				return $this->layer->sql_fetchrow($result, $type);	}		/**	 * Get a set of database result rows	 *	 * @param	mixed	$resource	Either the query resource identifier or the cache handle	 * @param	string	$type		The type of output to return (assoc, object or index)	 * @return	array	 */	function sql_fetchrowset($result, $row_type = 'assoc')	{		$rowset = array();		while ( $row = $this->sql_fetchrow($result, $row_type) )		{			$rowset[] = $row;		}				return $rowset;	}		/**	 * Free the result from a mysql query	 *	 * @param	mixed	$resource	Either the query resource identifier or the cache handle	 * @return	boolean	 */	function sql_freeresult($resource = false)	{		// Allow loose coding (no set resource)		$resource = ( $resource == false ) ? array_pop($this->layer->queries) : $resource;				// Check if the resource is actualy a cache handle		if ( is_string($resource) && isset ( $this->cache[$resource] ) )		{			// If so, unset and return			unset($this->cache[$resource]);			return true;		}				// Return boolean		return $this->layer->sql_freeresult($resource);	}		/**	 * Escape a single value, or array of values for safe entry in the db	 *	 * @param	mixed	$value	A value or array of values to escape for sql entry	 */	function sql_escape(&$value)	{		// Check if the value is an array of values		if ( is_array ( $value ) )		{			// If so, Loop through them			while ( list ( $key, ) = @each ( $value ) )			{				// And escape each value				$value[$key] = $this->layer->sql_escape($value[$key]);			}		}		else		{			// Else escape single value			$value = $this->layer->sql_escape($value);		}				// Return escaped value(s)		return $value;	}		/**	 * Build the sql for an update query	 *	 * @param	array	$valueset	The value set to use in the build, if no fieldset is defined array keys will be used.	 * @param	array	$fieldset	A set of field names to match the values.	 * @param	boolean	$escape_val	Automatically escapes values if true.	 */	function sql_build_update($valueset, $fieldset = false, $escape_val = false)	{		// Check for a fieldset		if ( ! $fieldset )		{			// If none defined, use valueset keys			$fieldset = array_keys($valueset);		}				// Unsure the arrays are not assoc		$valueset = array_values($valueset);		$fieldset = array_values($fieldset);				// Ensure the arrays are the same size		if ( sizeof ( $valueset ) <> sizeof ( $fieldset ) )		{			// Return false if so.			return false;		}				// Loop through the fields and values.		$return = array();		for ( $i = 0 ; $i < sizeof ( $valueset ) ; $i++ )		{			// Escape the value if needed			$valueset[$i] = ( $escape_val ) ? $this->sql_escape($valueset[$i]) : $valueset[$i];						// Add to the return values (Backticks for multi-word fields)			$return[] = "`{$fieldset[$i]}` = '{$valueset[$i]}'";		}				// Return the update string		return 'SET ' . implode(', ', $return);	}		/**	 * Build the sql for an insert query	 *	 * @param	array	$valueset	The value set to use in the build, if no fieldset is defined array keys will be used.	 * @param	array	$fieldset	A set of field names to match the values.	 * @param	boolean	$escape_val	Automatically escapes values if true.	 */	function sql_build_insert($valueset, $fieldset = false, $escape_val = false)	{		// Check for a fieldset		if ( ! $fieldset )		{			// If none defined, use valueset keys			$fieldset = array_keys($valueset);		}				// Unsure the arrays are not assoc		$valueset = array_values($valueset);		$fieldset = array_values($fieldset);				// Ensure the arrays are the same size		if ( sizeof ( $valueset ) <> sizeof ( $fieldset ) )		{			// Return false if so.			return false;		}				// Make the fields part		$fields = array();		for ( $i = 0 ; $i < sizeof ( $fieldset ) ; $i++ )		{			// Add to fields, backtick for multi-word fields			$fields[] = "`{$fieldset[$i]}`";		}				// Make the values part		$values = array();		for ( $i = 0 ; $i < sizeof ( $valueset ) ; $i++ )		{			// Escape the value if needed			$valueset[$i] = ( $escape_val ) ? $this->sql_escape($valueset[$i]) : $valueset[$i];						// Add to values			$values[] = "'{$valueset[$i]}'";		}				// Implode the fields and values		$fields = implode(', ', $fields);		$values = implode(', ', $values);				return "({$fields}) VALUES ({$values})";	}		/**	 * Executes an sql insert instruction	 *	 * @param	string	$table		The table to insert the row into	 * @param	array	$valueset	The value set to use in the build, if no fieldset is defined array keys will be used.	 * @param	array	$fieldset	A set of field names to match the values.	 * @param	boolean	$escape_val	Automatically escapes values if true.	 */	function sql_insert($table, $valueset, $fieldset = false, $escape_val = false)	{		// Build the query		$sql = 'INSERT INTO `' . $table . '` ' . $this->sql_build_insert($valueset, $fieldset, $escape_val);				// Execute the query		$result = $this->sql_query($sql);				// Free the result		$this->sql_freeresult($result);				return;	}		/**	 * Executes an sql update instruction	 *	 * @param	string	$table		The table to update values for	 * @param	array	$valueset	The value set to use in the build, if no fieldset is defined array keys will be used.	 * @param	array	$fieldset	A set of field names to match the values.	 * @param	string	$where_sql	The where condition for the update.	 * @param	boolean	$escape_val	Automatically escapes values if true.	 */	function sql_update($table, $valueset, $fieldset = false, $escape_val = false, $where_sql = '')	{		// Build the query		$sql = 'UPDATE `' . $table . '` ' . $this->sql_build_update($valueset, $fieldset, $escape_val) . ' ' . $where_sql;				// Execute the query		$result = $this->sql_query($sql);				// Free the result		$this->sql_freeresult($result);				return;	}		/**	 * Returns all available information for a field pointer or name	 *	 * @param	string	$field_key		The field name or pointer (depending on parameter 2)	 * @param	boolean	$force_pointer	Forces the field name parameter to use the pointer instead	 * @return	array	An associative array of various field information	 */	function sql_field_info($field_key, $force_pointer = false)	{		return array();	}	/**	 * Show tables in the current database.	 *	 * @return	array	 */	function sql_list_tables()	{		$sql = 'SHOW TABLES FROM `' . $this->layer->db_name . '`';		$result = $this->sql_query($sql);		$this->sql_freeresult($sql);				return $this->sql_fetchrowset($result);	}		/**	 * Show fields in the specified table	 *	 * @param	array	$table_name	 * @return	array	 */	function sql_list_fields($table_name)	{		$sql = 'SHOW FIELDS FROM ' . $table_name;		$result = $this->sql_query($sql);		$this->sql_freeresult($sql);				return $this->sql_fetchrowset($result);	}	function sql_num_fields($result)	{		return $this->layer->sql_num_fields($result);	}		function sql_num_rows($result)	{		return $this->layer->sql_num_rows($result);	}		function sql_info()	{		return $this->layer->sql_info();	}		function sql_create_db($db_name)	{		return $this->layer->sql_create_db($db_name);	}		function sql_select_db($dbname = DB_NAME)	{		return $this->layer->sql_select_db($dbname);	}		function sql_field_create($table, $field, $type = 'varchar', $len = 255)	{		return $this->layer->sql_field_create($table, $field, $type, $len);	}		function sql_field_delete($table, $field)	{		return $this->layer->sql_field_delete($table, $field);	}}?>