/extlib/DB/DataObject.php
PHP | 4354 lines | 2767 code | 579 blank | 1008 comment | 556 complexity | f44d3ca7b9672113004464317f671bd7 MD5 | raw file
Possible License(s): AGPL-3.0, GPL-2.0, LGPL-2.1, MIT, MPL-2.0-no-copyleft-exception, BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Object Based Database Query Builder and data store
- *
- * For PHP versions 4,5 and 6
- *
- * LICENSE: This source file is subject to version 3.01 of the PHP license
- * that is available through the world-wide-web at the following URI:
- * http://www.php.net/license/3_01.txt. If you did not receive a copy of
- * the PHP License and are unable to obtain it through the web, please
- * send a note to license@php.net so we can mail you a copy immediately.
- *
- * @category Database
- * @package DB_DataObject
- * @author Alan Knowles <alan@akbkhome.com>
- * @copyright 1997-2006 The PHP Group
- * @license http://www.php.net/license/3_01.txt PHP License 3.01
- * @version CVS: $Id: DataObject.php 291349 2009-11-27 09:15:18Z alan_k $
- * @link http://pear.php.net/package/DB_DataObject
- */
-
- /* ===========================================================================
- *
- * !!!!!!!!!!!!! W A R N I N G !!!!!!!!!!!
- *
- * THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it,
- * just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include
- * this file. reducing the optimization level may also solve the segfault.
- * ===========================================================================
- */
- /**
- * The main "DB_DataObject" class is really a base class for your own tables classes
- *
- * // Set up the class by creating an ini file (refer to the manual for more details
- * [DB_DataObject]
- * database = mysql:/username:password@host/database
- * schema_location = /home/myapplication/database
- * class_location = /home/myapplication/DBTables/
- * clase_prefix = DBTables_
- *
- *
- * //Start and initialize...................... - dont forget the &
- * $config = parse_ini_file('example.ini',true);
- * $options = &PEAR::getStaticProperty('DB_DataObject','options');
- * $options = $config['DB_DataObject'];
- *
- * // example of a class (that does not use the 'auto generated tables data')
- * class mytable extends DB_DataObject {
- * // mandatory - set the table
- * var $_database_dsn = "mysql://username:password@localhost/database";
- * var $__table = "mytable";
- * function table() {
- * return array(
- * 'id' => 1, // integer or number
- * 'name' => 2, // string
- * );
- * }
- * function keys() {
- * return array('id');
- * }
- * }
- *
- * // use in the application
- *
- *
- * Simple get one row
- *
- * $instance = new mytable;
- * $instance->get("id",12);
- * echo $instance->somedata;
- *
- *
- * Get multiple rows
- *
- * $instance = new mytable;
- * $instance->whereAdd("ID > 12");
- * $instance->whereAdd("ID < 14");
- * $instance->find();
- * while ($instance->fetch()) {
- * echo $instance->somedata;
- * }
- /**
- * Needed classes
- * - we use getStaticProperty from PEAR pretty extensively (cant remove it ATM)
- */
- require_once 'PEAR.php';
- /**
- * We are duping fetchmode constants to be compatible with
- * both DB and MDB2
- */
- define('DB_DATAOBJECT_FETCHMODE_ORDERED',1);
- define('DB_DATAOBJECT_FETCHMODE_ASSOC',2);
- /**
- * these are constants for the get_table array
- * user to determine what type of escaping is required around the object vars.
- */
- define('DB_DATAOBJECT_INT', 1); // does not require ''
- define('DB_DATAOBJECT_STR', 2); // requires ''
- define('DB_DATAOBJECT_DATE', 4); // is date #TODO
- define('DB_DATAOBJECT_TIME', 8); // is time #TODO
- define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
- define('DB_DATAOBJECT_TXT', 32); // is long text #TODO
- define('DB_DATAOBJECT_BLOB', 64); // is blob type
- define('DB_DATAOBJECT_NOTNULL', 128); // not null col.
- define('DB_DATAOBJECT_MYSQLTIMESTAMP' , 256); // mysql timestamps (ignored by update/insert)
- /*
- * Define this before you include DataObjects.php to disable overload - if it segfaults due to Zend optimizer..
- */
- //define('DB_DATAOBJECT_NO_OVERLOAD',true)
- /**
- * Theses are the standard error codes, most methods will fail silently - and return false
- * to access the error message either use $table->_lastError
- * or $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
- * the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
- */
- define('DB_DATAOBJECT_ERROR_INVALIDARGS', -1); // wrong args to function
- define('DB_DATAOBJECT_ERROR_NODATA', -2); // no data available
- define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3); // something wrong with the config
- define('DB_DATAOBJECT_ERROR_NOCLASS', -4); // no class exists
- define('DB_DATAOBJECT_ERROR_INVALID_CALL' ,-7); // overlad getter/setter failure
- /**
- * Used in methods like delete() and count() to specify that the method should
- * build the condition only out of the whereAdd's and not the object parameters.
- */
- define('DB_DATAOBJECT_WHEREADD_ONLY', true);
- /**
- *
- * storage for connection and result objects,
- * it is done this way so that print_r()'ing the is smaller, and
- * it reduces the memory size of the object.
- * -- future versions may use $this->_connection = & PEAR object..
- * although will need speed tests to see how this affects it.
- * - includes sub arrays
- * - connections = md5 sum mapp to pear db object
- * - results = [id] => map to pear db object
- * - resultseq = sequence id for results & results field
- * - resultfields = [id] => list of fields return from query (for use with toArray())
- * - ini = mapping of database to ini file results
- * - links = mapping of database to links file
- * - lasterror = pear error objects for last error event.
- * - config = aliased view of PEAR::getStaticPropery('DB_DataObject','options') * done for performance.
- * - array of loaded classes by autoload method - to stop it doing file access request over and over again!
- */
- $GLOBALS['_DB_DATAOBJECT']['RESULTS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ'] = 1;
- $GLOBALS['_DB_DATAOBJECT']['RESULTFIELDS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['INI'] = array();
- $GLOBALS['_DB_DATAOBJECT']['LINKS'] = array();
- $GLOBALS['_DB_DATAOBJECT']['SEQUENCE'] = array();
- $GLOBALS['_DB_DATAOBJECT']['LASTERROR'] = null;
- $GLOBALS['_DB_DATAOBJECT']['CONFIG'] = array();
- $GLOBALS['_DB_DATAOBJECT']['CACHE'] = array();
- $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = false;
- $GLOBALS['_DB_DATAOBJECT']['QUERYENDTIME'] = 0;
-
- // this will be horrifically slow!!!!
- // NOTE: Overload SEGFAULTS ON PHP4 + Zend Optimizer (see define before..)
- // these two are BC/FC handlers for call in PHP4/5
- if ( substr(phpversion(),0,1) == 5) {
- class DB_DataObject_Overload
- {
- function __call($method,$args)
- {
- $return = null;
- $this->_call($method,$args,$return);
- return $return;
- }
- function __sleep()
- {
- return array_keys(get_object_vars($this)) ;
- }
- }
- } else {
- if (version_compare(phpversion(),'4.3.10','eq') && !defined('DB_DATAOBJECT_NO_OVERLOAD')) {
- trigger_error(
- "overload does not work with PHP4.3.10, either upgrade
- (snaps.php.net) or more recent version
- or define DB_DATAOBJECT_NO_OVERLOAD as per the manual.
- ",E_USER_ERROR);
- }
- if (!function_exists('clone')) {
- // emulate clone - as per php_compact, slow but really the correct behaviour..
- eval('function clone($t) { $r = $t; if (method_exists($r,"__clone")) { $r->__clone(); } return $r; }');
- }
- eval('
- class DB_DataObject_Overload {
- function __call($method,$args,&$return) {
- return $this->_call($method,$args,$return);
- }
- }
- ');
- }
-
-
- /*
- *
- * @package DB_DataObject
- * @author Alan Knowles <alan@akbkhome.com>
- * @since PHP 4.0
- */
-
- class DB_DataObject extends DB_DataObject_Overload
- {
- /**
- * The Version - use this to check feature changes
- *
- * @access private
- * @var string
- */
- var $_DB_DataObject_version = "1.9.0";
- /**
- * The Database table (used by table extends)
- *
- * @access private
- * @var string
- */
- var $__table = ''; // database table
- /**
- * The Number of rows returned from a query
- *
- * @access public
- * @var int
- */
- var $N = 0; // Number of rows returned from a query
- /* ============================================================= */
- /* Major Public Methods */
- /* (designed to be optionally then called with parent::method()) */
- /* ============================================================= */
- /**
- * Get a result using key, value.
- *
- * for example
- * $object->get("ID",1234);
- * Returns Number of rows located (usually 1) for success,
- * and puts all the table columns into this classes variables
- *
- * see the fetch example on how to extend this.
- *
- * if no value is entered, it is assumed that $key is a value
- * and get will then use the first key in keys()
- * to obtain the key.
- *
- * @param string $k column
- * @param string $v value
- * @access public
- * @return int No. of rows
- */
- function get($k = null, $v = null)
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- $keys = array();
-
- if ($v === null) {
- $v = $k;
- $keys = $this->keys();
- if (!$keys) {
- $this->raiseError("No Keys available for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $k = $keys[0];
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$k $v " .print_r($keys,true), "GET");
- }
-
- if ($v === null) {
- $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- $this->$k = $v;
- return $this->find(1);
- }
- /**
- * An autoloading, caching static get method using key, value (based on get)
- * (depreciated - use ::get / and your own caching method)
- *
- * Usage:
- * $object = DB_DataObject::staticGet("DbTable_mytable",12);
- * or
- * $object = DB_DataObject::staticGet("DbTable_mytable","name","fred");
- *
- * or write it into your extended class:
- * function &staticGet($k,$v=NULL) { return DB_DataObject::staticGet("This_Class",$k,$v); }
- *
- * @param string $class class name
- * @param string $k column (or value if using keys)
- * @param string $v value (optional)
- * @access public
- * @return object
- */
- function &staticGet($class, $k, $v = null)
- {
- $lclass = strtolower($class);
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
-
- $key = "$k:$v";
- if ($v === null) {
- $key = $k;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
- }
- if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
- return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
- }
- $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
- if (PEAR::isError($obj)) {
- DB_DataObject::raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
- $r = false;
- return $r;
- }
-
- if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
- $_DB_DATAOBJECT['CACHE'][$lclass] = array();
- }
- if (!$obj->get($k,$v)) {
- DB_DataObject::raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
-
- $r = false;
- return $r;
- }
- $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
- return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
- }
- /**
- * find results, either normal or crosstable
- *
- * for example
- *
- * $object = new mytable();
- * $object->ID = 1;
- * $object->find();
- *
- *
- * will set $object->N to number of rows, and expects next command to fetch rows
- * will return $object->N
- *
- * @param boolean $n Fetch first result
- * @access public
- * @return mixed (number of rows returned, or true if numRows fetching is not supported)
- */
- function find($n = false)
- {
- global $_DB_DATAOBJECT;
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug($n, "find",1);
- }
- if (!$this->__table) {
- // xdebug can backtrace this!
- trigger_error("NO \$__table SPECIFIED in class definition",E_USER_ERROR);
- }
- $this->N = 0;
- $query_before = $this->_query;
- $this->_build_condition($this->table()) ;
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- /* We are checking for method modifyLimitQuery as it is PEAR DB specific */
- $sql = 'SELECT ' .
- $this->_query['data_select'] . " \n" .
- ' FROM ' . ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table) . " \n" .
- $this->_join . " \n" .
- $this->_query['condition'] . " \n" .
- $this->_query['group_by'] . " \n" .
- $this->_query['having'] . " \n" .
- $this->_query['order_by'] . " \n";
-
- if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) ||
- ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
- /* PEAR DB specific */
-
- if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
- $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
- }
- } else {
- /* theoretically MDB2! */
- if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
- $DB->setLimit($this->_query['limit_count'],$this->_query['limit_start']);
- }
- }
-
-
- $this->_query($sql);
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("CHECK autofetchd $n", "find", 1);
- }
-
- // find(true)
-
- $ret = $this->N;
- if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
- // clear up memory if nothing found!?
- unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
- }
-
- if ($n && $this->N > 0 ) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("ABOUT TO AUTOFETCH", "find", 1);
- }
- $fs = $this->fetch();
- // if fetch returns false (eg. failed), then the backend doesnt support numRows (eg. ret=true)
- // - hence find() also returns false..
- $ret = ($ret === true) ? $fs : $ret;
- }
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("DONE", "find", 1);
- }
- $this->_query = $query_before;
- return $ret;
- }
- /**
- * fetches next row into this objects var's
- *
- * returns 1 on success 0 on failure
- *
- *
- *
- * Example
- * $object = new mytable();
- * $object->name = "fred";
- * $object->find();
- * $store = array();
- * while ($object->fetch()) {
- * echo $this->ID;
- * $store[] = $object; // builds an array of object lines.
- * }
- *
- * to add features to a fetch
- * function fetch () {
- * $ret = parent::fetch();
- * $this->date_formated = date('dmY',$this->date);
- * return $ret;
- * }
- *
- * @access public
- * @return boolean on success
- */
- function fetch()
- {
- global $_DB_DATAOBJECT;
- if (empty($_DB_DATAOBJECT['CONFIG'])) {
- DB_DataObject::_loadConfig();
- }
- if (empty($this->N)) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
- }
- return false;
- }
-
- if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) ||
- !is_object($result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]))
- {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug('fetched on object after fetch completed (no results found)');
- }
- return false;
- }
-
-
- $array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug(serialize($array),"FETCH");
- }
-
- // fetched after last row..
- if ($array === null) {
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $t= explode(' ',microtime());
-
- $this->debug("Last Data Fetch'ed after " .
- ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME'] ) .
- " seconds",
- "FETCH", 1);
- }
- // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
- unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
-
- // we need to keep a copy of resultfields locally so toArray() still works
- // however we dont want to keep it in the global cache..
-
- if (!empty($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
- $this->_resultFields = $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid];
- unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
- }
- // this is probably end of data!!
- //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- // make sure resultFields is always empty..
- $this->_resultFields = false;
-
- if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
- // note: we dont declare this to keep the print_r size down.
- $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
- }
-
- foreach($array as $k=>$v) {
- $kk = str_replace(".", "_", $k);
- $kk = str_replace(" ", "_", $kk);
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
- }
- $this->$kk = $array[$k];
- }
-
- // set link flag
- $this->_link_loaded=false;
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("{$this->__table} DONE", "fetchrow",2);
- }
- if (($this->_query !== false) && empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
- $this->_query = false;
- }
- return true;
- }
- /**
- * Adds a condition to the WHERE statement, defaults to AND
- *
- * $object->whereAdd(); //reset or cleaer ewhwer
- * $object->whereAdd("ID > 20");
- * $object->whereAdd("age > 20","OR");
- *
- * @param string $cond condition
- * @param string $logic optional logic "OR" (defaults to "AND")
- * @access public
- * @return string|PEAR::Error - previous condition or Error when invalid args found
- */
- function whereAdd($cond = false, $logic = 'AND')
- {
- // for PHP5.2.3 - there is a bug with setting array properties of an object.
- $_query = $this->_query;
-
- if (!isset($this->_query) || ($_query === false)) {
- return $this->raiseError(
- "You cannot do two queries on the same object (clone it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if ($cond === false) {
- $r = $this->_query['condition'];
- $_query['condition'] = '';
- $this->_query = $_query;
- return preg_replace('/^\s+WHERE\s+/','',$r);
- }
- // check input...= 0 or ' ' == error!
- if (!trim($cond)) {
- return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
- $r = $_query['condition'];
- if ($_query['condition']) {
- $_query['condition'] .= " {$logic} ( {$cond} )";
- $this->_query = $_query;
- return $r;
- }
- $_query['condition'] = " WHERE ( {$cond} ) ";
- $this->_query = $_query;
- return $r;
- }
- /**
- * Adds a order by condition
- *
- * $object->orderBy(); //clears order by
- * $object->orderBy("ID");
- * $object->orderBy("ID,age");
- *
- * @param string $order Order
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function orderBy($order = false)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($order === false) {
- $this->_query['order_by'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($order)) {
- return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if (!$this->_query['order_by']) {
- $this->_query['order_by'] = " ORDER BY {$order} ";
- return;
- }
- $this->_query['order_by'] .= " , {$order}";
- }
- /**
- * Adds a group by condition
- *
- * $object->groupBy(); //reset the grouping
- * $object->groupBy("ID DESC");
- * $object->groupBy("ID,age");
- *
- * @param string $group Grouping
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function groupBy($group = false)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($group === false) {
- $this->_query['group_by'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($group)) {
- return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
-
- if (!$this->_query['group_by']) {
- $this->_query['group_by'] = " GROUP BY {$group} ";
- return;
- }
- $this->_query['group_by'] .= " , {$group}";
- }
- /**
- * Adds a having clause
- *
- * $object->having(); //reset the grouping
- * $object->having("sum(value) > 0 ");
- *
- * @param string $having condition
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function having($having = false)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($having === false) {
- $this->_query['having'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if (!trim($having)) {
- return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
-
- if (!$this->_query['having']) {
- $this->_query['having'] = " HAVING {$having} ";
- return;
- }
- $this->_query['having'] .= " AND {$having}";
- }
- /**
- * Sets the Limit
- *
- * $boject->limit(); // clear limit
- * $object->limit(12);
- * $object->limit(12,10);
- *
- * Note this will emit an error on databases other than mysql/postgress
- * as there is no 'clean way' to implement it. - you should consider refering to
- * your database manual to decide how you want to implement it.
- *
- * @param string $a limit start (or number), or blank to reset
- * @param string $b number
- * @access public
- * @return none|PEAR::Error - invalid args only
- */
- function limit($a = null, $b = null)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if ($a === null) {
- $this->_query['limit_start'] = '';
- $this->_query['limit_count'] = '';
- return;
- }
- // check input...= 0 or ' ' == error!
- if ((!is_int($a) && ((string)((int)$a) !== (string)$a))
- || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
- return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
- global $_DB_DATAOBJECT;
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
- $this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
-
- }
- /**
- * Adds a select columns
- *
- * $object->selectAdd(); // resets select to nothing!
- * $object->selectAdd("*"); // default select
- * $object->selectAdd("unixtime(DATE) as udate");
- * $object->selectAdd("DATE");
- *
- * to prepend distict:
- * $object->selectAdd('distinct ' . $object->selectAdd());
- *
- * @param string $k
- * @access public
- * @return mixed null or old string if you reset it.
- */
- function selectAdd($k = null)
- {
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- if ($k === null) {
- $old = $this->_query['data_select'];
- $this->_query['data_select'] = '';
- return $old;
- }
-
- // check input...= 0 or ' ' == error!
- if (!trim($k)) {
- return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
- }
-
- if ($this->_query['data_select']) {
- $this->_query['data_select'] .= ', ';
- }
- $this->_query['data_select'] .= " $k ";
- }
- /**
- * Adds multiple Columns or objects to select with formating.
- *
- * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
- * // note with null it will also clear the '*' default select
- * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
- * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
- * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
- * objectTableName.colnameA as prefix_colnameA
- *
- * @param array|object|null the array or object to take column names from.
- * @param string format in sprintf format (use %s for the colname)
- * @param string table name eg. if you have joinAdd'd or send $from as an array.
- * @access public
- * @return void
- */
- function selectAs($from = null,$format = '%s',$tableName=false)
- {
- global $_DB_DATAOBJECT;
-
- if ($this->_query === false) {
- $this->raiseError(
- "You cannot do two queries on the same object (copy it before finding)",
- DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
-
- if ($from === null) {
- // blank the '*'
- $this->selectAdd();
- $from = $this;
- }
-
-
- $table = $this->__table;
- if (is_object($from)) {
- $table = $from->__table;
- $from = array_keys($from->table());
- }
-
- if ($tableName !== false) {
- $table = $tableName;
- }
- $s = '%s';
- if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $s = $DB->quoteIdentifier($s);
- $format = $DB->quoteIdentifier($format);
- }
- foreach ($from as $k) {
- $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
- }
- $this->_query['data_select'] .= "\n";
- }
- /**
- * Insert the current objects variables into the database
- *
- * Returns the ID of the inserted element (if auto increment or sequences are used.)
- *
- * for example
- *
- * Designed to be extended
- *
- * $object = new mytable();
- * $object->name = "fred";
- * echo $object->insert();
- *
- * @access public
- * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
- */
- function insert()
- {
- global $_DB_DATAOBJECT;
-
- // we need to write to the connection (For nextid) - so us the real
- // one not, a copyied on (as ret-by-ref fails with overload!)
-
- if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
- $this->_connect();
- }
-
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
-
- $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
- $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
-
- if (!$items) {
- $this->raiseError("insert:No table definition for {$this->__table}",
- DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $options = &$_DB_DATAOBJECT['CONFIG'];
- $datasaved = 1;
- $leftq = '';
- $rightq = '';
-
- $seqKeys = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]) ?
- $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] :
- $this->sequenceKey();
-
- $key = isset($seqKeys[0]) ? $seqKeys[0] : false;
- $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
- $seq = isset($seqKeys[2]) ? $seqKeys[2] : false;
-
- $dbtype = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
-
-
- // nativeSequences or Sequences..
- // big check for using sequences
-
- if (($key !== false) && !$useNative) {
-
- if (!$seq) {
- $keyvalue = $DB->nextId($this->__table);
- } else {
- $f = $DB->getOption('seqname_format');
- $DB->setOption('seqname_format','%s');
- $keyvalue = $DB->nextId($seq);
- $DB->setOption('seqname_format',$f);
- }
- if (PEAR::isError($keyvalue)) {
- $this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $this->$key = $keyvalue;
- }
-
- // if we haven't set disable_null_strings to "full"
- $ignore_null = !isset($options['disable_null_strings'])
- || !is_string($options['disable_null_strings'])
- || strtolower($options['disable_null_strings']) !== 'full' ;
-
-
- foreach($items as $k => $v) {
-
- // if we are using autoincrement - skip the column...
- if ($key && ($k == $key) && $useNative) {
- continue;
- }
-
-
-
-
- // Ignore variables which aren't set to a value
- if ( !isset($this->$k) && $ignore_null) {
- continue;
- }
- // dont insert data into mysql timestamps
- // use query() if you really want to do this!!!!
- if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
- continue;
- }
-
- if ($leftq) {
- $leftq .= ', ';
- $rightq .= ', ';
- }
-
- $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ') : "$k ");
-
- if (is_a($this->$k,'DB_DataObject_Cast')) {
- $value = $this->$k->toString($v,$DB);
- if (PEAR::isError($value)) {
- $this->raiseError($value->toString() ,DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- $rightq .= $value;
- continue;
- }
-
-
- if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
- $rightq .= " NULL ";
- continue;
- }
- // DATE is empty... on a col. that can be null..
- // note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
- !($v & DB_DATAOBJECT_NOTNULL)) {
-
- $rightq .= " NULL ";
- continue;
- }
-
-
- if ($v & DB_DATAOBJECT_STR) {
- $rightq .= $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
- // use t/f for boolean.
- (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
- $this->$k
- )) . " ";
- continue;
- }
- if (is_numeric($this->$k)) {
- $rightq .=" {$this->$k} ";
- continue;
- }
- /* flag up string values - only at debug level... !!!??? */
- if (is_object($this->$k) || is_array($this->$k)) {
- $this->debug('ODD DATA: ' .$k . ' ' . print_r($this->$k,true),'ERROR');
- }
-
- // at present we only cast to integers
- // - V2 may store additional data about float/int
- $rightq .= ' ' . intval($this->$k) . ' ';
- }
-
- // not sure why we let empty insert here.. - I guess to generate a blank row..
-
-
- if ($leftq || $useNative) {
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
-
-
- if (($dbtype == 'pgsql') && empty($leftq)) {
- $r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
- } else {
- $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
- }
-
-
-
-
- if (PEAR::isError($r)) {
- $this->raiseError($r);
- return false;
- }
-
- if ($r < 1) {
- return 0;
- }
-
-
- // now do we have an integer key!
-
- if ($key && $useNative) {
- switch ($dbtype) {
- case 'mysql':
- case 'mysqli':
- $method = "{$dbtype}_insert_id";
- $this->$key = $method(
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
- );
- break;
-
- case 'mssql':
- // note this is not really thread safe - you should wrapp it with
- // transactions = eg.
- // $db->query('BEGIN');
- // $db->insert();
- // $db->query('COMMIT');
- $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
- $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
- $mssql_key = $DB->$method("SELECT @@IDENTITY");
- if (PEAR::isError($mssql_key)) {
- $this->raiseError($mssql_key);
- return false;
- }
- $this->$key = $mssql_key;
- break;
-
- case 'pgsql':
- if (!$seq) {
- $seq = $DB->getSequenceName(strtolower($this->__table));
- }
- $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
- $method = ($db_driver == 'DB') ? 'getOne' : 'queryOne';
- $pgsql_key = $DB->$method("SELECT currval('".$seq . "')");
- if (PEAR::isError($pgsql_key)) {
- $this->raiseError($pgsql_key);
- return false;
- }
- $this->$key = $pgsql_key;
- break;
-
- case 'ifx':
- $this->$key = array_shift (
- ifx_fetch_row (
- ifx_query(
- "select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
- $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
- IFX_SCROLL
- ),
- "FIRST"
- )
- );
- break;
-
- }
-
- }
- if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
- $this->_clear_cache();
- }
- if ($key) {
- return $this->$key;
- }
- return true;
- }
- $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- /**
- * Updates current objects variables into the database
- * uses the keys() to decide how to update
- * Returns the true on success
- *
- * for example
- *
- * $object = DB_DataObject::factory('mytable');
- * $object->get("ID",234);
- * $object->email="testing@test.com";
- * if(!$object->update())
- * echo "UPDATE FAILED";
- *
- * to only update changed items :
- * $dataobject->get(132);
- * $original = $dataobject; // clone/copy it..
- * $dataobject->setFrom($_POST);
- * if ($dataobject->validate()) {
- * $dataobject->update($original);
- * } // otherwise an error...
- *
- * performing global updates:
- * $object = DB_DataObject::factory('mytable');
- * $object->status = "dead";
- * $object->whereAdd('age > 150');
- * $object->update(DB_DATAOBJECT_WHEREADD_ONLY);
- *
- * @param object dataobject (optional) | DB_DATAOBJECT_WHEREADD_ONLY - used to only update changed items.
- * @access public
- * @return int rows affected or false on failure
- */
- function update($dataObject = false)
- {
- global $_DB_DATAOBJECT;
- // connect will load the config!
- $this->_connect();
-
-
- $original_query = $this->_query;
-
- $items = isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?
- $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
-
- // only apply update against sequence key if it is set?????
-
- $seq = $this->sequenceKey();
- if ($seq[0] !== false) {
- $keys = array($seq[0]);
- if (empty($this->{$keys[0]}) && $dataObject !== true) {
- $this->raiseError("update: trying to perform an update without
- the key set, and argument to update is not
- DB_DATAOBJECT_WHEREADD_ONLY
- ", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- } else {
- $keys = $this->keys();
- }
-
-
- if (!$items) {
- $this->raiseError("update:No table definition for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
- return false;
- }
- $datasaved = 1;
- $settings = '';
- $this->_connect();
-
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $dbtype = $DB->dsn["phptype"];
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
- $options = $_DB_DATAOBJECT['CONFIG'];
-
-
- $ignore_null = !isset($options['disable_null_strings'])
- || !is_string($options['disable_null_strings'])
- || strtolower($options['disable_null_strings']) !== 'full' ;
-
-
- foreach($items as $k => $v) {
-
- if (!isset($this->$k) && $ignore_null) {
- continue;
- }
- // ignore stuff thats
-
- // dont write things that havent changed..
- if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
- continue;
- }
-
- // - dont write keys to left.!!!
- if (in_array($k,$keys)) {
- continue;
- }
-
- // dont insert data into mysql timestamps
- // use query() if you really want to do this!!!!
- if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
- continue;
- }
-
-
- if ($settings) {
- $settings .= ', ';
- }
-
- $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
-
- if (is_a($this->$k,'DB_DataObject_Cast')) {
- $value = $this->$k->toString($v,$DB);
- if (PEAR::isError($value)) {
- $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
- return false;
- }
- $settings .= "$kSql = $value ";
- continue;
- }
-
- // special values ... at least null is handled...
- if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
- $settings .= "$kSql = NULL ";
- continue;
- }
- // DATE is empty... on a col. that can be null..
- // note: this may be usefull for time as well..
- if (!$this->$k &&
- (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) &&
- !($v & DB_DATAOBJECT_NOTNULL)) {
-
- $settings .= "$kSql = NULL ";
- continue;
- }
-
- if ($v & DB_DATAOBJECT_STR) {
- $settings .= "$kSql = ". $this->_quote((string) (
- ($v & DB_DATAOBJECT_BOOL) ?
- // this is thanks to the braindead idea of postgres to
- // use t/f for boolean.
- (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :
- $this->$k
- )) . ' ';
- continue;
- }
- if (is_numeric($this->$k)) {
- $settings .= "$kSql = {$this->$k} ";
- continue;
- }
- // at present we only cast to integers
- // - V2 may store additional data about float/int
- $settings .= "$kSql = " . intval($this->$k) . ' ';
- }
-
- if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
- $this->debug("got keys as ".serialize($keys),3);
- }
- if ($dataObject !== true) {
- $this->_build_condition($items,$keys);
- } else {
- // prevent wiping out of data!
- if (empty($this->_query['condition'])) {
- $this->raiseError("update: global table update not available
- do \$do->whereAdd('1=1'); if you really want to do that.
- ", DB_DATAOBJECT_ERROR_INVALIDARGS);
- return false;
- }
- }
-
-
-
- // echo " $settings, $this->condition ";
- if ($settings && isset($this->_query) && $this->_query['condition']) {
-
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
-
- $r = $this->_query("UPDATE {$table} SET {$settings} {$this->_query['condition']} ");
-
- // restore original query conditions.
- $this->_query = $original_query;
-
- if (PEAR::isError($r)) {
- $this->raiseError($r);
- return false;
- }
- if ($r < 1) {
- return 0;
- }
- $this->_clear_cache();
- return $r;
- }
- // restore original query conditions.
- $this->_query = $original_query;
-
- // if you manually specified a dataobject, and there where no changes - then it's ok..
- if ($dataObject !== false) {
- return true;
- }
-
- $this->raiseError(
- "update: No Data specifed for query $settings , {$this->_query['condition']}",
- DB_DATAOBJECT_ERROR_NODATA);
- return false;
- }
- /**
- * Deletes items from table which match current objects variables
- *
- * Returns the true on success
- *
- * for example
- *
- * Designed to be extended
- *
- * $object = new mytable();
- * $object->ID=123;
- * echo $object->delete(); // builds a conditon
- *
- * $object = new mytable();
- * $object->whereAdd('age > 12');
- * $object->limit(1);
- * $object->orderBy('age DESC');
- * $object->delete(true); // dont use object vars, use the conditions, limit and order.
- *
- * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
- * we will build the condition only using the whereAdd's. Default is to
- * build the condition only using the object parameters.
- *
- * @access public
- * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
- */
- function delete($useWhere = false)
- {
- global $_DB_DATAOBJECT;
- // connect will load the config!
- $this->_connect();
- $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
- $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
-
- $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : '');
-
- if (!$useWhere) {
- $keys = $this->keys();
- $this->_query = array(); // as it's probably unset!
- $this->_query['condition'] = ''; // default behaviour not to use where condition
- $this->_build_condition($this->table(),$keys);
- // if primary keys are not set then use data from rest of object.
- if (!$this->_query['condition']) {
- $this->_build_condition($this->table(),array(),$keys);
- }
- $extra_cond = '';
- }
-
- // don't delete without a condition
- if (($this->_query !== false) && $this->_query['condition']) {
-
- $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
- $sql = "DELETE ";
- // using a joined delete. - with useWhere..
- $sql .= (!empty($this->_join) && $useWhere) ?
- "{$table} FROM {$table} {$this->_join} " :
- "FROM {$table} ";
-
- $sql .= $this->_query['condition']. $extra_cond;
-
- // add limit..
-
- if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
-
- if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||
- ($_DB_DATAOBJECT['…
Large files files are truncated, but you can click here to view the full file