PageRenderTime 74ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/concreteOLD/libraries/3rdparty/adodb/adodb-active-recordx.inc.php

https://bitbucket.org/selfeky/xclusivescardwebsite
PHP | 1421 lines | 1114 code | 160 blank | 147 comment | 241 complexity | f4728fe9646996747a171f7f72ffe9da MD5 | raw file
  1. <?php
  2. /*
  3. @version V5.06 29 Sept 2008 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
  4. Latest version is available at http://adodb.sourceforge.net
  5. Released under both BSD license and Lesser GPL library license.
  6. Whenever there is any discrepancy between the two licenses,
  7. the BSD license will take precedence.
  8. Active Record implementation. Superset of Zend Framework's.
  9. This is "Active Record eXtended" to support JOIN, WORK and LAZY mode by Chris Ravenscroft chris#voilaweb.com
  10. Version 0.9
  11. See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
  12. for info on Ruby on Rails Active Record implementation
  13. */
  14. // CFR: Active Records Definitions
  15. define('ADODB_JOIN_AR', 0x01);
  16. define('ADODB_WORK_AR', 0x02);
  17. define('ADODB_LAZY_AR', 0x03);
  18. global $_ADODB_ACTIVE_DBS;
  19. global $ADODB_ACTIVE_CACHESECS; // set to true to enable caching of metadata such as field info
  20. global $ACTIVE_RECORD_SAFETY; // set to false to disable safety checks
  21. global $ADODB_ACTIVE_DEFVALS; // use default values of table definition when creating new active record.
  22. // array of ADODB_Active_DB's, indexed by ADODB_Active_Record->_dbat
  23. $_ADODB_ACTIVE_DBS = array();
  24. $ACTIVE_RECORD_SAFETY = true; // CFR: disabled while playing with relations
  25. $ADODB_ACTIVE_DEFVALS = false;
  26. class ADODB_Active_DB {
  27. var $db; // ADOConnection
  28. var $tables; // assoc array of ADODB_Active_Table objects, indexed by tablename
  29. }
  30. class ADODB_Active_Table {
  31. var $name; // table name
  32. var $flds; // assoc array of adofieldobjs, indexed by fieldname
  33. var $keys; // assoc array of primary keys, indexed by fieldname
  34. var $_created; // only used when stored as a cached file
  35. var $_belongsTo = array();
  36. var $_hasMany = array();
  37. var $_colsCount; // total columns count, including relations
  38. function updateColsCount()
  39. {
  40. $this->_colsCount = sizeof($this->flds);
  41. foreach($this->_belongsTo as $foreignTable)
  42. $this->_colsCount += sizeof($foreignTable->TableInfo()->flds);
  43. foreach($this->_hasMany as $foreignTable)
  44. $this->_colsCount += sizeof($foreignTable->TableInfo()->flds);
  45. }
  46. }
  47. // returns index into $_ADODB_ACTIVE_DBS
  48. function ADODB_SetDatabaseAdapter(&$db)
  49. {
  50. global $_ADODB_ACTIVE_DBS;
  51. foreach($_ADODB_ACTIVE_DBS as $k => $d) {
  52. if (PHP_VERSION >= 5) {
  53. if ($d->db === $db) return $k;
  54. } else {
  55. if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database)
  56. return $k;
  57. }
  58. }
  59. $obj = new ADODB_Active_DB();
  60. $obj->db = $db;
  61. $obj->tables = array();
  62. $_ADODB_ACTIVE_DBS[] = $obj;
  63. return sizeof($_ADODB_ACTIVE_DBS)-1;
  64. }
  65. class ADODB_Active_Record {
  66. static $_changeNames = true; // dynamically pluralize table names
  67. static $_foreignSuffix = '_id'; //
  68. var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
  69. var $_table; // tablename, if set in class definition then use it as table name
  70. var $_sTable; // singularized table name
  71. var $_pTable; // pluralized table name
  72. var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
  73. var $_where; // where clause set in Load()
  74. var $_saved = false; // indicates whether data is already inserted.
  75. var $_lasterr = false; // last error message
  76. var $_original = false; // the original values loaded or inserted, refreshed on update
  77. var $foreignName; // CFR: class name when in a relationship
  78. static function UseDefaultValues($bool=null)
  79. {
  80. global $ADODB_ACTIVE_DEFVALS;
  81. if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
  82. return $ADODB_ACTIVE_DEFVALS;
  83. }
  84. // should be static
  85. static function SetDatabaseAdapter(&$db)
  86. {
  87. return ADODB_SetDatabaseAdapter($db);
  88. }
  89. public function __set($name, $value)
  90. {
  91. $name = str_replace(' ', '_', $name);
  92. $this->$name = $value;
  93. }
  94. // php5 constructor
  95. // Note: if $table is defined, then we will use it as our table name
  96. // Otherwise we will use our classname...
  97. // In our database, table names are pluralized (because there can be
  98. // more than one row!)
  99. // Similarly, if $table is defined here, it has to be plural form.
  100. //
  101. // $options is an array that allows us to tweak the constructor's behaviour
  102. // if $options['refresh'] is true, we re-scan our metadata information
  103. // if $options['new'] is true, we forget all relations
  104. function __construct($table = false, $pkeyarr=false, $db=false, $options=array())
  105. {
  106. global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS;
  107. if ($db == false && is_object($pkeyarr)) {
  108. $db = $pkeyarr;
  109. $pkeyarr = false;
  110. }
  111. if($table)
  112. {
  113. // table argument exists. It is expected to be
  114. // already plural form.
  115. $this->_pTable = $table;
  116. $this->_sTable = $this->_singularize($this->_pTable);
  117. }
  118. else
  119. {
  120. // We will use current classname as table name.
  121. // We need to pluralize it for the real table name.
  122. $this->_sTable = strtolower(get_class($this));
  123. $this->_pTable = $this->_pluralize($this->_sTable);
  124. }
  125. $this->_table = &$this->_pTable;
  126. $this->foreignName = $this->_sTable; // CFR: default foreign name (singular)
  127. if ($db) {
  128. $this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
  129. } else
  130. $this->_dbat = sizeof($_ADODB_ACTIVE_DBS)-1;
  131. if ($this->_dbat < 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
  132. $this->_tableat = $this->_table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
  133. // CFR: Just added this option because UpdateActiveTable() can refresh its information
  134. // but there was no way to ask it to do that.
  135. $forceUpdate = (isset($options['refresh']) && true === $options['refresh']);
  136. $this->UpdateActiveTable($pkeyarr, $forceUpdate);
  137. if(isset($options['new']) && true === $options['new'])
  138. {
  139. $table =& $this->TableInfo();
  140. unset($table->_hasMany);
  141. unset($table->_belongsTo);
  142. $table->_hasMany = array();
  143. $table->_belongsTo = array();
  144. }
  145. }
  146. function __wakeup()
  147. {
  148. $class = get_class($this);
  149. new $class;
  150. }
  151. // CFR: Constants found in Rails
  152. static $IrregularP = array(
  153. 'PERSON' => 'people',
  154. 'MAN' => 'men',
  155. 'WOMAN' => 'women',
  156. 'CHILD' => 'children',
  157. 'COW' => 'kine',
  158. );
  159. static $IrregularS = array(
  160. 'PEOPLE' => 'PERSON',
  161. 'MEN' => 'man',
  162. 'WOMEN' => 'woman',
  163. 'CHILDREN' => 'child',
  164. 'KINE' => 'cow',
  165. );
  166. static $WeIsI = array(
  167. 'EQUIPMENT' => true,
  168. 'INFORMATION' => true,
  169. 'RICE' => true,
  170. 'MONEY' => true,
  171. 'SPECIES' => true,
  172. 'SERIES' => true,
  173. 'FISH' => true,
  174. 'SHEEP' => true,
  175. );
  176. function _pluralize($table)
  177. {
  178. if (!ADODB_Active_Record::$_changeNames) return $table;
  179. $ut = strtoupper($table);
  180. if(isset(self::$WeIsI[$ut]))
  181. {
  182. return $table;
  183. }
  184. if(isset(self::$IrregularP[$ut]))
  185. {
  186. return self::$IrregularP[$ut];
  187. }
  188. $len = strlen($table);
  189. $lastc = $ut[$len-1];
  190. $lastc2 = substr($ut,$len-2);
  191. switch ($lastc) {
  192. case 'S':
  193. return $table.'es';
  194. case 'Y':
  195. return substr($table,0,$len-1).'ies';
  196. case 'X':
  197. return $table.'es';
  198. case 'H':
  199. if ($lastc2 == 'CH' || $lastc2 == 'SH')
  200. return $table.'es';
  201. default:
  202. return $table.'s';
  203. }
  204. }
  205. // CFR Lamest singular inflector ever - @todo Make it real!
  206. // Note: There is an assumption here...and it is that the argument's length >= 4
  207. function _singularize($table)
  208. {
  209. if (!ADODB_Active_Record::$_changeNames) return $table;
  210. $ut = strtoupper($table);
  211. if(isset(self::$WeIsI[$ut]))
  212. {
  213. return $table;
  214. }
  215. if(isset(self::$IrregularS[$ut]))
  216. {
  217. return self::$IrregularS[$ut];
  218. }
  219. $len = strlen($table);
  220. if($ut[$len-1] != 'S')
  221. return $table; // I know...forget oxen
  222. if($ut[$len-2] != 'E')
  223. return substr($table, 0, $len-1);
  224. switch($ut[$len-3])
  225. {
  226. case 'S':
  227. case 'X':
  228. return substr($table, 0, $len-2);
  229. case 'I':
  230. return substr($table, 0, $len-3) . 'y';
  231. case 'H';
  232. if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
  233. return substr($table, 0, $len-2);
  234. default:
  235. return substr($table, 0, $len-1); // ?
  236. }
  237. }
  238. /*
  239. * ar->foreignName will contain the name of the tables associated with this table because
  240. * these other tables' rows may also be referenced by this table using theirname_id or the provided
  241. * foreign keys (this index name is stored in ar->foreignKey)
  242. *
  243. * this-table.id = other-table-#1.this-table_id
  244. * = other-table-#2.this-table_id
  245. */
  246. function hasMany($foreignRef,$foreignKey=false)
  247. {
  248. $ar = new ADODB_Active_Record($foreignRef);
  249. $ar->foreignName = $foreignRef;
  250. $ar->UpdateActiveTable();
  251. $ar->foreignKey = ($foreignKey) ? $foreignKey : strtolower(get_class($this)) . self::$_foreignSuffix;
  252. $table =& $this->TableInfo();
  253. if(!isset($table->_hasMany[$foreignRef]))
  254. {
  255. $table->_hasMany[$foreignRef] = $ar;
  256. $table->updateColsCount();
  257. }
  258. # @todo Can I make this guy be lazy?
  259. $this->$foreignRef = $table->_hasMany[$foreignRef]; // WATCHME Removed assignment by ref. to please __get()
  260. }
  261. /**
  262. * ar->foreignName will contain the name of the tables associated with this table because
  263. * this table's rows may also be referenced by those tables using thistable_id or the provided
  264. * foreign keys (this index name is stored in ar->foreignKey)
  265. *
  266. * this-table.other-table_id = other-table.id
  267. */
  268. function belongsTo($foreignRef,$foreignKey=false)
  269. {
  270. global $inflector;
  271. $ar = new ADODB_Active_Record($this->_pluralize($foreignRef));
  272. $ar->foreignName = $foreignRef;
  273. $ar->UpdateActiveTable();
  274. $ar->foreignKey = ($foreignKey) ? $foreignKey : $ar->foreignName . self::$_foreignSuffix;
  275. $table =& $this->TableInfo();
  276. if(!isset($table->_belongsTo[$foreignRef]))
  277. {
  278. $table->_belongsTo[$foreignRef] = $ar;
  279. $table->updateColsCount();
  280. }
  281. $this->$foreignRef = $table->_belongsTo[$foreignRef];
  282. }
  283. /**
  284. * __get Access properties - used for lazy loading
  285. *
  286. * @param mixed $name
  287. * @access protected
  288. * @return void
  289. */
  290. function __get($name)
  291. {
  292. return $this->LoadRelations($name, '', -1. -1);
  293. }
  294. function LoadRelations($name, $whereOrderBy, $offset=-1, $limit=-1)
  295. {
  296. $extras = array();
  297. if($offset >= 0) $extras['offset'] = $offset;
  298. if($limit >= 0) $extras['limit'] = $limit;
  299. $table =& $this->TableInfo();
  300. if (strlen($whereOrderBy))
  301. if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
  302. if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
  303. $whereOrderBy = 'AND '.$whereOrderBy;
  304. if(!empty($table->_belongsTo[$name]))
  305. {
  306. $obj = $table->_belongsTo[$name];
  307. $columnName = $obj->foreignKey;
  308. if(empty($this->$columnName))
  309. $this->$name = null;
  310. else
  311. {
  312. if(($k = reset($obj->TableInfo()->keys)))
  313. $belongsToId = $k;
  314. else
  315. $belongsToId = 'id';
  316. $arrayOfOne =
  317. $obj->Find(
  318. $belongsToId.'='.$this->$columnName.' '.$whereOrderBy, false, false, $extras);
  319. $this->$name = $arrayOfOne[0];
  320. }
  321. return $this->$name;
  322. }
  323. if(!empty($table->_hasMany[$name]))
  324. {
  325. $obj = $table->_hasMany[$name];
  326. if(($k = reset($table->keys)))
  327. $hasManyId = $k;
  328. else
  329. $hasManyId = 'id';
  330. $this->$name =
  331. $obj->Find(
  332. $obj->foreignKey.'='.$this->$hasManyId.' '.$whereOrderBy, false, false, $extras);
  333. return $this->$name;
  334. }
  335. }
  336. //////////////////////////////////
  337. // update metadata
  338. function UpdateActiveTable($pkeys=false,$forceUpdate=false)
  339. {
  340. global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS , $ADODB_CACHE_DIR, $ADODB_ACTIVE_CACHESECS;
  341. global $ADODB_ACTIVE_DEFVALS, $ADODB_FETCH_MODE;
  342. $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
  343. $table = $this->_table;
  344. $tables = $activedb->tables;
  345. $tableat = $this->_tableat;
  346. if (!$forceUpdate && !empty($tables[$tableat])) {
  347. $tobj = $tables[$tableat];
  348. foreach($tobj->flds as $name => $fld) {
  349. if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
  350. $this->$name = $fld->default_value;
  351. else
  352. $this->$name = null;
  353. }
  354. return;
  355. }
  356. $db = $activedb->db;
  357. $fname = $ADODB_CACHE_DIR . '/adodb_' . $db->databaseType . '_active_'. $table . '.cache';
  358. if (!$forceUpdate && $ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR && file_exists($fname)) {
  359. $fp = fopen($fname,'r');
  360. @flock($fp, LOCK_SH);
  361. $acttab = unserialize(fread($fp,100000));
  362. fclose($fp);
  363. if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) {
  364. // abs(rand()) randomizes deletion, reducing contention to delete/refresh file
  365. // ideally, you should cache at least 32 secs
  366. $activedb->tables[$table] = $acttab;
  367. //if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
  368. return;
  369. } else if ($db->debug) {
  370. ADOConnection::outp("Refreshing cached active record file: $fname");
  371. }
  372. }
  373. $activetab = new ADODB_Active_Table();
  374. $activetab->name = $table;
  375. $save = $ADODB_FETCH_MODE;
  376. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  377. if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
  378. $cols = $db->MetaColumns($table);
  379. if (isset($savem)) $db->SetFetchMode($savem);
  380. $ADODB_FETCH_MODE = $save;
  381. if (!$cols) {
  382. $this->Error("Invalid table name: $table",'UpdateActiveTable');
  383. return false;
  384. }
  385. $fld = reset($cols);
  386. if (!$pkeys) {
  387. if (isset($fld->primary_key)) {
  388. $pkeys = array();
  389. foreach($cols as $name => $fld) {
  390. if (!empty($fld->primary_key)) $pkeys[] = $name;
  391. }
  392. } else
  393. $pkeys = $this->GetPrimaryKeys($db, $table);
  394. }
  395. if (empty($pkeys)) {
  396. $this->Error("No primary key found for table $table",'UpdateActiveTable');
  397. return false;
  398. }
  399. $attr = array();
  400. $keys = array();
  401. switch($ADODB_ASSOC_CASE) {
  402. case 0:
  403. foreach($cols as $name => $fldobj) {
  404. $name = strtolower($name);
  405. if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
  406. $this->$name = $fldobj->default_value;
  407. else
  408. $this->$name = null;
  409. $attr[$name] = $fldobj;
  410. }
  411. foreach($pkeys as $k => $name) {
  412. $keys[strtolower($name)] = strtolower($name);
  413. }
  414. break;
  415. case 1:
  416. foreach($cols as $name => $fldobj) {
  417. $name = strtoupper($name);
  418. if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
  419. $this->$name = $fldobj->default_value;
  420. else
  421. $this->$name = null;
  422. $attr[$name] = $fldobj;
  423. }
  424. foreach($pkeys as $k => $name) {
  425. $keys[strtoupper($name)] = strtoupper($name);
  426. }
  427. break;
  428. default:
  429. foreach($cols as $name => $fldobj) {
  430. $name = ($fldobj->name);
  431. if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
  432. $this->$name = $fldobj->default_value;
  433. else
  434. $this->$name = null;
  435. $attr[$name] = $fldobj;
  436. }
  437. foreach($pkeys as $k => $name) {
  438. $keys[$name] = $cols[$name]->name;
  439. }
  440. break;
  441. }
  442. $activetab->keys = $keys;
  443. $activetab->flds = $attr;
  444. $activetab->updateColsCount();
  445. if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
  446. $activetab->_created = time();
  447. $s = serialize($activetab);
  448. if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  449. adodb_write_file($fname,$s);
  450. }
  451. if (isset($activedb->tables[$table])) {
  452. $oldtab = $activedb->tables[$table];
  453. if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
  454. if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
  455. }
  456. $activedb->tables[$table] = $activetab;
  457. }
  458. function GetPrimaryKeys(&$db, $table)
  459. {
  460. return $db->MetaPrimaryKeys($table);
  461. }
  462. // error handler for both PHP4+5.
  463. function Error($err,$fn)
  464. {
  465. global $_ADODB_ACTIVE_DBS;
  466. $fn = get_class($this).'::'.$fn;
  467. $this->_lasterr = $fn.': '.$err;
  468. if ($this->_dbat < 0) $db = false;
  469. else {
  470. $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
  471. $db = $activedb->db;
  472. }
  473. if (function_exists('adodb_throw')) {
  474. if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
  475. else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
  476. } else
  477. if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
  478. }
  479. // return last error message
  480. function ErrorMsg()
  481. {
  482. if (!function_exists('adodb_throw')) {
  483. if ($this->_dbat < 0) $db = false;
  484. else $db = $this->DB();
  485. // last error could be database error too
  486. if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
  487. }
  488. return $this->_lasterr;
  489. }
  490. function ErrorNo()
  491. {
  492. if ($this->_dbat < 0) return -9999; // no database connection...
  493. $db = $this->DB();
  494. return (int) $db->ErrorNo();
  495. }
  496. // retrieve ADOConnection from _ADODB_Active_DBs
  497. function DB()
  498. {
  499. global $_ADODB_ACTIVE_DBS;
  500. if ($this->_dbat < 0) {
  501. $false = false;
  502. $this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
  503. return $false;
  504. }
  505. $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
  506. $db = $activedb->db;
  507. return $db;
  508. }
  509. // retrieve ADODB_Active_Table
  510. function &TableInfo()
  511. {
  512. global $_ADODB_ACTIVE_DBS;
  513. $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
  514. $table = $activedb->tables[$this->_tableat];
  515. return $table;
  516. }
  517. // I have an ON INSERT trigger on a table that sets other columns in the table.
  518. // So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
  519. function Reload()
  520. {
  521. $db =& $this->DB(); if (!$db) return false;
  522. $table =& $this->TableInfo();
  523. $where = $this->GenWhere($db, $table);
  524. return($this->Load($where));
  525. }
  526. // set a numeric array (using natural table field ordering) as object properties
  527. function Set(&$row)
  528. {
  529. global $ACTIVE_RECORD_SAFETY;
  530. $db = $this->DB();
  531. if (!$row) {
  532. $this->_saved = false;
  533. return false;
  534. }
  535. $this->_saved = true;
  536. $table = $this->TableInfo();
  537. $sizeofFlds = sizeof($table->flds);
  538. $sizeofRow = sizeof($row);
  539. if ($ACTIVE_RECORD_SAFETY && $table->_colsCount != $sizeofRow && $sizeofFlds != $sizeofRow) {
  540. # <AP>
  541. $bad_size = TRUE;
  542. if($sizeofRow == 2 * $table->_colsCount || $sizeofRow == 2 * $sizeofFlds) {
  543. // Only keep string keys
  544. $keys = array_filter(array_keys($row), 'is_string');
  545. if (sizeof($keys) == sizeof($table->flds))
  546. $bad_size = FALSE;
  547. }
  548. if ($bad_size) {
  549. $this->Error("Table structure of $this->_table has changed","Load");
  550. return false;
  551. }
  552. # </AP>
  553. }
  554. else
  555. $keys = array_keys($row);
  556. # <AP>
  557. reset($keys);
  558. $this->_original = array();
  559. foreach($table->flds as $name=>$fld)
  560. {
  561. $value = $row[current($keys)];
  562. $this->$name = $value;
  563. $this->_original[] = $value;
  564. if(!next($keys)) break;
  565. }
  566. $table =& $this->TableInfo();
  567. foreach($table->_belongsTo as $foreignTable)
  568. {
  569. $ft = $foreignTable->TableInfo();
  570. $propertyName = $ft->name;
  571. foreach($ft->flds as $name=>$fld)
  572. {
  573. $value = $row[current($keys)];
  574. $foreignTable->$name = $value;
  575. $foreignTable->_original[] = $value;
  576. if(!next($keys)) break;
  577. }
  578. }
  579. foreach($table->_hasMany as $foreignTable)
  580. {
  581. $ft = $foreignTable->TableInfo();
  582. foreach($ft->flds as $name=>$fld)
  583. {
  584. $value = $row[current($keys)];
  585. $foreignTable->$name = $value;
  586. $foreignTable->_original[] = $value;
  587. if(!next($keys)) break;
  588. }
  589. }
  590. # </AP>
  591. return true;
  592. }
  593. // get last inserted id for INSERT
  594. function LastInsertID(&$db,$fieldname)
  595. {
  596. if ($db->hasInsertID)
  597. $val = $db->Insert_ID($this->_table,$fieldname);
  598. else
  599. $val = false;
  600. if (is_null($val) || $val === false) {
  601. // this might not work reliably in multi-user environment
  602. return $db->GetOne("select max(".$fieldname.") from ".$this->_table);
  603. }
  604. return $val;
  605. }
  606. // quote data in where clause
  607. function doquote(&$db, $val,$t)
  608. {
  609. switch($t) {
  610. case 'D':
  611. case 'T':
  612. if (empty($val)) return 'null';
  613. case 'C':
  614. case 'X':
  615. if (is_null($val)) return 'null';
  616. if (strlen($val)>1 &&
  617. (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
  618. return $db->qstr($val);
  619. break;
  620. }
  621. default:
  622. return $val;
  623. break;
  624. }
  625. }
  626. // generate where clause for an UPDATE/SELECT
  627. function GenWhere(&$db, &$table)
  628. {
  629. $keys = $table->keys;
  630. $parr = array();
  631. foreach($keys as $k) {
  632. $f = $table->flds[$k];
  633. if ($f) {
  634. $parr[] = $k.' = '.$this->doquote($db,$this->$k,$db->MetaType($f->type));
  635. }
  636. }
  637. return implode(' and ', $parr);
  638. }
  639. //------------------------------------------------------------ Public functions below
  640. function Load($where=null,$bindarr=false)
  641. {
  642. $db = $this->DB(); if (!$db) return false;
  643. $this->_where = $where;
  644. $save = $db->SetFetchMode(ADODB_FETCH_NUM);
  645. $qry = "select * from ".$this->_table;
  646. $table =& $this->TableInfo();
  647. if(($k = reset($table->keys)))
  648. $hasManyId = $k;
  649. else
  650. $hasManyId = 'id';
  651. foreach($table->_belongsTo as $foreignTable)
  652. {
  653. if(($k = reset($foreignTable->TableInfo()->keys)))
  654. {
  655. $belongsToId = $k;
  656. }
  657. else
  658. {
  659. $belongsToId = 'id';
  660. }
  661. $qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
  662. $this->_table.'.'.$foreignTable->foreignKey.'='.
  663. $foreignTable->_table.'.'.$belongsToId;
  664. }
  665. foreach($table->_hasMany as $foreignTable)
  666. {
  667. $qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
  668. $this->_table.'.'.$hasManyId.'='.
  669. $foreignTable->_table.'.'.$foreignTable->foreignKey;
  670. }
  671. if($where)
  672. $qry .= ' WHERE '.$where;
  673. // Simple case: no relations. Load row and return.
  674. if((count($table->_hasMany) + count($table->_belongsTo)) < 1)
  675. {
  676. $row = $db->GetRow($qry,$bindarr);
  677. if(!$row)
  678. return false;
  679. $db->SetFetchMode($save);
  680. return $this->Set($row);
  681. }
  682. // More complex case when relations have to be collated
  683. $rows = $db->GetAll($qry,$bindarr);
  684. if(!$rows)
  685. return false;
  686. $db->SetFetchMode($save);
  687. if(count($rows) < 1)
  688. return false;
  689. $class = get_class($this);
  690. $isFirstRow = true;
  691. if(($k = reset($this->TableInfo()->keys)))
  692. $myId = $k;
  693. else
  694. $myId = 'id';
  695. $index = 0; $found = false;
  696. /** @todo Improve by storing once and for all in table metadata */
  697. /** @todo Also re-use info for hasManyId */
  698. foreach($this->TableInfo()->flds as $fld)
  699. {
  700. if($fld->name == $myId)
  701. {
  702. $found = true;
  703. break;
  704. }
  705. $index++;
  706. }
  707. if(!$found)
  708. $this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
  709. foreach($rows as $row)
  710. {
  711. $rowId = intval($row[$index]);
  712. if($rowId > 0)
  713. {
  714. if($isFirstRow)
  715. {
  716. $isFirstRow = false;
  717. if(!$this->Set($row))
  718. return false;
  719. }
  720. $obj = new $class($table,false,$db);
  721. $obj->Set($row);
  722. // TODO Copy/paste code below: bad!
  723. if(count($table->_hasMany) > 0)
  724. {
  725. foreach($table->_hasMany as $foreignTable)
  726. {
  727. $foreignName = $foreignTable->foreignName;
  728. if(!empty($obj->$foreignName))
  729. {
  730. if(!is_array($this->$foreignName))
  731. {
  732. $foreignObj = $this->$foreignName;
  733. $this->$foreignName = array(clone($foreignObj));
  734. }
  735. else
  736. {
  737. $foreignObj = $obj->$foreignName;
  738. array_push($this->$foreignName, clone($foreignObj));
  739. }
  740. }
  741. }
  742. }
  743. if(count($table->_belongsTo) > 0)
  744. {
  745. foreach($table->_belongsTo as $foreignTable)
  746. {
  747. $foreignName = $foreignTable->foreignName;
  748. if(!empty($obj->$foreignName))
  749. {
  750. if(!is_array($this->$foreignName))
  751. {
  752. $foreignObj = $this->$foreignName;
  753. $this->$foreignName = array(clone($foreignObj));
  754. }
  755. else
  756. {
  757. $foreignObj = $obj->$foreignName;
  758. array_push($this->$foreignName, clone($foreignObj));
  759. }
  760. }
  761. }
  762. }
  763. }
  764. }
  765. return true;
  766. }
  767. // false on error
  768. function Save()
  769. {
  770. if ($this->_saved) $ok = $this->Update();
  771. else $ok = $this->Insert();
  772. return $ok;
  773. }
  774. // CFR: Sometimes we may wish to consider that an object is not to be replaced but inserted.
  775. // Sample use case: an 'undo' command object (after a delete())
  776. function Dirty()
  777. {
  778. $this->_saved = false;
  779. }
  780. // false on error
  781. function Insert()
  782. {
  783. $db = $this->DB(); if (!$db) return false;
  784. $cnt = 0;
  785. $table = $this->TableInfo();
  786. $valarr = array();
  787. $names = array();
  788. $valstr = array();
  789. foreach($table->flds as $name=>$fld) {
  790. $val = $this->$name;
  791. if(!is_null($val) || !array_key_exists($name, $table->keys)) {
  792. $valarr[] = $val;
  793. $names[] = $name;
  794. $valstr[] = $db->Param($cnt);
  795. $cnt += 1;
  796. }
  797. }
  798. if (empty($names)){
  799. foreach($table->flds as $name=>$fld) {
  800. $valarr[] = null;
  801. $names[] = $name;
  802. $valstr[] = $db->Param($cnt);
  803. $cnt += 1;
  804. }
  805. }
  806. $sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
  807. $ok = $db->Execute($sql,$valarr);
  808. if ($ok) {
  809. $this->_saved = true;
  810. $autoinc = false;
  811. foreach($table->keys as $k) {
  812. if (is_null($this->$k)) {
  813. $autoinc = true;
  814. break;
  815. }
  816. }
  817. if ($autoinc && sizeof($table->keys) == 1) {
  818. $k = reset($table->keys);
  819. $this->$k = $this->LastInsertID($db,$k);
  820. }
  821. }
  822. $this->_original = $valarr;
  823. return !empty($ok);
  824. }
  825. function Delete()
  826. {
  827. $db = $this->DB(); if (!$db) return false;
  828. $table = $this->TableInfo();
  829. $where = $this->GenWhere($db,$table);
  830. $sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
  831. $ok = $db->Execute($sql);
  832. return $ok ? true : false;
  833. }
  834. // returns an array of active record objects
  835. function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
  836. {
  837. $db = $this->DB(); if (!$db || empty($this->_table)) return false;
  838. $table =& $this->TableInfo();
  839. $arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
  840. array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
  841. return $arr;
  842. }
  843. // CFR: In introduced this method to ensure that inner workings are not disturbed by
  844. // subclasses...for instance when GetActiveRecordsClass invokes Find()
  845. // Why am I not invoking parent::Find?
  846. // Shockingly because I want to preserve PHP4 compatibility.
  847. function packageFind($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
  848. {
  849. $db = $this->DB(); if (!$db || empty($this->_table)) return false;
  850. $table =& $this->TableInfo();
  851. $arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
  852. array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
  853. return $arr;
  854. }
  855. // returns 0 on error, 1 on update, 2 on insert
  856. function Replace()
  857. {
  858. global $ADODB_ASSOC_CASE;
  859. $db = $this->DB(); if (!$db) return false;
  860. $table = $this->TableInfo();
  861. $pkey = $table->keys;
  862. foreach($table->flds as $name=>$fld) {
  863. $val = $this->$name;
  864. /*
  865. if (is_null($val)) {
  866. if (isset($fld->not_null) && $fld->not_null) {
  867. if (isset($fld->default_value) && strlen($fld->default_value)) continue;
  868. else {
  869. $this->Error("Cannot update null into $name","Replace");
  870. return false;
  871. }
  872. }
  873. }*/
  874. if (is_null($val) && !empty($fld->auto_increment)) {
  875. continue;
  876. }
  877. $t = $db->MetaType($fld->type);
  878. $arr[$name] = $this->doquote($db,$val,$t);
  879. $valarr[] = $val;
  880. }
  881. if (!is_array($pkey)) $pkey = array($pkey);
  882. if ($ADODB_ASSOC_CASE == 0)
  883. foreach($pkey as $k => $v)
  884. $pkey[$k] = strtolower($v);
  885. elseif ($ADODB_ASSOC_CASE == 1)
  886. foreach($pkey as $k => $v)
  887. $pkey[$k] = strtoupper($v);
  888. $ok = $db->Replace($this->_table,$arr,$pkey);
  889. if ($ok) {
  890. $this->_saved = true; // 1= update 2=insert
  891. if ($ok == 2) {
  892. $autoinc = false;
  893. foreach($table->keys as $k) {
  894. if (is_null($this->$k)) {
  895. $autoinc = true;
  896. break;
  897. }
  898. }
  899. if ($autoinc && sizeof($table->keys) == 1) {
  900. $k = reset($table->keys);
  901. $this->$k = $this->LastInsertID($db,$k);
  902. }
  903. }
  904. $this->_original = $valarr;
  905. }
  906. return $ok;
  907. }
  908. // returns 0 on error, 1 on update, -1 if no change in data (no update)
  909. function Update()
  910. {
  911. $db = $this->DB(); if (!$db) return false;
  912. $table = $this->TableInfo();
  913. $where = $this->GenWhere($db, $table);
  914. if (!$where) {
  915. $this->error("Where missing for table $table", "Update");
  916. return false;
  917. }
  918. $valarr = array();
  919. $neworig = array();
  920. $pairs = array();
  921. $i = -1;
  922. $cnt = 0;
  923. foreach($table->flds as $name=>$fld) {
  924. $i += 1;
  925. $val = $this->$name;
  926. $neworig[] = $val;
  927. if (isset($table->keys[$name])) {
  928. continue;
  929. }
  930. if (is_null($val)) {
  931. if (isset($fld->not_null) && $fld->not_null) {
  932. if (isset($fld->default_value) && strlen($fld->default_value)) continue;
  933. else {
  934. $this->Error("Cannot set field $name to NULL","Update");
  935. return false;
  936. }
  937. }
  938. }
  939. if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
  940. continue;
  941. }
  942. $valarr[] = $val;
  943. $pairs[] = $name.'='.$db->Param($cnt);
  944. $cnt += 1;
  945. }
  946. if (!$cnt) return -1;
  947. $sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
  948. $ok = $db->Execute($sql,$valarr);
  949. if ($ok) {
  950. $this->_original = $neworig;
  951. return 1;
  952. }
  953. return 0;
  954. }
  955. function GetAttributeNames()
  956. {
  957. $table = $this->TableInfo();
  958. if (!$table) return false;
  959. return array_keys($table->flds);
  960. }
  961. };
  962. function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bindarr, $primkeyArr,
  963. $extra, $relations)
  964. {
  965. global $_ADODB_ACTIVE_DBS;
  966. if (empty($extra['loading'])) $extra['loading'] = ADODB_LAZY_AR;
  967. $save = $db->SetFetchMode(ADODB_FETCH_NUM);
  968. $table = &$tableObj->_table;
  969. $tableInfo =& $tableObj->TableInfo();
  970. if(($k = reset($tableInfo->keys)))
  971. $myId = $k;
  972. else
  973. $myId = 'id';
  974. $index = 0; $found = false;
  975. /** @todo Improve by storing once and for all in table metadata */
  976. /** @todo Also re-use info for hasManyId */
  977. foreach($tableInfo->flds as $fld)
  978. {
  979. if($fld->name == $myId)
  980. {
  981. $found = true;
  982. break;
  983. }
  984. $index++;
  985. }
  986. if(!$found)
  987. $db->outp_throw("Unable to locate key $myId for $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
  988. $qry = "select * from ".$table;
  989. if(ADODB_JOIN_AR == $extra['loading'])
  990. {
  991. if(!empty($relations['belongsTo']))
  992. {
  993. foreach($relations['belongsTo'] as $foreignTable)
  994. {
  995. if(($k = reset($foreignTable->TableInfo()->keys)))
  996. {
  997. $belongsToId = $k;
  998. }
  999. else
  1000. {
  1001. $belongsToId = 'id';
  1002. }
  1003. $qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
  1004. $table.'.'.$foreignTable->foreignKey.'='.
  1005. $foreignTable->_table.'.'.$belongsToId;
  1006. }
  1007. }
  1008. if(!empty($relations['hasMany']))
  1009. {
  1010. if(empty($relations['foreignName']))
  1011. $db->outp_throw("Missing foreignName is relation specification in GetActiveRecordsClass()",'GetActiveRecordsClass');
  1012. if(($k = reset($tableInfo->keys)))
  1013. $hasManyId = $k;
  1014. else
  1015. $hasManyId = 'id';
  1016. foreach($relations['hasMany'] as $foreignTable)
  1017. {
  1018. $qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
  1019. $table.'.'.$hasManyId.'='.
  1020. $foreignTable->_table.'.'.$foreignTable->foreignKey;
  1021. }
  1022. }
  1023. }
  1024. if (!empty($whereOrderBy))
  1025. $qry .= ' WHERE '.$whereOrderBy;
  1026. if(isset($extra['limit']))
  1027. {
  1028. $rows = false;
  1029. if(isset($extra['offset'])) {
  1030. $rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset']);
  1031. } else {
  1032. $rs = $db->SelectLimit($qry, $extra['limit']);
  1033. }
  1034. if ($rs) {
  1035. while (!$rs->EOF) {
  1036. $rows[] = $rs->fields;
  1037. $rs->MoveNext();
  1038. }
  1039. }
  1040. } else
  1041. $rows = $db->GetAll($qry,$bindarr);
  1042. $db->SetFetchMode($save);
  1043. $false = false;
  1044. if ($rows === false) {
  1045. return $false;
  1046. }
  1047. if (!isset($_ADODB_ACTIVE_DBS)) {
  1048. include(ADODB_DIR.'/adodb-active-record.inc.php');
  1049. }
  1050. if (!class_exists($class)) {
  1051. $db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
  1052. return $false;
  1053. }
  1054. $uniqArr = array(); // CFR Keep track of records for relations
  1055. $arr = array();
  1056. // arrRef will be the structure that knows about our objects.
  1057. // It is an associative array.
  1058. // We will, however, return arr, preserving regular 0.. order so that
  1059. // obj[0] can be used by app developpers.
  1060. $arrRef = array();
  1061. $bTos = array(); // Will store belongTo's indices if any
  1062. foreach($rows as $row) {
  1063. $obj = new $class($table,$primkeyArr,$db);
  1064. if ($obj->ErrorNo()){
  1065. $db->_errorMsg = $obj->ErrorMsg();
  1066. return $false;
  1067. }
  1068. $obj->Set($row);
  1069. // CFR: FIXME: Insane assumption here:
  1070. // If the first column returned is an integer, then it's a 'id' field
  1071. // And to make things a bit worse, I use intval() rather than is_int() because, in fact,
  1072. // $row[0] is not an integer.
  1073. //
  1074. // So, what does this whole block do?
  1075. // When relationships are found, we perform JOINs. This is fast. But not accurate:
  1076. // instead of returning n objects with their n' associated cousins,
  1077. // we get n*n' objects. This code fixes this.
  1078. // Note: to-many relationships mess around with the 'limit' parameter
  1079. $rowId = intval($row[$index]);
  1080. if(ADODB_WORK_AR == $extra['loading'])
  1081. {
  1082. $arrRef[$rowId] = $obj;
  1083. $arr[] = &$arrRef[$rowId];
  1084. if(!isset($indices))
  1085. $indices = $rowId;
  1086. else
  1087. $indices .= ','.$rowId;
  1088. if(!empty($relations['belongsTo']))
  1089. {
  1090. foreach($relations['belongsTo'] as $foreignTable)
  1091. {
  1092. $foreignTableRef = $foreignTable->foreignKey;
  1093. // First array: list of foreign ids we are looking for
  1094. if(empty($bTos[$foreignTableRef]))
  1095. $bTos[$foreignTableRef] = array();
  1096. // Second array: list of ids found
  1097. if(empty($obj->$foreignTableRef))
  1098. continue;
  1099. if(empty($bTos[$foreignTableRef][$obj->$foreignTableRef]))
  1100. $bTos[$foreignTableRef][$obj->$foreignTableRef] = array();
  1101. $bTos[$foreignTableRef][$obj->$foreignTableRef][] = $obj;
  1102. }
  1103. }
  1104. continue;
  1105. }
  1106. if($rowId>0)
  1107. {
  1108. if(ADODB_JOIN_AR == $extra['loading'])
  1109. {
  1110. $isNewObj = !isset($uniqArr['_'.$row[0]]);
  1111. if($isNewObj)
  1112. $uniqArr['_'.$row[0]] = $obj;
  1113. // TODO Copy/paste code below: bad!
  1114. if(!empty($relations['hasMany']))
  1115. {
  1116. foreach($relations['hasMany'] as $foreignTable)
  1117. {
  1118. $foreignName = $foreignTable->foreignName;
  1119. if(!empty($obj->$foreignName))
  1120. {
  1121. $masterObj = &$uniqArr['_'.$row[0]];
  1122. // Assumption: this property exists in every object since they are instances of the same class
  1123. if(!is_array($masterObj->$foreignName))
  1124. {
  1125. // Pluck!
  1126. $foreignObj = $masterObj->$foreignName;
  1127. $masterObj->$foreignName = array(clone($foreignObj));
  1128. }
  1129. else
  1130. {
  1131. // Pluck pluck!
  1132. $foreignObj = $obj->$foreignName;
  1133. array_push($masterObj->$foreignName, clone($foreignObj));
  1134. }
  1135. }
  1136. }
  1137. }
  1138. if(!empty($relations['belongsTo']))
  1139. {
  1140. foreach($relations['belongsTo'] as $foreignTable)
  1141. {
  1142. $foreignName = $foreignTable->foreignName;
  1143. if(!empty($obj->$foreignName))
  1144. {
  1145. $masterObj = &$uniqArr['_'.$row[0]];
  1146. // Assumption: this property exists in every object since they are instances of the same class
  1147. if(!is_array($masterObj->$foreignName))
  1148. {
  1149. // Pluck!
  1150. $foreignObj = $masterObj->$foreignName;
  1151. $masterObj->$foreignName = array(clone($foreignObj));
  1152. }
  1153. else
  1154. {
  1155. // Pluck pluck!
  1156. $foreignObj = $obj->$foreignName;
  1157. array_push($masterObj->$foreignName, clone($foreignObj));
  1158. }
  1159. }
  1160. }
  1161. }
  1162. if(!$isNewObj)
  1163. unset($obj); // We do not need this object itself anymore and do not want it re-added to the main array
  1164. }
  1165. else if(ADODB_LAZY_AR == $extra['loading'])
  1166. {
  1167. // Lazy loading: we need to give AdoDb a hint that we have not really loaded
  1168. // anything, all the while keeping enough information on what we wish to load.
  1169. // Let's do this by keeping the relevant info in our relationship arrays
  1170. // but get rid of the actual properties.
  1171. // We will then use PHP's __get to load these properties on-demand.
  1172. if(!empty($relations['hasMany']))
  1173. {
  1174. foreach($relations['hasMany'] as $foreignTable)
  1175. {
  1176. $foreignName = $foreignTable->foreignName;
  1177. if(!empty($obj->$foreignName))
  1178. {
  1179. unset($obj->$foreignName);
  1180. }
  1181. }
  1182. }
  1183. if(!empty($relations['belongsTo']))
  1184. {
  1185. foreach($relations['belongsTo'] as $foreignTable)
  1186. {
  1187. $foreignName = $foreignTable->foreignName;
  1188. if(!empty($obj->$foreignName))
  1189. {
  1190. unset($obj->$foreignName);
  1191. }
  1192. }
  1193. }
  1194. }
  1195. }
  1196. if(isset($obj))
  1197. $arr[] = $obj;
  1198. }
  1199. if(ADODB_WORK_AR == $extra['loading'])
  1200. {
  1201. // The best of both worlds?
  1202. // Here, the number of queries is constant: 1 + n*relationship.
  1203. // The second query will allow us to perform a good join
  1204. // while preserving LIMIT etc.
  1205. if(!empty($relations['hasMany']))
  1206. {
  1207. foreach($relations['hasMany'] as $foreignTable)
  1208. {
  1209. $foreignName = $foreignTable->foreignName;
  1210. $className = ucfirst($foreignTable->_singularize($foreignName));
  1211. $obj = new $className();
  1212. $dbClassRef = $foreignTable->foreignKey;
  1213. $objs = $obj->packageFind($dbClassRef.' IN ('.$indices.')');
  1214. foreach($objs as $obj)
  1215. {
  1216. if(!is_array($arrRef[$obj->$dbClassRef]->$foreignName))
  1217. $arrRef[$obj->$dbClassRef]->$foreignName = array();
  1218. array_push($arrRef[$obj->$dbClassRef]->$foreignName, $obj);
  1219. }
  1220. }
  1221. }
  1222. if(!empty($relations['belongsTo']))
  1223. {
  1224. foreach($relations['belongsTo'] as $foreignTable)
  1225. {
  1226. $foreignTableRef = $foreignTable->foreignKey;
  1227. if(empty($bTos[$foreignTableRef]))
  1228. continue;
  1229. if(($k = reset($foreignTable->TableInfo()->keys)))
  1230. {
  1231. $belongsToId = $k;
  1232. }
  1233. else
  1234. {
  1235. $belongsToId = 'id';
  1236. }
  1237. $origObjsArr = $bTos[$foreignTableRef];
  1238. $bTosString = implode(',', array_keys($bTos[$foreignTableRef]));
  1239. $foreignName = $foreignTable->foreignName;
  1240. $className = ucfirst($foreignTable->_singularize($foreignName));
  1241. $obj = new $className();
  1242. $objs = $obj->packageFind($belongsToId.' IN ('.$bTosString.')');
  1243. foreach($objs as $obj)
  1244. {
  1245. foreach($origObjsArr[$obj->$belongsToId] as $idx=>$origObj)
  1246. {
  1247. $origObj->$foreignName = $obj;
  1248. }
  1249. }
  1250. }
  1251. }
  1252. }
  1253. return $arr;
  1254. }
  1255. ?>