Fix #8135 - fixes to image captcha
[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 #[AllowDynamicProperties] 
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                         number_format($t[0]+$t[1]- $_DB_DATAOBJECT['QUERYENDTIME']  , 4) . 
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         
2199         if (isset($_GET['db-dataobject-clear-cache'])) {
2200             foreach ($schemas as $ini) {
2201                 if (file_exists($ini) && is_file($ini)) {
2202                     unlink($ini);
2203                 }
2204             }
2205             die('DataObject Cache has been deleted, <a href="javascript:history.back()">Go Back to previous page and try again</a>');
2206         }
2207         
2208         $e = new Exception();
2209         $this->debug("Cant find database schema: {$this->_database}/{$this->tableName()} \n".
2210                     "in links file data: " . print_r($_DB_DATAOBJECT['INI'],true) . "\n BACKTRACE:" .
2211                     $e->getTraceAsString(),"databaseStructure",5);
2212         // we have to die here!! - it causes chaos if we dont (including looping forever!)
2213         $this->raiseError( "Unable to load schema for database and table - (try deleting cache then  turn debugging up to 5 for full error message)" .
2214                           ' - try <a href="?db-dataobject-clear-cache">this link</a> to see if it fixes it.',
2215                           DB_DATAOBJECT_ERROR_INVALIDARGS, PEAR_ERROR_DIE);
2216         return false;
2217         
2218          
2219     }
2220
2221
2222
2223
2224     /**
2225      * Return or assign the name of the current table
2226      *
2227      *
2228      * @param   string optinal table name to set
2229      * @access public
2230      * @return string The name of the current table
2231      */
2232     function tableName()
2233     {
2234         global $_DB_DATAOBJECT;
2235         $args = func_get_args();
2236         if (count($args)) {
2237             $this->__table = $args[0];
2238         }
2239         if (empty($this->__table)) {
2240             return '';
2241         }
2242         $table = $this->__table;
2243         if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
2244             $table = strtolower($this->__table);
2245         }
2246         if (!empty($_DB_DATAOBJECT['CONFIG']['table_alias']) && isset($_DB_DATAOBJECT['CONFIG']['table_alias'][$table])) {
2247             return $_DB_DATAOBJECT['CONFIG']['table_alias'][$table];
2248            
2249         }
2250         
2251         return $table;
2252     }
2253     /**
2254      * Wrapper for migration to PDO DataObjects
2255      */
2256     function databaseNickname()
2257     {
2258         return $this->database();
2259     }
2260   
2261     /**
2262      * Return or assign the name of the current database
2263      *
2264      * @param   string optional database name to set
2265      * @access public
2266      * @return string The name of the current database
2267      */
2268     function database()
2269     {
2270         $args = func_get_args();
2271         if (count($args)) {
2272             $this->_database = $args[0];
2273         } else {
2274             $this->_connect();
2275         }
2276         
2277         return $this->_database;
2278     }
2279     
2280     
2281     /**
2282      * Wrapper for migration to PDO DataObjects
2283      */
2284   
2285     function tableColumns()
2286     {
2287         return call_user_func_array(array($this,'table'), func_get_args());
2288     }
2289   
2290     /**
2291      * get/set an associative array of table columns
2292      *
2293      * @access public
2294      * @param  array key=>type array
2295      * @return array (associative)
2296      */
2297     function table()
2298     {
2299         
2300         // for temporary storage of database fields..
2301         // note this is not declared as we dont want to bloat the print_r output
2302         $args = func_get_args();
2303         if (count($args)) {
2304             $this->_database_fields = $args[0];
2305         }
2306         if (isset($this->_database_fields)) {
2307             return $this->_database_fields;
2308         }
2309         
2310         
2311         global $_DB_DATAOBJECT;
2312         if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2313             $this->_connect();
2314         }
2315           
2316         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
2317             return $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()];
2318         }
2319         
2320         $this->databaseStructure();
2321  
2322          
2323         $ret = array();
2324         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()])) {
2325             $ret =  $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()];
2326         } 
2327         
2328         return $ret;
2329     }
2330
2331     /**
2332      * get/set an  array of table primary keys
2333      *
2334      * set usage: $do->keys('id','code');
2335      *
2336      * This is defined in the table definition if it gets it wrong,
2337      * or you do not want to use ini tables, you can override this.
2338      * NOTE - this will remove 'unique keys???'
2339      *
2340      * 
2341      * @param  string optional set the key
2342      * @param  *   optional  set more keys
2343      * @access public
2344      * @return array
2345      */
2346     function keys()
2347     {
2348         // for temporary storage of database fields..
2349         // note this is not declared as we dont want to bloat the print_r output
2350         $args = func_get_args();
2351         if (count($args)) {
2352             $this->_database_keys = $args;
2353         }
2354         if (isset($this->_database_keys)) {
2355             return $this->_database_keys;
2356         }
2357         
2358         global $_DB_DATAOBJECT;
2359         if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2360             $this->_connect();
2361         }
2362         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"])) {
2363            
2364             $ret = array();
2365             foreach($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"] as $k=>$v) {
2366                 if ($v != 'U') {
2367                     $ret[] = $k;
2368                 }
2369             }
2370             
2371             
2372             return $ret;
2373             
2374             
2375         }
2376         $this->databaseStructure();
2377         
2378         if (isset($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"])) {
2379             $ret = array();
2380             foreach($_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"] as $k=>$v) {
2381                 if ($v != 'U') {
2382                     $ret[] = $k;
2383                 }
2384             }
2385             return $ret;
2386         }
2387         return array();
2388     }
2389     /**
2390      * get/set an  sequence key
2391      *
2392      * by default it returns the first key from keys()
2393      * set usage: $do->sequenceKey('id',true);
2394      *
2395      * override this to return array(false,false) if table has no real sequence key.
2396      *
2397      * @param  string  optional the key sequence/autoinc. key
2398      * @param  boolean optional use native increment. default false 
2399      * @param  false|string optional native sequence name
2400      * @access public
2401      * @return array (column,use_native,sequence_name)
2402      */
2403     function sequenceKey()
2404     {
2405         global $_DB_DATAOBJECT;
2406           
2407         // call setting
2408         if (!$this->_database) {
2409             $this->_connect();
2410         }
2411         
2412         if (!isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database])) {
2413             $_DB_DATAOBJECT['SEQUENCE'][$this->_database] = array();
2414         }
2415
2416         
2417         $args = func_get_args();
2418         if (count($args)) {
2419             $args[1] = isset($args[1]) ? $args[1] : false;
2420             $args[2] = isset($args[2]) ? $args[2] : false;
2421             $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = $args;
2422         }
2423         if (isset($_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()])) {
2424             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()];
2425         }
2426         // end call setting (eg. $do->sequenceKeys(a,b,c); )
2427         
2428        
2429         
2430         
2431         $keys = $this->keys();
2432         if (!$keys) {
2433             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] 
2434                 = array(false,false,false);
2435         }
2436  
2437
2438         $table =  $this->table();
2439        
2440         $dbtype    = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'];
2441         
2442         $usekey = $keys[0];
2443         
2444         
2445         
2446         $seqname = false;
2447         
2448         if (!empty($_DB_DATAOBJECT['CONFIG']['sequence_'.$this->tableName()])) {
2449             $seqname = $_DB_DATAOBJECT['CONFIG']['sequence_'.$this->tableName()];
2450             if (strpos($seqname,':') !== false) {
2451                 list($usekey,$seqname) = explode(':',$seqname);
2452             }
2453         }  
2454         
2455         
2456         // if the key is not an integer - then it's not a sequence or native
2457         if (empty($table[$usekey]) || !($table[$usekey] & DB_DATAOBJECT_INT)) {
2458                 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,false);
2459         }
2460         
2461         
2462         if (!empty($_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'])) {
2463             $ignore =  $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'];
2464             if (is_string($ignore) && (strtoupper($ignore) == 'ALL')) {
2465                 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
2466             }
2467             if (is_string($ignore)) {
2468                 $ignore = $_DB_DATAOBJECT['CONFIG']['ignore_sequence_keys'] = explode(',',$ignore);
2469             }
2470             if (in_array($this->tableName(),$ignore)) {
2471                 return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
2472             }
2473         }
2474          
2475         
2476         $realkeys = $_DB_DATAOBJECT['INI'][$this->_database][$this->tableName()."__keys"];
2477         
2478         // if you are using an old ini file - go back to old behaviour...
2479         if (is_numeric($realkeys[$usekey])) {
2480             $realkeys[$usekey] = 'N';
2481         }
2482         
2483         // multiple unique primary keys without a native sequence...
2484         if (($realkeys[$usekey] == 'K') && (count($keys) > 1)) {
2485             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array(false,false,$seqname);
2486         }
2487         // use native sequence keys...
2488         // technically postgres native here...
2489         // we need to get the new improved tabledata sorted out first.
2490         
2491         // support named sequence keys.. - currently postgres only..
2492         
2493         if (    in_array($dbtype , array('pgsql')) &&
2494                 ($table[$usekey] & DB_DATAOBJECT_INT) && 
2495                 isset($realkeys[$usekey]) && strlen($realkeys[$usekey]) > 1) {
2496             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,true, $realkeys[$usekey]);
2497         }
2498         
2499         if (    in_array($dbtype , array('pgsql', 'mysql', 'mysqli', 'mysqlfb', 'mssql', 'ifx')) && 
2500                 ($table[$usekey] & DB_DATAOBJECT_INT) && 
2501                 isset($realkeys[$usekey]) && ($realkeys[$usekey] == 'N')
2502                 ) {
2503             return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,true,$seqname);
2504         }
2505         
2506         
2507         // if not a native autoinc, and we have not assumed all primary keys are sequence
2508         if (($realkeys[$usekey] != 'N') && 
2509             !empty($_DB_DATAOBJECT['CONFIG']['dont_use_pear_sequences'])) {
2510             return array(false,false,false);
2511         }
2512         
2513         
2514         
2515         // I assume it's going to try and be a nextval DB sequence.. (not native)
2516         return $_DB_DATAOBJECT['SEQUENCE'][$this->_database][$this->tableName()] = array($usekey,false,$seqname);
2517     }
2518     
2519     
2520     
2521     /* =========================================================== */
2522     /*  Major Private Methods - the core part!              */
2523     /* =========================================================== */
2524
2525  
2526     
2527     /**
2528      * clear the cache values for this class  - normally done on insert/update etc.
2529      *
2530      * @access private
2531      * @return void
2532      */
2533     function _clear_cache()
2534     {
2535         global $_DB_DATAOBJECT;
2536         
2537         $class = strtolower(get_class($this));
2538         
2539         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2540             $this->debug("Clearing Cache for ".$class,1);
2541         }
2542         
2543         if (!empty($_DB_DATAOBJECT['CACHE'][$class])) {
2544             unset($_DB_DATAOBJECT['CACHE'][$class]);
2545         }
2546     }
2547
2548     
2549     /**
2550      * backend wrapper for quoting, as MDB2 and DB do it differently...
2551      *
2552      * @access private
2553      * @return string quoted
2554      */
2555     
2556     function _quote($str) 
2557     {
2558         global $_DB_DATAOBJECT;
2559         return (empty($_DB_DATAOBJECT['CONFIG']['db_driver']) || 
2560                 ($_DB_DATAOBJECT['CONFIG']['db_driver'] == 'DB'))
2561             ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quoteSmart($str)
2562             : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->quote($str);
2563     }
2564     
2565     
2566     /**
2567      * connects to the database
2568      *
2569      *
2570      * TODO: tidy this up - This has grown to support a number of connection options like
2571      *  a) dynamic changing of ini file to change which database to connect to
2572      *  b) multi data via the table_{$table} = dsn ini option
2573      *  c) session based storage.
2574      *
2575      * @access private
2576      * @return true | PEAR::error
2577      */
2578     function _connect()
2579     {
2580         global $_DB_DATAOBJECT;
2581         if (empty($_DB_DATAOBJECT['CONFIG'])) {
2582             $this->_loadConfig();
2583         }
2584         // Set database driver for reference 
2585         $db_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 
2586                 'DB' : $_DB_DATAOBJECT['CONFIG']['db_driver'];
2587         
2588         // is it already connected ?    
2589         if ($this->_database_dsn_md5 && !empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2590             
2591             // connection is an error...
2592             if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2593                 return $this->raiseError(
2594                         $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->message,
2595                         $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2596                 );
2597                  
2598             }
2599
2600             if (empty($this->_database)) {
2601                 $this->_database = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2602                 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2603                 
2604                 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)  
2605                         ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase() 
2606                         : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2607
2608                 
2609                 
2610                 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite') 
2611                     && is_file($this->_database))  {
2612                     $this->_database = basename($this->_database);
2613                 }
2614                 if ($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'ibase')  {
2615                     $this->_database = substr(basename($this->_database), 0, -4);
2616                 }
2617                 
2618             }
2619             // theoretically we have a md5, it's listed in connections and it's not an error.
2620             // so everything is ok!
2621             return true;
2622             
2623         }
2624
2625         // it's not currently connected!
2626         // try and work out what to use for the dsn !
2627
2628         $options = $_DB_DATAOBJECT['CONFIG'];
2629         // if the databse dsn dis defined in the object..
2630         $dsn = isset($this->_database_dsn) ? $this->_database_dsn : null;
2631         
2632         if (!$dsn) {
2633             if (!$this->_database && !strlen($this->tableName())) {
2634                 $this->_database = isset($options["table_{$this->tableName()}"]) ? $options["table_{$this->tableName()}"] : null;
2635             }
2636             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2637                 $this->debug("Checking for database specific ini ('{$this->_database}') : database_{$this->_database} in options","CONNECT");
2638             }
2639             
2640             if ($this->_database && !empty($options["database_{$this->_database}"]))  {
2641                 $dsn = $options["database_{$this->_database}"];
2642             } else if (!empty($options['database'])) {
2643                 $dsn = $options['database'];
2644                   
2645             }
2646         }
2647
2648         // if still no database...
2649         if (!$dsn) {
2650             return $this->raiseError(
2651                 "No database name / dsn found anywhere",
2652                 DB_DATAOBJECT_ERROR_INVALIDCONFIG, PEAR_ERROR_DIE
2653             );
2654                  
2655         }
2656         
2657         
2658         if (is_string($dsn)) {
2659             $this->_database_dsn_md5 = md5($dsn);
2660         } else {
2661             /// support array based dsn's
2662             $this->_database_dsn_md5 = md5(serialize($dsn));
2663         }
2664
2665         if (!empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2666             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2667                 $this->debug("USING CACHED CONNECTION", "CONNECT",3);
2668             }
2669             
2670             
2671             
2672             if (!$this->_database) {
2673
2674                 $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2675                 $this->_database = ($db_driver != 'DB' && $hasGetDatabase)  
2676                         ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase() 
2677                         : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2678                 
2679                 if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite') 
2680                     && is_file($this->_database)) 
2681                 {
2682                     $this->_database = basename($this->_database);
2683                 }
2684             }
2685             return true;
2686         }
2687
2688         
2689         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2690             $this->debug("NEW CONNECTION TP DATABASE :" .$this->_database , "CONNECT",3);
2691             /* actualy make a connection */
2692             $this->debug(print_r($dsn,true) ." {$this->_database_dsn_md5}", "CONNECT",3);
2693         }
2694         
2695         // Note this is verbose deliberatly! 
2696         
2697         if ($db_driver == 'DB') {
2698             
2699             /* PEAR DB connect */
2700             
2701             // this allows the setings of compatibility on DB 
2702             $db_options = PEAR::getStaticProperty('DB','options');
2703             // allow for fake DB....
2704             class_exists('DB') ? '' : require_once 'DB.php';
2705             if ($db_options) {
2706                 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn,$db_options);
2707             } else {
2708                 $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = DB::connect($dsn);
2709             }
2710              
2711         } else {
2712             /* assumption is MDB2 */
2713             require_once 'MDB2.php';
2714             // this allows the setings of compatibility on MDB2 
2715             $db_options = PEAR::getStaticProperty('MDB2','options');
2716             $db_options = is_array($db_options) ? $db_options : array();
2717             $db_options['portability'] = isset($db_options['portability'] )
2718                 ? $db_options['portability']  : MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_FIX_CASE;
2719             $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5] = MDB2::connect($dsn,$db_options);
2720             
2721         }
2722  
2723         
2724         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2725             $this->debug(print_r($_DB_DATAOBJECT['CONNECTIONS'],true), "CONNECT",5);
2726         }
2727         if (PEAR::isError($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
2728             $this->debug($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->toString(), "CONNECT FAILED",5);
2729             return $this->raiseError(
2730                     "Connect failed, turn on debugging to 5 see why",
2731                         $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->code, PEAR_ERROR_DIE
2732             );
2733
2734         }
2735          
2736         if (empty($this->_database)) {
2737             $hasGetDatabase = method_exists($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5], 'getDatabase');
2738             
2739             $this->_database = ($db_driver != 'DB' && $hasGetDatabase)  
2740                     ? $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->getDatabase() 
2741                     : $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['database'];
2742
2743
2744             if (($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->dsn['phptype'] == 'sqlite') 
2745                 && is_file($this->_database)) 
2746             {
2747                 $this->_database = basename($this->_database);
2748             }
2749         }
2750         
2751         // Oracle need to optimize for portibility - not sure exactly what this does though :)
2752          
2753         return true;
2754     }
2755
2756      
2757     
2758     /**
2759      * sends query to database - this is the private one that must work 
2760      *   - internal functions use this rather than $this->query()
2761      *
2762      * @param  string  $string
2763      * @access private
2764      * @return mixed none or PEAR_Error
2765      */
2766     function _query($string)
2767     {
2768         global $_DB_DATAOBJECT;
2769         $this->_connect();
2770         
2771
2772         $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2773
2774         $options = $_DB_DATAOBJECT['CONFIG'];
2775         
2776         $_DB_driver = empty($_DB_DATAOBJECT['CONFIG']['db_driver']) ? 
2777                     'DB':  $_DB_DATAOBJECT['CONFIG']['db_driver'];
2778         
2779         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2780             $this->debug($string,$log="QUERY");
2781             
2782         }
2783         
2784         if (
2785             strtoupper($string) == 'BEGIN' ||
2786             strtoupper($string) == 'START TRANSACTION'
2787         ) {
2788             $this->debug('BEGIN');
2789             if ($_DB_driver == 'DB') {
2790                 $DB->autoCommit(false);
2791                 $DB->simpleQuery('BEGIN');
2792             } else {
2793                 $DB->beginTransaction();
2794             }
2795             return true;
2796         }
2797         
2798         if (strtoupper($string) == 'COMMIT') {
2799             $this->debug('COMMIT');
2800             $res = $DB->commit();
2801             if ($_DB_driver == 'DB') {
2802                 $DB->autoCommit(true);
2803             }
2804             return $res;
2805         }
2806         
2807         if (strtoupper($string) == 'ROLLBACK') {
2808             $this->debug('ROLLBACK');
2809             $DB->rollback();
2810             if ($_DB_driver == 'DB') {
2811                 $DB->autoCommit(true);
2812             }
2813             return true;
2814         }
2815         
2816
2817         if (!empty($options['debug_ignore_updates']) &&
2818             (strtolower(substr(trim($string), 0, 6)) != 'select') &&
2819             (strtolower(substr(trim($string), 0, 4)) != 'show') &&
2820             (strtolower(substr(trim($string), 0, 8)) != 'describe')) {
2821
2822             $this->debug('Disabling Update as you are in debug mode');
2823             return $this->raiseError("Disabling Update as you are in debug mode", null) ;
2824
2825         }
2826         //if (@$_DB_DATAOBJECT['CONFIG']['debug'] > 1) {
2827             // this will only work when PEAR:DB supports it.
2828             //$this->debug($DB->getAll('explain ' .$string,DB_DATAOBJECT_FETCHMODE_ASSOC), $log="sql",2);
2829         //}
2830         
2831         // some sim
2832         $t= explode(' ',microtime());
2833         $_DB_DATAOBJECT['QUERYENDTIME'] = $time = $t[0]+$t[1];
2834          
2835         
2836         for ($tries = 0;$tries < 3;$tries++) {
2837             
2838             if ($_DB_driver == 'DB') {
2839                 
2840                 $result = $DB->query($string);
2841             } else {
2842                 switch (strtolower(substr(trim($string),0,6))) {
2843                 
2844                     case 'insert':
2845                     case 'update':
2846                     case 'delete':
2847                         $result = $DB->exec($string);
2848                         break;
2849                         
2850                     default:
2851                         $result = $DB->query($string);
2852                         break;
2853                 }
2854             }
2855             
2856             // see if we got a failure.. - try again a few times..
2857             if (!is_object($result) || !is_a($result,'PEAR_Error')) {
2858                 break;
2859             }
2860             if ($result->getCode() != -14) {  // *DB_ERROR_NODBSELECTED
2861                 break; // not a connection error..
2862             }
2863             sleep(1); // wait before retyring..
2864             $DB->connect($DB->dsn);
2865         }
2866        
2867
2868         if (is_object($result) && is_a($result,'PEAR_Error')) {
2869             if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) { 
2870                 $this->debug($result->toString(), "Query Error",1 );
2871             }
2872             $this->N = false;
2873             return $this->raiseError($result);
2874         }
2875         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2876             $t= explode(' ',microtime());
2877             $_DB_DATAOBJECT['QUERYENDTIME'] = $t[0]+$t[1];
2878             $this->debug('QUERY DONE IN  '.number_format($t[0]+$t[1]-$time,4)." seconds", 'query',1);
2879         }
2880         switch (strtolower(substr(trim($string),0,6))) {
2881             case 'insert':
2882             case 'update':
2883             case 'delete':
2884                 if ($_DB_driver == 'DB') {
2885                     // pear DB specific
2886                     return $DB->affectedRows(); 
2887                 }
2888                 return $result;
2889         }
2890         if (is_object($result)) {
2891             // lets hope that copying the result object is OK!
2892             
2893             $_DB_resultid  = $GLOBALS['_DB_DATAOBJECT']['RESULTSEQ']++;
2894             $_DB_DATAOBJECT['RESULTS'][$_DB_resultid] = $result; 
2895             $this->_DB_resultid = $_DB_resultid;
2896         }
2897         $this->N = 0;
2898         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
2899             $this->debug(serialize($result), 'RESULT',5);
2900         }
2901         if (is_object($result) && method_exists($result, 'numRows')) {
2902             if ($_DB_driver == 'DB') {
2903                 $DB->expectError(DB_ERROR_UNSUPPORTED);
2904             } else {
2905                 $DB->expectError(MDB2_ERROR_UNSUPPORTED);
2906             }
2907             
2908             $this->N = $result->numRows();
2909             //var_dump($this->N);
2910             
2911             if (is_object($this->N) && is_a($this->N,'PEAR_Error')) {
2912                 $this->N = true;
2913             }
2914             $DB->popExpect();
2915         }
2916     }
2917
2918     /**
2919      * Builds the WHERE based on the values of of this object
2920      *
2921      * @param   mixed   $keys
2922      * @param   array   $filter (used by update to only uses keys in this filter list).
2923      * @param   array   $negative_filter (used by delete to prevent deleting using the keys mentioned..)
2924      * @access  private
2925      * @return  string
2926      */
2927     function _build_condition($keys, $filter = array(),$negative_filter=array())
2928     {
2929         global $_DB_DATAOBJECT;
2930         $this->_connect();
2931         $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2932        
2933         $quoteIdentifiers  = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
2934         $options = $_DB_DATAOBJECT['CONFIG'];
2935         
2936         // if we dont have query vars.. - reset them.
2937         if ($this->_query === false) {
2938             $x = new DB_DataObject;
2939             $this->_query= $x->_query;
2940         }
2941        
2942         
2943         foreach($keys as $k => $v) {
2944             // index keys is an indexed array
2945             /* these filter checks are a bit suspicious..
2946                 - need to check that update really wants to work this way */
2947
2948             if ($filter) {
2949                 if (!in_array($k, $filter)) {
2950                     continue;
2951                 }
2952             }
2953             if ($negative_filter) {
2954                 if (in_array($k, $negative_filter)) {
2955                     continue;
2956                 }
2957             }
2958             if (!isset($this->$k)) {
2959                 continue;
2960             }
2961             
2962             $kSql = $quoteIdentifiers 
2963                 ? ( $DB->quoteIdentifier($this->tableName()) . '.' . $DB->quoteIdentifier($k) )  
2964                 : "{$this->tableName()}.{$k}";
2965              
2966         
2967             
2968             if (is_object($this->$k) && is_a($this->$k,'DB_DataObject_Cast')) {
2969                 $dbtype = $DB->dsn["phptype"];
2970                 $value = $this->$k->toString($v,$DB);
2971                 if (PEAR::isError($value)) {
2972                     $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
2973                     return false;
2974                 }
2975                 if ((strtolower($value) === 'null') && !($v & DB_DATAOBJECT_NOTNULL)) {
2976                     $this->whereAdd(" $kSql IS NULL");
2977                     continue;
2978                 }
2979                 $this->whereAdd(" $kSql = $value");
2980                 continue;
2981             }
2982             
2983             if (!($v & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($this,$k)) {
2984                 $this->whereAdd(" $kSql  IS NULL");
2985                 continue;
2986             }
2987             
2988
2989             if ($v & DB_DATAOBJECT_STR) {
2990                 $this->whereAdd(" $kSql  = " . $this->_quote((string) (
2991                         ($v & DB_DATAOBJECT_BOOL) ? 
2992                             // this is thanks to the braindead idea of postgres to 
2993                             // use t/f for boolean.
2994                             (($this->$k === 'f') ? 0 : (int)(bool) $this->$k) :  
2995                             $this->$k
2996                     )) );
2997                 continue;
2998             }
2999             if (is_numeric($this->$k)) {
3000                 $this->whereAdd(" $kSql = {$this->$k}");
3001                 continue;
3002             }
3003             /* this is probably an error condition! */
3004             $this->whereAdd(" $kSql = ".intval($this->$k));
3005         }
3006     }
3007
3008     
3009     
3010      /**
3011      * classic factory method for loading a table class
3012      * usage: $do = DB_DataObject::factory('person')
3013      * WARNING - this may emit a include error if the file does not exist..
3014      * use @ to silence it (if you are sure it is acceptable)
3015      * eg. $do = @DB_DataObject::factory('person')
3016      *
3017      * table name can bedatabasename/table
3018      * - and allow modular dataobjects to be written..
3019      * (this also helps proxy creation)
3020      *
3021      * Experimental Support for Multi-Database factory eg. mydatabase.mytable
3022      * 
3023      * 
3024      * @param  string  $table  tablename (use blank to create a new instance of the same class.)
3025      * @access private
3026      * @return DataObject|PEAR_Error 
3027      */
3028     
3029     
3030
3031     static function factory($in_table = '')
3032     {
3033         global $_DB_DATAOBJECT;
3034         static $cache = array();
3035          
3036         // multi-database support.. - experimental.
3037         $database = '';
3038         $table = $in_table;
3039          
3040         if (strpos( $in_table,'/') !== false ) {
3041             list($database,$in_table) = explode('/',$in_table, 2);
3042         }
3043         
3044         if (empty($_DB_DATAOBJECT['CONFIG'])) {
3045             DB_DataObject::_loadConfig();
3046         }
3047         if (!empty($_DB_DATAOBJECT['CONFIG']['table_alias'])) {
3048             // old name -> loads 'new' class...
3049             $flip  = array_flip($_DB_DATAOBJECT['CONFIG']['table_alias']);
3050             if (isset($flip[$table])) {
3051                 $table = $flip[$table];
3052                 $in_table = (strlen($database) ? "$database/" : '') . $table;
3053             }
3054         }
3055         
3056         if (isset($cache[$in_table])) {
3057             $rclass = $cache[$in_table];
3058             $ret = new $rclass();
3059  
3060             if (!empty($database)) {
3061                 DB_DataObject::debug("Setting database to $database","FACTORY",1);
3062                 $ret->database($database);
3063             }
3064             return $ret;
3065         }
3066         
3067          
3068        
3069         // no configuration available for database
3070         if (!empty($database) && empty($_DB_DATAOBJECT['CONFIG']['database_'.$database])) {
3071                 $do = new DB_DataObject();
3072                 $do->raiseError(
3073                     "unable to find database_{$database} in Configuration, It is required for factory with database"
3074                     , 0, PEAR_ERROR_DIE );   
3075        }
3076         
3077        
3078         /*
3079         if ($table === '') {
3080             if (is_a($this,'DB_DataObject') && strlen($this->tableName())) {
3081                 $table = $this->tableName();
3082             } else {
3083                 return DB_DataObject::raiseError(
3084                     "factory did not recieve a table name",
3085                     DB_DATAOBJECT_ERROR_INVALIDARGS);
3086             }
3087         }
3088         
3089         */
3090         // does this need multi db support??
3091         $cp = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
3092             explode(PATH_SEPARATOR, $_DB_DATAOBJECT['CONFIG']['class_prefix']) : '';
3093         
3094         
3095         //self::debug("CLASS PREFIX {$_DB_DATAOBJECT['CONFIG']['class_prefix']}" , __FUNCTION__,5);
3096         //print_r($cp);
3097         
3098         // multiprefix support.
3099         $tbl = preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
3100         if (is_array($cp)) {
3101             $class = array();
3102             foreach($cp as $cpr) {
3103                 $ce = substr(phpversion(),0,1) > 4 ? class_exists($cpr . $tbl,false) : class_exists($cpr . $tbl);
3104                 
3105                 if ($ce && empty($class)) {
3106                     $class = $cpr . $tbl;
3107                     break;
3108                 }
3109                 $class[] = $cpr . $tbl;
3110                 $ce = false; // it's an array of options...
3111             }
3112         } else {
3113             $class = $tbl;
3114             $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
3115         }
3116         
3117         //self::debug("CLASS TRY " . var_export($class,true) , __FUNCTION__,5);
3118         
3119         $rclass = $ce ? $class  : DB_DataObject::_autoloadClass($class, $table);
3120         // proxy = full|light
3121         if (!$rclass && isset($_DB_DATAOBJECT['CONFIG']['proxy'])) { 
3122         
3123             DB_DataObject::debug("FAILED TO Autoload  $database.$table - using proxy.","FACTORY",1);
3124         
3125         
3126             $proxyMethod = 'getProxy'.$_DB_DATAOBJECT['CONFIG']['proxy'];
3127             // if you have loaded (some other way) - dont try and load it again..
3128             class_exists('DB_DataObject_Generator') ? '' : 
3129                     require_once 'DB/DataObject/Generator.php';
3130             
3131             $d = new DB_DataObject;
3132            
3133             $d->__table = $table;
3134             
3135             $ret = $d->_connect();
3136             if (is_object($ret) && is_a($ret, 'PEAR_Error')) {
3137                 return $ret;
3138             }
3139             
3140             $x = new DB_DataObject_Generator;
3141             return $x->$proxyMethod( $d->_database, $table);
3142         }
3143         
3144         if (!$rclass || !class_exists($rclass)) {
3145             $dor = new DB_DataObject();
3146             return $dor->raiseError(
3147                 "factory could not find class " . 
3148                 (is_array($class) ? implode(PATH_SEPARATOR, $class)  : $class  ). 
3149                 "from $table",
3150                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3151         }
3152  
3153         $ret = new $rclass();
3154  
3155         if (!empty($database)) {
3156             DB_DataObject::debug("Setting database to $database","FACTORY",1);
3157             $ret->database($database);
3158         }
3159         $cache[$in_table] = $rclass;
3160         return $ret;
3161     }
3162     /**
3163      * autoload Class
3164      *
3165      * @param  string|array  $class  Class
3166      * @param  string  $table  Table trying to load.
3167      * @access private
3168      * @return string classname on Success
3169      * @static
3170      */
3171     static function _autoloadClass($class, $table=false)
3172     {
3173         global $_DB_DATAOBJECT;
3174         
3175         if (empty($_DB_DATAOBJECT['CONFIG'])) {
3176             DB_DataObject::_loadConfig();
3177         }
3178         $class_prefix = empty($_DB_DATAOBJECT['CONFIG']['class_prefix']) ? 
3179                 '' : $_DB_DATAOBJECT['CONFIG']['class_prefix'];
3180                 
3181         $table   = $table ? $table : substr($class,strlen($class_prefix));
3182
3183         // only include the file if it exists - and barf badly if it has parse errors :)
3184         if (!empty($_DB_DATAOBJECT['CONFIG']['proxy']) || empty($_DB_DATAOBJECT['CONFIG']['class_location'])) {
3185             return false;
3186         }
3187         // support for:
3188         // class_location = mydir/ => maps to mydir/Tablename.php
3189         // class_location = mydir/myfile_%s.php => maps to mydir/myfile_Tablename
3190         // with directory sepr
3191         // class_location = mydir/:mydir2/: => tries all of thes locations.
3192         $cl = $_DB_DATAOBJECT['CONFIG']['class_location'];
3193         
3194         
3195         switch (true) {
3196             case (strpos($cl ,'%s') !== false):
3197                 $file = sprintf($cl , preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)));
3198                 break;
3199                 
3200             case (strpos($cl , PATH_SEPARATOR) !== false):
3201                 $file = array();
3202                 foreach(explode(PATH_SEPARATOR, $cl ) as $p) {
3203                     $file[] =  $p .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
3204                 }
3205                 break;
3206             default:
3207                 $file = $cl .'/'.preg_replace('/[^A-Z0-9]/i','_',ucfirst($table)).".php";
3208                 break;
3209         }
3210         
3211         $cls = is_array($class) ? $class : array($class);
3212         
3213         if (is_array($file) || !file_exists($file)) {
3214             $found = false;
3215             
3216             $file = is_array($file) ? $file : array($file);
3217             $search = implode(PATH_SEPARATOR, $file);
3218             foreach($file as $f) {
3219                 foreach(explode(PATH_SEPARATOR, '' . PATH_SEPARATOR . ini_get('include_path')) as $p) {
3220                     $ff = empty($p) ? $f : "$p/$f";
3221
3222                     if (file_exists($ff)) {
3223                         $file = $ff;
3224                         $found = true;
3225                         break;
3226                     }
3227                 }
3228                 if ($found) {
3229                     break;
3230                 }
3231             }
3232             if (!$found) {
3233                 $dor = new DB_DataObject();
3234                 $dor->raiseError(
3235                     "autoload:Could not find class " . implode(',', $cls) .
3236                     " using class_location value :" . $search .
3237                     " using include_path value :" . ini_get('include_path'), 
3238                     DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3239                 return false;
3240             }
3241         }
3242         
3243         include_once $file;
3244         
3245        
3246         $ce = false;
3247         foreach($cls as $c) {
3248             $ce = substr(phpversion(),0,1) > 4 ? class_exists($c,false) : class_exists($c);
3249             if ($ce) {
3250                 $class = $c;
3251                 break;
3252             }
3253         }
3254         if (!$ce) {
3255             $dor = new DB_DataObject();
3256             $dor->raiseError(
3257                 "autoload:Could not autoload " . implode(',', $cls) , 
3258                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3259             return false;
3260         }
3261         return $class;
3262     }
3263     
3264     
3265     
3266     /**
3267      * Have the links been loaded?
3268      * if they have it contains a array of those variables.
3269      *
3270      * @access  private
3271      * @var     boolean | array
3272      */
3273     var $_link_loaded = false;
3274     
3275     /**
3276     * Get the links associate array  as defined by the links.ini file.
3277     * 
3278     *
3279     * Experimental... - 
3280     * Should look a bit like
3281     *       [local_col_name] => "related_tablename:related_col_name"
3282     * 
3283     * @param    array $new_links optional - force update of the links for this table
3284     *               You probably want to restore it to it's original state after,
3285     *               as modifying here does it for the whole PHP request.
3286     * 
3287     * @return   array|null    
3288     *           array       = if there are links defined for this table.
3289     *           empty array - if there is a links.ini file, but no links on this table
3290     *           false       - if no links.ini exists for this database (hence try auto_links).
3291     * @access   public
3292     * @see      DB_DataObject::getLinks(), DB_DataObject::getLink()
3293     */
3294     
3295     function links()
3296     {
3297         global $_DB_DATAOBJECT;
3298         if (empty($_DB_DATAOBJECT['CONFIG'])) {
3299             $this->_loadConfig();
3300         }
3301         // have to connect.. -> otherwise things break later.
3302         $this->_connect();
3303         
3304         // alias for shorter code..
3305         $lcfg  = &$_DB_DATAOBJECT['LINKS'];
3306         $cfg   =  $_DB_DATAOBJECT['CONFIG'];
3307
3308         if ($args = func_get_args()) {
3309             // an associative array was specified, that updates the current
3310             // schema... - be careful doing this
3311             if (empty( $lcfg[$this->_database])) {
3312                 $lcfg[$this->_database] = array();
3313             }
3314             $lcfg[$this->_database][$this->tableName()] = $args[0];
3315             
3316         }
3317         // loaded and available.
3318         if (isset($lcfg[$this->_database][$this->tableName()])) {
3319             return $lcfg[$this->_database][$this->tableName()];
3320         }
3321         /*
3322         if (!empty($cfg['table_alias']) && isset($cfg['table_alias'][$this->__table])) {
3323             
3324             if (isset($lcfg[$this->_database][$this->__table])) {
3325                 return $lcfg[$this->_database][$this->__table];
3326             }
3327         }*/
3328
3329         // loaded 
3330         if (isset($lcfg[$this->_database])) {
3331             // either no file, or empty..
3332             return $lcfg[$this->_database] === false ? null : array();
3333         }
3334         
3335         // links are same place as schema by default.
3336         $schemas = isset($cfg['schema_location']) ?
3337             array("{$cfg['schema_location']}/{$this->_database}.ini") :
3338             array() ;
3339
3340         // if ini_* is set look there instead.
3341         // and support multiple locations.                 
3342         if (isset($cfg["ini_{$this->_database}"])) {
3343             $schemas = is_array($cfg["ini_{$this->_database}"]) ?
3344                 $cfg["ini_{$this->_database}"] :
3345                 explode(PATH_SEPARATOR,$cfg["ini_{$this->_database}"]);
3346         }
3347                         
3348         // default to not available.
3349         $lcfg[$this->_database] = false;
3350
3351         foreach ($schemas as $ini) {
3352                 
3353             $links = isset($cfg["links_{$this->_database}"]) ?
3354                     $cfg["links_{$this->_database}"] :
3355                     str_replace('.ini','.links.ini',$ini);
3356             
3357             // file really exists..
3358             if (!file_exists($links) || !is_file($links)) {
3359                 if (!empty($cfg['debug'])) {
3360                     $this->debug("Missing links.ini file: $links","links",1);
3361                 }
3362                 continue;
3363             }
3364
3365             // set to empty array - as we have at least one file now..
3366             $lcfg[$this->_database] = empty($lcfg[$this->_database]) ? array() : $lcfg[$this->_database];
3367
3368             // merge schema file into lcfg..
3369             $lcfg[$this->_database] = array_merge(
3370                 $lcfg[$this->_database],
3371                 parse_ini_file($links, true)
3372             );
3373
3374                         
3375             if (!empty($cfg['debug'])) {
3376                 $this->debug("Loaded links.ini file: $links","links",1);
3377             }
3378              
3379         }
3380         
3381         if (!empty($_DB_DATAOBJECT['CONFIG']['portability']) && $_DB_DATAOBJECT['CONFIG']['portability'] & 1) {
3382             foreach($lcfg[$this->_database] as $k=>$v) {
3383                 
3384                 $nk = strtolower($k);
3385                 // results in duplicate cols.. but not a big issue..
3386                 $lcfg[$this->_database][$nk] = isset($lcfg[$this->_database][$nk])
3387                     ? $lcfg[$this->_database][$nk]  : array();
3388                 
3389                 foreach($v as $kk =>$vv) {
3390                     //var_Dump($vv);exit;
3391                     $vv =explode(':', $vv);
3392                     $vv[0] = strtolower($vv[0]);
3393                     $lcfg[$this->_database][$nk][$kk] = implode(':', $vv);
3394                 }
3395                 
3396                 
3397             }
3398         }
3399         
3400         
3401         if (!empty($cfg['table_alias'])) {
3402             $ta = $cfg['table_alias'];
3403             foreach($lcfg[$this->_database] as $k=>$v) {
3404                 $kk = $k;
3405                 if (isset($ta[$k])) {
3406                     $kk = $ta[$k];
3407                     if (!isset($lcfg[$this->_database][$kk])) {
3408                         $lcfg[$this->_database][$kk] = array();
3409                     }
3410                 }
3411                 foreach($v as $l => $t_c) {
3412                     $bits = explode(':',$t_c);
3413                     $tt = isset($ta[$bits[0]]) ? $ta[$bits[0]] : $bits[0];
3414                     if ($tt == $bits[0] && $kk == $k) {
3415                         continue;
3416                     }
3417                     
3418                     $lcfg[$this->_database][$kk][$l] = $tt .':'. $bits[1];
3419                     
3420                     
3421                 }
3422                 
3423             }
3424         }
3425         
3426         //echo '<PRE>';print_r($lcfg);exit;
3427         
3428         // if there is no link data at all on the file!
3429         // we return null.
3430         if ($lcfg[$this->_database] === false) {
3431             return null;
3432         }
3433         
3434         if (isset($lcfg[$this->_database][$this->tableName()])) {
3435             return $lcfg[$this->_database][$this->tableName()];
3436         }
3437          
3438         return array();
3439     }
3440     
3441     
3442     /**
3443      * generic getter/setter for links
3444      *
3445      * This is the new 'recommended' way to get get/set linked objects.
3446      * must be used with links.ini
3447      *
3448      * usage:
3449      *  get:
3450      *  $obj = $do->link('company_id');
3451      *  $obj = $do->link(array('local_col', 'linktable:linked_col'));
3452      *  
3453      *  set:
3454      *  $do->link('company_id',0);
3455      *  $do->link('company_id',$obj);
3456      *  $do->link('company_id', array($obj));
3457      *
3458      *  example function
3459      *
3460      *  function company() {
3461      *     $this->link(array('company_id','company:id'), func_get_args());
3462      *   }
3463      *
3464      * 
3465      *
3466      * @param  mixed $link_spec              link specification (normally a string)
3467      *                                       uses similar rules to  joinAdd() array argument.
3468      * @param  mixed $set_value (optional)   int, DataObject, or array('set')
3469      * @author Alan Knowles
3470      * @access public
3471      * @return mixed true or false on setting, object on getting
3472      */
3473     function link($field, $set_args = array())
3474     {
3475         require_once 'DB/DataObject/Links.php';
3476         $l = new DB_DataObject_Links($this);
3477         return  $l->link($field,$set_args) ;
3478         
3479     }
3480     
3481       /**
3482      * load related objects
3483      *
3484      * Generally not recommended to use this.
3485      * The generator should support creating getter_setter methods which are better suited.
3486      *
3487      * Relies on  <dbname>.links.ini
3488      *
3489      * Sets properties on the calling dataobject  you can change what
3490      * object vars the links are stored in by  changeing the format parameter
3491      *
3492      *
3493      * @param  string format (default _%s) where %s is the table name.
3494      * @author Tim White <tim@cyface.com>
3495      * @access public
3496      * @return boolean , true on success
3497      */
3498     function getLinks($format = '_%s')
3499     {
3500         require_once 'DB/DataObject/Links.php';
3501          $l = new DB_DataObject_Links($this);
3502         return $l->applyLinks($format);
3503            
3504     }
3505
3506     /**
3507      * deprecited : @use link() 
3508      */
3509     function getLink($row, $table = null, $link = false)
3510     {
3511         require_once 'DB/DataObject/Links.php';
3512         $l = new DB_DataObject_Links($this);
3513         return $l->getLink($row, $table === null ? false: $table, $link);
3514          
3515         
3516     }
3517
3518     /**
3519      * getLinkArray
3520      * 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).
3521      * You may also use this with all parameters to specify, the column and related table.
3522      * This is highly dependant on naming columns 'correctly' :)
3523      * using colname = xxxxx_yyyyyy
3524      * xxxxxx = related table; (yyyyy = user defined..)
3525      * looks up table xxxxx, for value id=$this->xxxxx
3526      * stores it in $this->_xxxxx_yyyyy
3527      *
3528      * @access public
3529      * @param string $column - either column or column.xxxxx
3530      * @param string $table - name of table to look up value in
3531      * @return array - array of results (empty array on failure)
3532      * 
3533      * Example - Getting the related objects
3534      * 
3535      * $person = DB_DataObject::factory('Person');
3536      * $person->get(12);
3537      * $children = $person->getLinkArray('children');
3538      * 
3539      * echo 'There are ', count($children), ' descendant(s):<br />';
3540      * foreach ($children as $child) {
3541      *     echo $child->name, '<br />';
3542      * }
3543      * 
3544      */
3545     function getLinkArray($row, $table = null)
3546     {
3547         require_once 'DB/DataObject/Links.php';
3548         $l = new DB_DataObject_Links($this);
3549         return $l->getLinkArray($row, $table === null ? false: $table);
3550      
3551     }
3552
3553      /**
3554      * unionAdd - adds another dataobject to this, building a unioned query.
3555      *
3556      * usage:  
3557      * $doTable1 = DB_DataObject::factory("table1");
3558      * $doTable2 = DB_DataObject::factory("table2");
3559      * 
3560      * $doTable1->selectAdd();
3561      * $doTable1->selectAdd("col1,col2");
3562      * $doTable1->whereAdd("col1 > 100");
3563      * $doTable1->orderBy("col1");
3564      *
3565      * $doTable2->selectAdd();
3566      * $doTable2->selectAdd("col1, col2");
3567      * $doTable2->whereAdd("col2 = 'v'");
3568      * 
3569      * $doTable1->unionAdd($doTable2);
3570      * $doTable1->find();
3571       * 
3572      * Note: this model may be a better way to implement joinAdd?, eg. do the building in find?
3573      * 
3574      * 
3575      * @param             $obj       object|false the union object or false to reset
3576      * @param    optional $is_all    string 'ALL' to do all.
3577      * @returns           $obj       object|array the added object, or old list if reset.
3578      */
3579     
3580     function unionAdd($obj,$is_all= '')
3581     {
3582         if ($obj === false) {
3583             $ret = $this->_query['unions'];
3584             $this->_query['unions'] = array();
3585             return $ret;
3586         }
3587         $this->_query['unions'][] = array($obj, 'UNION ' . $is_all . ' ') ;
3588         return $obj;
3589     }
3590
3591     
3592     
3593     /**
3594      * The JOIN condition
3595      *
3596      * @access  private
3597      * @var     string
3598      */
3599     var $_join = '';
3600
3601     /**
3602      * joinAdd - adds another dataobject to this, building a joined query.
3603      *
3604      * example (requires links.ini to be set up correctly)
3605      * // get all the images for product 24
3606      * $i = DB_DataObject::factory('image');
3607      * $pi = DB_DAtaObject::factory('product_image');
3608      * $pi->product_id = 24; // set the product id to 24
3609      * $i->joinAdd($pi); // add the product_image connectoin
3610      * $i->find();
3611      * while ($i->fetch()) {
3612      *     // do stuff
3613      * }
3614      * // an example with 2 joins
3615      * // get all the images linked with products or productgroups
3616      * $i = new DataObject_Image();
3617      * $pi = new DataObject_Product_image();
3618      * $pgi = new DataObject_Productgroup_image();
3619      * $i->joinAdd($pi);
3620      * $i->joinAdd($pgi);
3621      * $i->find();
3622      * while ($i->fetch()) {
3623      *     // do stuff
3624      * }
3625      *
3626      *
3627      * @param    optional $obj       object |array    the joining object (no value resets the join)
3628      *                                          If you use an array here it should be in the format:
3629      *                                          array('local_column','remotetable:remote_column');
3630      *                                             if remotetable does not have a definition, you should
3631      *                                             use @ to hide the include error message..
3632      *                                          array('local_column',  $dataobject , 'remote_column');
3633      *                                             if array has 3 args, then second is assumed to be the linked dataobject.
3634      *
3635      * @param    optional $joinType  string | array
3636      *                                          'LEFT'|'INNER'|'RIGHT'|'' Inner is default, '' indicates 
3637      *                                          just select ... from a,b,c with no join and 
3638      *                                          links are added as where items.
3639      *                                          
3640      *                                          If second Argument is array, it is assumed to be an associative
3641      *                                          array with arguments matching below = eg.
3642      *                                          'joinType' => 'INNER',
3643      *                                          'joinAs' => '...'
3644      *                                          'joinCol' => ....
3645      *                                          'useWhereAsOn' => false,
3646      *
3647      * @param    optional $joinAs    string     if you want to select the table as anther name
3648      *                                          useful when you want to select multiple columsn
3649      *                                          from a secondary table.
3650      
3651      * @param    optional $joinCol   string     The column on This objects table to match (needed
3652      *                                          if this table links to the child object in 
3653      *                                          multiple places eg.
3654      *                                          user->friend (is a link to another user)
3655      *                                          user->mother (is a link to another user..)
3656      *
3657      *           optional 'useWhereAsOn' bool   default false;
3658      *                                          convert the where argments from the object being added
3659      *                                          into ON arguments.
3660      * 
3661      * 
3662      * @return   none
3663      * @access   public
3664      * @author   Stijn de Reede      <sjr@gmx.co.uk>
3665      */
3666     function joinAdd($obj = false, $joinType='INNER', $joinAs=false, $joinCol=false)
3667     {
3668         global $_DB_DATAOBJECT;
3669         if ($obj === false) {
3670             $this->_join = '';
3671             return;
3672         }
3673          
3674         //echo '<PRE>'; print_r(func_get_args());
3675         $useWhereAsOn = false;
3676         // support for 2nd argument as an array of options
3677         if (is_array($joinType)) {
3678             // new options can now go in here... (dont forget to document them)
3679             $useWhereAsOn = !empty($joinType['useWhereAsOn']);
3680             $joinCol      = isset($joinType['joinCol'])  ? $joinType['joinCol']  : $joinCol;
3681             $joinAs       = isset($joinType['joinAs'])   ? $joinType['joinAs']   : $joinAs;
3682             $joinType     = isset($joinType['joinType']) ? $joinType['joinType'] : 'INNER';
3683         }
3684         // support for array as first argument 
3685         // this assumes that you dont have a links.ini for the specified table.
3686         // and it doesnt exist as am extended dataobject!! - experimental.
3687         
3688         $ofield = false; // object field
3689         $tfield = false; // this field
3690         $toTable = false;
3691         if (is_array($obj)) {
3692             $tfield = $obj[0];
3693             
3694             if (count($obj) == 3) {
3695                 $ofield = $obj[2];
3696                 $obj = $obj[1];
3697             } else {
3698                 list($toTable,$ofield) = explode(':',$obj[1]);
3699             
3700                 $obj = is_string($toTable) ? DB_DataObject::factory($toTable) : $toTable;
3701             
3702                 if (!$obj || !is_object($obj) || is_a($obj,'PEAR_Error')) {
3703                     $obj = new DB_DataObject;
3704                     $obj->__table = $toTable;
3705                 }
3706                 $obj->_connect();
3707             }
3708             // set the table items to nothing.. - eg. do not try and match
3709             // things in the child table...???
3710             $items = array();
3711         }
3712         
3713         if (!is_object($obj) || !is_a($obj,'DB_DataObject')) {
3714             return $this->raiseError("joinAdd: called without an object", DB_DATAOBJECT_ERROR_NODATA,PEAR_ERROR_DIE);
3715         }
3716         /*  make sure $this->_database is set.  */
3717         $this->_connect();
3718         $DB = $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
3719        
3720
3721         /// CHANGED 26 JUN 2009 - we prefer links from our local table over the remote one.
3722         
3723         /* otherwise see if there are any links from this table to the obj. */
3724         
3725         if (($ofield === false) && ($links = $this->links())) {
3726             // this enables for support for arrays of links in ini file.
3727             // link contains this_column[] =  linked_table:linked_column
3728             // or standard way.
3729             // link contains this_column =  linked_table:linked_column
3730             foreach ($links as $k => $linkVar) {
3731             
3732                 if (!is_array($linkVar)) {
3733                     $linkVar  = array($linkVar);
3734                 }
3735                 foreach($linkVar as $v) {
3736
3737                     
3738                     /* link contains {this column} = {linked table}:{linked column} */
3739                     $ar = explode(':', $v);
3740                     if (!isset($ar[1])) {
3741                         return $this->raiseError("invalid join for [{$this->tableName()}] $k = ". var_export($linkVar,true),
3742                                                     DB_DATAOBJECT_ERROR_INVALIDCONFIG,PEAR_ERROR_DIE);
3743                     }
3744                     // Feature Request #4266 - Allow joins with multiple keys
3745                     if (strpos($k, ',') !== false) {
3746                         $k = explode(',', $k);
3747                     }
3748                     if (strpos($ar[1], ',') !== false) {
3749                         $ar[1] = explode(',', $ar[1]);
3750                     }
3751
3752                     if ($ar[0] != $obj->tableName()) {
3753                         continue;
3754                     }
3755                     if ($joinCol !== false) {
3756                         if ($k == $joinCol) {
3757                             // got it!?
3758                             $tfield = $k;
3759                             $ofield = $ar[1];
3760                             break;
3761                         } 
3762                         continue;
3763                         
3764                     } 
3765                     $tfield = $k;
3766                     $ofield = $ar[1];
3767                     break;
3768                         
3769                 }
3770             }
3771         }
3772          /* look up the links for obj table */
3773         //print_r($obj->links());
3774         if (!$ofield && ($olinks = $obj->links())) {
3775             
3776             foreach ($olinks as $k => $linkVar) {
3777                 /* link contains {this column} = array ( {linked table}:{linked column} )*/
3778                 if (!is_array($linkVar)) {
3779                     $linkVar  = array($linkVar);
3780                 }
3781                 foreach($linkVar as $v) {
3782                     
3783                     /* link contains {this column} = {linked table}:{linked column} */
3784                     $ar = explode(':', $v);
3785                     
3786                     // Feature Request #4266 - Allow joins with multiple keys
3787                     $links_key_array = strpos($k,',');
3788                     if ($links_key_array !== false) {
3789                         $k = explode(',', $k);
3790                     }
3791                     
3792                     $ar_array = strpos($ar[1],',');
3793                     if ($ar_array !== false) {
3794                         $ar[1] = explode(',', $ar[1]);
3795                     }
3796                  
3797                     if ($ar[0] != $this->tableName()) {
3798                         continue;
3799                     }
3800                     
3801                     // you have explictly specified the column
3802                     // and the col is listed here..
3803                     // not sure if 1:1 table could cause probs here..
3804                     
3805                     if ($joinCol !== false) {
3806                          $this->raiseError( 
3807                             "joinAdd: You cannot target a join column in the " .
3808                             "'link from' table ({$obj->tableName()}). " . 
3809                             "Either remove the fourth argument to joinAdd() ".
3810                             "({$joinCol}), or alter your links.ini file. ",
3811                             DB_DATAOBJECT_ERROR_NODATA);
3812                         return false;
3813                     }
3814                 
3815                     $ofield = $k;
3816                     $tfield = $ar[1];
3817                     break;
3818                     
3819                 }
3820             }
3821         }
3822
3823         // finally if these two table have column names that match do a join by default on them
3824
3825         if (($ofield === false) && $joinCol) {
3826             $ofield = $joinCol;
3827             $tfield = $joinCol;
3828
3829         }
3830         /* did I find a conneciton between them? */
3831
3832         if ($ofield === false) {
3833             $this->raiseError(
3834                 "joinAdd: {$obj->tableName()} has no link with {$this->tableName()}",
3835                 DB_DATAOBJECT_ERROR_NODATA);
3836             return false;
3837         }
3838         $joinType = strtoupper($joinType);
3839         
3840         // we default to joining as the same name (this is remvoed later..)
3841         $quoteIdentifiers = !empty($_DB_DATAOBJECT['CONFIG']['quote_identifiers']);
3842         
3843          
3844         if ($joinAs === false) {
3845             $joinAs = $obj->tableName();
3846         }
3847         $joinAs   = $quoteIdentifiers ?  $DB->quoteIdentifier($joinAs) : $joinAs;
3848         
3849         $options = $_DB_DATAOBJECT['CONFIG'];
3850         
3851         // not sure  how portable adding database prefixes is..
3852         $objTable = $quoteIdentifiers ? 
3853                 $DB->quoteIdentifier($obj->tableName()) : 
3854                  $obj->tableName() ;
3855                 
3856         $dbPrefix  = '';
3857         if (strlen($obj->_database) && in_array($DB->dsn['phptype'],array('mysql','mysqli', 'mysqlfb'))) {
3858             $dbPrefix = ($quoteIdentifiers
3859                          ? $DB->quoteIdentifier($obj->_database)
3860                          : $obj->_database) . '.';    
3861         }
3862         
3863         // if they are the same, then dont add a prefix...                
3864         if ($obj->_database == $this->_database) {
3865            $dbPrefix = '';
3866         }
3867         // as far as we know only mysql supports database prefixes..
3868         // prefixing the database name is now the default behaviour,
3869         // as it enables joining mutiple columns from multiple databases...
3870          
3871             // prefix database (quoted if neccessary..)
3872         $objTable = $dbPrefix . $objTable;
3873        
3874         $cond = '';
3875
3876         // if obj only a dataobject - eg. no extended class has been defined..
3877         // it obvioulsy cant work out what child elements might exist...
3878         // until we get on the fly querying of tables..
3879         // note: we have already checked that it is_a(db_dataobject earlier)
3880         if ( strtolower(get_class($obj)) != 'db_dataobject') {
3881                  
3882             // now add where conditions for anything that is set in the object 
3883         
3884         
3885         
3886             $items = $obj->table();
3887             // will return an array if no items..
3888             
3889             // only fail if we where expecting it to work (eg. not joined on a array)
3890              
3891             if (!$items) {
3892                 $this->raiseError(
3893                     "joinAdd: No table definition for {$obj->tableName()}", 
3894                     DB_DATAOBJECT_ERROR_INVALIDCONFIG);
3895                 return false;
3896             }
3897             
3898             $ignore_null = !isset($options['disable_null_strings'])
3899                     || !is_string($options['disable_null_strings'])
3900                     || strtolower($options['disable_null_strings']) !== 'full' ;
3901             
3902
3903             foreach($items as $k => $v) {
3904                 if (!isset($obj->$k) && $ignore_null) {
3905                     continue;
3906                 }
3907                 
3908                 $kSql = ($quoteIdentifiers ? $DB->quoteIdentifier($k) : $k);
3909                 
3910                 if (DB_DataObject::_is_null($obj,$k)) {
3911                         $obj->whereAdd("{$joinAs}.{$kSql} IS NULL");
3912                         continue;
3913                 }
3914                 
3915                 if ($v & DB_DATAOBJECT_STR) {
3916                     $obj->whereAdd("{$joinAs}.{$kSql} = " . $this->_quote((string) (
3917                             ($v & DB_DATAOBJECT_BOOL) ? 
3918                                 // this is thanks to the braindead idea of postgres to 
3919                                 // use t/f for boolean.
3920                                 (($obj->$k === 'f') ? 0 : (int)(bool) $obj->$k) :  
3921                                 $obj->$k
3922                         )));
3923                     continue;
3924                 }
3925                 if (is_numeric($obj->$k)) {
3926                     $obj->whereAdd("{$joinAs}.{$kSql} = {$obj->$k}");
3927                     continue;
3928                 }
3929                             
3930                 if (is_object($obj->$k) && is_a($obj->$k,'DB_DataObject_Cast')) {
3931                     $value = $obj->$k->toString($v,$DB);
3932                     if (PEAR::isError($value)) {
3933                         $this->raiseError($value->getMessage() ,DB_DATAOBJECT_ERROR_INVALIDARG);
3934                         return false;
3935                     } 
3936                     $obj->whereAdd("{$joinAs}.{$kSql} = $value");
3937                     continue;
3938                 }
3939                 
3940                 
3941                 /* this is probably an error condition! */
3942                 $obj->whereAdd("{$joinAs}.{$kSql} = 0");
3943             }
3944             if ($this->_query === false) {
3945                 $this->raiseError(
3946                     "joinAdd can not be run from a object that has had a query run on it,
3947                     clone the object or create a new one and use setFrom()", 
3948                     DB_DATAOBJECT_ERROR_INVALIDARGS);
3949                 return false;
3950             }
3951         }
3952
3953         // and finally merge the whereAdd from the child..
3954         if ($obj->_query['condition']) {
3955             $cond = preg_replace('/^\sWHERE/i','',$obj->_query['condition']);
3956
3957             if (!$useWhereAsOn) {
3958                 $this->whereAdd($cond);
3959             }
3960         }
3961     
3962         
3963         
3964         
3965         // nested (join of joined objects..)
3966         $appendJoin = '';
3967         if ($obj->_join) {
3968             // postgres allows nested queries, with ()'s
3969             // not sure what the results are with other databases..
3970             // may be unpredictable..
3971             if (in_array($DB->dsn["phptype"],array('pgsql'))) {
3972                 $objTable = "($objTable {$obj->_join})";
3973             } else {
3974                 $appendJoin = $obj->_join;
3975             }
3976         }
3977         
3978   
3979         // fix for #2216
3980         // add the joinee object's conditions to the ON clause instead of the WHERE clause
3981         if ($useWhereAsOn && strlen($cond)) {
3982             $appendJoin = ' AND ' . $cond . ' ' . $appendJoin;
3983         }
3984                
3985         
3986         
3987         $table = $this->tableName();
3988         
3989         if ($quoteIdentifiers) {
3990            
3991             $table    = $DB->quoteIdentifier($table);     
3992             $ofield   = (is_array($ofield)) ? array_map(array($DB, 'quoteIdentifier'), $ofield) : $DB->quoteIdentifier($ofield);
3993             $tfield   = (is_array($tfield)) ? array_map(array($DB, 'quoteIdentifier'), $tfield) : $DB->quoteIdentifier($tfield); 
3994         }
3995         // add database prefix if they are different databases
3996        
3997         
3998         $fullJoinAs = '';
3999         $addJoinAs  = ($quoteIdentifiers ? $DB->quoteIdentifier($obj->tableName()) : $obj->tableName()) != $joinAs;
4000         if ($addJoinAs) {
4001             // join table a AS b - is only supported by a few databases and is probably not needed
4002             // , however since it makes the whole Statement alot clearer we are leaving it in
4003             // for those databases.
4004             $fullJoinAs = in_array($DB->dsn["phptype"],array('mysql','mysqli', 'mysqlfb', 'pgsql')) ? "AS {$joinAs}" :  $joinAs;
4005         } else {
4006             // if 
4007             $joinAs = $dbPrefix . $joinAs;
4008         }
4009         
4010         
4011         switch ($joinType) {
4012             case 'INNER':
4013             case 'LEFT': 
4014             case 'RIGHT': // others??? .. cross, left outer, right outer, natural..?
4015                 
4016                 // Feature Request #4266 - Allow joins with multiple keys
4017                 $jadd = "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
4018                 //$this->_join .= "\n {$joinType} JOIN {$objTable} {$fullJoinAs}";
4019                 if (is_array($ofield)) {
4020                         $key_count = count($ofield);
4021                     for($i = 0; $i < $key_count; $i++) {
4022                         if ($i == 0) {
4023                                 $jadd .= " ON ({$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]}) ";
4024                         }
4025                         else {
4026                                 $jadd .= " AND {$joinAs}.{$ofield[$i]}={$table}.{$tfield[$i]} ";
4027                         }
4028                     }
4029                     $jadd .= ' ' . $appendJoin . ' ';
4030                 } else {
4031                         $jadd .= " ON ({$joinAs}.{$ofield}={$table}.{$tfield}) {$appendJoin} ";
4032                 }
4033                 // jadd avaliable for debugging join build.
4034                 //echo $jadd ."\n";
4035                 $this->_join .= $jadd;
4036                 break;
4037                 
4038             case '': // this is just a standard multitable select..
4039                 $this->_join .= "\n , {$objTable} {$fullJoinAs} {$appendJoin}";
4040                 $this->whereAdd("{$joinAs}.{$ofield}={$table}.{$tfield}");
4041         }
4042          
4043          
4044         return true;
4045
4046     }
4047
4048     /**
4049      * autoJoin - using the links.ini file, it builds a query with all the joins 
4050      * usage: 
4051      * $x = DB_DataObject::factory('mytable');
4052      * $x->autoJoin();
4053      * $x->get(123); 
4054      *   will result in all of the joined data being added to the fetched object..
4055      * 
4056      * $x = DB_DataObject::factory('mytable');
4057      * $x->autoJoin();
4058      * $ar = $x->fetchAll();
4059      *   will result in an array containing all the data from the table, and any joined tables..
4060      * 
4061      * $x = DB_DataObject::factory('mytable');
4062      * $jdata = $x->autoJoin();
4063      * $x->selectAdd(); //reset..
4064      * foreach($_REQUEST['requested_cols'] as $c) {
4065      *    if (!isset($jdata[$c])) continue; // ignore columns not available..
4066      *    $x->selectAdd( $jdata[$c] . ' as ' . $c);
4067      * }
4068      * $ar = $x->fetchAll(); 
4069      *   will result in only the columns requested being fetched...
4070      *
4071      *
4072      *
4073      * @param     array     Configuration
4074      *          exclude  Array of columns to exclude from results (eg. modified_by_id)
4075      *                    Use TABLENAME.* to prevent a join occuring to a specific table.
4076      *          links    The equivilant links.ini data for this table eg.
4077      *                    array( 'person_id' => 'person:id', .... )
4078      *          include  Array of columns to include
4079      *          distinct Array of distinct columns.
4080      *          
4081      * @return   array      info about joins
4082      *                      cols => map of resulting {joined_tablename}.{joined_table_column_name}
4083      *                      join_names => map of resulting {join_name_as}.{joined_table_column_name}
4084      *                      count => the column to count on.
4085      * @access   public
4086      */
4087     function autoJoin($cfg = array())
4088     { 
4089         global $_DB_DATAOBJECT;
4090         //var_Dump($cfg);exit;
4091         $pre_links = $this->links();
4092         if (!empty($cfg['links'])) {
4093             $this->links(array_merge( $pre_links , $cfg['links']));
4094         }
4095         $map = $this->links( );
4096         
4097         $this->databaseStructure();
4098         $dbstructure = $_DB_DATAOBJECT['INI'][$this->_database];
4099         //print_r($map);
4100         $tabdef = $this->table();
4101          
4102         // we need this as normally it's only cleared by an empty selectAs call.
4103        
4104         
4105         $keys = array_keys($tabdef);
4106         if (!empty($cfg['exclude'])) {
4107             $keys = array_intersect($keys, array_diff($keys, $cfg['exclude'])); 
4108         }
4109         
4110         if (!empty($cfg['include'])) {
4111             $keys =  array_intersect($keys,  $cfg['include']); 
4112         }
4113         
4114         $selectAs = array();
4115         
4116         if (!empty($keys)) {
4117             $selectAs = array(array( $keys , '%s', false));
4118         }
4119         
4120         $ret = array(
4121             'cols' => array(),
4122             'join_names' => array(),
4123             'count' => false,
4124         );
4125         
4126         
4127         
4128         $has_distinct = false;
4129         if (!empty($cfg['distinct']) && $keys) {
4130             
4131             // reset the columsn?
4132             $cols = array();
4133             
4134              //echo '<PRE>' ;print_r($xx);exit;
4135             foreach($keys as $c) {
4136                 //var_dump($c);
4137                 
4138                 if (  $cfg['distinct'] == $c) {
4139                     $has_distinct = 'DISTINCT( ' . $this->tableName() .'.'. $c .') as ' . $c;
4140                     $ret['count'] =  'DISTINCT  ' . $this->tableName() .'.'. $c .'';
4141                     continue;
4142                 }
4143                 // cols is in our filtered keys...
4144                 $cols = $c;
4145                 
4146             }
4147             // apply our filtered version, which excludes the distinct column.
4148             
4149             $selectAs = empty($cols) ?  array() : array(array(array(  $cols) , '%s', false)) ;
4150             
4151             
4152             
4153         } 
4154                 
4155         foreach($keys as $k) {
4156             $ret['cols'][$k] = $this->tableName(). '.' . $k;
4157         }
4158         
4159         
4160         
4161         foreach($map as $ocl=>$info) {
4162             if (strpos($info, ':') === false) {
4163                 $this->raiseError(
4164                     "format of links.ini is not correct for table {$this->tableName()} - missing 'colon:' in value - " . print_R($map,true), 
4165                     DB_DATAOBJECT_ERROR_INVALIDCONFIG);
4166                 continue;
4167             }
4168             list($tab,$col) = explode(':', $info);
4169             // what about multiple joins on the same table!!!
4170             
4171             // if links point to a table that does not exist - ignore.
4172             if (!isset($dbstructure[$tab])) {
4173                 continue;
4174             }
4175              if (!empty($cfg['exclude']) && in_array($tab .'.*', $cfg['exclude'])) {
4176                 continue;
4177             }
4178             
4179             $xx = DB_DataObject::factory($tab);
4180             if (!is_object($xx) || !is_a($xx, 'DB_DataObject')) {
4181                 continue;
4182             }
4183             // skip columns that are excluded.
4184             
4185             // we ignore include here... - as
4186              
4187             // this is borked ... for multiple jions..
4188             $this->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
4189             
4190             if (!empty($cfg['exclude']) && in_array($ocl, $cfg['exclude'])) {
4191                 continue;
4192             }
4193             
4194             $tabdef = $xx->table();
4195             $table = $xx->tableName();
4196             
4197             $keys = array_keys($tabdef);
4198             
4199             
4200             if (!empty($cfg['exclude'])) {
4201                 $keys = array_intersect($keys, array_diff($keys, $cfg['exclude']));
4202                 
4203                 foreach($keys as $k) {
4204                     if (in_array($ocl.'_'.$k, $cfg['exclude'])) {
4205                         $keys = array_diff($keys, array($k)); // removes the k..
4206                     }
4207                 }
4208                 
4209             }
4210             
4211             if (!empty($cfg['include'])) {
4212                 // include will basically be BASECOLNAME_joinedcolname
4213                 $nkeys = array();
4214                 foreach($keys as $k) {
4215                     if (in_array( sprintf($ocl.'_%s', $k), $cfg['include'])) {
4216                         $nkeys[] = $k;
4217                     }
4218                 }
4219                 $keys = $nkeys;
4220             }
4221             
4222             if (empty($keys)) {
4223                 continue;
4224             }
4225             // got distinct, and not yet found it..
4226             if (!$has_distinct && !empty($cfg['distinct']))  {
4227                 $cols = array();
4228                 foreach($keys as $c) {
4229                     $tn = sprintf($ocl.'_%s', $c);
4230                       
4231                     if ( $tn == $cfg['distinct']) {
4232                         
4233                         $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$c .')  as ' . $tn ;
4234                         $ret['count'] =  'DISTINCT  join_'.$ocl.'_'.$col.'.'.$c;
4235                        // var_dump($this->countWhat );
4236                         continue;
4237                     }
4238                     $cols[] = $c;
4239                      
4240                 }
4241                 
4242                 if (!empty($cols)) {
4243                     $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
4244                 }
4245                 
4246             } else {
4247                 $selectAs[] = array($keys, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
4248             }
4249               
4250             foreach($keys as $k) {
4251                 $ret['cols'][sprintf('%s_%s', $ocl, $k)] = $tab.'.'.$k;
4252                 $ret['join_names'][sprintf('%s_%s', $ocl, $k)] = sprintf('join_%s_%s.%s',$ocl, $col, $k);
4253             }
4254              
4255         }
4256         
4257         // fill in the select details..
4258         $this->selectAdd(); 
4259         
4260         if ($has_distinct) {
4261             $this->selectAdd($has_distinct);
4262         }
4263        
4264         foreach($selectAs as $ar) {            
4265             $this->selectAs($ar[0], $ar[1], $ar[2]);
4266         }
4267         // restore links..
4268         $this->links( $pre_links );
4269         
4270         return $ret;
4271         
4272     }
4273     
4274     /**
4275      * Factory method for calling DB_DataObject_Cast
4276      *
4277      * if used with 1 argument DB_DataObject_Cast::sql($value) is called
4278      * 
4279      * if used with 2 arguments DB_DataObject_Cast::$value($callvalue) is called
4280      * valid first arguments are: blob, string, date, sql
4281      * 
4282      * eg. $member->updated = $member->sqlValue('NOW()');
4283      * 
4284      * 
4285      * might handle more arguments for escaping later...
4286      * 
4287      *
4288      * @param string $value (or type if used with 2 arguments)
4289      * @param string $callvalue (optional) used with date/null etc..
4290      */
4291     
4292     function sqlValue($value)
4293     {
4294         $method = 'sql';
4295         if (func_num_args() == 2) {
4296             $method = $value;
4297             $value = func_get_arg(1);
4298         }
4299         require_once 'DB/DataObject/Cast.php';
4300         return call_user_func(array('DB_DataObject_Cast', $method), $value);
4301         
4302     }
4303     
4304     
4305     /**
4306      * Copies items that are in the table definitions from an
4307      * array or object into the current object
4308      * will not override key values.
4309      *
4310      *
4311      * @param    array | object  $from
4312      * @param    string  $format eg. map xxxx_name to $object->name using 'xxxx_%s' (defaults to %s - eg. name -> $object->name
4313      * @param    boolean  $skipEmpty (dont assign empty values if a column is empty (eg. '' / 0 etc...)
4314      * @access   public
4315      * @return   true on success or array of key=>setValue error message
4316      */
4317     function setFrom($from, $format = '%s', $skipEmpty=false)
4318     {
4319          
4320         $keys  = $this->keys();
4321         $items = $this->table();
4322       
4323         if (!$items) {
4324             $this->raiseError(
4325                 "setFrom:Could not find table definition for {$this->tableName()}", 
4326                 DB_DATAOBJECT_ERROR_INVALIDCONFIG);
4327             return;
4328         }
4329         $overload_return = array();
4330         foreach (array_keys($items) as $k) {
4331             if (in_array($k,$keys)) {
4332                 continue; // dont overwrite keys
4333             }
4334             if (!$k) {
4335                 continue; // ignore empty keys!!! what
4336             }
4337           
4338             $chk = is_object($from) &&  
4339                 (version_compare(phpversion(), "5.1.0" , ">=") ? 
4340                     property_exists($from, sprintf($format,$k)) :  // php5.1
4341                     array_key_exists( sprintf($format,$k), get_class_vars($from)) //older
4342                 );
4343             // if from has property ($format($k)      
4344             if ($chk) {
4345                 $kk = (strtolower($k) == 'from') ? '_from' : $k;
4346                 if (method_exists($this,'set'.$kk)) {
4347                     $ret = $this->{'set'.$kk}($from->{sprintf($format,$k)});
4348                     if (is_string($ret)) {
4349                         $overload_return[$k] = $ret;
4350                     }
4351                     continue;
4352                 }
4353                 $this->$k = $from->{sprintf($format,$k)};
4354                 continue;
4355             }
4356             
4357             if (is_object($from)) {
4358                 continue;
4359             }
4360             
4361  
4362             if (empty($from[sprintf($format,$k)]) && $skipEmpty) {
4363                 continue;
4364             }
4365             
4366             if (!isset($from[sprintf($format,$k)]) && !DB_DataObject::_is_null($from, sprintf($format,$k))) {
4367                 continue;
4368             }
4369            
4370             $kk = (strtolower($k) == 'from') ? '_from' : $k;
4371             if (method_exists($this,'set'. $kk)) {
4372                 $ret =  $this->{'set'.$kk}($from[sprintf($format,$k)]);
4373                 if (is_string($ret)) {
4374                     $overload_return[$k] = $ret;
4375                 }
4376                 continue;
4377             }
4378             $val = $from[sprintf($format,$k)];
4379             if (is_a($val, 'DB_DataObject_Cast')) {
4380                 $this->$k = $val;
4381                 continue;
4382             }
4383             if (is_object($val) || is_array($val)) {
4384                 continue;
4385             }
4386             $ret = $this->fromValue($k,$val);
4387             if ($ret !== true)  {
4388                 $overload_return[$k] = 'Not A Valid Value';
4389             }
4390             //$this->$k = $from[sprintf($format,$k)];
4391         }
4392         if ($overload_return) {
4393             return $overload_return;
4394         }
4395         return true;
4396     }
4397
4398     /**
4399      * Returns an associative array from the current data
4400      * (kind of oblivates the idea behind DataObjects, but
4401      * is usefull if you use it with things like QuickForms.
4402      *
4403      * you can use the format to return things like user[key]
4404      * by sending it $object->toArray('user[%s]')
4405      *
4406      * will also return links converted to arrays.
4407      *
4408      * @param   string  sprintf format for array
4409      * @param   bool||number    [true = elemnts that have a value set],
4410      *                          [false = table + returned colums] ,
4411      *                          [0 = returned columsn only]
4412      *
4413      * @access   public
4414      * @return   array of key => value for row
4415      */
4416
4417     function toArray($format = '%s', $hideEmpty = false) 
4418     {
4419         global $_DB_DATAOBJECT;
4420         
4421         // we use false to ignore sprintf.. (speed up..)
4422         $format = $format == '%s' ? false : $format;
4423         
4424         $ret = array();
4425         $rf = ($this->_resultFields !== false) ? $this->_resultFields : 
4426                 (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]) ?
4427                  $_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid] : false);
4428         
4429         $ar = ($rf !== false) ?
4430             (($hideEmpty === 0) ? $rf : array_merge($rf, $this->table())) :
4431             $this->table();
4432
4433         foreach($ar as $k=>$v) {
4434              
4435             if (!isset($this->$k)) {
4436                 if (!$hideEmpty) {
4437                     $ret[$format === false ? $k : sprintf($format,$k)] = '';
4438                 }
4439                 continue;
4440             }
4441             // call the overloaded getXXXX() method. - except getLink and getLinks
4442             if (method_exists($this,'get'.$k) && !in_array(strtolower($k),array('links','link'))) {
4443                 $ret[$format === false ? $k : sprintf($format,$k)] = $this->{'get'.$k}();
4444                 continue;
4445             }
4446             // should this call toValue() ???
4447             $ret[$format === false ? $k : sprintf($format,$k)] = $this->$k;
4448         }
4449         if (!$this->_link_loaded) {
4450             return $ret;
4451         }
4452         foreach($this->_link_loaded as $k) {
4453             $ret[$format === false ? $k : sprintf($format,$k)] = $this->$k->toArray();
4454         
4455         }
4456         
4457         return $ret;
4458     }
4459
4460      
4461     
4462     /**
4463      * validate the values of the object (usually prior to inserting/updating..)
4464      *
4465      * Note: This was always intended as a simple validation routine.
4466      * It lacks understanding of field length, whether you are inserting or updating (and hence null key values)
4467      *
4468      * This should be moved to another class: DB_DataObject_Validate 
4469      *      FEEL FREE TO SEND ME YOUR VERSION FOR CONSIDERATION!!!
4470      *
4471      * Usage:
4472      * if (is_array($ret = $obj->validate())) { ... there are problems with the data ... }
4473      *
4474      * Logic:
4475      *   - defaults to only testing strings/numbers if numbers or strings are the correct type and null values are correct
4476      *   - validate Column methods : "validate{ROWNAME}()"  are called if they are defined.
4477      *            These methods should return 
4478      *                  true = everything ok
4479      *                  false|object = something is wrong!
4480      * 
4481      *   - This method loads and uses the PEAR Validate Class.
4482      *
4483      *
4484      * @access  public
4485      * @return  array of validation results (where key=>value, value=false|object if it failed) or true (if they all succeeded)
4486      */
4487     function validate()
4488     {
4489         global $_DB_DATAOBJECT;
4490         require_once 'Validate.php';
4491         $table = $this->table();
4492         $ret   = array();
4493         $seq   = $this->sequenceKey();
4494         $options = $_DB_DATAOBJECT['CONFIG'];
4495         foreach($table as $key => $val) {
4496             
4497             
4498             // call user defined validation always...
4499             $method = "Validate" . ucfirst($key);
4500             if (method_exists($this, $method)) {
4501                 $ret[$key] = $this->$method();
4502                 continue;
4503             }
4504             
4505             // if not null - and it's not set.......
4506             
4507             if ($val & DB_DATAOBJECT_NOTNULL && DB_DataObject::_is_null($this, $key)) {
4508                 // dont check empty sequence key values..
4509                 if (($key == $seq[0]) && ($seq[1] == true)) {
4510                     continue;
4511                 }
4512                 $ret[$key] = false;
4513                 continue;
4514             }
4515             
4516             
4517              if (DB_DataObject::_is_null($this, $key)) {
4518                 if ($val & DB_DATAOBJECT_NOTNULL) {
4519                     $this->debug("'null' field used for '$key', but it is defined as NOT NULL", 'VALIDATION', 4);
4520                     $ret[$key] = false;
4521                     continue;
4522                 }
4523                 continue;
4524             }
4525
4526             // ignore things that are not set. ?
4527            
4528             if (!isset($this->$key)) {
4529                 continue;
4530             }
4531             
4532             // if the string is empty.. assume it is ok..
4533             if (!is_object($this->$key) && !is_array($this->$key) && !strlen((string) $this->$key)) {
4534                 continue;
4535             }
4536             
4537             // dont try and validate cast objects - assume they are problably ok..
4538             if (is_object($this->$key) && is_a($this->$key,'DB_DataObject_Cast')) {
4539                 continue;
4540             }
4541             // at this point if you have set something to an object, and it's not expected
4542             // the Validate will probably break!!... - rightly so! (your design is broken, 
4543             // so issuing a runtime error like PEAR_Error is probably not appropriate..
4544             
4545             switch (true) {
4546                 // todo: date time.....
4547                 case  ($val & DB_DATAOBJECT_STR):
4548                     $ret[$key] = Validate::string($this->$key, VALIDATE_PUNCTUATION . VALIDATE_NAME);
4549                     continue 2;
4550                 case  ($val & DB_DATAOBJECT_INT):
4551                     $ret[$key] = Validate::number($this->$key, array('decimal'=>'.'));
4552                     continue 2;
4553             }
4554         }
4555         // if any of the results are false or an object (eg. PEAR_Error).. then return the array..
4556         foreach ($ret as $key => $val) {
4557             if ($val !== true) {
4558                 return $ret;
4559             }
4560         }
4561         return true; // everything is OK.
4562     }
4563
4564     /**
4565      * Gets the DB object related to an object - so you can use funky peardb stuf with it :)
4566      *
4567      * @access public
4568      * @return object The DB connection
4569      */
4570     function getDatabaseConnection()
4571     {
4572         global $_DB_DATAOBJECT;
4573         if (($e = $this->_connect()) !== true) {
4574             return $e;
4575         }
4576
4577         if (!isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
4578             $r = false;
4579             return $r;
4580         }
4581         return $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
4582     }
4583  
4584  
4585     /**
4586      * Gets the DB result object related to the objects active query
4587      *  - so you can use funky pear stuff with it - like pager for example.. :)
4588      *
4589      * @access public
4590      * @return object The DB result object
4591      */
4592      
4593     function getDatabaseResult()
4594     {
4595         global $_DB_DATAOBJECT;
4596         $this->_connect();
4597         if (!isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {
4598             $r = false;
4599             return $r;
4600         }
4601         return $_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid];
4602     }
4603
4604     /**
4605      * Overload Extension support
4606      *  - enables setCOLNAME/getCOLNAME
4607      *  if you define a set/get method for the item it will be called.
4608      * otherwise it will just return/set the value.
4609      * NOTE this currently means that a few Names are NO-NO's 
4610      * eg. links,link,linksarray, from, Databaseconnection,databaseresult
4611      *
4612      * note 
4613      *  - set is automatically called by setFrom.
4614      *   - get is automatically called by toArray()
4615      *  
4616      * setters return true on success. = strings on failure
4617      * getters return the value!
4618      *
4619      * this fires off trigger_error - if any problems.. pear_error, 
4620      * has problems with 4.3.2RC2 here
4621      *
4622      * @access public
4623      * @return true?
4624      * @see overload
4625      */
4626
4627     
4628     function _call($method,$params,&$return) {
4629         
4630         //$this->debug("ATTEMPTING OVERLOAD? $method");
4631         // ignore constructors : - mm
4632         if (strtolower($method) == strtolower(get_class($this))) {
4633             return true;
4634         }
4635         $type = strtolower(substr($method,0,3));
4636         $class = get_class($this);
4637         if (($type != 'set') && ($type != 'get')) {
4638             return false;
4639         }
4640          
4641         
4642         
4643         // deal with naming conflick of setFrom = this is messy ATM!
4644         
4645         if (strtolower($method) == 'set_from') {
4646             $return = $this->toValue('from',isset($params[0]) ? $params[0] : null);
4647             return  true;
4648         }
4649         
4650         $element = substr($method,3);
4651         
4652         // dont you just love php's case insensitivity!!!!
4653         
4654         $array =  array_keys(get_class_vars($class));
4655         /* php5 version which segfaults on 5.0.3 */
4656         if (class_exists('ReflectionClass')) {
4657             $reflection = new ReflectionClass($class);
4658             $array = array_keys($reflection->getdefaultProperties());
4659         }
4660         
4661         if (!in_array($element,$array)) {
4662             // munge case
4663             foreach($array as $k) {
4664                 $case[strtolower($k)] = $k;
4665             }
4666             if ((substr(phpversion(),0,1) == 5) && isset($case[strtolower($element)])) {
4667                 trigger_error("PHP5 set/get calls should match the case of the variable",E_USER_WARNING);
4668                 $element = strtolower($element);
4669             }
4670             
4671             // does it really exist?
4672             if (!isset($case[$element])) {
4673                 return false;            
4674             }
4675             // use the mundged case
4676             $element = $case[$element]; // real case !
4677         }
4678         
4679         
4680         if ($type == 'get') {
4681             $return = $this->toValue($element,isset($params[0]) ? $params[0] : null);
4682             return true;
4683         }
4684         
4685         
4686         $return = $this->fromValue($element, $params[0]);
4687          
4688         return true;
4689             
4690           
4691     }
4692         
4693     
4694     /**
4695     * standard set* implementation.
4696     *
4697     * takes data and uses it to set dates/strings etc.
4698     * normally called from __call..  
4699     *
4700     * Current supports
4701     *   date      = using (standard time format, or unixtimestamp).... so you could create a method :
4702     *               function setLastread($string) { $this->fromValue('lastread',strtotime($string)); }
4703     *
4704     *   time      = using strtotime 
4705     *   datetime  = using  same as date - accepts iso standard or unixtimestamp.
4706     *   string    = typecast only..
4707     * 
4708     * TODO: add formater:: eg. d/m/Y for date! ???
4709     *
4710     * @param   string       column of database
4711     * @param   mixed        value to assign
4712     *
4713     * @return   true| false     (False on error)
4714     * @access   public 
4715     * @see      DB_DataObject::_call
4716     */
4717   
4718     
4719     function fromValue($col,$value) 
4720     {
4721         global $_DB_DATAOBJECT;
4722         $options = $_DB_DATAOBJECT['CONFIG'];
4723         $cols = $this->table();
4724         // dont know anything about this col..
4725         if (!isset($cols[$col]) || is_a($value, 'DB_DataObject_Cast')) {
4726             $this->$col = $value;
4727             return true;
4728         }
4729         //echo "FROM VALUE $col, {$cols[$col]}, $value\n";
4730         switch (true) {
4731             // set to null and column is can be null...
4732             case ((!($cols[$col] & DB_DATAOBJECT_NOTNULL)) && DB_DataObject::_is_null($value, false)):
4733             case (is_object($value) && is_a($value,'DB_DataObject_Cast')): 
4734                 $this->$col = $value;
4735                 return true;
4736                 
4737             // fail on setting null on a not null field..
4738             case (($cols[$col] & DB_DATAOBJECT_NOTNULL) && DB_DataObject::_is_null($value,false)):
4739
4740                 return false;
4741         
4742             case (($cols[$col] & DB_DATAOBJECT_DATE) &&  ($cols[$col] & DB_DATAOBJECT_TIME)):
4743                 // empty values get set to '' (which is inserted/updated as NULl
4744                 if (!$value) {
4745                     $this->$col = '';
4746                 }
4747             
4748                 if (is_numeric($value)) {
4749                     $this->$col = date('Y-m-d H:i:s', $value);
4750                     return true;
4751                 }
4752               
4753                 // eak... - no way to validate date time otherwise...
4754                 $this->$col = (string) $value;
4755                 return true;
4756             
4757             case ($cols[$col] & DB_DATAOBJECT_DATE):
4758                 // empty values get set to '' (which is inserted/updated as NULl
4759                  
4760                 if (!$value) {
4761                     $this->$col = '';
4762                     return true; 
4763                 }
4764             
4765                 if (is_numeric($value)) {
4766                     $this->$col = date('Y-m-d',$value);
4767                     return true;
4768                 }
4769                  
4770                 // try date!!!!
4771                 require_once 'Date.php';
4772                 $x = new Date($value);
4773                 $this->$col = $x->format("%Y-%m-%d");
4774                 return true;
4775             
4776             case ($cols[$col] & DB_DATAOBJECT_TIME):
4777                 // empty values get set to '' (which is inserted/updated as NULl
4778                 if (!$value) {
4779                     $this->$col = '';
4780                 }
4781             
4782                 $guess = strtotime($value);
4783                 if ($guess != -1) {
4784                      $this->$col = date('H:i:s', $guess);
4785                     return $return = true;
4786                 }
4787                 // otherwise an error in type...
4788                 return false;
4789             
4790             case ($cols[$col] & DB_DATAOBJECT_STR):
4791                 
4792                 $this->$col = (string) $value;
4793                 return true;
4794                 
4795             // todo : floats numerics and ints...
4796             default:
4797                 $this->$col = $value;
4798                 return true;
4799         }
4800     
4801     
4802     
4803     }
4804      /**
4805     * standard get* implementation.
4806     *
4807     *  with formaters..
4808     * supported formaters:  
4809     *   date/time : %d/%m/%Y (eg. php strftime) or pear::Date 
4810     *   numbers   : %02d (eg. sprintf)
4811     *  NOTE you will get unexpected results with times like 0000-00-00 !!!
4812     *
4813     *
4814     * 
4815     * @param   string       column of database
4816     * @param   format       foramt
4817     *
4818     * @return   true     Description
4819     * @access   public 
4820     * @see      DB_DataObject::_call(),strftime(),Date::format()
4821     */
4822     function toValue($col,$format = null) 
4823     {
4824         if (is_null($format)) {
4825             return $this->$col;
4826         }
4827         $cols = $this->table();
4828         switch (true) {
4829             case (($cols[$col] & DB_DATAOBJECT_DATE) &&  ($cols[$col] & DB_DATAOBJECT_TIME)):
4830                 if (!$this->$col) {
4831                     return '';
4832                 }
4833                 if (empty($format)) {
4834                     return $this->col;
4835                 }
4836                 require_once 'Date.php';
4837                 $x = new Date($this->$col);
4838                 return $x->format($format);
4839             
4840             case ($cols[$col] & DB_DATAOBJECT_DATE):
4841                 if (!$this->$col) {
4842                     return '';
4843                 } 
4844                 if (empty($format)) {
4845                     return $this->$col;
4846                 }
4847                 require_once 'Date.php';
4848                 $x = new Date($this->$col);
4849                 return $x->format($format);
4850                 
4851             case ($cols[$col] & DB_DATAOBJECT_TIME):
4852                 if (!$this->$col) {
4853                     return '';
4854                 }
4855                 if (empty($format)) {
4856                     return $this->col;
4857                 }
4858                 require_once 'Date.php';
4859                 $x = new Date('1000-01-01 '. $this->$col);
4860                 return $x->format($format);
4861             
4862                 
4863             case ($cols[$col] &  DB_DATAOBJECT_MYSQLTIMESTAMP):
4864                 if (!$this->$col) {
4865                     return '';
4866                 }
4867                 require_once 'Date.php';
4868                 
4869                 $x = new Date($this->$col);
4870                 
4871                 return $x->format($format);
4872             
4873              
4874             case ($cols[$col] &  DB_DATAOBJECT_BOOL):
4875                 
4876                 if ($cols[$col] &  DB_DATAOBJECT_STR) {
4877                     // it's a 't'/'f' !
4878                     return ($this->$col === 't');
4879                 }
4880                 return (bool) $this->$col;
4881             
4882                
4883             default:
4884                 return sprintf($format,$this->col);
4885         }
4886             
4887
4888     }
4889     
4890     
4891     /* ----------------------- Debugger ------------------ */
4892
4893     /**
4894      * Debugger. - use this in your extended classes to output debugging information.
4895      *
4896      * Uses DB_DataObject::DebugLevel(x) to turn it on
4897      *
4898      * @param    string $message - message to output
4899      * @param    string $logtype - bold at start
4900      * @param    string $level   - output level
4901      * @access   public
4902      * @return   none
4903      */
4904     function debug($message, $logtype = 0, $level = 1)
4905     {
4906         global $_DB_DATAOBJECT;
4907
4908         if (empty($_DB_DATAOBJECT['CONFIG']['debug'])  || 
4909             (is_numeric($_DB_DATAOBJECT['CONFIG']['debug']) &&  $_DB_DATAOBJECT['CONFIG']['debug'] < $level)) {
4910             return;
4911         }
4912         // this is a bit flaky due to php's wonderfull class passing around crap..
4913         // but it's about as good as it gets..
4914         $class = (isset($this) && is_a($this,'DB_DataObject')) ? get_class($this) : 'DB_DataObject';
4915         
4916         if (!is_string($message)) {
4917             $message = print_r($message,true);
4918         }
4919         if (!is_numeric( $_DB_DATAOBJECT['CONFIG']['debug']) && is_callable( $_DB_DATAOBJECT['CONFIG']['debug'])) {
4920             return call_user_func($_DB_DATAOBJECT['CONFIG']['debug'], $class, $message, $logtype, $level);
4921         }
4922         
4923         if (!ini_get('html_errors')) {
4924             echo "$class   : $logtype       : $message\n";
4925             flush();
4926             return;
4927         }
4928         if (!is_string($message)) {
4929             $message = print_r($message,true);
4930         }
4931         $colorize = ($logtype == 'ERROR') ? '<font color="red">' : '<font>';
4932         echo "<code>{$colorize}<B>$class: $logtype:</B> ". nl2br(htmlspecialchars($message)) . "</font></code><BR>\n";
4933     }
4934
4935     /**
4936      * sets and returns debug level
4937      * eg. DB_DataObject::debugLevel(4);
4938      *
4939      * @param   int     $v  level
4940      * @access  public
4941      * @return  none
4942      */
4943     static function debugLevel($v = null)
4944     {
4945         global $_DB_DATAOBJECT;
4946         if (empty($_DB_DATAOBJECT['CONFIG'])) {
4947             DB_DataObject::_loadConfig();
4948         }
4949         if ($v !== null) {
4950             $r = isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4951             $_DB_DATAOBJECT['CONFIG']['debug']  = $v;
4952             return $r;
4953         }
4954         return isset($_DB_DATAOBJECT['CONFIG']['debug']) ? $_DB_DATAOBJECT['CONFIG']['debug'] : 0;
4955     }
4956
4957     /**
4958      * Last Error that has occured
4959      * - use $this->_lastError or
4960      * $last_error = PEAR::getStaticProperty('DB_DataObject','lastError');
4961      *
4962      * @access  public
4963      * @var     object PEAR_Error (or false)
4964      */
4965     var $_lastError = false;
4966
4967     /**
4968      * Default error handling is to create a pear error, but never return it.
4969      * if you need to handle errors you should look at setting the PEAR_Error callback
4970      * this is due to the fact it would wreck havoc on the internal methods!
4971      *
4972      * @param  int $message    message
4973      * @param  int $type       type
4974      * @param  int $behaviour  behaviour (die or continue!);
4975      * @access public
4976      * @return error object
4977      */
4978     function raiseError($message, $type = null, $behaviour = null)
4979     {
4980         global $_DB_DATAOBJECT;
4981         
4982         if ($behaviour == PEAR_ERROR_DIE && !empty($_DB_DATAOBJECT['CONFIG']['dont_die'])) {
4983             $behaviour = null;
4984         }
4985         
4986         $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
4987         
4988         
4989         // no checks for production here?....... - we log  errors before we throw them.
4990         DB_DataObject::debug($message,'ERROR',1);
4991         $e = new Exception();
4992         DB_DataObject::debug($e->getTraceAsString(),'ERROR',5);
4993         
4994         if (PEAR::isError($message)) {
4995             $error = $message;
4996         } else {
4997             require_once 'DB/DataObject/Error.php';
4998             $dor = new PEAR();
4999             $error = $dor->raiseError($message, $type, $behaviour,
5000                             $opts=null, $userinfo=null, 'DB_DataObject_Error'
5001                         );
5002         }
5003         // this will never work totally with PHP's object model.
5004         // as this is passed on static calls (like staticGet in our case)
5005  
5006         $_DB_DATAOBJECT['LASTERROR'] = $error;
5007         
5008         if (isset($this) && is_object($this) && is_subclass_of($this,'db_dataobject')) {
5009             $this->_lastError = $error;
5010         }
5011    
5012         return $error;
5013     }
5014     
5015     
5016
5017     /**
5018      * Define the global $_DB_DATAOBJECT['CONFIG'] as an alias to  PEAR::getStaticProperty('DB_DataObject','options');
5019      *
5020      * After Profiling DB_DataObject, I discoved that the debug calls where taking
5021      * considerable time (well 0.1 ms), so this should stop those calls happening. as
5022      * all calls to debug are wrapped with direct variable queries rather than actually calling the funciton
5023      * THIS STILL NEEDS FURTHER INVESTIGATION
5024      *
5025      * @access   public
5026      * @return   object an error object
5027      */
5028     static function _loadConfig()
5029     {
5030         global $_DB_DATAOBJECT;
5031
5032         $_DB_DATAOBJECT['CONFIG'] = &PEAR::getStaticProperty('DB_DataObject','options');
5033
5034
5035     }
5036      /**
5037      * Free global arrays associated with this object.
5038      *
5039      *
5040      * @access   public
5041      * @return   none
5042      */
5043     function free() 
5044     {
5045         global $_DB_DATAOBJECT;
5046           
5047         if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid])) {
5048             unset($_DB_DATAOBJECT['RESULTFIELDS'][$this->_DB_resultid]);
5049         }
5050         if (isset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid])) {     
5051             unset($_DB_DATAOBJECT['RESULTS'][$this->_DB_resultid]);
5052         }
5053         // clear the staticGet cache as well.
5054         $this->_clear_cache();
5055         // this is a huge bug in DB!
5056         if (isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]) && isset($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows)) {
5057             $_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5]->num_rows = array();
5058         }
5059
5060         if (is_array($this->_link_loaded)) {
5061             foreach ($this->_link_loaded as $do) {
5062                 if (
5063                         !empty($this->{$do}) &&
5064                         is_object($this->{$do}) &&
5065                         method_exists($this->{$do}, 'free')
5066                     ) {
5067                     $this->{$do}->free();
5068                 }
5069             }
5070         }
5071
5072         
5073     }
5074     /**
5075     * Evaluate whether or not a value is set to null, taking the 'disable_null_strings' option into account.
5076     * If the value is a string set to "null" and the "disable_null_strings" option is not set to 
5077     * true, then the value is considered to be null.
5078     * If the value is actually a PHP NULL value, and "disable_null_strings" has been set to 
5079     * the value "full", then it will also be considered null. - this can not differenticate between not set
5080     * 
5081     * 
5082     * @param  object|array $obj_or_ar 
5083     * @param  string|false $prop prperty
5084     
5085     * @access private
5086     * @return bool  object
5087     */
5088     function _is_null($obj_or_ar , $prop) 
5089     {
5090         global $_DB_DATAOBJECT;
5091         
5092         
5093         $isset = $prop === false ? isset($obj_or_ar) : 
5094             (is_array($obj_or_ar) ? isset($obj_or_ar[$prop]) : isset($obj_or_ar->$prop));
5095         
5096         $value = $isset ? 
5097             ($prop === false ? $obj_or_ar : 
5098                 (is_array($obj_or_ar) ? $obj_or_ar[$prop] : $obj_or_ar->$prop))
5099             : null;
5100         
5101         
5102         
5103         $options = $_DB_DATAOBJECT['CONFIG'];
5104         
5105         $null_strings = !isset($options['disable_null_strings'])
5106                     || $options['disable_null_strings'] === false;
5107                     
5108         $crazy_null = isset($options['disable_null_strings'])
5109                 && is_string($options['disable_null_strings'])
5110                 && strtolower($options['disable_null_strings'] === 'full');
5111         
5112         if ( $null_strings && $isset  && is_string($value)  && (strtolower($value) === 'null') ) {
5113             return true;
5114         }
5115         
5116         if ( $crazy_null && !$isset )  {
5117                 return true;
5118         }
5119         
5120         return false;
5121     }
5122     
5123     
5124     /**
5125      * FC for PDO DataObject.
5126      *
5127      * @category introspect
5128      * @access public
5129      * @return array associative array of table => array ( col -> table:col )
5130      */
5131     function databaseLinks()
5132     {
5133         global $_DB_DATAOBJECT;
5134         $this->links(); // force loading using this method.
5135         return $_DB_DATAOBJECT['LINKS'][$this->_database];
5136     }
5137     
5138     /**
5139      * (deprecated - use ::get / and your own caching method)
5140      */
5141     static function staticGet($class, $k, $v = null)
5142     {
5143         $lclass = strtolower($class);
5144         global $_DB_DATAOBJECT;
5145         if (empty($_DB_DATAOBJECT['CONFIG'])) {
5146             DB_DataObject::_loadConfig();
5147         }
5148
5149         
5150
5151         $key = "$k:$v";
5152         if ($v === null) {
5153             $key = $k;
5154         }
5155         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
5156             DB_DataObject::debug("$class $key","STATIC GET - TRY CACHE");
5157         }
5158         if (!empty($_DB_DATAOBJECT['CACHE'][$lclass][$key])) {
5159             return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
5160         }
5161         if (!empty($_DB_DATAOBJECT['CONFIG']['debug'])) {
5162             DB_DataObject::debug("$class $key","STATIC GET - NOT IN CACHE");
5163         }
5164
5165         $obj = DB_DataObject::factory(substr($class,strlen($_DB_DATAOBJECT['CONFIG']['class_prefix'])));
5166         if (PEAR::isError($obj)) {
5167             $dor = new DB_DataObject();
5168             $dor->raiseError("could not autoload $class", DB_DATAOBJECT_ERROR_NOCLASS);
5169             $r = false;
5170             return $r;
5171         }
5172         
5173         if (!isset($_DB_DATAOBJECT['CACHE'][$lclass])) {
5174             $_DB_DATAOBJECT['CACHE'][$lclass] = array();
5175         }
5176         if (!$obj->get($k,$v)) {
5177             $dor = new DB_DataObject();
5178             $dor->raiseError("No Data return from get $k $v", DB_DATAOBJECT_ERROR_NODATA);
5179             
5180             $r = false;
5181             return $r;
5182         }
5183         $_DB_DATAOBJECT['CACHE'][$lclass][$key] = $obj;
5184         return $_DB_DATAOBJECT['CACHE'][$lclass][$key];
5185     }
5186     
5187     /**
5188      * autoload Class relating to a table
5189      * (deprecited - use ::factory)
5190      *
5191      * @param  string  $table  table
5192      * @access private
5193      * @return string classname on Success
5194      */
5195     function staticAutoloadTable($table)
5196     {
5197         global $_DB_DATAOBJECT;
5198         if (empty($_DB_DATAOBJECT['CONFIG'])) {
5199             DB_DataObject::_loadConfig();
5200         }
5201         $p = isset($_DB_DATAOBJECT['CONFIG']['class_prefix']) ?
5202             $_DB_DATAOBJECT['CONFIG']['class_prefix'] : '';
5203         $class = $p . preg_replace('/[^A-Z0-9]/i','_',ucfirst($table));
5204         
5205         $ce = substr(phpversion(),0,1) > 4 ? class_exists($class,false) : class_exists($class);
5206         $class = $ce ? $class  : DB_DataObject::_autoloadClass($class);
5207         return $class;
5208     }
5209     
5210     /* ---- LEGACY BC METHODS - NOT DOCUMENTED - See Documentation on New Methods. ---*/
5211     
5212     function _get_table() { return $this->table(); }
5213     function _get_keys()  { return $this->keys();  }
5214     
5215     
5216     
5217     
5218 }
5219 // technially 4.3.2RC1 was broken!!
5220 // looks like 4.3.3 may have problems too....
5221 if (!defined('DB_DATAOBJECT_NO_OVERLOAD')) {
5222
5223     if ((phpversion() != '4.3.2-RC1') && (version_compare( phpversion(), "4.3.1") > 0)) {
5224         if (version_compare( phpversion(), "5") < 0) {
5225            overload('DB_DataObject');
5226         } 
5227         $GLOBALS['_DB_DATAOBJECT']['OVERLOADED'] = true;
5228     }
5229 }
5230
5231