]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - extlib/DB/DataObject.php
Merge branch 'master' into 1.0.x
[quix0rs-gnu-social.git] / extlib / DB / DataObject.php
1 <?php
2 /**
3  * Object Based Database Query Builder and data store
4  *
5  * For PHP versions 4,5 and 6
6  *
7  * LICENSE: This source file is subject to version 3.01 of the PHP license
8  * that is available through the world-wide-web at the following URI:
9  * http://www.php.net/license/3_01.txt.  If you did not receive a copy of
10  * the PHP License and are unable to obtain it through the web, please
11  * send a note to license@php.net so we can mail you a copy immediately.
12  *
13  * @category   Database
14  * @package    DB_DataObject
15  * @author     Alan Knowles <alan@akbkhome.com>
16  * @copyright  1997-2006 The PHP Group
17  * @license    http://www.php.net/license/3_01.txt  PHP License 3.01
18  * @version    CVS: $Id: DataObject.php 301030 2010-07-07 02:26:31Z alan_k $
19  * @link       http://pear.php.net/package/DB_DataObject
20  */
21   
22
23 /* =========================================================================== 
24  *
25  *    !!!!!!!!!!!!!               W A R N I N G                !!!!!!!!!!!
26  *
27  *  THIS MAY SEGFAULT PHP IF YOU ARE USING THE ZEND OPTIMIZER (to fix it, 
28  *  just add "define('DB_DATAOBJECT_NO_OVERLOAD',true);" before you include 
29  *  this file. reducing the optimization level may also solve the segfault.
30  *  ===========================================================================
31  */
32
33 /**
34  * The main "DB_DataObject" class is really a base class for your own tables classes
35  *
36  * // Set up the class by creating an ini file (refer to the manual for more details
37  * [DB_DataObject]
38  * database         = mysql:/username:password@host/database
39  * schema_location = /home/myapplication/database
40  * class_location  = /home/myapplication/DBTables/
41  * clase_prefix    = DBTables_
42  *
43  *
44  * //Start and initialize...................... - dont forget the &
45  * $config = parse_ini_file('example.ini',true);
46  * $options = &PEAR::getStaticProperty('DB_DataObject','options');
47  * $options = $config['DB_DataObject'];
48  *
49  * // example of a class (that does not use the 'auto generated tables data')
50  * class mytable extends DB_DataObject {
51  *     // mandatory - set the table
52  *     var $_database_dsn = "mysql://username:password@localhost/database";
53  *     var $__table = "mytable";
54  *     function table() {
55  *         return array(
56  *             'id' => 1, // integer or number
57  *             'name' => 2, // string
58  *        );
59  *     }
60  *     function keys() {
61  *         return array('id');
62  *     }
63  * }
64  *
65  * // use in the application
66  *
67  *
68  * Simple get one row
69  *
70  * $instance = new mytable;
71  * $instance->get("id",12);
72  * echo $instance->somedata;
73  *
74  *
75  * Get multiple rows
76  *
77  * $instance = new mytable;
78  * $instance->whereAdd("ID > 12");
79  * $instance->whereAdd("ID < 14");
80  * $instance->find();
81  * while ($instance->fetch()) {
82  *     echo $instance->somedata;
83  * }
84
85
86 /**
87  * Needed classes
88  * - we use getStaticProperty from PEAR pretty extensively (cant remove it ATM)
89  */
90
91 require_once 'PEAR.php';
92
93 /**
94  * We are duping fetchmode constants to be compatible with
95  * both DB and MDB2
96  */
97 define('DB_DATAOBJECT_FETCHMODE_ORDERED',1); 
98 define('DB_DATAOBJECT_FETCHMODE_ASSOC',2);
99
100
101
102
103
104 /**
105  * these are constants for the get_table array
106  * user to determine what type of escaping is required around the object vars.
107  */
108 define('DB_DATAOBJECT_INT',  1);  // does not require ''
109 define('DB_DATAOBJECT_STR',  2);  // requires ''
110
111 define('DB_DATAOBJECT_DATE', 4);  // is date #TODO
112 define('DB_DATAOBJECT_TIME', 8);  // is time #TODO
113 define('DB_DATAOBJECT_BOOL', 16); // is boolean #TODO
114 define('DB_DATAOBJECT_TXT',  32); // is long text #TODO
115 define('DB_DATAOBJECT_BLOB', 64); // is blob type
116
117
118 define('DB_DATAOBJECT_NOTNULL', 128);           // not null col.
119 define('DB_DATAOBJECT_MYSQLTIMESTAMP'   , 256);           // mysql timestamps (ignored by update/insert)
120 /*
121  * Define this before you include DataObjects.php to  disable overload - if it segfaults due to Zend optimizer..
122  */
123 //define('DB_DATAOBJECT_NO_OVERLOAD',true)  
124
125
126 /**
127  * Theses are the standard error codes, most methods will fail silently - and return false
128  * to access the error message either use $table->_lastError
129  * or $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
130  * the code is $last_error->code, and the message is $last_error->message (a standard PEAR error)
131  */
132
133 define('DB_DATAOBJECT_ERROR_INVALIDARGS',   -1);  // wrong args to function
134 define('DB_DATAOBJECT_ERROR_NODATA',        -2);  // no data available
135 define('DB_DATAOBJECT_ERROR_INVALIDCONFIG', -3);  // something wrong with the config
136 define('DB_DATAOBJECT_ERROR_NOCLASS',       -4);  // no class exists
137 define('DB_DATAOBJECT_ERROR_INVALID_CALL'  ,-7);  // overlad getter/setter failure
138
139 /**
140  * Used in methods like delete() and count() to specify that the method should
141  * build the condition only out of the whereAdd's and not the object parameters.
142  */
143 define('DB_DATAOBJECT_WHEREADD_ONLY', true);
144
145 /**
146  *
147  * storage for connection and result objects,
148  * it is done this way so that print_r()'ing the is smaller, and
149  * it reduces the memory size of the object.
150  * -- future versions may use $this->_connection = & PEAR object..
151  *   although will need speed tests to see how this affects it.
152  * - includes sub arrays
153  *   - connections = md5 sum mapp to pear db object
154  *   - results     = [id] => map to pear db object
155  *   - resultseq   = sequence id for results & results field
156  *   - resultfields = [id] => list of fields return from query (for use with toArray())
157  *   - ini         = mapping of database to ini file results
158  *   - links       = mapping of database to links file
159  *   - lasterror   = pear error objects for last error event.
160  *   - config      = aliased view of PEAR::getStaticPropery('DB_DataObject','options') * done for performance.
161  *   - array of loaded classes by autoload method - to stop it doing file access request over and over again!
162  */
163 $GLOBALS['_DB_DATAOBJECT']['RESULTS']   = array();
164 $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ'] = 1;
165 $GLOBALS['_DB_DATAOBJECT']['RESULTFIELDS'] = array();
166 $GLOBALS['_DB_DATAOBJECT']['CONNECTIONS'] = array();
167 $GLOBALS['_DB_DATAOBJECT']['INI'] = array();
168 $GLOBALS['_DB_DATAOBJECT']['LINKS'] = array();
169 $GLOBALS['_DB_DATAOBJECT']['SEQUENCE'] = array();
170 $GLOBALS['_DB_DATAOBJECT']['LASTERROR'] = null;
171 $GLOBALS['_DB_DATAOBJECT']['CONFIG'] = array();
172 $GLOBALS['_DB_DATAOBJECT']['CACHE'] = array();
173 $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = false;
174 $GLOBALS['_DB_DATAOBJECT']['QUERYENDTIME'] = 0;
175
176
177  
178 // this will be horrifically slow!!!!
179 // NOTE: Overload SEGFAULTS ON PHP4 + Zend Optimizer (see define before..)
180 // these two are BC/FC handlers for call in PHP4/5
181
182 if ( substr(phpversion(),0,1) == 5) {
183     class DB_DataObject_Overload 
184     {
185         function __call($method,$args) 
186         {
187             $return = null;
188             $this->_call($method,$args,$return);
189             return $return;
190         }
191         function __sleep() 
192         {
193             return array_keys(get_object_vars($this)) ; 
194         }
195     }
196 } else {
197     if (version_compare(phpversion(),'4.3.10','eq') && !defined('DB_DATAOBJECT_NO_OVERLOAD')) {
198         trigger_error(
199             "overload does not work with PHP4.3.10, either upgrade 
200             (snaps.php.net) or more recent version 
201             or define DB_DATAOBJECT_NO_OVERLOAD as per the manual.
202             ",E_USER_ERROR);
203     }
204
205     if (!function_exists('clone')) {
206         // emulate clone  - as per php_compact, slow but really the correct behaviour..
207         eval('function clone($t) { $r = $t; if (method_exists($r,"__clone")) { $r->__clone(); } return $r; }');
208     }
209     eval('
210         class DB_DataObject_Overload {
211             function __call($method,$args,&$return) {
212                 return $this->_call($method,$args,$return); 
213             }
214         }
215     ');
216 }
217
218     
219
220
221  
222
223  /*
224  *
225  * @package  DB_DataObject
226  * @author   Alan Knowles <alan@akbkhome.com>
227  * @since    PHP 4.0
228  */
229  
230 class DB_DataObject extends DB_DataObject_Overload
231 {
232    /**
233     * The Version - use this to check feature changes
234     *
235     * @access   private
236     * @var      string
237     */
238     var $_DB_DataObject_version = "1.9.5";
239
240     /**
241      * The Database table (used by table extends)
242      *
243      * @access  private
244      * @var     string
245      */
246     var $__table = '';  // database table
247
248     /**
249      * The Number of rows returned from a query
250      *
251      * @access  public
252      * @var     int
253      */
254     var $N = 0;  // Number of rows returned from a query
255
256     /* ============================================================= */
257     /*                      Major Public Methods                     */
258     /* (designed to be optionally then called with parent::method()) */
259     /* ============================================================= */
260
261
262     /**
263      * Get a result using key, value.
264      *
265      * for example
266      * $object->get("ID",1234);
267      * Returns Number of rows located (usually 1) for success,
268      * and puts all the table columns into this classes variables
269      *
270      * see the fetch example on how to extend this.
271      *
272      * if no value is entered, it is assumed that $key is a value
273      * and get will then use the first key in keys()
274      * to obtain the key.
275      *
276      * @param   string  $k column
277      * @param   string  $v value
278      * @access  public
279      * @return  int     No. of rows
280      */
281     function get($k = null, $v = null)
282     {
283         global $_DB_DATAOBJECT;
284         if (empty($_DB_DATAOBJECT['CONFIG'])) {
285             DB_DataObject::_loadConfig();
286         }
287         $keys = array();
288         
289         if ($v === null) {
290             $v = $k;
291             $keys = $this->keys();
292             if (!$keys) {
293                 $this->raiseError("No Keys available for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
294                 return false;
295             }
296             $k = $keys[0];
297         }
298         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
299             $this->debug("$k $v " .print_r($keys,true), "GET");
300         }
301         
302         if ($v === null) {
303             $this->raiseError("No Value specified for get", DB_DATAOBJECT_ERROR_INVALIDARGS);
304             return false;
305         }
306         $this->$k = $v;
307         return $this->find(1);
308     }
309
310     /**
311      * An autoloading, caching static get method  using key, value (based on get)
312      * (depreciated - use ::get / and your own caching method)
313      * 
314      * Usage:
315      * $object = DB_DataObject::staticGet("DbTable_mytable",12);
316      * or
317      * $object =  DB_DataObject::staticGet("DbTable_mytable","name","fred");
318      *
319      * or write it into your extended class:
320      * function &staticGet($k,$v=NULL) { return DB_DataObject::staticGet("This_Class",$k,$v);  }
321      *
322      * @param   string  $class class name
323      * @param   string  $k     column (or value if using keys)
324      * @param   string  $v     value (optional)
325      * @access  public
326      * @return  object
327      */
328     function &staticGet($class, $k, $v = null)
329     {
330         $lclass = strtolower($class);
331         global $_DB_DATAOBJECT;
332         if (empty($_DB_DATAOBJECT['CONFIG'])) {
333             DB_DataObject::_loadConfig();
334         }
335
336         
337
338         $key = "$k:$v";
339         if ($v === null) {
340             $key = $k;
341         }
342         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
343             DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
344         }
345         if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
346             return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
347         }
348         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
349             DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
350         }
351
352         $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
353         if (PEAR::isError($obj)) {
354             DB_DataObject::raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
355             $r = false;
356             return $r;
357         }
358         
359         if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
360             $_DB_DATAOBJECT['CACHE'][$lclass] = array();
361         }
362         if (!$obj->get($k,$v)) {
363             DB_DataObject::raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
364             
365             $r = false;
366             return $r;
367         }
368         $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
369         return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
370     }
371
372     /**
373      * build the basic select query.
374      * 
375      * @access private
376      */
377     
378     function _build_select()
379     {
380         global $_DB_DATAOBJECT;
381         $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
382         if ($quoteIdentifiers) {
383             $this->_connect();
384             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
385         }
386         $sql = 'SELECT ' .
387             $this->_query['data_select'] . " \n" .
388             ' FROM ' . ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table) . " \n" .
389             $this->_join . " \n" .
390             $this->_query['condition'] . " \n" .
391             $this->_query['group_by'] . " \n" .
392             $this->_query['having'] . " \n";
393                  
394         return $sql;
395     }
396
397      
398     /**
399      * find results, either normal or crosstable
400      *
401      * for example
402      *
403      * $object = new mytable();
404      * $object->ID = 1;
405      * $object->find();
406      *
407      *
408      * will set $object->N to number of rows, and expects next command to fetch rows
409      * will return $object->N
410      *
411      * @param   boolean $n Fetch first result
412      * @access  public
413      * @return  mixed (number of rows returned, or true if numRows fetching is not supported)
414      */
415     function find($n = false)
416     {
417         global $_DB_DATAOBJECT;
418         if ($this->_query === false) {
419             $this->raiseError(
420                 "You cannot do two queries on the same object (copy it before finding)", 
421                 DB_DATAOBJECT_ERROR_INVALIDARGS);
422             return false;
423         }
424         
425         if (empty($_DB_DATAOBJECT['CONFIG'])) {
426             DB_DataObject::_loadConfig();
427         }
428
429         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
430             $this->debug($n, "find",1);
431         }
432         if (!$this->__table) {
433             // xdebug can backtrace this!
434             trigger_error("NO \$__table SPECIFIED in class definition",E_USER_ERROR);
435         }
436         $this->N = 0;
437         $query_before = $this->_query;
438         $this->_build_condition($this->table()) ;
439         
440        
441         $this->_connect();
442         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
443        
444         
445         $sql = $this->_build_select();
446         
447         foreach ($this->_query['unions'] as $union_ar) {  
448             $sql .=   $union_ar[1] .   $union_ar[0]->_build_select() . " \n";
449         }
450         
451         $sql .=  $this->_query['order_by']  . " \n";
452         
453         
454         /* We are checking for method modifyLimitQuery as it is PEAR DB specific */
455         if ((!isset($_DB_DATAOBJECT['CONFIG']['db_driver'])) || 
456             ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
457             /* PEAR DB specific */
458         
459             if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
460                 $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
461             }
462         } else {
463             /* theoretically MDB2! */
464             if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
465                     $DB->setLimit($this->_query['limit_count'],$this->_query['limit_start']);
466                 }
467         }
468         
469         
470         $this->_query($sql);
471         
472         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
473             $this->debug("CHECK autofetchd $n", "find", 1);
474         }
475         
476         // find(true)
477         
478         $ret = $this->N;
479         if (!$ret && !empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {     
480             // clear up memory if nothing found!?
481             unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
482         }
483         
484         if ($n && $this->N > 0 ) {
485             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
486                 $this->debug("ABOUT TO AUTOFETCH", "find", 1);
487             }
488             $fs = $this->fetch();
489             // if fetch returns false (eg. failed), then the backend doesnt support numRows (eg. ret=true)
490             // - hence find() also returns false..
491             $ret = ($ret === true) ? $fs : $ret;
492         }
493         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
494             $this->debug("DONE", "find", 1);
495         }
496         $this->_query = $query_before;
497         return $ret;
498     }
499
500     /**
501      * fetches next row into this objects var's
502      *
503      * returns 1 on success 0 on failure
504      *
505      *
506      *
507      * Example
508      * $object = new mytable();
509      * $object->name = "fred";
510      * $object->find();
511      * $store = array();
512      * while ($object->fetch()) {
513      *   echo $this->ID;
514      *   $store[] = $object; // builds an array of object lines.
515      * }
516      *
517      * to add features to a fetch
518      * function fetch () {
519      *    $ret = parent::fetch();
520      *    $this->date_formated = date('dmY',$this->date);
521      *    return $ret;
522      * }
523      *
524      * @access  public
525      * @return  boolean on success
526      */
527     function fetch()
528     {
529
530         global $_DB_DATAOBJECT;
531         if (empty($_DB_DATAOBJECT['CONFIG'])) {
532             DB_DataObject::_loadConfig();
533         }
534         if (empty($this->N)) {
535             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
536                 $this->debug("No data returned from FIND (eg. N is 0)","FETCH", 3);
537             }
538             return false;
539         }
540         
541         if (empty($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]) || 
542             !is_object($result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) 
543         {
544             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
545                 $this->debug('fetched on object after fetch completed (no results found)');
546             }
547             return false;
548         }
549         
550         
551         $array = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ASSOC);
552         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
553             $this->debug(serialize($array),"FETCH");
554         }
555         
556         // fetched after last row..
557         if ($array === null) {
558             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
559                 $t= explode(' ',microtime());
560             
561                 $this->debug("Last Data Fetch'ed after " . 
562                         ($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME']  ) . 
563                         " seconds",
564                     "FETCH", 1);
565             }
566             // reduce the memory usage a bit... (but leave the id in, so count() works ok on it)
567             unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
568             
569             // we need to keep a copy of resultfields locally so toArray() still works
570             // however we dont want to keep it in the global cache..
571             
572             if (!empty($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
573                 $this->_resultFields = $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid];
574                 unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
575             }
576             // this is probably end of data!!
577             //DB_DataObject::raiseError("fetch: no data returned", DB_DATAOBJECT_ERROR_NODATA);
578             return false;
579         }
580         // make sure resultFields is always empty..
581         $this->_resultFields = false;
582         
583         if (!isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
584             // note: we dont declare this to keep the print_r size down.
585             $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]= array_flip(array_keys($array));
586         }
587         
588         foreach($array as $k=>$v) {
589             $kk = str_replace(".", "_", $k);
590             $kk = str_replace(" ", "_", $kk);
591             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
592                 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
593             }
594             $this->$kk = $array[$k];
595         }
596         
597         // set link flag
598         $this->_link_loaded=false;
599         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
600             $this->debug("{$this->__table} DONE", "fetchrow",2);
601         }
602         if (($this->_query !== false) &&  empty($_DB_DATAOBJECT['CONFIG']['keep_query_after_fetch'])) {
603             $this->_query = false;
604         }
605         return true;
606     }
607
608     
609      /**
610      * fetches all results as an array,
611      *
612      * return format is dependant on args.
613      * if selectAdd() has not been called on the object, then it will add the correct columns to the query.
614      * 
615      * A) Array of values (eg. a list of 'id')
616      *
617      * $x = DB_DataObject::factory('mytable');
618      * $x->whereAdd('something = 1')
619      * $ar = $x->fetchAll('id');
620      * -- returns array(1,2,3,4,5)
621      *
622      * B) Array of values (not from table)
623      *
624      * $x = DB_DataObject::factory('mytable');
625      * $x->whereAdd('something = 1');
626      * $x->selectAdd();
627      * $x->selectAdd('distinct(group_id) as group_id');
628      * $ar = $x->fetchAll('group_id');
629      * -- returns array(1,2,3,4,5)
630      *     *
631      * C) A key=>value associative array
632      *
633      * $x = DB_DataObject::factory('mytable');
634      * $x->whereAdd('something = 1')
635      * $ar = $x->fetchAll('id','name');
636      * -- returns array(1=>'fred',2=>'blogs',3=> .......
637      *
638      * D) array of objects
639      * $x = DB_DataObject::factory('mytable');
640      * $x->whereAdd('something = 1');
641      * $ar = $x->fetchAll();
642      *
643      * E) array of arrays (for example)
644      * $x = DB_DataObject::factory('mytable');
645      * $x->whereAdd('something = 1');
646      * $ar = $x->fetchAll(false,false,'toArray');
647      *
648      *
649      * @param    string|false  $k key
650      * @param    string|false  $v value
651      * @param    string|false  $method method to call on each result to get array value (eg. 'toArray')
652      * @access  public
653      * @return  array  format dependant on arguments, may be empty
654      */
655     function fetchAll($k= false, $v = false, $method = false)  
656     {
657         // should it even do this!!!?!?
658         if ($k !== false && 
659                 (   // only do this is we have not been explicit..
660                     empty($this->_query['data_select']) || 
661                     ($this->_query['data_select'] == '*')
662                 )
663             ) {
664             $this->selectAdd();
665             $this->selectAdd($k);
666             if ($v !== false) {
667                 $this->selectAdd($v);
668             }
669         }
670         
671         $this->find();
672         $ret = array();
673         while ($this->fetch()) {
674             if ($v !== false) {
675                 $ret[$this->$k] = $this->$v;
676                 continue;
677             }
678             $ret[] = $k === false ? 
679                 ($method == false ? clone($this)  : $this->$method())
680                 : $this->$k;
681         }
682         return $ret;
683          
684     }
685     
686     
687     /**
688      * Adds a condition to the WHERE statement, defaults to AND
689      *
690      * $object->whereAdd(); //reset or cleaer ewhwer
691      * $object->whereAdd("ID > 20");
692      * $object->whereAdd("age > 20","OR");
693      *
694      * @param    string  $cond  condition
695      * @param    string  $logic optional logic "OR" (defaults to "AND")
696      * @access   public
697      * @return   string|PEAR::Error - previous condition or Error when invalid args found
698      */
699     function whereAdd($cond = false, $logic = 'AND')
700     {
701         // for PHP5.2.3 - there is a bug with setting array properties of an object.
702         $_query = $this->_query;
703          
704         if (!isset($this->_query) || ($_query === false)) {
705             return $this->raiseError(
706                 "You cannot do two queries on the same object (clone it before finding)", 
707                 DB_DATAOBJECT_ERROR_INVALIDARGS);
708         }
709         
710         if ($cond === false) {
711             $r = $this->_query['condition'];
712             $_query['condition'] = '';
713             $this->_query = $_query;
714             return preg_replace('/^\s+WHERE\s+/','',$r);
715         }
716         // check input...= 0 or '   ' == error!
717         if (!trim($cond)) {
718             return $this->raiseError("WhereAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
719         }
720         $r = $_query['condition'];
721         if ($_query['condition']) {
722             $_query['condition'] .= " {$logic} ( {$cond} )";
723             $this->_query = $_query;
724             return $r;
725         }
726         $_query['condition'] = " WHERE ( {$cond} ) ";
727         $this->_query = $_query;
728         return $r;
729     }
730
731     /**
732     * Adds a 'IN' condition to the WHERE statement
733     *
734     * $object->whereAddIn('id', $array, 'int'); //minimal usage
735     * $object->whereAddIn('price', $array, 'float', 'OR');  // cast to float, and call whereAdd with 'OR'
736     * $object->whereAddIn('name', $array, 'string');  // quote strings
737     *
738     * @param    string  $key  key column to match
739     * @param    array  $list  list of values to match
740     * @param    string  $type  string|int|integer|float|bool  cast to type. 
741     * @param    string  $logic optional logic to call whereAdd with eg. "OR" (defaults to "AND")
742     * @access   public
743     * @return   string|PEAR::Error - previous condition or Error when invalid args found
744     */
745     function whereAddIn($key, $list, $type, $logic = 'AND') 
746     {
747         $not = '';
748         if ($key[0] == '!') {
749             $not = 'NOT ';
750             $key = substr($key, 1);
751         }
752         // fix type for short entry. 
753         $type = $type == 'int' ? 'integer' : $type; 
754
755         if ($type == 'string') {
756             $this->_connect();
757         }
758
759         $ar = array();
760         foreach($list as $k) {
761             settype($k, $type);
762             $ar[] = $type =='string' ? $this->_quote($k) : $k;
763         }
764         if (!$ar) {
765             return $not ? $this->_query['condition'] : $this->whereAdd("1=0");
766         }
767         return $this->whereAdd("$key $not IN (". implode(',', $ar). ')', $logic );    
768     }
769
770     
771     
772     /**
773      * Adds a order by condition
774      *
775      * $object->orderBy(); //clears order by
776      * $object->orderBy("ID");
777      * $object->orderBy("ID,age");
778      *
779      * @param  string $order  Order
780      * @access public
781      * @return none|PEAR::Error - invalid args only
782      */
783     function orderBy($order = false)
784     {
785         if ($this->_query === false) {
786             $this->raiseError(
787                 "You cannot do two queries on the same object (copy it before finding)", 
788                 DB_DATAOBJECT_ERROR_INVALIDARGS);
789             return false;
790         }
791         if ($order === false) {
792             $this->_query['order_by'] = '';
793             return;
794         }
795         // check input...= 0 or '    ' == error!
796         if (!trim($order)) {
797             return $this->raiseError("orderBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
798         }
799         
800         if (!$this->_query['order_by']) {
801             $this->_query['order_by'] = " ORDER BY {$order} ";
802             return;
803         }
804         $this->_query['order_by'] .= " , {$order}";
805     }
806
807     /**
808      * Adds a group by condition
809      *
810      * $object->groupBy(); //reset the grouping
811      * $object->groupBy("ID DESC");
812      * $object->groupBy("ID,age");
813      *
814      * @param  string  $group  Grouping
815      * @access public
816      * @return none|PEAR::Error - invalid args only
817      */
818     function groupBy($group = false)
819     {
820         if ($this->_query === false) {
821             $this->raiseError(
822                 "You cannot do two queries on the same object (copy it before finding)", 
823                 DB_DATAOBJECT_ERROR_INVALIDARGS);
824             return false;
825         }
826         if ($group === false) {
827             $this->_query['group_by'] = '';
828             return;
829         }
830         // check input...= 0 or '    ' == error!
831         if (!trim($group)) {
832             return $this->raiseError("groupBy: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
833         }
834         
835         
836         if (!$this->_query['group_by']) {
837             $this->_query['group_by'] = " GROUP BY {$group} ";
838             return;
839         }
840         $this->_query['group_by'] .= " , {$group}";
841     }
842
843     /**
844      * Adds a having clause
845      *
846      * $object->having(); //reset the grouping
847      * $object->having("sum(value) > 0 ");
848      *
849      * @param  string  $having  condition
850      * @access public
851      * @return none|PEAR::Error - invalid args only
852      */
853     function having($having = false)
854     {
855         if ($this->_query === false) {
856             $this->raiseError(
857                 "You cannot do two queries on the same object (copy it before finding)", 
858                 DB_DATAOBJECT_ERROR_INVALIDARGS);
859             return false;
860         }
861         if ($having === false) {
862             $this->_query['having'] = '';
863             return;
864         }
865         // check input...= 0 or '    ' == error!
866         if (!trim($having)) {
867             return $this->raiseError("Having: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
868         }
869         
870         
871         if (!$this->_query['having']) {
872             $this->_query['having'] = " HAVING {$having} ";
873             return;
874         }
875         $this->_query['having'] .= " AND {$having}";
876     }
877
878     /**
879      * Sets the Limit
880      *
881      * $boject->limit(); // clear limit
882      * $object->limit(12);
883      * $object->limit(12,10);
884      *
885      * Note this will emit an error on databases other than mysql/postgress
886      * as there is no 'clean way' to implement it. - you should consider refering to
887      * your database manual to decide how you want to implement it.
888      *
889      * @param  string $a  limit start (or number), or blank to reset
890      * @param  string $b  number
891      * @access public
892      * @return none|PEAR::Error - invalid args only
893      */
894     function limit($a = null, $b = null)
895     {
896         if ($this->_query === false) {
897             $this->raiseError(
898                 "You cannot do two queries on the same object (copy it before finding)", 
899                 DB_DATAOBJECT_ERROR_INVALIDARGS);
900             return false;
901         }
902         
903         if ($a === null) {
904            $this->_query['limit_start'] = '';
905            $this->_query['limit_count'] = '';
906            return;
907         }
908         // check input...= 0 or '    ' == error!
909         if ((!is_int($a) && ((string)((int)$a) !== (string)$a)) 
910             || (($b !== null) && (!is_int($b) && ((string)((int)$b) !== (string)$b)))) {
911             return $this->raiseError("limit: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
912         }
913         global $_DB_DATAOBJECT;
914         $this->_connect();
915         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
916         
917         $this->_query['limit_start'] = ($b == null) ? 0 : (int)$a;
918         $this->_query['limit_count'] = ($b == null) ? (int)$a : (int)$b;
919         
920     }
921
922     /**
923      * Adds a select columns
924      *
925      * $object->selectAdd(); // resets select to nothing!
926      * $object->selectAdd("*"); // default select
927      * $object->selectAdd("unixtime(DATE) as udate");
928      * $object->selectAdd("DATE");
929      *
930      * to prepend distict:
931      * $object->selectAdd('distinct ' . $object->selectAdd());
932      *
933      * @param  string  $k
934      * @access public
935      * @return mixed null or old string if you reset it.
936      */
937     function selectAdd($k = null)
938     {
939         if ($this->_query === false) {
940             $this->raiseError(
941                 "You cannot do two queries on the same object (copy it before finding)", 
942                 DB_DATAOBJECT_ERROR_INVALIDARGS);
943             return false;
944         }
945         if ($k === null) {
946             $old = $this->_query['data_select'];
947             $this->_query['data_select'] = '';
948             return $old;
949         }
950         
951         // check input...= 0 or '    ' == error!
952         if (!trim($k)) {
953             return $this->raiseError("selectAdd: No Valid Arguments", DB_DATAOBJECT_ERROR_INVALIDARGS);
954         }
955         
956         if ($this->_query['data_select']) {
957             $this->_query['data_select'] .= ', ';
958         }
959         $this->_query['data_select'] .= " $k ";
960     }
961     /**
962      * Adds multiple Columns or objects to select with formating.
963      *
964      * $object->selectAs(null); // adds "table.colnameA as colnameA,table.colnameB as colnameB,......"
965      *                      // note with null it will also clear the '*' default select
966      * $object->selectAs(array('a','b'),'%s_x'); // adds "a as a_x, b as b_x"
967      * $object->selectAs(array('a','b'),'ddd_%s','ccc'); // adds "ccc.a as ddd_a, ccc.b as ddd_b"
968      * $object->selectAdd($object,'prefix_%s'); // calls $object->get_table and adds it all as
969      *                  objectTableName.colnameA as prefix_colnameA
970      *
971      * @param  array|object|null the array or object to take column names from.
972      * @param  string           format in sprintf format (use %s for the colname)
973      * @param  string           table name eg. if you have joinAdd'd or send $from as an array.
974      * @access public
975      * @return void
976      */
977     function selectAs($from = null,$format = '%s',$tableName=false)
978     {
979         global $_DB_DATAOBJECT;
980         
981         if ($this->_query === false) {
982             $this->raiseError(
983                 "You cannot do two queries on the same object (copy it before finding)", 
984                 DB_DATAOBJECT_ERROR_INVALIDARGS);
985             return false;
986         }
987         
988         if ($from === null) {
989             // blank the '*' 
990             $this->selectAdd();
991             $from = $this;
992         }
993         
994         
995         $table = $this->__table;
996         if (is_object($from)) {
997             $table = $from->__table;
998             $from = array_keys($from->table());
999         }
1000         
1001         if ($tableName !== false) {
1002             $table = $tableName;
1003         }
1004         $s = '%s';
1005         if (!empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers'])) {
1006             $this->_connect();
1007             $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1008             $s      = $DB->quoteIdentifier($s);
1009             $format = $DB->quoteIdentifier($format); 
1010         }
1011         foreach ($from as $k) {
1012             $this->selectAdd(sprintf("{$s}.{$s} as {$format}",$table,$k,$k));
1013         }
1014         $this->_query['data_select'] .= "\n";
1015     }
1016     /**
1017      * Insert the current objects variables into the database
1018      *
1019      * Returns the ID of the inserted element (if auto increment or sequences are used.)
1020      *
1021      * for example
1022      *
1023      * Designed to be extended
1024      *
1025      * $object = new mytable();
1026      * $object->name = "fred";
1027      * echo $object->insert();
1028      *
1029      * @access public
1030      * @return mixed false on failure, int when auto increment or sequence used, otherwise true on success
1031      */
1032     function insert()
1033     {
1034         global $_DB_DATAOBJECT;
1035         
1036         // we need to write to the connection (For nextid) - so us the real
1037         // one not, a copyied on (as ret-by-ref fails with overload!)
1038         
1039         if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
1040             $this->_connect();
1041         }
1042         
1043         $quoteIdentifiers  = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1044         
1045         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1046          
1047         $items =  isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?   
1048             $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
1049             
1050         if (!$items) {
1051             $this->raiseError("insert:No table definition for {$this->__table}",
1052                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1053             return false;
1054         }
1055         $options = &$_DB_DATAOBJECT['CONFIG'];
1056
1057
1058         $datasaved = 1;
1059         $leftq     = '';
1060         $rightq    = '';
1061      
1062         $seqKeys   = isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table]) ?
1063                         $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] : 
1064                         $this->sequenceKey();
1065         
1066         $key       = isset($seqKeys[0]) ? $seqKeys[0] : false;
1067         $useNative = isset($seqKeys[1]) ? $seqKeys[1] : false;
1068         $seq       = isset($seqKeys[2]) ? $seqKeys[2] : false;
1069         
1070         $dbtype    = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn["phptype"];
1071         
1072          
1073         // nativeSequences or Sequences..     
1074
1075         // big check for using sequences
1076         
1077         if (($key !== false) && !$useNative) { 
1078         
1079             if (!$seq) {
1080                 $keyvalue =  $DB->nextId($this->__table);
1081             } else {
1082                 $f = $DB->getOption('seqname_format');
1083                 $DB->setOption('seqname_format','%s');
1084                 $keyvalue =  $DB->nextId($seq);
1085                 $DB->setOption('seqname_format',$f);
1086             }
1087             if (PEAR::isError($keyvalue)) {
1088                 $this->raiseError($keyvalue->toString(), DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1089                 return false;
1090             }
1091             $this->$key = $keyvalue;
1092         }
1093         
1094         // if we haven't set disable_null_strings to "full"
1095         $ignore_null = !isset($options['disable_null_strings'])
1096                     || !is_string($options['disable_null_strings'])
1097                     || strtolower($options['disable_null_strings']) !== 'full' ;
1098                     
1099              
1100         foreach($items as $k => $v) {
1101             
1102             // if we are using autoincrement - skip the column...
1103             if ($key && ($k == $key) && $useNative) {
1104                 continue;
1105             }
1106         
1107             
1108            
1109            
1110             // Ignore variables which aren't set to a value
1111                 if ( !isset($this->$k) && $ignore_null) {
1112                 continue;
1113             }
1114             // dont insert data into mysql timestamps 
1115             // use query() if you really want to do this!!!!
1116             if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
1117                 continue;
1118             }
1119             
1120             if ($leftq) {
1121                 $leftq  .= ', ';
1122                 $rightq .= ', ';
1123             }
1124             
1125             $leftq .= ($quoteIdentifiers ? ($DB->quoteIdentifier($k) . ' ')  : "$k ");
1126             
1127             if (is_a($this->$k,'DB_DataObject_Cast')) {
1128                 $value = $this->$k->toString($v,$DB);
1129                 if (PEAR::isError($value)) {
1130                     $this->raiseError($value->toString() ,DB_DATAOBJECT_ERROR_INVALIDARGS);
1131                     return false;
1132                 }
1133                 $rightq .=  $value;
1134                 continue;
1135             }
1136             
1137             
1138             if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
1139                 $rightq .= " NULL ";
1140                 continue;
1141             }
1142             // DATE is empty... on a col. that can be null.. 
1143             // note: this may be usefull for time as well..
1144             if (!$this->$k && 
1145                     (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) && 
1146                     !($v & DB_DATAOBJECT_NOTNULL)) {
1147                     
1148                 $rightq .= " NULL ";
1149                 continue;
1150             }
1151               
1152             
1153             if ($v & DB_DATAOBJECT_STR) {
1154                 $rightq .= $this->_quote((string) (
1155                         ($v & DB_DATAOBJECT_BOOL) ? 
1156                             // this is thanks to the braindead idea of postgres to 
1157                             // use t/f for boolean.
1158                             (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :  
1159                             $this->$k
1160                     )) . " ";
1161                 continue;
1162             }
1163             if (is_numeric($this->$k)) {
1164                 $rightq .=" {$this->$k} ";
1165                 continue;
1166             }
1167             /* flag up string values - only at debug level... !!!??? */
1168             if (is_object($this->$k) || is_array($this->$k)) {
1169                 $this->debug('ODD DATA: ' .$k . ' ' .  print_r($this->$k,true),'ERROR');
1170             }
1171             
1172             // at present we only cast to integers
1173             // - V2 may store additional data about float/int
1174             $rightq .= ' ' . intval($this->$k) . ' ';
1175
1176         }
1177         
1178         // not sure why we let empty insert here.. - I guess to generate a blank row..
1179         
1180         
1181         if ($leftq || $useNative) {
1182             $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table)    : $this->__table);
1183             
1184             
1185             if (($dbtype == 'pgsql') && empty($leftq)) {
1186                 $r = $this->_query("INSERT INTO {$table} DEFAULT VALUES");
1187             } else {
1188                $r = $this->_query("INSERT INTO {$table} ($leftq) VALUES ($rightq) ");
1189             }
1190             
1191  
1192             
1193             
1194             if (PEAR::isError($r)) {
1195                 $this->raiseError($r);
1196                 return false;
1197             }
1198             
1199             if ($r < 1) {
1200                 return 0;
1201             }
1202             
1203             
1204             // now do we have an integer key!
1205             
1206             if ($key && $useNative) {
1207                 switch ($dbtype) {
1208                     case 'mysql':
1209                     case 'mysqli':
1210                         $method = "{$dbtype}_insert_id";
1211                         $this->$key = $method(
1212                             $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection
1213                         );
1214                         break;
1215                     
1216                     case 'mssql':
1217                         // note this is not really thread safe - you should wrapp it with 
1218                         // transactions = eg.
1219                         // $db->query('BEGIN');
1220                         // $db->insert();
1221                         // $db->query('COMMIT');
1222                         $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1223                         $method = ($db_driver  == 'DB') ? 'getOne' : 'queryOne';
1224                         $mssql_key = $DB->$method("SELECT @@IDENTITY");
1225                         if (PEAR::isError($mssql_key)) {
1226                             $this->raiseError($mssql_key);
1227                             return false;
1228                         }
1229                         $this->$key = $mssql_key;
1230                         break; 
1231                         
1232                     case 'pgsql':
1233                         if (!$seq) {
1234                             $seq = $DB->getSequenceName(strtolower($this->__table));
1235                         }
1236                         $db_driver = empty($options['db_driver']) ? 'DB' : $options['db_driver'];
1237                         $method = ($db_driver  == 'DB') ? 'getOne' : 'queryOne';
1238                         $pgsql_key = $DB->$method("SELECT currval('".$seq . "')"); 
1239
1240
1241                         if (PEAR::isError($pgsql_key)) {
1242                             $this->raiseError($pgsql_key);
1243                             return false;
1244                         }
1245                         $this->$key = $pgsql_key;
1246                         break;
1247                     
1248                     case 'ifx':
1249                         $this->$key = array_shift (
1250                             ifx_fetch_row (
1251                                 ifx_query(
1252                                     "select DBINFO('sqlca.sqlerrd1') FROM systables where tabid=1",
1253                                     $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->connection,
1254                                     IFX_SCROLL
1255                                 ), 
1256                                 "FIRST"
1257                             )
1258                         ); 
1259                         break;
1260                     
1261                 }
1262                         
1263             }
1264
1265             if (isset($_DB_DATAOBJECT['CACHE'][strtolower(get_class($this))])) {
1266                 $this->_clear_cache();
1267             }
1268             if ($key) {
1269                 return $this->$key;
1270             }
1271             return true;
1272         }
1273         $this->raiseError("insert: No Data specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1274         return false;
1275     }
1276
1277     /**
1278      * Updates  current objects variables into the database
1279      * uses the keys() to decide how to update
1280      * Returns the  true on success
1281      *
1282      * for example
1283      *
1284      * $object = DB_DataObject::factory('mytable');
1285      * $object->get("ID",234);
1286      * $object->email="testing@test.com";
1287      * if(!$object->update())
1288      *   echo "UPDATE FAILED";
1289      *
1290      * to only update changed items :
1291      * $dataobject->get(132);
1292      * $original = $dataobject; // clone/copy it..
1293      * $dataobject->setFrom($_POST);
1294      * if ($dataobject->validate()) {
1295      *    $dataobject->update($original);
1296      * } // otherwise an error...
1297      *
1298      * performing global updates:
1299      * $object = DB_DataObject::factory('mytable');
1300      * $object->status = "dead";
1301      * $object->whereAdd('age > 150');
1302      * $object->update(DB_DATAOBJECT_WHEREADD_ONLY);
1303      *
1304      * @param object dataobject (optional) | DB_DATAOBJECT_WHEREADD_ONLY - used to only update changed items.
1305      * @access public
1306      * @return  int rows affected or false on failure
1307      */
1308     function update($dataObject = false)
1309     {
1310         global $_DB_DATAOBJECT;
1311         // connect will load the config!
1312         $this->_connect();
1313         
1314         
1315         $original_query =  $this->_query;
1316         
1317         $items =  isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?   
1318             $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
1319         
1320         // only apply update against sequence key if it is set?????
1321         
1322         $seq    = $this->sequenceKey();
1323         if ($seq[0] !== false) {
1324             $keys = array($seq[0]);
1325             if (!isset($this->{$keys[0]}) && $dataObject !== true) {
1326                 $this->raiseError("update: trying to perform an update without 
1327                         the key set, and argument to update is not 
1328                         DB_DATAOBJECT_WHEREADD_ONLY
1329                     ", DB_DATAOBJECT_ERROR_INVALIDARGS);
1330                 return false;  
1331             }
1332         } else {
1333             $keys = $this->keys();
1334         }
1335         
1336          
1337         if (!$items) {
1338             $this->raiseError("update:No table definition for {$this->__table}", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1339             return false;
1340         }
1341         $datasaved = 1;
1342         $settings  = '';
1343         $this->_connect();
1344         
1345         $DB            = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1346         $dbtype        = $DB->dsn["phptype"];
1347         $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1348         $options = $_DB_DATAOBJECT['CONFIG'];
1349         
1350         
1351         $ignore_null = !isset($options['disable_null_strings'])
1352                     || !is_string($options['disable_null_strings'])
1353                     || strtolower($options['disable_null_strings']) !== 'full' ;
1354                     
1355         
1356         foreach($items as $k => $v) {
1357             
1358             if (!isset($this->$k) && $ignore_null) {
1359                 continue;
1360             }
1361             // ignore stuff thats 
1362           
1363             // dont write things that havent changed..
1364             if (($dataObject !== false) && isset($dataObject->$k) && ($dataObject->$k === $this->$k)) {
1365                 continue;
1366             }
1367             
1368             // - dont write keys to left.!!!
1369             if (in_array($k,$keys)) {
1370                 continue;
1371             }
1372             
1373              // dont insert data into mysql timestamps 
1374             // use query() if you really want to do this!!!!
1375             if ($v & DB_DATAOBJECT_MYSQLTIMESTAMP) {
1376                 continue;
1377             }
1378             
1379             
1380             if ($settings)  {
1381                 $settings .= ', ';
1382             }
1383             
1384             $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
1385             
1386             if (is_a($this->$k,'DB_DataObject_Cast')) {
1387                 $value = $this->$k->toString($v,$DB);
1388                 if (PEAR::isError($value)) {
1389                     $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
1390                     return false;
1391                 }
1392                 $settings .= "$kSql = $value ";
1393                 continue;
1394             }
1395             
1396             // special values ... at least null is handled...
1397             if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
1398                 $settings .= "$kSql = NULL ";
1399                 continue;
1400             }
1401             // DATE is empty... on a col. that can be null.. 
1402             // note: this may be usefull for time as well..
1403             if (!$this->$k && 
1404                     (($v & DB_DATAOBJECT_DATE) || ($v & DB_DATAOBJECT_TIME)) && 
1405                     !($v & DB_DATAOBJECT_NOTNULL)) {
1406                     
1407                 $settings .= "$kSql = NULL ";
1408                 continue;
1409             }
1410             
1411
1412             if ($v & DB_DATAOBJECT_STR) {
1413                 $settings .= "$kSql = ". $this->_quote((string) (
1414                         ($v & DB_DATAOBJECT_BOOL) ? 
1415                             // this is thanks to the braindead idea of postgres to 
1416                             // use t/f for boolean.
1417                             (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :  
1418                             $this->$k
1419                     )) . ' ';
1420                 continue;
1421             }
1422             if (is_numeric($this->$k)) {
1423                 $settings .= "$kSql = {$this->$k} ";
1424                 continue;
1425             }
1426             // at present we only cast to integers
1427             // - V2 may store additional data about float/int
1428             $settings .= "$kSql = " . intval($this->$k) . ' ';
1429         }
1430
1431         
1432         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1433             $this->debug("got keys as ".serialize($keys),3);
1434         }
1435         if ($dataObject !== true) {
1436             $this->_build_condition($items,$keys);
1437         } else {
1438             // prevent wiping out of data!
1439             if (empty($this->_query['condition'])) {
1440                  $this->raiseError("update: global table update not available
1441                         do \$do->whereAdd('1=1'); if you really want to do that.
1442                     ", DB_DATAOBJECT_ERROR_INVALIDARGS);
1443                 return false;
1444             }
1445         }
1446         
1447         
1448         
1449         //  echo " $settings, $this->condition ";
1450         if ($settings && isset($this->_query) && $this->_query['condition']) {
1451             
1452             $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1453         
1454             $r = $this->_query("UPDATE  {$table}  SET {$settings} {$this->_query['condition']} ");
1455             
1456             // restore original query conditions.
1457             $this->_query = $original_query;
1458             
1459             if (PEAR::isError($r)) {
1460                 $this->raiseError($r);
1461                 return false;
1462             }
1463             if ($r < 1) {
1464                 return 0;
1465             }
1466
1467             $this->_clear_cache();
1468             return $r;
1469         }
1470         // restore original query conditions.
1471         $this->_query = $original_query;
1472         
1473         // if you manually specified a dataobject, and there where no changes - then it's ok..
1474         if ($dataObject !== false) {
1475             return true;
1476         }
1477         
1478         $this->raiseError(
1479             "update: No Data specifed for query $settings , {$this->_query['condition']}", 
1480             DB_DATAOBJECT_ERROR_NODATA);
1481         return false;
1482     }
1483
1484     /**
1485      * Deletes items from table which match current objects variables
1486      *
1487      * Returns the true on success
1488      *
1489      * for example
1490      *
1491      * Designed to be extended
1492      *
1493      * $object = new mytable();
1494      * $object->ID=123;
1495      * echo $object->delete(); // builds a conditon
1496      *
1497      * $object = new mytable();
1498      * $object->whereAdd('age > 12');
1499      * $object->limit(1);
1500      * $object->orderBy('age DESC');
1501      * $object->delete(true); // dont use object vars, use the conditions, limit and order.
1502      *
1503      * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1504      *             we will build the condition only using the whereAdd's.  Default is to
1505      *             build the condition only using the object parameters.
1506      *
1507      * @access public
1508      * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
1509      */
1510     function delete($useWhere = false)
1511     {
1512         global $_DB_DATAOBJECT;
1513         // connect will load the config!
1514         $this->_connect();
1515         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1516         $quoteIdentifiers  = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1517         
1518         $extra_cond = ' ' . (isset($this->_query['order_by']) ? $this->_query['order_by'] : ''); 
1519         
1520         if (!$useWhere) {
1521
1522             $keys = $this->keys();
1523             $this->_query = array(); // as it's probably unset!
1524             $this->_query['condition'] = ''; // default behaviour not to use where condition
1525             $this->_build_condition($this->table(),$keys);
1526             // if primary keys are not set then use data from rest of object.
1527             if (!$this->_query['condition']) {
1528                 $this->_build_condition($this->table(),array(),$keys);
1529             }
1530             $extra_cond = '';
1531         } 
1532             
1533
1534         // don't delete without a condition
1535         if (($this->_query !== false) && $this->_query['condition']) {
1536         
1537             $table = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1538             $sql = "DELETE ";
1539             // using a joined delete. - with useWhere..
1540             $sql .= (!empty($this->_join) && $useWhere) ? 
1541                 "{$table} FROM {$table} {$this->_join} " : 
1542                 "FROM {$table} ";
1543                 
1544             $sql .= $this->_query['condition']. $extra_cond;
1545             
1546             // add limit..
1547             
1548             if (isset($this->_query['limit_start']) && strlen($this->_query['limit_start'] . $this->_query['limit_count'])) {
1549                 
1550                 if (!isset($_DB_DATAOBJECT['CONFIG']['db_driver']) ||  
1551                     ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB')) {
1552                     // pear DB 
1553                     $sql = $DB->modifyLimitQuery($sql,$this->_query['limit_start'], $this->_query['limit_count']);
1554                     
1555                 } else {
1556                     // MDB2
1557                     $DB->setLimit( $this->_query['limit_count'],$this->_query['limit_start']);
1558                 }
1559                     
1560             }
1561             
1562             
1563             $r = $this->_query($sql);
1564             
1565             
1566             if (PEAR::isError($r)) {
1567                 $this->raiseError($r);
1568                 return false;
1569             }
1570             if ($r < 1) {
1571                 return 0;
1572             }
1573             $this->_clear_cache();
1574             return $r;
1575         } else {
1576             $this->raiseError("delete: No condition specifed for query", DB_DATAOBJECT_ERROR_NODATA);
1577             return false;
1578         }
1579     }
1580
1581     /**
1582      * fetches a specific row into this object variables
1583      *
1584      * Not recommended - better to use fetch()
1585      *
1586      * Returens true on success
1587      *
1588      * @param  int   $row  row
1589      * @access public
1590      * @return boolean true on success
1591      */
1592     function fetchRow($row = null)
1593     {
1594         global $_DB_DATAOBJECT;
1595         if (empty($_DB_DATAOBJECT['CONFIG'])) {
1596             $this->_loadConfig();
1597         }
1598         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1599             $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
1600         }
1601         if (!$this->__table) {
1602             $this->raiseError("fetchrow: No table", DB_DATAOBJECT_ERROR_INVALIDCONFIG);
1603             return false;
1604         }
1605         if ($row === null) {
1606             $this->raiseError("fetchrow: No row specified", DB_DATAOBJECT_ERROR_INVALIDARGS);
1607             return false;
1608         }
1609         if (!$this->N) {
1610             $this->raiseError("fetchrow: No results avaiable", DB_DATAOBJECT_ERROR_NODATA);
1611             return false;
1612         }
1613         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1614             $this->debug("{$this->__table} $row of {$this->N}", "fetchrow",3);
1615         }
1616
1617
1618         $result = &$_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
1619         $array  = $result->fetchrow(DB_DATAOBJECT_FETCHMODE_ASSOC,$row);
1620         if (!is_array($array)) {
1621             $this->raiseError("fetchrow: No results available", DB_DATAOBJECT_ERROR_NODATA);
1622             return false;
1623         }
1624
1625         foreach($array as $k => $v) {
1626             $kk = str_replace(".", "_", $k);
1627             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1628                 $this->debug("$kk = ". $array[$k], "fetchrow LINE", 3);
1629             }
1630             $this->$kk = $array[$k];
1631         }
1632
1633         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1634             $this->debug("{$this->__table} DONE", "fetchrow", 3);
1635         }
1636         return true;
1637     }
1638
1639     /**
1640      * Find the number of results from a simple query
1641      *
1642      * for example
1643      *
1644      * $object = new mytable();
1645      * $object->name = "fred";
1646      * echo $object->count();
1647      * echo $object->count(true);  // dont use object vars.
1648      * echo $object->count('distinct mycol');   count distinct mycol.
1649      * echo $object->count('distinct mycol',true); // dont use object vars.
1650      * echo $object->count('distinct');      // count distinct id (eg. the primary key)
1651      *
1652      *
1653      * @param bool|string  (optional)
1654      *                  (true|false => see below not on whereAddonly)
1655      *                  (string)
1656      *                      "DISTINCT" => does a distinct count on the tables 'key' column
1657      *                      otherwise  => normally it counts primary keys - you can use 
1658      *                                    this to do things like $do->count('distinct mycol');
1659      *                  
1660      * @param bool      $whereAddOnly (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
1661      *                  we will build the condition only using the whereAdd's.  Default is to
1662      *                  build the condition using the object parameters as well.
1663      *                  
1664      * @access public
1665      * @return int
1666      */
1667     function count($countWhat = false,$whereAddOnly = false)
1668     {
1669         global $_DB_DATAOBJECT;
1670         
1671         if (is_bool($countWhat)) {
1672             $whereAddOnly = $countWhat;
1673         }
1674         
1675         $t = clone($this);
1676         $items   = $t->table();
1677         
1678         $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
1679         
1680         
1681         if (!isset($t->_query)) {
1682             $this->raiseError(
1683                 "You cannot do run count after you have run fetch()", 
1684                 DB_DATAOBJECT_ERROR_INVALIDARGS);
1685             return false;
1686         }
1687         $this->_connect();
1688         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1689        
1690
1691         if (!$whereAddOnly && $items)  {
1692             $t->_build_condition($items);
1693         }
1694         $keys = $this->keys();
1695
1696         if (empty($keys[0]) && (!is_string($countWhat) || (strtoupper($countWhat) == 'DISTINCT'))) {
1697             $this->raiseError(
1698                 "You cannot do run count without keys - use \$do->count('id'), or use \$do->count('distinct id')';", 
1699                 DB_DATAOBJECT_ERROR_INVALIDARGS,PEAR_ERROR_DIE);
1700             return false;
1701             
1702         }
1703         $table   = ($quoteIdentifiers ? $DB->quoteIdentifier($this->__table) : $this->__table);
1704         $key_col = empty($keys[0]) ? '' : (($quoteIdentifiers ? $DB->quoteIdentifier($keys[0]) : $keys[0]));
1705         $as      = ($quoteIdentifiers ? $DB->quoteIdentifier('DATAOBJECT_NUM') : 'DATAOBJECT_NUM');
1706         
1707         // support distinct on default keys.
1708         $countWhat = (strtoupper($countWhat) == 'DISTINCT') ? 
1709             "DISTINCT {$table}.{$key_col}" : $countWhat;
1710         
1711         $countWhat = is_string($countWhat) ? $countWhat : "{$table}.{$key_col}";
1712         
1713         $r = $t->_query(
1714             "SELECT count({$countWhat}) as $as
1715                 FROM $table {$t->_join} {$t->_query['condition']}");
1716         if (PEAR::isError($r)) {
1717             return false;
1718         }
1719          
1720         $result  = &$_DB_DATAOBJECT['RESULTS'][$t->_DB_resultid];
1721         $l = $result->fetchRow(DB_DATAOBJECT_FETCHMODE_ORDERED);
1722         // free the results - essential on oracle.
1723         $t->free();
1724         
1725         return (int) $l[0];
1726     }
1727
1728     /**
1729      * sends raw query to database
1730      *
1731      * Since _query has to be a private 'non overwriteable method', this is a relay
1732      *
1733      * @param  string  $string  SQL Query
1734      * @access public
1735      * @return void or DB_Error
1736      */
1737     function query($string)
1738     {
1739         return $this->_query($string);
1740     }
1741
1742
1743     /**
1744      * an escape wrapper around DB->escapeSimple()
1745      * can be used when adding manual queries or clauses
1746      * eg.
1747      * $object->query("select * from xyz where abc like '". $object->escape($_GET['name']) . "'");
1748      *
1749      * @param  string  $string  value to be escaped 
1750      * @param  bool $likeEscape  escapes % and _ as well. - so like queries can be protected.
1751      * @access public
1752      * @return string
1753      */
1754     function escape($string, $likeEscape=false)
1755     {
1756         global $_DB_DATAOBJECT;
1757         $this->_connect();
1758         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1759         // mdb2 uses escape...
1760         $dd = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
1761         $ret = ($dd == 'DB') ? $DB->escapeSimple($string) : $DB->escape($string);
1762         if ($likeEscape) {
1763             $ret = str_replace(array('_','%'), array('\_','\%'), $ret);
1764         }
1765         return $ret;
1766         
1767     }
1768
1769     /* ==================================================== */
1770     /*        Major Private Vars                            */
1771     /* ==================================================== */
1772
1773     /**
1774      * The Database connection dsn (as described in the PEAR DB)
1775      * only used really if you are writing a very simple application/test..
1776      * try not to use this - it is better stored in configuration files..
1777      *
1778      * @access  private
1779      * @var     string
1780      */
1781     var $_database_dsn = '';
1782
1783     /**
1784      * The Database connection id (md5 sum of databasedsn)
1785      *
1786      * @access  private
1787      * @var     string
1788      */
1789     var $_database_dsn_md5 = '';
1790
1791     /**
1792      * The Database name
1793      * created in __connection
1794      *
1795      * @access  private
1796      * @var  string
1797      */
1798     var $_database = '';
1799
1800     
1801     
1802     /**
1803      * The QUERY rules
1804      * This replaces alot of the private variables 
1805      * used to build a query, it is unset after find() is run.
1806      * 
1807      *
1808      *
1809      * @access  private
1810      * @var     array
1811      */
1812     var $_query = array(
1813         'condition'   => '', // the WHERE condition
1814         'group_by'    => '', // the GROUP BY condition
1815         'order_by'    => '', // the ORDER BY condition
1816         'having'      => '', // the HAVING condition
1817         'limit_start' => '', // the LIMIT condition
1818         'limit_count' => '', // the LIMIT condition
1819         'data_select' => '*', // the columns to be SELECTed
1820         'unions'      => array(), // the added unions
1821     );
1822         
1823     
1824   
1825
1826     /**
1827      * Database result id (references global $_DB_DataObject[results]
1828      *
1829      * @access  private
1830      * @var     integer
1831      */
1832     var $_DB_resultid;
1833      
1834      /**
1835      * ResultFields - on the last call to fetch(), resultfields is sent here,
1836      * so we can clean up the memory.
1837      *
1838      * @access  public
1839      * @var     array
1840      */
1841     var $_resultFields = false; 
1842
1843
1844     /* ============================================================== */
1845     /*  Table definition layer (started of very private but 'came out'*/
1846     /* ============================================================== */
1847
1848     /**
1849      * Autoload or manually load the table definitions
1850      *
1851      *
1852      * usage :
1853      * DB_DataObject::databaseStructure(  'databasename',
1854      *                                    parse_ini_file('mydb.ini',true), 
1855      *                                    parse_ini_file('mydb.link.ini',true)); 
1856      *
1857      * obviously you dont have to use ini files.. (just return array similar to ini files..)
1858      *  
1859      * It should append to the table structure array 
1860      *
1861      *     
1862      * @param optional string  name of database to assign / read
1863      * @param optional array   structure of database, and keys
1864      * @param optional array  table links
1865      *
1866      * @access public
1867      * @return true or PEAR:error on wrong paramenters.. or false if no file exists..
1868      *              or the array(tablename => array(column_name=>type)) if called with 1 argument.. (databasename)
1869      */
1870     function databaseStructure()
1871     {
1872
1873         global $_DB_DATAOBJECT;
1874         
1875         // Assignment code 
1876         
1877         if ($args = func_get_args()) {
1878         
1879             if (count($args) == 1) {
1880                 
1881                 // this returns all the tables and their structure..
1882                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1883                     $this->debug("Loading Generator as databaseStructure called with args",1);
1884                 }
1885                 
1886                 $x = new DB_DataObject;
1887                 $x->_database = $args[0];
1888                 $this->_connect();
1889                 $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
1890        
1891                 $tables = $DB->getListOf('tables');
1892                 class_exists('DB_DataObject_Generator') ? '' : 
1893                     require_once 'DB/DataObject/Generator.php';
1894                     
1895                 foreach($tables as $table) {
1896                     $y = new DB_DataObject_Generator;
1897                     $y->fillTableSchema($x->_database,$table);
1898                 }
1899                 return $_DB_DATAOBJECT['INI'][$x->_database];            
1900             } else {
1901         
1902                 $_DB_DATAOBJECT['INI'][$args[0]] = isset($_DB_DATAOBJECT['INI'][$args[0]]) ?
1903                     $_DB_DATAOBJECT['INI'][$args[0]] + $args[1] : $args[1];
1904                 
1905                 if (isset($args[1])) {
1906                     $_DB_DATAOBJECT['LINKS'][$args[0]] = isset($_DB_DATAOBJECT['LINKS'][$args[0]]) ?
1907                         $_DB_DATAOBJECT['LINKS'][$args[0]] + $args[2] : $args[2];
1908                 }
1909                 return true;
1910             }
1911           
1912         }
1913         
1914         
1915         
1916         if (!$this->_database) {
1917             $this->_connect();
1918         }
1919         
1920         // loaded already?
1921         if (!empty($_DB_DATAOBJECT['INI'][$this->_database])) {
1922             
1923             // database loaded - but this is table is not available..
1924             if (
1925                     empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) 
1926                     && !empty($_DB_DATAOBJECT['CONFIG']['proxy'])
1927                 ) {
1928                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1929                     $this->debug("Loading Generator to fetch Schema",1);
1930                 }
1931                 class_exists('DB_DataObject_Generator') ? '' : 
1932                     require_once 'DB/DataObject/Generator.php';
1933                     
1934                 
1935                 $x = new DB_DataObject_Generator;
1936                 $x->fillTableSchema($this->_database,$this->__table);
1937             }
1938             return true;
1939         }
1940         
1941         
1942         if (empty($_DB_DATAOBJECT['CONFIG'])) {
1943             DB_DataObject::_loadConfig();
1944         }
1945         
1946         // if you supply this with arguments, then it will take those
1947         // as the database and links array...
1948          
1949         $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
1950             array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
1951             array() ;
1952                  
1953         if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
1954             $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
1955                 $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
1956                 explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
1957         }
1958                     
1959          
1960         $_DB_DATAOBJECT['INI'][$this->_database] = array();
1961         foreach ($schemas as $ini) {
1962              if (file_exists($ini) && is_file($ini)) {
1963                 
1964                 $_DB_DATAOBJECT['INI'][$this->_database] = array_merge(
1965                     $_DB_DATAOBJECT['INI'][$this->_database],
1966                     parse_ini_file($ini, true)
1967                 );
1968                     
1969                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) { 
1970                     if (!is_readable ($ini)) {
1971                         $this->debug("ini file is not readable: $ini","databaseStructure",1);
1972                     } else {
1973                         $this->debug("Loaded ini file: $ini","databaseStructure",1);
1974                     }
1975                 }
1976             } else {
1977                 if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
1978                     $this->debug("Missing ini file: $ini","databaseStructure",1);
1979                 }
1980             }
1981              
1982         }
1983         // now have we loaded the structure.. 
1984         
1985         if (!empty($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
1986             return true;
1987         }
1988         // - if not try building it..
1989         if (!empty($_DB_DATAOBJECT['CONFIG']['proxy'])) {
1990             class_exists('DB_DataObject_Generator') ? '' : 
1991                 require_once 'DB/DataObject/Generator.php';
1992                 
1993             $x = new DB_DataObject_Generator;
1994             $x->fillTableSchema($this->_database,$this->__table);
1995             // should this fail!!!???
1996             return true;
1997         }
1998         $this->debug("Cant find database schema: {$this->_database}/{$this->__table} \n".
1999                     "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true),"databaseStructure",5);
2000         // we have to die here!! - it causes chaos if we dont (including looping forever!)
2001         $this->raiseError( "Unable to load schema for database and table (turn debugging up to 5 for full error message)", DB_DATAOBJECT_ERROR_INVALIDARGS, PEAR_ERROR_DIE);
2002         return false;
2003         
2004          
2005     }
2006
2007
2008
2009
2010     /**
2011      * Return or assign the name of the current table
2012      *
2013      *
2014      * @param   string optinal table name to set
2015      * @access public
2016      * @return string The name of the current table
2017      */
2018     function tableName()
2019     {
2020         $args = func_get_args();
2021         if (count($args)) {
2022             $this->__table = $args[0];
2023         }
2024         return $this->__table;
2025     }
2026     
2027     /**
2028      * Return or assign the name of the current database
2029      *
2030      * @param   string optional database name to set
2031      * @access public
2032      * @return string The name of the current database
2033      */
2034     function database()
2035     {
2036         $args = func_get_args();
2037         if (count($args)) {
2038             $this->_database = $args[0];
2039         }
2040         return $this->_database;
2041     }
2042   
2043     /**
2044      * get/set an associative array of table columns
2045      *
2046      * @access public
2047      * @param  array key=>type array
2048      * @return array (associative)
2049      */
2050     function table()
2051     {
2052         
2053         // for temporary storage of database fields..
2054         // note this is not declared as we dont want to bloat the print_r output
2055         $args = func_get_args();
2056         if (count($args)) {
2057             $this->_database_fields = $args[0];
2058         }
2059         if (isset($this->_database_fields)) {
2060             return $this->_database_fields;
2061         }
2062         
2063         
2064         global $_DB_DATAOBJECT;
2065         if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2066             $this->_connect();
2067         }
2068         
2069         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
2070             return $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
2071         }
2072         
2073         $this->databaseStructure();
2074  
2075         
2076         $ret = array();
2077         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table])) {
2078             $ret =  $_DB_DATAOBJECT['INI'][$this->_database][$this->__table];
2079         }
2080         
2081         return $ret;
2082     }
2083
2084     /**
2085      * get/set an  array of table primary keys
2086      *
2087      * set usage: $do->keys('id','code');
2088      *
2089      * This is defined in the table definition if it gets it wrong,
2090      * or you do not want to use ini tables, you can override this.
2091      * @param  string optional set the key
2092      * @param  *   optional  set more keys
2093      * @access private
2094      * @return array
2095      */
2096     function keys()
2097     {
2098         // for temporary storage of database fields..
2099         // note this is not declared as we dont want to bloat the print_r output
2100         $args = func_get_args();
2101         if (count($args)) {
2102             $this->_database_keys = $args;
2103         }
2104         if (isset($this->_database_keys)) {
2105             return $this->_database_keys;
2106         }
2107         
2108         global $_DB_DATAOBJECT;
2109         if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2110             $this->_connect();
2111         }
2112         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
2113             return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
2114         }
2115         $this->databaseStructure();
2116         
2117         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"])) {
2118             return array_keys($_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"]);
2119         }
2120         return array();
2121     }
2122     /**
2123      * get/set an  sequence key
2124      *
2125      * by default it returns the first key from keys()
2126      * set usage: $do->sequenceKey('id',true);
2127      *
2128      * override this to return array(false,false) if table has no real sequence key.
2129      *
2130      * @param  string  optional the key sequence/autoinc. key
2131      * @param  boolean optional use native increment. default false 
2132      * @param  false|string optional native sequence name
2133      * @access private
2134      * @return array (column,use_native,sequence_name)
2135      */
2136     function sequenceKey()
2137     {
2138         global $_DB_DATAOBJECT;
2139           
2140         // call setting
2141         if (!$this->_database) {
2142             $this->_connect();
2143         }
2144         
2145         if (!isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database])) {
2146             $_DB_DATAOBJECT['SEQUENCE'][$this->_database] = array();
2147         }
2148
2149         
2150         $args = func_get_args();
2151         if (count($args)) {
2152             $args[1] = isset($args[1]) ? $args[1] : false;
2153             $args[2] = isset($args[2]) ? $args[2] : false;
2154             $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = $args;
2155         }
2156         if (isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table])) {
2157             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table];
2158         }
2159         // end call setting (eg. $do->sequenceKeys(a,b,c); )
2160         
2161        
2162         
2163         
2164         $keys = $this->keys();
2165         if (!$keys) {
2166             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] 
2167                 = array(false,false,false);
2168         }
2169  
2170
2171         $table =  isset($_DB_DATAOBJECT['INI'][$this->_database][$this->__table]) ?   
2172             $_DB_DATAOBJECT['INI'][$this->_database][$this->__table] : $this->table();
2173        
2174         $dbtype    = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'];
2175         
2176         $usekey = $keys[0];
2177         
2178         
2179         
2180         $seqname = false;
2181         
2182         if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table])) {
2183             $seqname = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->__table];
2184             if (strpos($seqname,':') !== false) {
2185                 list($usekey,$seqname) = explode(':',$seqname);
2186             }
2187         }  
2188         
2189         
2190         // if the key is not an integer - then it's not a sequence or native
2191         if (empty($table[$usekey]) || !($table[$usekey] & DB_DATAOBJECT_INT)) {
2192                 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,false);
2193         }
2194         
2195         
2196         if (!empty($_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'])) {
2197             $ignore =  $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'];
2198             if (is_string($ignore) && (strtoupper($ignore) == 'ALL')) {
2199                 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2200             }
2201             if (is_string($ignore)) {
2202                 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',',$ignore);
2203             }
2204             if (in_array($this->__table,$ignore)) {
2205                 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2206             }
2207         }
2208         
2209         
2210         $realkeys = $_DB_DATAOBJECT['INI'][$this->_database][$this->__table."__keys"];
2211         
2212         // if you are using an old ini file - go back to old behaviour...
2213         if (is_numeric($realkeys[$usekey])) {
2214             $realkeys[$usekey] = 'N';
2215         }
2216         
2217         // multiple unique primary keys without a native sequence...
2218         if (($realkeys[$usekey] == 'K') && (count($keys) > 1)) {
2219             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array(false,false,$seqname);
2220         }
2221         // use native sequence keys...
2222         // technically postgres native here...
2223         // we need to get the new improved tabledata sorted out first.
2224         
2225         if (    in_array($dbtype , array('pgsql', 'mysql', 'mysqli', 'mssql', 'ifx')) && 
2226                 ($table[$usekey] & DB_DATAOBJECT_INT) && 
2227                 isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
2228                 ) {
2229             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,true,$seqname);
2230         }
2231         // if not a native autoinc, and we have not assumed all primary keys are sequence
2232         if (($realkeys[$usekey] != 'N') && 
2233             !empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
2234             return array(false,false,false);
2235         }
2236         // I assume it's going to try and be a nextval DB sequence.. (not native)
2237         return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->__table] = array($usekey,false,$seqname);
2238     }
2239     
2240     
2241     
2242     /* =========================================================== */
2243     /*  Major Private Methods - the core part!              */
2244     /* =========================================================== */
2245
2246  
2247     
2248     /**
2249      * clear the cache values for this class  - normally done on insert/update etc.
2250      *
2251      * @access private
2252      * @return void
2253      */
2254     function _clear_cache()
2255     {
2256         global $_DB_DATAOBJECT;
2257         
2258         $class = strtolower(get_class($this));
2259         
2260         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2261             $this->debug("Clearing Cache for ".$class,1);
2262         }
2263         
2264         if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
2265             unset($_DB_DATAOBJECT['CACHE'][$class]);
2266         }
2267     }
2268
2269     
2270     /**
2271      * backend wrapper for quoting, as MDB2 and DB do it differently...
2272      *
2273      * @access private
2274      * @return string quoted
2275      */
2276     
2277     function _quote($str) 
2278     {
2279         global $_DB_DATAOBJECT;
2280         return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) || 
2281                 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB'))
2282             ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quoteSmart($str)
2283             : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quote($str);
2284     }
2285     
2286     
2287     /**
2288      * connects to the database
2289      *
2290      *
2291      * TODO: tidy this up - This has grown to support a number of connection options like
2292      *  a) dynamic changing of ini file to change which database to connect to
2293      *  b) multi data via the table_{$table} = dsn ini option
2294      *  c) session based storage.
2295      *
2296      * @access private
2297      * @return true | PEAR::error
2298      */
2299     function _connect()
2300     {
2301         global $_DB_DATAOBJECT;
2302         if (empty($_DB_DATAOBJECT['CONFIG'])) {
2303             $this->_loadConfig();
2304         }
2305         // Set database driver for reference 
2306         $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 
2307                 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
2308         
2309         // is it already connected ?    
2310         if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2311             
2312             // connection is an error...
2313             if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2314                 return $this->raiseError(
2315                         $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
2316                         $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2317                 );
2318                  
2319             }
2320
2321             if (empty($this->_database)) {
2322                 $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2323                 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2324                 
2325                 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)  
2326                         ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase() 
2327                         : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2328
2329                 
2330                 
2331                 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite') 
2332                     && is_file($this->_database))  {
2333                     $this->_database = basename($this->_database);
2334                 }
2335                 if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase')  {
2336                     $this->_database = substr(basename($this->_database), 0, -4);
2337                 }
2338                 
2339             }
2340             // theoretically we have a md5, it's listed in connections and it's not an error.
2341             // so everything is ok!
2342             return true;
2343             
2344         }
2345
2346         // it's not currently connected!
2347         // try and work out what to use for the dsn !
2348
2349         $options= &$_DB_DATAOBJECT['CONFIG'];
2350         // if the databse dsn dis defined in the object..
2351         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
2352         
2353         if (!$dsn) {
2354             if (!$this->_database) {
2355                 $this->_database = isset($options["table_{$this->__table}"]) ? $options["table_{$this->__table}"] : null;
2356             }
2357             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2358                 $this->debug("Checking for database specific ini ('{$this->_database}') : database_{$this->_database} in options","CONNECT");
2359             }
2360             
2361             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
2362                 $dsn = $options["database_{$this->_database}"];
2363             } else if (!empty($options['database'])) {
2364                 $dsn = $options['database'];
2365                   
2366             }
2367         }
2368         
2369         // if still no database...
2370         if (!$dsn) {
2371             return $this->raiseError(
2372                 "No database name / dsn found anywhere",
2373                 DB_DATAOBJECT_ERROR_INVALIDCONFIG, PEAR_ERROR_DIE
2374             );
2375                  
2376         }
2377         
2378         
2379         if (is_string($dsn)) {
2380             $this->_database_dsn_md5 = md5($dsn);
2381         } else {
2382             /// support array based dsn's
2383             $this->_database_dsn_md5 = md5(serialize($dsn));
2384         }
2385
2386         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2387             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2388                 $this->debug("USING CACHED CONNECTION", "CONNECT",3);
2389             }
2390             
2391             
2392             
2393             if (!$this->_database) {
2394
2395                 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2396                 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)  
2397                         ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase() 
2398                         : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2399                 
2400                 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite') 
2401                     && is_file($this->_database)) 
2402                 {
2403                     $this->_database = basename($this->_database);
2404                 }
2405             }
2406             return true;
2407         }
2408         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2409             $this->debug("NEW CONNECTION TP DATABASE :" .$this->_database , "CONNECT",3);
2410             /* actualy make a connection */
2411             $this->debug(print_r($dsn,true) ." {$this->_database_dsn_md5}", "CONNECT",3);
2412         }
2413         
2414         // Note this is verbose deliberatly! 
2415         
2416         if ($db_driver == 'DB') {
2417             
2418             /* PEAR DB connect */
2419             
2420             // this allows the setings of compatibility on DB 
2421             $db_options = PEAR::getStaticProperty('DB','options');
2422             require_once 'DB.php';
2423             if ($db_options) {
2424                 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &DB::connect($dsn,$db_options);
2425             } else {
2426                 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &DB::connect($dsn);
2427             }
2428             
2429         } else {
2430             /* assumption is MDB2 */
2431             require_once 'MDB2.php';
2432             // this allows the setings of compatibility on MDB2 
2433             $db_options = PEAR::getStaticProperty('MDB2','options');
2434             $db_options = is_array($db_options) ? $db_options : array();
2435             $db_options['portability'] = isset($db_options['portability'] )
2436                 ? $db_options['portability']  : MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE;
2437             $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = &MDB2::connect($dsn,$db_options);
2438             
2439         }
2440         
2441         
2442         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2443             $this->debug(serialize($_DB_DATAOBJECT['CONNECTIONS']), "CONNECT",5);
2444         }
2445         if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2446             $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED",5);
2447             return $this->raiseError(
2448                     "Connect failed, turn on debugging to 5 see why",
2449                         $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2450             );
2451
2452         }
2453          
2454         if (empty($this->_database)) {
2455             $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2456             
2457             $this->_database = ($db_driver != 'DB' && $hasGetDatabase)  
2458                     ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase() 
2459                     : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2460
2461
2462             if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite') 
2463                 && is_file($this->_database)) 
2464             {
2465                 $this->_database = basename($this->_database);
2466             }
2467         }
2468         
2469         // Oracle need to optimize for portibility - not sure exactly what this does though :)
2470         $c = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2471          
2472         return true;
2473     }
2474
2475     /**
2476      * sends query to database - this is the private one that must work 
2477      *   - internal functions use this rather than $this->query()
2478      *
2479      * @param  string  $string
2480      * @access private
2481      * @return mixed none or PEAR_Error
2482      */
2483     function _query($string)
2484     {
2485         global $_DB_DATAOBJECT;
2486         $this->_connect();
2487         
2488
2489         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2490
2491         $options = &$_DB_DATAOBJECT['CONFIG'];
2492         
2493         $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 
2494                     'DB':  $_DB_DATAOBJECT['CONFIG']['db_driver'];
2495         
2496         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2497             $this->debug($string,$log="QUERY");
2498             
2499         }
2500         
2501         if (strtoupper($string) == 'BEGIN') {
2502             if ($_DB_driver == 'DB') {
2503                 $DB->autoCommit(false);
2504             } else {
2505                 $DB->beginTransaction();
2506             }
2507             // db backend adds begin anyway from now on..
2508             return true;
2509         }
2510         if (strtoupper($string) == 'COMMIT') {
2511             $res = $DB->commit();
2512             if ($_DB_driver == 'DB') {
2513                 $DB->autoCommit(true);
2514             }
2515             return $res;
2516         }
2517         
2518         if (strtoupper($string) == 'ROLLBACK') {
2519             $DB->rollback();
2520             if ($_DB_driver == 'DB') {
2521                 $DB->autoCommit(true);
2522             }
2523             return true;
2524         }
2525         
2526
2527         if (!empty($options['debug_ignore_updates']) &&
2528             (strtolower(substr(trim($string), 0, 6)) != 'select') &&
2529             (strtolower(substr(trim($string), 0, 4)) != 'show') &&
2530             (strtolower(substr(trim($string), 0, 8)) != 'describe')) {
2531
2532             $this->debug('Disabling Update as you are in debug mode');
2533             return $this->raiseError("Disabling Update as you are in debug mode", null) ;
2534
2535         }
2536         //if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
2537             // this will only work when PEAR:DB supports it.
2538             //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
2539         //}
2540         
2541         // some sim
2542         $t= explode(' ',microtime());
2543         $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
2544          
2545         
2546         for ($tries = 0;$tries < 3;$tries++) {
2547             
2548             if ($_DB_driver == 'DB') {
2549                 
2550                 $result = $DB->query($string);
2551             } else {
2552                 switch (strtolower(substr(trim($string),0,6))) {
2553                 
2554                     case 'insert':
2555                     case 'update':
2556                     case 'delete':
2557                         $result = $DB->exec($string);
2558                         break;
2559                         
2560                     default:
2561                         $result = $DB->query($string);
2562                         break;
2563                 }
2564             }
2565             
2566             // see if we got a failure.. - try again a few times..
2567             if (!is_a($result,'PEAR_Error')) {
2568                 break;
2569             }
2570             if ($result->getCode() != -14) {  // *DB_ERROR_NODBSELECTED
2571                 break; // not a connection error..
2572             }
2573             sleep(1); // wait before retyring..
2574             $DB->connect($DB->dsn);
2575         }
2576        
2577
2578         if (is_a($result,'PEAR_Error')) {
2579             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) { 
2580                 $this->debug($result->toString(), "Query Error",1 );
2581             }
2582             return $this->raiseError($result);
2583         }
2584         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2585             $t= explode(' ',microtime());
2586             $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
2587             $this->debug('QUERY DONE IN  '.($t[0]+$t[1]-$time)." seconds", 'query',1);
2588         }
2589         switch (strtolower(substr(trim($string),0,6))) {
2590             case 'insert':
2591             case 'update':
2592             case 'delete':
2593                 if ($_DB_driver == 'DB') {
2594                     // pear DB specific
2595                     return $DB->affectedRows(); 
2596                 }
2597                 return $result;
2598         }
2599         if (is_object($result)) {
2600             // lets hope that copying the result object is OK!
2601             
2602             $_DB_resultid  = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
2603             $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result; 
2604             $this->_DB_resultid = $_DB_resultid;
2605         }
2606         $this->N = 0;
2607         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2608             $this->debug(serialize($result), 'RESULT',5);
2609         }
2610         if (method_exists($result, 'numrows')) {
2611             if ($_DB_driver == 'DB') {
2612                 $DB->expectError(DB_ERROR_UNSUPPORTED);
2613             } else {
2614                 $DB->expectError(MDB2_ERROR_UNSUPPORTED);
2615             }
2616             $this->N = $result->numrows();
2617             if (is_a($this->N,'PEAR_Error')) {
2618                 $this->N = true;
2619             }
2620             $DB->popExpect();
2621         }
2622     }
2623
2624     /**
2625      * Builds the WHERE based on the values of of this object
2626      *
2627      * @param   mixed   $keys
2628      * @param   array   $filter (used by update to only uses keys in this filter list).
2629      * @param   array   $negative_filter (used by delete to prevent deleting using the keys mentioned..)
2630      * @access  private
2631      * @return  string
2632      */
2633     function _build_condition($keys, $filter = array(),$negative_filter=array())
2634     {
2635         global $_DB_DATAOBJECT;
2636         $this->_connect();
2637         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2638        
2639         $quoteIdentifiers  = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
2640         $options = $_DB_DATAOBJECT['CONFIG'];
2641         
2642         // if we dont have query vars.. - reset them.
2643         if ($this->_query === false) {
2644             $x = new DB_DataObject;
2645             $this->_query= $x->_query;
2646         }
2647        
2648                     
2649         foreach($keys as $k => $v) {
2650             // index keys is an indexed array
2651             /* these filter checks are a bit suspicious..
2652                 - need to check that update really wants to work this way */
2653
2654             if ($filter) {
2655                 if (!in_array($k, $filter)) {
2656                     continue;
2657                 }
2658             }
2659             if ($negative_filter) {
2660                 if (in_array($k, $negative_filter)) {
2661                     continue;
2662                 }
2663             }
2664             if (!isset($this->$k)) {
2665                 continue;
2666             }
2667             
2668             $kSql = $quoteIdentifiers 
2669                 ? ( $DB->quoteIdentifier($this->__table) . '.' . $DB->quoteIdentifier($k) )  
2670                 : "{$this->__table}.{$k}";
2671              
2672              
2673             
2674             if (is_a($this->$k,'DB_DataObject_Cast')) {
2675                 $dbtype = $DB->dsn["phptype"];
2676                 $value = $this->$k->toString($v,$DB);
2677                 if (PEAR::isError($value)) {
2678                     $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
2679                     return false;
2680                 }
2681                 if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2682                     $this->whereAdd(" $kSql IS NULL");
2683                     continue;
2684                 }
2685                 $this->whereAdd(" $kSql = $value");
2686                 continue;
2687             }
2688             
2689             if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
2690                 $this->whereAdd(" $kSql  IS NULL");
2691                 continue;
2692             }
2693             
2694
2695             if ($v & DB_DATAOBJECT_STR) {
2696                 $this->whereAdd(" $kSql  = " . $this->_quote((string) (
2697                         ($v & DB_DATAOBJECT_BOOL) ? 
2698                             // this is thanks to the braindead idea of postgres to 
2699                             // use t/f for boolean.
2700                             (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :  
2701                             $this->$k
2702                     )) );
2703                 continue;
2704             }
2705             if (is_numeric($this->$k)) {
2706                 $this->whereAdd(" $kSql = {$this->$k}");
2707                 continue;
2708             }
2709             /* this is probably an error condition! */
2710             $this->whereAdd(" $kSql = ".intval($this->$k));
2711         }
2712     }
2713
2714     /**
2715      * autoload Class relating to a table
2716      * (depreciated - use ::factory)
2717      *
2718      * @param  string  $table  table
2719      * @access private
2720      * @return string classname on Success
2721      */
2722     function staticAutoloadTable($table)
2723     {
2724         global $_DB_DATAOBJECT;
2725         if (empty($_DB_DATAOBJECT['CONFIG'])) {
2726             DB_DataObject::_loadConfig();
2727         }
2728         $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2729             $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
2730         $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2731         
2732         $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2733         $class = $ce ? $class  : DB_DataObject::_autoloadClass($class);
2734         return $class;
2735     }
2736     
2737     
2738      /**
2739      * classic factory method for loading a table class
2740      * usage: $do = DB_DataObject::factory('person')
2741      * WARNING - this may emit a include error if the file does not exist..
2742      * use @ to silence it (if you are sure it is acceptable)
2743      * eg. $do = @DB_DataObject::factory('person')
2744      *
2745      * table name can bedatabasename/table
2746      * - and allow modular dataobjects to be written..
2747      * (this also helps proxy creation)
2748      *
2749      * Experimental Support for Multi-Database factory eg. mydatabase.mytable
2750      * 
2751      * 
2752      * @param  string  $table  tablename (use blank to create a new instance of the same class.)
2753      * @access private
2754      * @return DataObject|PEAR_Error 
2755      */
2756     
2757     
2758
2759     function factory($table = '') {
2760         global $_DB_DATAOBJECT;
2761         
2762         
2763         // multi-database support.. - experimental.
2764         $database = '';
2765        
2766         if (strpos( $table,'/') !== false ) {
2767             list($database,$table) = explode('.',$table, 2);
2768           
2769         }
2770          
2771         if (empty($_DB_DATAOBJECT['CONFIG'])) {
2772             DB_DataObject::_loadConfig();
2773         }
2774         // no configuration available for database
2775         if (!empty($database) && empty($_DB_DATAOBJECT['CONFIG']['database_'.$database])) {
2776                 return DB_DataObject::raiseError(
2777                     "unable to find database_{$database} in Configuration, It is required for factory with database"
2778                     , 0, PEAR_ERROR_DIE );   
2779        }
2780         
2781        
2782         
2783         if ($table === '') {
2784             if (is_a($this,'DB_DataObject') && strlen($this->__table)) {
2785                 $table = $this->__table;
2786             } else {
2787                 return DB_DataObject::raiseError(
2788                     "factory did not recieve a table name",
2789                     DB_DATAOBJECT_ERROR_INVALIDARGS);
2790             }
2791         }
2792         
2793         // does this need multi db support??
2794         $cp = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
2795             explode(PATH_SEPARATOR, $_DB_DATAOBJECT['CONFIG']['class_prefix']) : '';
2796         
2797         // multiprefix support.
2798         $tbl = preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
2799         if (is_array($cp)) {
2800             $class = array();
2801             foreach($cp as $cpr) {
2802                 $ce = substr(phpversion(),0,1) > 4 ? class_exists($cpr . $tbl,false) : class_exists($cpr . $tbl);
2803                 if ($ce) {
2804                     $class = $cpr . $tbl;
2805                     break;
2806                 }
2807                 $class[] = $cpr . $tbl;
2808             }
2809         } else {
2810             $class = $tbl;
2811             $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
2812         }
2813         
2814         
2815         $rclass = $ce ? $class  : DB_DataObject::_autoloadClass($class, $table);
2816         
2817         // proxy = full|light
2818         if (!$rclass && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) { 
2819         
2820             DB_DataObject::debug("FAILED TO Autoload  $database.$table - using proxy.","FACTORY",1);
2821         
2822         
2823             $proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
2824             // if you have loaded (some other way) - dont try and load it again..
2825             class_exists('DB_DataObject_Generator') ? '' : 
2826                     require_once 'DB/DataObject/Generator.php';
2827             
2828             $d = new DB_DataObject;
2829            
2830             $d->__table = $table;
2831             if (is_a($ret = $d->_connect(), 'PEAR_Error')) {
2832                 return $ret;
2833             }
2834             
2835             $x = new DB_DataObject_Generator;
2836             return $x->$proxyMethod( $d->_database, $table);
2837         }
2838         
2839         if (!$rclass) {
2840             return DB_DataObject::raiseError(
2841                 "factory could not find class " . 
2842                 (is_array($class) ? implode(PATH_SEPARATOR, $class)  : $class  ). 
2843                 "from $table",
2844                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2845         }
2846         $ret = new $rclass;
2847         if (!empty($database)) {
2848             DB_DataObject::debug("Setting database to $database","FACTORY",1);
2849             $ret->database($database);
2850         }
2851         return $ret;
2852     }
2853     /**
2854      * autoload Class
2855      *
2856      * @param  string|array  $class  Class
2857      * @param  string  $table  Table trying to load.
2858      * @access private
2859      * @return string classname on Success
2860      */
2861     function _autoloadClass($class, $table=false)
2862     {
2863         global $_DB_DATAOBJECT;
2864         
2865         if (empty($_DB_DATAOBJECT['CONFIG'])) {
2866             DB_DataObject::_loadConfig();
2867         }
2868         $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ? 
2869                 '' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
2870                 
2871         $table   = $table ? $table : substr($class,strlen($class_prefix));
2872
2873         // only include the file if it exists - and barf badly if it has parse errors :)
2874         if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
2875             return false;
2876         }
2877         // support for:
2878         // class_location = mydir/ => maps to mydir/Tablename.php
2879         // class_location = mydir/myfile_%s.php => maps to mydir/myfile_Tablename
2880         // with directory sepr
2881         // class_location = mydir/:mydir2/: => tries all of thes locations.
2882         $cl = $_DB_DATAOBJECT['CONFIG']['class_location'];
2883         
2884         
2885         switch (true) {
2886             case (strpos($cl ,'%s') !== false):
2887                 $file = sprintf($cl , preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)));
2888                 break;
2889                 
2890             case (strpos($cl , PATH_SEPARATOR) !== false):
2891                 $file = array();
2892                 foreach(explode(PATH_SEPARATOR, $cl ) as $p) {
2893                     $file[] =  $p .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2894                 }
2895                 break;
2896             default:
2897                 $file = $cl .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
2898                 break;
2899         }
2900         
2901         $cls = is_array($class) ? $class : array($class);
2902         
2903         if (is_array($file) || !file_exists($file)) {
2904             $found = false;
2905             
2906             $file = is_array($file) ? $file : array($file);
2907             $search = implode(PATH_SEPARATOR, $file);
2908             foreach($file as $f) {
2909                 foreach(explode(PATH_SEPARATOR, '' . PATH_SEPARATOR . ini_get('include_path')) as $p) {
2910                     $ff = empty($p) ? $f : "$p/$f";
2911
2912                     if (file_exists($ff)) {
2913                         $file = $ff;
2914                         $found = true;
2915                         break;
2916                     }
2917                 }
2918                 if ($found) {
2919                     break;
2920                 }
2921             }
2922             if (!$found) {
2923                 DB_DataObject::raiseError(
2924                     "autoload:Could not find class " . implode(',', $cls) .
2925                     " using class_location value :" . $search .
2926                     " using include_path value :" . ini_get('include_path'), 
2927                     DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2928                 return false;
2929             }
2930         }
2931         
2932         include_once $file;
2933         
2934        
2935         $ce = false;
2936         foreach($cls as $c) {
2937             $ce = substr(phpversion(),0,1) > 4 ? class_exists($c,false) : class_exists($c);
2938             if ($ce) {
2939                 $class = $c;
2940                 break;
2941             }
2942         }
2943         if (!$ce) {
2944             DB_DataObject::raiseError(
2945                 "autoload:Could not autoload " . implode(',', $cls) , 
2946                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
2947             return false;
2948         }
2949         return $class;
2950     }
2951     
2952     
2953     
2954     /**
2955      * Have the links been loaded?
2956      * if they have it contains a array of those variables.
2957      *
2958      * @access  private
2959      * @var     boolean | array
2960      */
2961     var $_link_loaded = false;
2962     
2963     /**
2964     * Get the links associate array  as defined by the links.ini file.
2965     * 
2966     *
2967     * Experimental... - 
2968     * Should look a bit like
2969     *       [local_col_name] => "related_tablename:related_col_name"
2970     * 
2971     * 
2972     * @return   array|null    
2973     *           array       = if there are links defined for this table.
2974     *           empty array - if there is a links.ini file, but no links on this table
2975     *           null        - if no links.ini exists for this database (hence try auto_links).
2976     * @access   public
2977     * @see      DB_DataObject::getLinks(), DB_DataObject::getLink()
2978     */
2979     
2980     function links()
2981     {
2982         global $_DB_DATAOBJECT;
2983         if (empty($_DB_DATAOBJECT['CONFIG'])) {
2984             $this->_loadConfig();
2985         }
2986         // have to connect.. -> otherwise things break later.
2987         $this->_connect();
2988         
2989         if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
2990             return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
2991         }
2992         
2993         
2994         
2995         
2996         
2997         // attempt to load links file here..
2998         
2999         if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
3000             $schemas = isset($_DB_DATAOBJECT['CONFIG']['schema_location']) ?
3001                 array("{$_DB_DATAOBJECT['CONFIG']['schema_location']}/{$this->_database}.ini") :
3002                 array() ;
3003                      
3004             if (isset($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"])) {
3005                 $schemas = is_array($_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]) ?
3006                     $_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"] :
3007                     explode(PATH_SEPARATOR,$_DB_DATAOBJECT['CONFIG']["ini_{$this->_database}"]);
3008             }
3009                         
3010              
3011             $_DB_DATAOBJECT['LINKS'][$this->_database] = array();
3012             foreach ($schemas as $ini) {
3013                 
3014                 $links =
3015                     isset($_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"]) ?
3016                         $_DB_DATAOBJECT['CONFIG']["links_{$this->_database}"] :
3017                         str_replace('.ini','.links.ini',$ini);
3018         
3019                 if (file_exists($links) && is_file($links)) {
3020                     /* not sure why $links = ... here  - TODO check if that works */
3021                     $_DB_DATAOBJECT['LINKS'][$this->_database] = array_merge(
3022                         $_DB_DATAOBJECT['LINKS'][$this->_database],
3023                         parse_ini_file($links, true)
3024                     );
3025                         
3026                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
3027                         $this->debug("Loaded links.ini file: $links","links",1);
3028                     }
3029                 } else {
3030                     if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
3031                         $this->debug("Missing links.ini file: $links","links",1);
3032                     }
3033                 }
3034             }
3035         }
3036         
3037         
3038         // if there is no link data at all on the file!
3039         // we return null.
3040         if (!isset($_DB_DATAOBJECT['LINKS'][$this->_database])) {
3041             return null;
3042         }
3043         
3044         if (isset($_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table])) {
3045             return $_DB_DATAOBJECT['LINKS'][$this->_database][$this->__table];
3046         }
3047         
3048         return array();
3049     }
3050     /**
3051      * load related objects
3052      *
3053      * There are two ways to use this, one is to set up a <dbname>.links.ini file
3054      * into a static property named <dbname>.links and specifies the table joins,
3055      * the other highly dependent on naming columns 'correctly' :)
3056      * using colname = xxxxx_yyyyyy
3057      * xxxxxx = related table; (yyyyy = user defined..)
3058      * looks up table xxxxx, for value id=$this->xxxxx
3059      * stores it in $this->_xxxxx_yyyyy
3060      * you can change what object vars the links are stored in by 
3061      * changeing the format parameter
3062      *
3063      *
3064      * @param  string format (default _%s) where %s is the table name.
3065      * @author Tim White <tim@cyface.com>
3066      * @access public
3067      * @return boolean , true on success
3068      */
3069     function getLinks($format = '_%s')
3070     {
3071          
3072         // get table will load the options.
3073         if ($this->_link_loaded) {
3074             return true;
3075         }
3076         $this->_link_loaded = false;
3077         $cols  = $this->table();
3078         $links = $this->links();
3079          
3080         $loaded = array();
3081         
3082         if ($links) {   
3083             foreach($links as $key => $match) {
3084                 list($table,$link) = explode(':', $match);
3085                 $k = sprintf($format, str_replace('.', '_', $key));
3086                 // makes sure that '.' is the end of the key;
3087                 if ($p = strpos($key,'.')) {
3088                       $key = substr($key, 0, $p);
3089                 }
3090                 
3091                 $this->$k = $this->getLink($key, $table, $link);
3092                 
3093                 if (is_object($this->$k)) {
3094                     $loaded[] = $k; 
3095                 }
3096             }
3097             $this->_link_loaded = $loaded;
3098             return true;
3099         }
3100         // this is the autonaming stuff..
3101         // it sends the column name down to getLink and lets that sort it out..
3102         // if there is a links file then it is not used!
3103         // IT IS DEPRECIATED!!!! - USE 
3104         if (!is_null($links)) {    
3105             return false;
3106         }
3107         
3108         
3109         foreach (array_keys($cols) as $key) {
3110             if (!($p = strpos($key, '_'))) {
3111                 continue;
3112             }
3113             // does the table exist.
3114             $k =sprintf($format, $key);
3115             $this->$k = $this->getLink($key);
3116             if (is_object($this->$k)) {
3117                 $loaded[] = $k; 
3118             }
3119         }
3120         $this->_link_loaded = $loaded;
3121         return true;
3122     }
3123
3124     /**
3125      * return name from related object
3126      *
3127      * There are two ways to use this, one is to set up a <dbname>.links.ini file
3128      * into a static property named <dbname>.links and specifies the table joins,
3129      * the other is highly dependant on naming columns 'correctly' :)
3130      *
3131      * NOTE: the naming convention is depreciated!!! - use links.ini
3132      *
3133      * using colname = xxxxx_yyyyyy
3134      * xxxxxx = related table; (yyyyy = user defined..)
3135      * looks up table xxxxx, for value id=$this->xxxxx
3136      * stores it in $this->_xxxxx_yyyyy
3137      *
3138      * you can also use $this->getLink('thisColumnName','otherTable','otherTableColumnName')
3139      *
3140      *
3141      * @param string $row    either row or row.xxxxx
3142      * @param string $table  name of table to look up value in
3143      * @param string $link   name of column in other table to match
3144      * @author Tim White <tim@cyface.com>
3145      * @access public
3146      * @return mixed object on success
3147      */
3148     function getLink($row, $table = null, $link = false)
3149     {
3150         
3151         
3152         // GUESS THE LINKED TABLE.. (if found - recursevly call self)
3153         
3154         if ($table === null) {
3155             $links = $this->links();
3156             
3157             if (is_array($links)) {
3158             
3159                 if ($links[$row]) {
3160                     list($table,$link) = explode(':', $links[$row]);
3161                     if ($p = strpos($row,".")) {
3162                         $row = substr($row,0,$p);
3163                     }
3164                     return $this->getLink($row,$table,$link);
3165                     
3166                 } 
3167                 
3168                 $this->raiseError(
3169                     "getLink: $row is not defined as a link (normally this is ok)", 
3170                     DB_DATAOBJECT_ERROR_NODATA);
3171                     
3172                 $r = false;
3173                 return $r;// technically a possible error condition?
3174
3175             }  
3176             // use the old _ method - this shouldnt happen if called via getLinks()
3177             if (!($p = strpos($row, '_'))) {
3178                 $r = null;
3179                 return $r; 
3180             }
3181             $table = substr($row, 0, $p);
3182             return $this->getLink($row, $table);
3183             
3184
3185         }
3186         
3187         
3188         
3189         if (!isset($this->$row)) {
3190             $this->raiseError("getLink: row not set $row", DB_DATAOBJECT_ERROR_NODATA);
3191             return false;
3192         }
3193         
3194         // check to see if we know anything about this table..
3195         
3196         $obj = $this->factory($table);
3197         
3198         if (!is_a($obj,'DB_DataObject')) {
3199             $this->raiseError(
3200                 "getLink:Could not find class for row $row, table $table", 
3201                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3202             return false;
3203         }
3204         if ($link) {
3205             if ($obj->get($link, $this->$row)) {
3206                 return $obj;
3207             } 
3208             return  false;
3209         }
3210         
3211         if ($obj->get($this->$row)) {
3212             return $obj;
3213         }
3214         return false;
3215         
3216     }
3217
3218     /**
3219      * getLinkArray
3220      * Fetch an array of related objects. This should be used in conjunction with a <dbname>.links.ini file configuration (see the introduction on linking for details on this).
3221      * You may also use this with all parameters to specify, the column and related table.
3222      * This is highly dependant on naming columns 'correctly' :)
3223      * using colname = xxxxx_yyyyyy
3224      * xxxxxx = related table; (yyyyy = user defined..)
3225      * looks up table xxxxx, for value id=$this->xxxxx
3226      * stores it in $this->_xxxxx_yyyyy
3227      *
3228      * @access public
3229      * @param string $column - either column or column.xxxxx
3230      * @param string $table - name of table to look up value in
3231      * @return array - array of results (empty array on failure)
3232      * 
3233      * Example - Getting the related objects
3234      * 
3235      * $person = new DataObjects_Person;
3236      * $person->get(12);
3237      * $children = $person->getLinkArray('children');
3238      * 
3239      * echo 'There are ', count($children), ' descendant(s):<br />';
3240      * foreach ($children as $child) {
3241      *     echo $child->name, '<br />';
3242      * }
3243      * 
3244      */
3245     function &getLinkArray($row, $table = null)
3246     {
3247         
3248         $ret = array();
3249         if (!$table) {
3250             $links = $this->links();
3251             
3252             if (is_array($links)) {
3253                 if (!isset($links[$row])) {
3254                     // failed..
3255                     return $ret;
3256                 }
3257                 list($table,$link) = explode(':',$links[$row]);
3258             } else {
3259                 if (!($p = strpos($row,'_'))) {
3260                     return $ret;
3261                 }
3262                 $table = substr($row,0,$p);
3263             }
3264         }
3265         
3266         $c  = $this->factory($table);
3267         
3268         if (!is_a($c,'DB_DataObject')) {
3269             $this->raiseError(
3270                 "getLinkArray:Could not find class for row $row, table $table", 
3271                 DB_DATAOBJECT_ERROR_INVALIDCONFIG
3272             );
3273             return $ret;
3274         }
3275
3276         // if the user defined method list exists - use it...
3277         if (method_exists($c, 'listFind')) {
3278             $c->listFind($this->id);
3279         } else {
3280             $c->find();
3281         }
3282         while ($c->fetch()) {
3283             $ret[] = $c;
3284         }
3285         return $ret;
3286     }
3287
3288      /**
3289      * unionAdd - adds another dataobject to this, building a unioned query.
3290      *
3291      * usage:  
3292      * $doTable1 = DB_DataObject::factory("table1");
3293      * $doTable2 = DB_DataObject::factory("table2");
3294      * 
3295      * $doTable1->selectAdd();
3296      * $doTable1->selectAdd("col1,col2");
3297      * $doTable1->whereAdd("col1 > 100");
3298      * $doTable1->orderBy("col1");
3299      *
3300      * $doTable2->selectAdd();
3301      * $doTable2->selectAdd("col1, col2");
3302      * $doTable2->whereAdd("col2 = 'v'");
3303      * 
3304      * $doTable1->unionAdd($doTable2);
3305      * $doTable1->find();
3306       * 
3307      * Note: this model may be a better way to implement joinAdd?, eg. do the building in find?
3308      * 
3309      * 
3310      * @param             $obj       object|false the union object or false to reset
3311      * @param    optional $is_all    string 'ALL' to do all.
3312      * @returns           $obj       object|array the added object, or old list if reset.
3313      */
3314     
3315     function unionAdd($obj,$is_all= '')
3316     {
3317         if ($obj === false) {
3318             $ret = $this->_query['unions'];
3319             $this->_query['unions'] = array();
3320             return $ret;
3321         }
3322         $this->_query['unions'][] = array($obj, 'UNION ' . $is_all . ' ') ;
3323         return $obj;
3324     }
3325
3326     
3327     
3328     /**
3329      * The JOIN condition
3330      *
3331      * @access  private
3332      * @var     string
3333      */
3334     var $_join = '';
3335
3336     /**
3337      * joinAdd - adds another dataobject to this, building a joined query.
3338      *
3339      * example (requires links.ini to be set up correctly)
3340      * // get all the images for product 24
3341      * $i = new DataObject_Image();
3342      * $pi = new DataObjects_Product_image();
3343      * $pi->product_id = 24; // set the product id to 24
3344      * $i->joinAdd($pi); // add the product_image connectoin
3345      * $i->find();
3346      * while ($i->fetch()) {
3347      *     // do stuff
3348      * }
3349      * // an example with 2 joins
3350      * // get all the images linked with products or productgroups
3351      * $i = new DataObject_Image();
3352      * $pi = new DataObject_Product_image();
3353      * $pgi = new DataObject_Productgroup_image();
3354      * $i->joinAdd($pi);
3355      * $i->joinAdd($pgi);
3356      * $i->find();
3357      * while ($i->fetch()) {
3358      *     // do stuff
3359      * }
3360      *
3361      *
3362      * @param    optional $obj       object |array    the joining object (no value resets the join)
3363      *                                          If you use an array here it should be in the format:
3364      *                                          array('local_column','remotetable:remote_column');
3365      *                                          if remotetable does not have a definition, you should
3366      *                                          use @ to hide the include error message..
3367      *                                      
3368      *
3369      * @param    optional $joinType  string | array
3370      *                                          'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates 
3371      *                                          just select ... from a,b,c with no join and 
3372      *                                          links are added as where items.
3373      *                                          
3374      *                                          If second Argument is array, it is assumed to be an associative
3375      *                                          array with arguments matching below = eg.
3376      *                                          'joinType' => 'INNER',
3377      *                                          'joinAs' => '...'
3378      *                                          'joinCol' => ....
3379      *                                          'useWhereAsOn' => false,
3380      *
3381      * @param    optional $joinAs    string     if you want to select the table as anther name
3382      *                                          useful when you want to select multiple columsn
3383      *                                          from a secondary table.
3384      
3385      * @param    optional $joinCol   string     The column on This objects table to match (needed
3386      *                                          if this table links to the child object in 
3387      *                                          multiple places eg.
3388      *                                          user->friend (is a link to another user)
3389      *                                          user->mother (is a link to another user..)
3390      *
3391      *           optional 'useWhereAsOn' bool   default false;
3392      *                                          convert the where argments from the object being added
3393      *                                          into ON arguments.
3394      * 
3395      * 
3396      * @return   none
3397      * @access   public
3398      * @author   Stijn de Reede      <sjr@gmx.co.uk>
3399      */
3400     function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
3401     {
3402         global $_DB_DATAOBJECT;
3403         if ($obj === false) {
3404             $this->_join = '';
3405             return;
3406         }
3407          
3408         //echo '<PRE>'; print_r(func_get_args());
3409         $useWhereAsOn = false;
3410         // support for 2nd argument as an array of options
3411         if (is_array($joinType)) {
3412             // new options can now go in here... (dont forget to document them)
3413             $useWhereAsOn = !empty($joinType['useWhereAsOn']);
3414             $joinCol      = isset($joinType['joinCol'])  ? $joinType['joinCol']  : $joinCol;
3415             $joinAs       = isset($joinType['joinAs'])   ? $joinType['joinAs']   : $joinAs;
3416             $joinType     = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
3417         }
3418         // support for array as first argument 
3419         // this assumes that you dont have a links.ini for the specified table.
3420         // and it doesnt exist as am extended dataobject!! - experimental.
3421         
3422         $ofield = false; // object field
3423         $tfield = false; // this field
3424         $toTable = false;
3425         if (is_array($obj)) {
3426             $tfield = $obj[0];
3427             list($toTable,$ofield) = explode(':',$obj[1]);
3428             $obj = DB_DataObject::factory($toTable);
3429             
3430             if (!$obj || is_a($obj,'PEAR_Error')) {
3431                 $obj = new DB_DataObject;
3432                 $obj->__table = $toTable;
3433             }
3434             $obj->_connect();
3435             // set the table items to nothing.. - eg. do not try and match
3436             // things in the child table...???
3437             $items = array();
3438         }
3439         
3440         if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
3441             return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
3442         }
3443         /*  make sure $this->_database is set.  */
3444         $this->_connect();
3445         $DB = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3446        
3447
3448         /// CHANGED 26 JUN 2009 - we prefer links from our local table over the remote one.
3449         
3450         /* otherwise see if there are any links from this table to the obj. */
3451         //print_r($this->links());
3452         if (($ofield === false) && ($links = $this->links())) {
3453             // this enables for support for arrays of links in ini file.
3454             // link contains this_column[] =  linked_table:linked_column
3455             // or standard way.
3456             // link contains this_column =  linked_table:linked_column
3457             foreach ($links as $k => $linkVar) {
3458             
3459                 if (!is_array($linkVar)) {
3460                     $linkVar  = array($linkVar);
3461                 }
3462                 foreach($linkVar as $v) {
3463
3464                     
3465                     
3466                     /* link contains {this column} = {linked table}:{linked column} */
3467                     $ar = explode(':', $v);
3468                     // Feature Request #4266 - Allow joins with multiple keys
3469                     if (strpos($k, ',') !== false) {
3470                         $k = explode(',', $k);
3471                     }
3472                     if (strpos($ar[1], ',') !== false) {
3473                         $ar[1] = explode(',', $ar[1]);
3474                     }
3475
3476                     if ($ar[0] != $obj->__table) {
3477                         continue;
3478                     }
3479                     if ($joinCol !== false) {
3480                         if ($k == $joinCol) {
3481                             // got it!?
3482                             $tfield = $k;
3483                             $ofield = $ar[1];
3484                             break;
3485                         } 
3486                         continue;
3487                         
3488                     } 
3489                     $tfield = $k;
3490                     $ofield = $ar[1];
3491                     break;
3492                         
3493                 }
3494             }
3495         }
3496          /* look up the links for obj table */
3497         //print_r($obj->links());
3498         if (!$ofield && ($olinks = $obj->links())) {
3499             
3500             foreach ($olinks as $k => $linkVar) {
3501                 /* link contains {this column} = array ( {linked table}:{linked column} )*/
3502                 if (!is_array($linkVar)) {
3503                     $linkVar  = array($linkVar);
3504                 }
3505                 foreach($linkVar as $v) {
3506                     
3507                     /* link contains {this column} = {linked table}:{linked column} */
3508                     $ar = explode(':', $v);
3509                     
3510                     // Feature Request #4266 - Allow joins with multiple keys
3511                     $links_key_array = strpos($k,',');
3512                     if ($links_key_array !== false) {
3513                         $k = explode(',', $k);
3514                     }
3515                     
3516                     $ar_array = strpos($ar[1],',');
3517                     if ($ar_array !== false) {
3518                         $ar[1] = explode(',', $ar[1]);
3519                     }
3520                  
3521                     if ($ar[0] != $this->__table) {
3522                         continue;
3523                     }
3524                     
3525                     // you have explictly specified the column
3526                     // and the col is listed here..
3527                     // not sure if 1:1 table could cause probs here..
3528                     
3529                     if ($joinCol !== false) {
3530                         $this->raiseError( 
3531                             "joinAdd: You cannot target a join column in the " .
3532                             "'link from' table ({$obj->__table}). " . 
3533                             "Either remove the fourth argument to joinAdd() ".
3534                             "({$joinCol}), or alter your links.ini file.",
3535                             DB_DATAOBJECT_ERROR_NODATA);
3536                         return false;
3537                     }
3538                 
3539                     $ofield = $k;
3540                     $tfield = $ar[1];
3541                     break;
3542                     
3543                 }
3544             }
3545         }
3546
3547         // finally if these two table have column names that match do a join by default on them
3548
3549         if (($ofield === false) && $joinCol) {
3550             $ofield = $joinCol;
3551             $tfield = $joinCol;
3552
3553         }
3554         /* did I find a conneciton between them? */
3555
3556         if ($ofield === false) {
3557             $this->raiseError(
3558                 "joinAdd: {$obj->__table} has no link with {$this->__table}",
3559                 DB_DATAOBJECT_ERROR_NODATA);
3560             return false;
3561         }
3562         $joinType = strtoupper($joinType);
3563         
3564         // we default to joining as the same name (this is remvoed later..)
3565         
3566         if ($joinAs === false) {
3567             $joinAs = $obj->__table;
3568         }
3569         
3570         $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
3571         $options = $_DB_DATAOBJECT['CONFIG'];
3572         
3573         // not sure  how portable adding database prefixes is..
3574         $objTable = $quoteIdentifiers ? 
3575                 $DB->quoteIdentifier($obj->__table) : 
3576                  $obj->__table ;
3577                 
3578         $dbPrefix  = '';
3579         if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli'))) {
3580             $dbPrefix = ($quoteIdentifiers
3581                          ? $DB->quoteIdentifier($obj->_database)
3582                          : $obj->_database) . '.';    
3583         }
3584         
3585         // if they are the same, then dont add a prefix...                
3586         if ($obj->_database == $this->_database) {
3587            $dbPrefix = '';
3588         }
3589         // as far as we know only mysql supports database prefixes..
3590         // prefixing the database name is now the default behaviour,
3591         // as it enables joining mutiple columns from multiple databases...
3592          
3593             // prefix database (quoted if neccessary..)
3594         $objTable = $dbPrefix . $objTable;
3595        
3596         $cond = '';
3597
3598         // if obj only a dataobject - eg. no extended class has been defined..
3599         // it obvioulsy cant work out what child elements might exist...
3600         // until we get on the fly querying of tables..
3601         // note: we have already checked that it is_a(db_dataobject earlier)
3602         if ( strtolower(get_class($obj)) != 'db_dataobject') {
3603                  
3604             // now add where conditions for anything that is set in the object 
3605         
3606         
3607         
3608             $items = $obj->table();
3609             // will return an array if no items..
3610             
3611             // only fail if we where expecting it to work (eg. not joined on a array)
3612              
3613             if (!$items) {
3614                 $this->raiseError(
3615                     "joinAdd: No table definition for {$obj->__table}", 
3616                     DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3617                 return false;
3618             }
3619             
3620             $ignore_null = !isset($options['disable_null_strings'])
3621                     || !is_string($options['disable_null_strings'])
3622                     || strtolower($options['disable_null_strings']) !== 'full' ;
3623             
3624
3625             foreach($items as $k => $v) {
3626                 if (!isset($obj->$k) && $ignore_null) {
3627                     continue;
3628                 }
3629                 
3630                 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
3631                 
3632                 if (DB_DataObject::_is_null($obj,$k)) {
3633                         $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
3634                         continue;
3635                 }
3636                 
3637                 if ($v & DB_DATAOBJECT_STR) {
3638                     $obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
3639                             ($v & DB_DATAOBJECT_BOOL) ? 
3640                                 // this is thanks to the braindead idea of postgres to 
3641                                 // use t/f for boolean.
3642                                 (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :  
3643                                 $obj->$k
3644                         )));
3645                     continue;
3646                 }
3647                 if (is_numeric($obj->$k)) {
3648                     $obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
3649                     continue;
3650                 }
3651                             
3652                 if (is_a($obj->$k,'DB_DataObject_Cast')) {
3653                     $value = $obj->$k->toString($v,$DB);
3654                     if (PEAR::isError($value)) {
3655                         $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
3656                         return false;
3657                     } 
3658                     $obj->whereAdd("{$joinAs}.{$kSql} = $value");
3659                     continue;
3660                 }
3661                 
3662                 
3663                 /* this is probably an error condition! */
3664                 $obj->whereAdd("{$joinAs}.{$kSql} = 0");
3665             }
3666             if ($this->_query === false) {
3667                 $this->raiseError(
3668                     "joinAdd can not be run from a object that has had a query run on it,
3669                     clone the object or create a new one and use setFrom()", 
3670                     DB_DATAOBJECT_ERROR_INVALIDARGS);
3671                 return false;
3672             }
3673         }
3674
3675         // and finally merge the whereAdd from the child..
3676         if ($obj->_query['condition']) {
3677             $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
3678
3679             if (!$useWhereAsOn) {
3680                 $this->whereAdd($cond);
3681             }
3682         }
3683     
3684         
3685         
3686         
3687         // nested (join of joined objects..)
3688         $appendJoin = '';
3689         if ($obj->_join) {
3690             // postgres allows nested queries, with ()'s
3691             // not sure what the results are with other databases..
3692             // may be unpredictable..
3693             if (in_array($DB->dsn["phptype"],array('pgsql'))) {
3694                 $objTable = "($objTable {$obj->_join})";
3695             } else {
3696                 $appendJoin = $obj->_join;
3697             }
3698         }
3699         
3700   
3701         // fix for #2216
3702         // add the joinee object's conditions to the ON clause instead of the WHERE clause
3703         if ($useWhereAsOn && strlen($cond)) {
3704             $appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
3705         }
3706                
3707         
3708         
3709         $table = $this->__table;
3710         
3711         if ($quoteIdentifiers) {
3712             $joinAs   = $DB->quoteIdentifier($joinAs);
3713             $table    = $DB->quoteIdentifier($table);     
3714             $ofield   = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
3715             $tfield   = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield); 
3716         }
3717         // add database prefix if they are different databases
3718        
3719         
3720         $fullJoinAs = '';
3721         $addJoinAs  = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->__table) : $obj->__table) != $joinAs;
3722         if ($addJoinAs) {
3723             // join table a AS b - is only supported by a few databases and is probably not needed
3724             // , however since it makes the whole Statement alot clearer we are leaving it in
3725             // for those databases.
3726             $fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli','pgsql')) ? "AS {$joinAs}" :  $joinAs;
3727         } else {
3728             // if 
3729             $joinAs = $dbPrefix . $joinAs;
3730         }
3731         
3732         
3733         switch ($joinType) {
3734             case 'INNER':
3735             case 'LEFT': 
3736             case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
3737                 
3738                 // Feature Request #4266 - Allow joins with multiple keys
3739                 $jadd = "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3740                 //$this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
3741                 if (is_array($ofield)) {
3742                         $key_count = count($ofield);
3743                     for($i = 0; $i < $key_count; $i++) {
3744                         if ($i == 0) {
3745                                 $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
3746                         }
3747                         else {
3748                                 $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
3749                         }
3750                     }
3751                     $jadd .= ' ' . $appendJoin . ' ';
3752                 } else {
3753                         $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
3754                 }
3755                 // jadd avaliable for debugging join build.
3756                 //echo $jadd ."\n";
3757                 $this->_join .= $jadd;
3758                 break;
3759                 
3760             case '': // this is just a standard multitable select..
3761                 $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
3762                 $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
3763         }
3764          
3765          
3766         return true;
3767
3768     }
3769
3770     /**
3771      * Copies items that are in the table definitions from an
3772      * array or object into the current object
3773      * will not override key values.
3774      *
3775      *
3776      * @param    array | object  $from
3777      * @param    string  $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
3778      * @param    boolean  $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
3779      * @access   public
3780      * @return   true on success or array of key=>setValue error message
3781      */
3782     function setFrom($from, $format = '%s', $skipEmpty=false)
3783     {
3784         global $_DB_DATAOBJECT;
3785         $keys  = $this->keys();
3786         $items = $this->table();
3787         if (!$items) {
3788             $this->raiseError(
3789                 "setFrom:Could not find table definition for {$this->__table}", 
3790                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3791             return;
3792         }
3793         $overload_return = array();
3794         foreach (array_keys($items) as $k) {
3795             if (in_array($k,$keys)) {
3796                 continue; // dont overwrite keys
3797             }
3798             if (!$k) {
3799                 continue; // ignore empty keys!!! what
3800             }
3801             
3802             $chk = is_object($from) &&  
3803                 (version_compare(phpversion(), "5.1.0" , ">=") ? 
3804                     property_exists($from, sprintf($format,$k)) :  // php5.1
3805                     array_key_exists( sprintf($format,$k), get_class_vars($from)) //older
3806                 );
3807             // if from has property ($format($k)      
3808             if ($chk) {
3809                 $kk = (strtolower($k) == 'from') ? '_from' : $k;
3810                 if (method_exists($this,'set'.$kk)) {
3811                     $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
3812                     if (is_string($ret)) {
3813                         $overload_return[$k] = $ret;
3814                     }
3815                     continue;
3816                 }
3817                 $this->$k = $from->{sprintf($format,$k)};
3818                 continue;
3819             }
3820             
3821             if (is_object($from)) {
3822                 continue;
3823             }
3824             
3825             if (empty($from[sprintf($format,$k)]) && $skipEmpty) {
3826                 continue;
3827             }
3828             
3829             if (!isset($from[sprintf($format,$k)]) && !DB_DataObject::_is_null($from, sprintf($format,$k))) {
3830                 continue;
3831             }
3832            
3833             $kk = (strtolower($k) == 'from') ? '_from' : $k;
3834             if (method_exists($this,'set'. $kk)) {
3835                 $ret =  $this->{'set'.$kk}($from[sprintf($format,$k)]);
3836                 if (is_string($ret)) {
3837                     $overload_return[$k] = $ret;
3838                 }
3839                 continue;
3840             }
3841             if (is_object($from[sprintf($format,$k)])) {
3842                 continue;
3843             }
3844             if (is_array($from[sprintf($format,$k)])) {
3845                 continue;
3846             }
3847             $ret = $this->fromValue($k,$from[sprintf($format,$k)]);
3848             if ($ret !== true)  {
3849                 $overload_return[$k] = 'Not A Valid Value';
3850             }
3851             //$this->$k = $from[sprintf($format,$k)];
3852         }
3853         if ($overload_return) {
3854             return $overload_return;
3855         }
3856         return true;
3857     }
3858
3859     /**
3860      * Returns an associative array from the current data
3861      * (kind of oblivates the idea behind DataObjects, but
3862      * is usefull if you use it with things like QuickForms.
3863      *
3864      * you can use the format to return things like user[key]
3865      * by sending it $object->toArray('user[%s]')
3866      *
3867      * will also return links converted to arrays.
3868      *
3869      * @param   string  sprintf format for array
3870      * @param   bool    empty only return elemnts that have a value set.
3871      *
3872      * @access   public
3873      * @return   array of key => value for row
3874      */
3875
3876     function toArray($format = '%s', $hideEmpty = false) 
3877     {
3878         global $_DB_DATAOBJECT;
3879         $ret = array();
3880         $rf = ($this->_resultFields !== false) ? $this->_resultFields : 
3881                 (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ? $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
3882         $ar = ($rf !== false) ?
3883             array_merge($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid],$this->table()) :
3884             $this->table();
3885
3886         foreach($ar as $k=>$v) {
3887              
3888             if (!isset($this->$k)) {
3889                 if (!$hideEmpty) {
3890                     $ret[sprintf($format,$k)] = '';
3891                 }
3892                 continue;
3893             }
3894             // call the overloaded getXXXX() method. - except getLink and getLinks
3895             if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
3896                 $ret[sprintf($format,$k)] = $this->{'get'.$k}();
3897                 continue;
3898             }
3899             // should this call toValue() ???
3900             $ret[sprintf($format,$k)] = $this->$k;
3901         }
3902         if (!$this->_link_loaded) {
3903             return $ret;
3904         }
3905         foreach($this->_link_loaded as $k) {
3906             $ret[sprintf($format,$k)] = $this->$k->toArray();
3907         
3908         }
3909         
3910         return $ret;
3911     }
3912
3913     /**
3914      * validate the values of the object (usually prior to inserting/updating..)
3915      *
3916      * Note: This was always intended as a simple validation routine.
3917      * It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
3918      *
3919      * This should be moved to another class: DB_DataObject_Validate 
3920      *      FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
3921      *
3922      * Usage:
3923      * if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
3924      *
3925      * Logic:
3926      *   - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
3927      *   - validate Column methods : "validate{ROWNAME}()"  are called if they are defined.
3928      *            These methods should return 
3929      *                  true = everything ok
3930      *                  false|object = something is wrong!
3931      * 
3932      *   - This method loads and uses the PEAR Validate Class.
3933      *
3934      *
3935      * @access  public
3936      * @return  array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
3937      */
3938     function validate()
3939     {
3940         global $_DB_DATAOBJECT;
3941         require_once 'Validate.php';
3942         $table = $this->table();
3943         $ret   = array();
3944         $seq   = $this->sequenceKey();
3945         $options = $_DB_DATAOBJECT['CONFIG'];
3946         foreach($table as $key => $val) {
3947             
3948             
3949             // call user defined validation always...
3950             $method = "Validate" . ucfirst($key);
3951             if (method_exists($this, $method)) {
3952                 $ret[$key] = $this->$method();
3953                 continue;
3954             }
3955             
3956             // if not null - and it's not set.......
3957             
3958             if ($val & DB_DATAOBJECT_NOTNULL && DB_DataObject::_is_null($this, $key)) {
3959                 // dont check empty sequence key values..
3960                 if (($key == $seq[0]) && ($seq[1] == true)) {
3961                     continue;
3962                 }
3963                 $ret[$key] = false;
3964                 continue;
3965             }
3966             
3967             
3968              if (DB_DataObject::_is_null($this, $key)) {
3969                 if ($val & DB_DATAOBJECT_NOTNULL) {
3970                     $this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
3971                     $ret[$key] = false;
3972                     continue;
3973                 }
3974                 continue;
3975             }
3976
3977             // ignore things that are not set. ?
3978            
3979             if (!isset($this->$key)) {
3980                 continue;
3981             }
3982             
3983             // if the string is empty.. assume it is ok..
3984             if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
3985                 continue;
3986             }
3987             
3988             // dont try and validate cast objects - assume they are problably ok..
3989             if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
3990                 continue;
3991             }
3992             // at this point if you have set something to an object, and it's not expected
3993             // the Validate will probably break!!... - rightly so! (your design is broken, 
3994             // so issuing a runtime error like PEAR_Error is probably not appropriate..
3995             
3996             switch (true) {
3997                 // todo: date time.....
3998                 case  ($val & DB_DATAOBJECT_STR):
3999                     $ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
4000                     continue;
4001                 case  ($val & DB_DATAOBJECT_INT):
4002                     $ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
4003                     continue;
4004             }
4005         }
4006         // if any of the results are false or an object (eg. PEAR_Error).. then return the array..
4007         foreach ($ret as $key => $val) {
4008             if ($val !== true) {
4009                 return $ret;
4010             }
4011         }
4012         return true; // everything is OK.
4013     }
4014
4015     /**
4016      * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
4017      *
4018      * @access public
4019      * @return object The DB connection
4020      */
4021     function &getDatabaseConnection()
4022     {
4023         global $_DB_DATAOBJECT;
4024
4025         if (($e = $this->_connect()) !== true) {
4026             return $e;
4027         }
4028         if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4029             $r = false;
4030             return $r;
4031         }
4032         return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
4033     }
4034  
4035  
4036     /**
4037      * Gets the DB result object related to the objects active query
4038      *  - so you can use funky pear stuff with it - like pager for example.. :)
4039      *
4040      * @access public
4041      * @return object The DB result object
4042      */
4043      
4044     function &getDatabaseResult()
4045     {
4046         global $_DB_DATAOBJECT;
4047         $this->_connect();
4048         if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4049             $r = false;
4050             return $r;
4051         }
4052         return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
4053     }
4054
4055     /**
4056      * Overload Extension support
4057      *  - enables setCOLNAME/getCOLNAME
4058      *  if you define a set/get method for the item it will be called.
4059      * otherwise it will just return/set the value.
4060      * NOTE this currently means that a few Names are NO-NO's 
4061      * eg. links,link,linksarray, from, Databaseconnection,databaseresult
4062      *
4063      * note 
4064      *  - set is automatically called by setFrom.
4065      *   - get is automatically called by toArray()
4066      *  
4067      * setters return true on success. = strings on failure
4068      * getters return the value!
4069      *
4070      * this fires off trigger_error - if any problems.. pear_error, 
4071      * has problems with 4.3.2RC2 here
4072      *
4073      * @access public
4074      * @return true?
4075      * @see overload
4076      */
4077
4078     
4079     function _call($method,$params,&$return) {
4080         
4081         //$this->debug("ATTEMPTING OVERLOAD? $method");
4082         // ignore constructors : - mm
4083         if (strtolower($method) == strtolower(get_class($this))) {
4084             return true;
4085         }
4086         $type = strtolower(substr($method,0,3));
4087         $class = get_class($this);
4088         if (($type != 'set') && ($type != 'get')) {
4089             return false;
4090         }
4091          
4092         
4093         
4094         // deal with naming conflick of setFrom = this is messy ATM!
4095         
4096         if (strtolower($method) == 'set_from') {
4097             $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
4098             return  true;
4099         }
4100         
4101         $element = substr($method,3);
4102         
4103         // dont you just love php's case insensitivity!!!!
4104         
4105         $array =  array_keys(get_class_vars($class));
4106         /* php5 version which segfaults on 5.0.3 */
4107         if (class_exists('ReflectionClass')) {
4108             $reflection = new ReflectionClass($class);
4109             $array = array_keys($reflection->getdefaultProperties());
4110         }
4111         
4112         if (!in_array($element,$array)) {
4113             // munge case
4114             foreach($array as $k) {
4115                 $case[strtolower($k)] = $k;
4116             }
4117             if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
4118                 trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
4119                 $element = strtolower($element);
4120             }
4121             
4122             // does it really exist?
4123             if (!isset($case[$element])) {
4124                 return false;            
4125             }
4126             // use the mundged case
4127             $element = $case[$element]; // real case !
4128         }
4129         
4130         
4131         if ($type == 'get') {
4132             $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
4133             return true;
4134         }
4135         
4136         
4137         $return = $this->fromValue($element, $params[0]);
4138          
4139         return true;
4140             
4141           
4142     }
4143         
4144     
4145     /**
4146     * standard set* implementation.
4147     *
4148     * takes data and uses it to set dates/strings etc.
4149     * normally called from __call..  
4150     *
4151     * Current supports
4152     *   date      = using (standard time format, or unixtimestamp).... so you could create a method :
4153     *               function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
4154     *
4155     *   time      = using strtotime 
4156     *   datetime  = using  same as date - accepts iso standard or unixtimestamp.
4157     *   string    = typecast only..
4158     * 
4159     * TODO: add formater:: eg. d/m/Y for date! ???
4160     *
4161     * @param   string       column of database
4162     * @param   mixed        value to assign
4163     *
4164     * @return   true| false     (False on error)
4165     * @access   public 
4166     * @see      DB_DataObject::_call
4167     */
4168   
4169     
4170     function fromValue($col,$value) 
4171     {
4172         global $_DB_DATAOBJECT;
4173         $options = $_DB_DATAOBJECT['CONFIG'];
4174         $cols = $this->table();
4175         // dont know anything about this col..
4176         if (!isset($cols[$col])) {
4177             $this->$col = $value;
4178             return true;
4179         }
4180         //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
4181         switch (true) {
4182             // set to null and column is can be null...
4183             case ((!($cols[$col] & DB_DATAOBJECT_NOTNULL)) && DB_DataObject::_is_null($value, false)):
4184             case (is_object($value) && is_a($value,'DB_DataObject_Cast')): 
4185                 $this->$col = $value;
4186                 return true;
4187                 
4188             // fail on setting null on a not null field..
4189             case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value,false)):
4190
4191                 return false;
4192         
4193             case (($cols[$col] & DB_DATAOBJECT_DATE) &&  ($cols[$col] & DB_DATAOBJECT_TIME)):
4194                 // empty values get set to '' (which is inserted/updated as NULl
4195                 if (!$value) {
4196                     $this->$col = '';
4197                 }
4198             
4199                 if (is_numeric($value)) {
4200                     $this->$col = date('Y-m-d H:i:s', $value);
4201                     return true;
4202                 }
4203               
4204                 // eak... - no way to validate date time otherwise...
4205                 $this->$col = (string) $value;
4206                 return true;
4207             
4208             case ($cols[$col] & DB_DATAOBJECT_DATE):
4209                 // empty values get set to '' (which is inserted/updated as NULl
4210                  
4211                 if (!$value) {
4212                     $this->$col = '';
4213                     return true; 
4214                 }
4215             
4216                 if (is_numeric($value)) {
4217                     $this->$col = date('Y-m-d',$value);
4218                     return true;
4219                 }
4220                  
4221                 // try date!!!!
4222                 require_once 'Date.php';
4223                 $x = new Date($value);
4224                 $this->$col = $x->format("%Y-%m-%d");
4225                 return true;
4226             
4227             case ($cols[$col] & DB_DATAOBJECT_TIME):
4228                 // empty values get set to '' (which is inserted/updated as NULl
4229                 if (!$value) {
4230                     $this->$col = '';
4231                 }
4232             
4233                 $guess = strtotime($value);
4234                 if ($guess != -1) {
4235                      $this->$col = date('H:i:s', $guess);
4236                     return $return = true;
4237                 }
4238                 // otherwise an error in type...
4239                 return false;
4240             
4241             case ($cols[$col] & DB_DATAOBJECT_STR):
4242                 
4243                 $this->$col = (string) $value;
4244                 return true;
4245                 
4246             // todo : floats numerics and ints...
4247             default:
4248                 $this->$col = $value;
4249                 return true;
4250         }
4251     
4252     
4253     
4254     }
4255      /**
4256     * standard get* implementation.
4257     *
4258     *  with formaters..
4259     * supported formaters:  
4260     *   date/time : %d/%m/%Y (eg. php strftime) or pear::Date 
4261     *   numbers   : %02d (eg. sprintf)
4262     *  NOTE you will get unexpected results with times like 0000-00-00 !!!
4263     *
4264     *
4265     * 
4266     * @param   string       column of database
4267     * @param   format       foramt
4268     *
4269     * @return   true     Description
4270     * @access   public 
4271     * @see      DB_DataObject::_call(),strftime(),Date::format()
4272     */
4273     function toValue($col,$format = null) 
4274     {
4275         if (is_null($format)) {
4276             return $this->$col;
4277         }
4278         $cols = $this->table();
4279         switch (true) {
4280             case (($cols[$col] & DB_DATAOBJECT_DATE) &&  ($cols[$col] & DB_DATAOBJECT_TIME)):
4281                 if (!$this->$col) {
4282                     return '';
4283                 }
4284                 $guess = strtotime($this->$col);
4285                 if ($guess != -1) {
4286                     return strftime($format, $guess);
4287                 }
4288                 // eak... - no way to validate date time otherwise...
4289                 return $this->$col;
4290             case ($cols[$col] & DB_DATAOBJECT_DATE):
4291                 if (!$this->$col) {
4292                     return '';
4293                 } 
4294                 $guess = strtotime($this->$col);
4295                 if ($guess != -1) {
4296                     return strftime($format,$guess);
4297                 }
4298                 // try date!!!!
4299                 require_once 'Date.php';
4300                 $x = new Date($this->$col);
4301                 return $x->format($format);
4302                 
4303             case ($cols[$col] & DB_DATAOBJECT_TIME):
4304                 if (!$this->$col) {
4305                     return '';
4306                 }
4307                 $guess = strtotime($this->$col);
4308                 if ($guess > -1) {
4309                     return strftime($format, $guess);
4310                 }
4311                 // otherwise an error in type...
4312                 return $this->$col;
4313                 
4314             case ($cols[$col] &  DB_DATAOBJECT_MYSQLTIMESTAMP):
4315                 if (!$this->$col) {
4316                     return '';
4317                 }
4318                 require_once 'Date.php';
4319                 
4320                 $x = new Date($this->$col);
4321                 
4322                 return $x->format($format);
4323             
4324              
4325             case ($cols[$col] &  DB_DATAOBJECT_BOOL):
4326                 
4327                 if ($cols[$col] &  DB_DATAOBJECT_STR) {
4328                     // it's a 't'/'f' !
4329                     return ($this->$col === 't');
4330                 }
4331                 return (bool) $this->$col;
4332             
4333                
4334             default:
4335                 return sprintf($format,$this->col);
4336         }
4337             
4338
4339     }
4340     
4341     
4342     /* ----------------------- Debugger ------------------ */
4343
4344     /**
4345      * Debugger. - use this in your extended classes to output debugging information.
4346      *
4347      * Uses DB_DataObject::DebugLevel(x) to turn it on
4348      *
4349      * @param    string $message - message to output
4350      * @param    string $logtype - bold at start
4351      * @param    string $level   - output level
4352      * @access   public
4353      * @return   none
4354      */
4355     function debug($message, $logtype = 0, $level = 1)
4356     {
4357         global $_DB_DATAOBJECT;
4358
4359         if (empty($_DB_DATAOBJECT['CONFIG']['debug'])  || 
4360             (is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) &&  $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
4361             return;
4362         }
4363         // this is a bit flaky due to php's wonderfull class passing around crap..
4364         // but it's about as good as it gets..
4365         $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
4366         
4367         if (!is_string($message)) {
4368             $message = print_r($message,true);
4369         }
4370         if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
4371             return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
4372         }
4373         
4374         if (!ini_get('html_errors')) {
4375             echo "$class   : $logtype       : $message\n";
4376             flush();
4377             return;
4378         }
4379         if (!is_string($message)) {
4380             $message = print_r($message,true);
4381         }
4382         $colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
4383         echo "<code>{$colorize}<B>$class: $logtype:</B> ". nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
4384     }
4385
4386     /**
4387      * sets and returns debug level
4388      * eg. DB_DataObject::debugLevel(4);
4389      *
4390      * @param   int     $v  level
4391      * @access  public
4392      * @return  none
4393      */
4394     function debugLevel($v = null)
4395     {
4396         global $_DB_DATAOBJECT;
4397         if (empty($_DB_DATAOBJECT['CONFIG'])) {
4398             DB_DataObject::_loadConfig();
4399         }
4400         if ($v !== null) {
4401             $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4402             $_DB_DATAOBJECT['CONFIG']['debug']  = $v;
4403             return $r;
4404         }
4405         return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4406     }
4407
4408     /**
4409      * Last Error that has occured
4410      * - use $this->_lastError or
4411      * $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4412      *
4413      * @access  public
4414      * @var     object PEAR_Error (or false)
4415      */
4416     var $_lastError = false;
4417
4418     /**
4419      * Default error handling is to create a pear error, but never return it.
4420      * if you need to handle errors you should look at setting the PEAR_Error callback
4421      * this is due to the fact it would wreck havoc on the internal methods!
4422      *
4423      * @param  int $message    message
4424      * @param  int $type       type
4425      * @param  int $behaviour  behaviour (die or continue!);
4426      * @access public
4427      * @return error object
4428      */
4429     function raiseError($message, $type = null, $behaviour = null)
4430     {
4431         global $_DB_DATAOBJECT;
4432         
4433         if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
4434             $behaviour = null;
4435         }
4436         $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4437         
4438         // this will never work totally with PHP's object model.
4439         // as this is passed on static calls (like staticGet in our case)
4440
4441         if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
4442             $this->_lastError = $error;
4443         }
4444
4445         $_DB_DATAOBJECT['LASTERROR'] = $error;
4446
4447         // no checks for production here?....... - we log  errors before we throw them.
4448         DB_DataObject::debug($message,'ERROR',1);
4449         
4450         
4451         if (PEAR::isError($message)) {
4452             $error = $message;
4453         } else {
4454             require_once 'DB/DataObject/Error.php';
4455             $error = PEAR::raiseError($message, $type, $behaviour,
4456                             $opts=null, $userinfo=null, 'DB_DataObject_Error'
4457                         );
4458         }
4459    
4460         return $error;
4461     }
4462
4463     /**
4464      * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to  PEAR::getStaticProperty('DB_DataObject','options');
4465      *
4466      * After Profiling DB_DataObject, I discoved that the debug calls where taking
4467      * considerable time (well 0.1 ms), so this should stop those calls happening. as
4468      * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
4469      * THIS STILL NEEDS FURTHER INVESTIGATION
4470      *
4471      * @access   public
4472      * @return   object an error object
4473      */
4474     function _loadConfig()
4475     {
4476         global $_DB_DATAOBJECT;
4477
4478         $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
4479
4480
4481     }
4482      /**
4483      * Free global arrays associated with this object.
4484      *
4485      *
4486      * @access   public
4487      * @return   none
4488      */
4489     function free() 
4490     {
4491         global $_DB_DATAOBJECT;
4492           
4493         if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
4494             unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
4495         }
4496         if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {     
4497             unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
4498         }
4499         // clear the staticGet cache as well.
4500         $this->_clear_cache();
4501         // this is a huge bug in DB!
4502         if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4503             $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
4504         }
4505
4506         if (is_array($this->_link_loaded)) {
4507             foreach ($this->_link_loaded as $do) {
4508                 $do->free();
4509             }
4510         }
4511
4512         
4513     }
4514     /**
4515     * Evaluate whether or not a value is set to null, taking the 'disable_null_strings' option into account.
4516     * If the value is a string set to "null" and the "disable_null_strings" option is not set to 
4517     * true, then the value is considered to be null.
4518     * If the value is actually a PHP NULL value, and "disable_null_strings" has been set to 
4519     * the value "full", then it will also be considered null. - this can not differenticate between not set
4520     * 
4521     * 
4522     * @param  object|array $obj_or_ar 
4523     * @param  string|false $prop prperty
4524     
4525     * @access private
4526     * @return bool  object
4527     */
4528     function _is_null($obj_or_ar , $prop) 
4529     {
4530         global $_DB_DATAOBJECT;
4531         
4532         
4533         $isset = $prop === false ? isset($obj_or_ar) : 
4534             (is_array($obj_or_ar) ? isset($obj_or_ar[$prop]) : isset($obj_or_ar->$prop));
4535         
4536         $value = $isset ? 
4537             ($prop === false ? $obj_or_ar : 
4538                 (is_array($obj_or_ar) ? $obj_or_ar[$prop] : $obj_or_ar->$prop))
4539             : null;
4540         
4541         
4542         
4543         $options = $_DB_DATAOBJECT['CONFIG'];
4544         
4545         $null_strings = !isset($options['disable_null_strings'])
4546                     || $options['disable_null_strings'] === false;
4547                     
4548         $crazy_null = isset($options['disable_null_strings'])
4549                 && is_string($options['disable_null_strings'])
4550                 && strtolower($options['disable_null_strings'] === 'full');
4551         
4552         if ( $null_strings && $isset  && is_string($value)  && (strtolower($value) === 'null') ) {
4553             return true;
4554         }
4555         
4556         if ( $crazy_null && !$isset )  {
4557                 return true;
4558         }
4559         
4560         return false;
4561         
4562         
4563     }
4564     
4565     /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
4566     
4567     function _get_table() { return $this->table(); }
4568     function _get_keys()  { return $this->keys();  }
4569     
4570     
4571     
4572     
4573 }
4574 // technially 4.3.2RC1 was broken!!
4575 // looks like 4.3.3 may have problems too....
4576 if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
4577
4578     if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
4579         if (version_compare( phpversion(), "5") < 0) {
4580            overload('DB_DataObject');
4581         } 
4582         $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;
4583     }
4584 }
4585
4586