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