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