PageRenderTime 78ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/extlib/DB/DataObject.php

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