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