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