Subversion Repositories Applications.gtt

Rev

Rev 94 | Details | Compare with Previous | Last modification | View Log | RSS feed

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