PageRenderTime 72ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/extlib/DB/DataObject.php

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