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