PageRenderTime 86ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 1ms

/extlib/DB/DataObject.php

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