PageRenderTime 67ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/extlib/DB/DataObject.php

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