adodb-active-recordx.inc.php 37.5 KB
Newer Older
1
2
3
<?php
/*

4
@version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
5
  Latest version is available at http://adodb.sourceforge.net
6
7
8

  Released under both BSD license and Lesser GPL library license.
  Whenever there is any discrepancy between the two licenses,
9
  the BSD license will take precedence.
10

11
  Active Record implementation. Superset of Zend Framework's.
12
13
14

  This is "Active Record eXtended" to support JOIN, WORK and LAZY mode by Chris Ravenscroft  chris#voilaweb.com

15
  Version 0.9
16
17

  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
18
  	for info on Ruby on Rails Active Record implementation
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
*/


	// CFR: Active Records Definitions
define('ADODB_JOIN_AR', 0x01);
define('ADODB_WORK_AR', 0x02);
define('ADODB_LAZY_AR', 0x03);


global $_ADODB_ACTIVE_DBS;
global $ADODB_ACTIVE_CACHESECS; // set to true to enable caching of metadata such as field info
global $ACTIVE_RECORD_SAFETY; // set to false to disable safety checks
global $ADODB_ACTIVE_DEFVALS; // use default values of table definition when creating new active record.

// array of ADODB_Active_DB's, indexed by ADODB_Active_Record->_dbat
$_ADODB_ACTIVE_DBS = array();
$ACTIVE_RECORD_SAFETY = true; // CFR: disabled while playing with relations
$ADODB_ACTIVE_DEFVALS = false;

class ADODB_Active_DB {
	var $db; // ADOConnection
	var $tables; // assoc array of ADODB_Active_Table objects, indexed by tablename
}

class ADODB_Active_Table {
	var $name; // table name
	var $flds; // assoc array of adofieldobjs, indexed by fieldname
	var $keys; // assoc array of primary keys, indexed by fieldname
	var $_created; // only used when stored as a cached file
	var $_belongsTo = array();
	var $_hasMany = array();
	var $_colsCount; // total columns count, including relations

	function updateColsCount()
	{
		$this->_colsCount = sizeof($this->flds);
		foreach($this->_belongsTo as $foreignTable)
			$this->_colsCount += sizeof($foreignTable->TableInfo()->flds);
		foreach($this->_hasMany as $foreignTable)
			$this->_colsCount += sizeof($foreignTable->TableInfo()->flds);
	}
}

// returns index into $_ADODB_ACTIVE_DBS
function ADODB_SetDatabaseAdapter(&$db)
{
	global $_ADODB_ACTIVE_DBS;
66

67
68
69
70
		foreach($_ADODB_ACTIVE_DBS as $k => $d) {
			if (PHP_VERSION >= 5) {
				if ($d->db === $db) return $k;
			} else {
71
				if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database)
72
73
74
					return $k;
			}
		}
75

76
77
78
		$obj = new ADODB_Active_DB();
		$obj->db = $db;
		$obj->tables = array();
79

80
		$_ADODB_ACTIVE_DBS[] = $obj;
81

82
83
84
85
86
87
		return sizeof($_ADODB_ACTIVE_DBS)-1;
}


class ADODB_Active_Record {
	static $_changeNames = true; // dynamically pluralize table names
88
	static $_foreignSuffix = '_id'; //
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
	var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
	var $_table; // tablename, if set in class definition then use it as table name
	var $_sTable; // singularized table name
	var $_pTable; // pluralized table name
	var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
	var $_where; // where clause set in Load()
	var $_saved = false; // indicates whether data is already inserted.
	var $_lasterr = false; // last error message
	var $_original = false; // the original values loaded or inserted, refreshed on update

	var $foreignName; // CFR: class name when in a relationship

	static function UseDefaultValues($bool=null)
	{
	global $ADODB_ACTIVE_DEFVALS;
		if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
		return $ADODB_ACTIVE_DEFVALS;
	}

	// should be static
109
	static function SetDatabaseAdapter(&$db)
110
111
112
	{
		return ADODB_SetDatabaseAdapter($db);
	}
113
114


115
116
117
118
119
	public function __set($name, $value)
	{
		$name = str_replace(' ', '_', $name);
		$this->$name = $value;
	}
120

121
122
123
124
125
126
127
128
129
130
131
132
133
	// php5 constructor
	// Note: if $table is defined, then we will use it as our table name
	// Otherwise we will use our classname...
	// In our database, table names are pluralized (because there can be
	// more than one row!)
	// Similarly, if $table is defined here, it has to be plural form.
	//
	// $options is an array that allows us to tweak the constructor's behaviour
	// if $options['refresh'] is true, we re-scan our metadata information
	// if $options['new'] is true, we forget all relations
	function __construct($table = false, $pkeyarr=false, $db=false, $options=array())
	{
	global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS;
134

135
136
137
138
		if ($db == false && is_object($pkeyarr)) {
			$db = $pkeyarr;
			$pkeyarr = false;
		}
139

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
		if($table)
		{
			// table argument exists. It is expected to be
			// already plural form.
			$this->_pTable = $table;
			$this->_sTable = $this->_singularize($this->_pTable);
		}
		else
		{
			// We will use current classname as table name.
			// We need to pluralize it for the real table name.
			$this->_sTable = strtolower(get_class($this));
			$this->_pTable = $this->_pluralize($this->_sTable);
		}
		$this->_table = &$this->_pTable;

		$this->foreignName = $this->_sTable; // CFR: default foreign name (singular)

		if ($db) {
			$this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
		} else
			$this->_dbat = sizeof($_ADODB_ACTIVE_DBS)-1;
162
163


164
		if ($this->_dbat < 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
165

166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
		$this->_tableat = $this->_table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future

		// CFR: Just added this option because UpdateActiveTable() can refresh its information
		// but there was no way to ask it to do that.
		$forceUpdate = (isset($options['refresh']) && true === $options['refresh']);
		$this->UpdateActiveTable($pkeyarr, $forceUpdate);
		if(isset($options['new']) && true === $options['new'])
		{
			$table =& $this->TableInfo();
			unset($table->_hasMany);
			unset($table->_belongsTo);
			$table->_hasMany = array();
			$table->_belongsTo = array();
		}
	}
181

182
183
	function __wakeup()
	{
184
185
  		$class = get_class($this);
  		new $class;
186
	}
187

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
	// CFR: Constants found in Rails
	static $IrregularP = array(
		'PERSON'    => 'people',
		'MAN'       => 'men',
		'WOMAN'     => 'women',
		'CHILD'     => 'children',
		'COW'       => 'kine',
	);

	static $IrregularS = array(
		'PEOPLE'    => 'PERSON',
		'MEN'       => 'man',
		'WOMEN'     => 'woman',
		'CHILDREN'  => 'child',
		'KINE'      => 'cow',
	);

	static $WeIsI = array(
		'EQUIPMENT' => true,
		'INFORMATION'   => true,
		'RICE'      => true,
		'MONEY'     => true,
		'SPECIES'   => true,
		'SERIES'    => true,
		'FISH'      => true,
		'SHEEP'     => true,
	);

	function _pluralize($table)
	{
		if (!ADODB_Active_Record::$_changeNames) return $table;

		$ut = strtoupper($table);
		if(isset(self::$WeIsI[$ut]))
		{
			return $table;
		}
		if(isset(self::$IrregularP[$ut]))
		{
			return self::$IrregularP[$ut];
		}
		$len = strlen($table);
		$lastc = $ut[$len-1];
		$lastc2 = substr($ut,$len-2);
		switch ($lastc) {
		case 'S':
234
			return $table.'es';
235
236
		case 'Y':
			return substr($table,0,$len-1).'ies';
237
		case 'X':
238
			return $table.'es';
239
		case 'H':
240
241
242
243
244
245
			if ($lastc2 == 'CH' || $lastc2 == 'SH')
				return $table.'es';
		default:
			return $table.'s';
		}
	}
246

247
248
249
250
	// CFR Lamest singular inflector ever - @todo Make it real!
	// Note: There is an assumption here...and it is that the argument's length >= 4
	function _singularize($table)
	{
251

252
		if (!ADODB_Active_Record::$_changeNames) return $table;
253

254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
		$ut = strtoupper($table);
		if(isset(self::$WeIsI[$ut]))
		{
			return $table;
		}
		if(isset(self::$IrregularS[$ut]))
		{
			return self::$IrregularS[$ut];
		}
		$len = strlen($table);
		if($ut[$len-1] != 'S')
			return $table; // I know...forget oxen
		if($ut[$len-2] != 'E')
			return substr($table, 0, $len-1);
		switch($ut[$len-3])
		{
			case 'S':
			case 'X':
				return substr($table, 0, $len-2);
			case 'I':
				return substr($table, 0, $len-3) . 'y';
			case 'H';
				if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
					return substr($table, 0, $len-2);
			default:
				return substr($table, 0, $len-1); // ?
		}
	}

	/*
	 * ar->foreignName will contain the name of the tables associated with this table because
	 * these other tables' rows may also be referenced by this table using theirname_id or the provided
	 * foreign keys (this index name is stored in ar->foreignKey)
	 *
	 * this-table.id = other-table-#1.this-table_id
	 *               = other-table-#2.this-table_id
	 */
	function hasMany($foreignRef,$foreignKey=false)
	{
		$ar = new ADODB_Active_Record($foreignRef);
		$ar->foreignName = $foreignRef;
		$ar->UpdateActiveTable();
		$ar->foreignKey = ($foreignKey) ? $foreignKey : strtolower(get_class($this)) . self::$_foreignSuffix;

		$table =& $this->TableInfo();
		if(!isset($table->_hasMany[$foreignRef]))
		{
			$table->_hasMany[$foreignRef] = $ar;
			$table->updateColsCount();
		}
# @todo Can I make this guy be lazy?
		$this->$foreignRef = $table->_hasMany[$foreignRef]; // WATCHME Removed assignment by ref. to please __get()
	}

	/**
	 * ar->foreignName will contain the name of the tables associated with this table because
	 * this table's rows may also be referenced by those tables using thistable_id or the provided
	 * foreign keys (this index name is stored in ar->foreignKey)
	 *
	 * this-table.other-table_id = other-table.id
	 */
	function belongsTo($foreignRef,$foreignKey=false)
	{
		global $inflector;

		$ar = new ADODB_Active_Record($this->_pluralize($foreignRef));
		$ar->foreignName = $foreignRef;
		$ar->UpdateActiveTable();
		$ar->foreignKey = ($foreignKey) ? $foreignKey : $ar->foreignName . self::$_foreignSuffix;
323

324
325
326
327
328
329
330
331
332
333
334
		$table =& $this->TableInfo();
		if(!isset($table->_belongsTo[$foreignRef]))
		{
			$table->_belongsTo[$foreignRef] = $ar;
			$table->updateColsCount();
		}
		$this->$foreignRef = $table->_belongsTo[$foreignRef];
	}

	/**
	 * __get Access properties - used for lazy loading
335
336
	 *
	 * @param mixed $name
337
338
339
340
341
342
343
344
345
346
347
348
349
350
	 * @access protected
	 * @return void
	 */
	function __get($name)
	{
		return $this->LoadRelations($name, '', -1. -1);
	}

	function LoadRelations($name, $whereOrderBy, $offset=-1, $limit=-1)
	{
		$extras = array();
		if($offset >= 0) $extras['offset'] = $offset;
		if($limit >= 0) $extras['limit'] = $limit;
		$table =& $this->TableInfo();
351
352

		if (strlen($whereOrderBy))
353
354
355
			if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
				if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
					$whereOrderBy = 'AND '.$whereOrderBy;
356

357
358
359
360
361
362
363
364
365
366
367
368
		if(!empty($table->_belongsTo[$name]))
		{
			$obj = $table->_belongsTo[$name];
			$columnName = $obj->foreignKey;
			if(empty($this->$columnName))
				$this->$name = null;
			else
			{
				if(($k = reset($obj->TableInfo()->keys)))
					$belongsToId = $k;
				else
					$belongsToId = 'id';
369

370
371
372
373
374
375
376
377
378
379
380
381
382
				$arrayOfOne =
					$obj->Find(
						$belongsToId.'='.$this->$columnName.' '.$whereOrderBy, false, false, $extras);
				$this->$name = $arrayOfOne[0];
			}
			return $this->$name;
		}
		if(!empty($table->_hasMany[$name]))
		{
			$obj = $table->_hasMany[$name];
			if(($k = reset($table->keys)))
				$hasManyId   = $k;
			else
383
				$hasManyId   = 'id';
384
385
386
387
388
389
390
391

			$this->$name =
				$obj->Find(
					$obj->foreignKey.'='.$this->$hasManyId.' '.$whereOrderBy, false, false, $extras);
			return $this->$name;
		}
	}
	//////////////////////////////////
392

393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
	// update metadata
	function UpdateActiveTable($pkeys=false,$forceUpdate=false)
	{
	global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS , $ADODB_CACHE_DIR, $ADODB_ACTIVE_CACHESECS;
	global $ADODB_ACTIVE_DEFVALS, $ADODB_FETCH_MODE;

		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];

		$table = $this->_table;
		$tables = $activedb->tables;
		$tableat = $this->_tableat;
		if (!$forceUpdate && !empty($tables[$tableat])) {

			$tobj = $tables[$tableat];
			foreach($tobj->flds as $name => $fld) {
408
			if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
409
410
411
412
413
414
				$this->$name = $fld->default_value;
			else
				$this->$name = null;
			}
			return;
		}
415

416
417
418
419
420
421
422
		$db = $activedb->db;
		$fname = $ADODB_CACHE_DIR . '/adodb_' . $db->databaseType . '_active_'. $table . '.cache';
		if (!$forceUpdate && $ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR && file_exists($fname)) {
			$fp = fopen($fname,'r');
			@flock($fp, LOCK_SH);
			$acttab = unserialize(fread($fp,100000));
			fclose($fp);
423
			if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) {
424
425
426
				// abs(rand()) randomizes deletion, reducing contention to delete/refresh file
				// ideally, you should cache at least 32 secs
				$activedb->tables[$table] = $acttab;
427

428
				//if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
429
			  	return;
430
431
432
433
434
435
			} else if ($db->debug) {
				ADOConnection::outp("Refreshing cached active record file: $fname");
			}
		}
		$activetab = new ADODB_Active_Table();
		$activetab->name = $table;
436

437
438
439
		$save = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
		if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
440

441
		$cols = $db->MetaColumns($table);
442

443
444
		if (isset($savem)) $db->SetFetchMode($savem);
		$ADODB_FETCH_MODE = $save;
445

446
		if (!$cols) {
447
			$this->Error("Invalid table name: $table",'UpdateActiveTable');
448
449
450
451
452
453
454
455
456
			return false;
		}
		$fld = reset($cols);
		if (!$pkeys) {
			if (isset($fld->primary_key)) {
				$pkeys = array();
				foreach($cols as $name => $fld) {
					if (!empty($fld->primary_key)) $pkeys[] = $name;
				}
457
			} else
458
459
460
461
462
463
				$pkeys = $this->GetPrimaryKeys($db, $table);
		}
		if (empty($pkeys)) {
			$this->Error("No primary key found for table $table",'UpdateActiveTable');
			return false;
		}
464

465
466
		$attr = array();
		$keys = array();
467

468
469
470
471
472
473
474
475
476
477
478
479
480
481
		switch($ADODB_ASSOC_CASE) {
		case 0:
			foreach($cols as $name => $fldobj) {
				$name = strtolower($name);
                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
                    $this->$name = $fldobj->default_value;
                else
					$this->$name = null;
				$attr[$name] = $fldobj;
			}
			foreach($pkeys as $k => $name) {
				$keys[strtolower($name)] = strtolower($name);
			}
			break;
482
483

		case 1:
484
485
			foreach($cols as $name => $fldobj) {
				$name = strtoupper($name);
486

487
488
489
490
491
492
                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
                    $this->$name = $fldobj->default_value;
                else
					$this->$name = null;
				$attr[$name] = $fldobj;
			}
493

494
495
496
497
498
499
500
			foreach($pkeys as $k => $name) {
				$keys[strtoupper($name)] = strtoupper($name);
			}
			break;
		default:
			foreach($cols as $name => $fldobj) {
				$name = ($fldobj->name);
501

502
503
504
505
506
507
508
509
510
511
512
                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
                    $this->$name = $fldobj->default_value;
                else
					$this->$name = null;
				$attr[$name] = $fldobj;
			}
			foreach($pkeys as $k => $name) {
				$keys[$name] = $cols[$name]->name;
			}
			break;
		}
513

514
515
516
517
518
519
520
521
522
523
524
525
		$activetab->keys = $keys;
		$activetab->flds = $attr;
		$activetab->updateColsCount();

		if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
			$activetab->_created = time();
			$s = serialize($activetab);
			if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
			adodb_write_file($fname,$s);
		}
		if (isset($activedb->tables[$table])) {
			$oldtab = $activedb->tables[$table];
526

527
528
529
530
531
			if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
			if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
		}
		$activedb->tables[$table] = $activetab;
	}
532

533
534
535
536
	function GetPrimaryKeys(&$db, $table)
	{
		return $db->MetaPrimaryKeys($table);
	}
537
538

	// error handler for both PHP4+5.
539
540
541
	function Error($err,$fn)
	{
	global $_ADODB_ACTIVE_DBS;
542

543
544
		$fn = get_class($this).'::'.$fn;
		$this->_lasterr = $fn.': '.$err;
545

546
547
548
549
550
		if ($this->_dbat < 0) $db = false;
		else {
			$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
			$db = $activedb->db;
		}
551
552

		if (function_exists('adodb_throw')) {
553
554
555
556
			if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
			else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
		} else
			if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
557

558
	}
559

560
561
562
563
564
565
	// return last error message
	function ErrorMsg()
	{
		if (!function_exists('adodb_throw')) {
			if ($this->_dbat < 0) $db = false;
			else $db = $this->DB();
566

567
568
569
570
571
			// last error could be database error too
			if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
		}
		return $this->_lasterr;
	}
572
573

	function ErrorNo()
574
575
576
	{
		if ($this->_dbat < 0) return -9999; // no database connection...
		$db = $this->DB();
577

578
579
580
581
582
583
584
585
		return (int) $db->ErrorNo();
	}


	// retrieve ADOConnection from _ADODB_Active_DBs
	function DB()
	{
	global $_ADODB_ACTIVE_DBS;
586

587
588
589
590
591
592
593
594
595
		if ($this->_dbat < 0) {
			$false = false;
			$this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
			return $false;
		}
		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
		$db = $activedb->db;
		return $db;
	}
596

597
598
599
600
	// retrieve ADODB_Active_Table
	function &TableInfo()
	{
	global $_ADODB_ACTIVE_DBS;
601

602
603
604
605
		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
		$table = $activedb->tables[$this->_tableat];
		return $table;
	}
606
607


608
609
610
611
612
613
614
615
616
617
	// I have an ON INSERT trigger on a table that sets other columns in the table.
	// So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
	function Reload()
	{
		$db =& $this->DB(); if (!$db) return false;
		$table =& $this->TableInfo();
		$where = $this->GenWhere($db, $table);
		return($this->Load($where));
	}

618

619
620
621
622
	// set a numeric array (using natural table field ordering) as object properties
	function Set(&$row)
	{
	global $ACTIVE_RECORD_SAFETY;
623

624
		$db = $this->DB();
625

626
		if (!$row) {
627
			$this->_saved = false;
628
629
			return false;
		}
630

631
		$this->_saved = true;
632

633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
		$table = $this->TableInfo();
		$sizeofFlds = sizeof($table->flds);
		$sizeofRow  = sizeof($row);
		if ($ACTIVE_RECORD_SAFETY && $table->_colsCount != $sizeofRow && $sizeofFlds != $sizeofRow) {
            # <AP>
            $bad_size = TRUE;
	if($sizeofRow == 2 * $table->_colsCount || $sizeofRow == 2 * $sizeofFlds) {
                // Only keep string keys
                $keys = array_filter(array_keys($row), 'is_string');
                if (sizeof($keys) == sizeof($table->flds))
                    $bad_size = FALSE;
            }
            if ($bad_size) {
			$this->Error("Table structure of $this->_table has changed","Load");
			return false;
		}
            # </AP>
		}
        else
		$keys = array_keys($row);
        # <AP>
        reset($keys);
        $this->_original = array();
		foreach($table->flds as $name=>$fld)
		{
            $value = $row[current($keys)];
			$this->$name = $value;
            $this->_original[] = $value;
            if(!next($keys)) break;
		}
		$table =& $this->TableInfo();
		foreach($table->_belongsTo as $foreignTable)
		{
			$ft = $foreignTable->TableInfo();
			$propertyName = $ft->name;
			foreach($ft->flds as $name=>$fld)
			{
				$value = $row[current($keys)];
				$foreignTable->$name = $value;
				$foreignTable->_original[] = $value;
				if(!next($keys)) break;
			}
		}
		foreach($table->_hasMany as $foreignTable)
		{
			$ft = $foreignTable->TableInfo();
			foreach($ft->flds as $name=>$fld)
			{
				$value = $row[current($keys)];
				$foreignTable->$name = $value;
				$foreignTable->_original[] = $value;
				if(!next($keys)) break;
			}
		}
        # </AP>
		return true;
	}
690

691
692
693
694
695
696
697
	// get last inserted id for INSERT
	function LastInsertID(&$db,$fieldname)
	{
		if ($db->hasInsertID)
			$val = $db->Insert_ID($this->_table,$fieldname);
		else
			$val = false;
698

699
700
701
702
703
704
		if (is_null($val) || $val === false) {
			// this might not work reliably in multi-user environment
			return $db->GetOne("select max(".$fieldname.") from ".$this->_table);
		}
		return $val;
	}
705

706
707
708
709
710
711
712
	// quote data in where clause
	function doquote(&$db, $val,$t)
	{
		switch($t) {
		case 'D':
		case 'T':
			if (empty($val)) return 'null';
713

714
715
716
		case 'C':
		case 'X':
			if (is_null($val)) return 'null';
717
718
719

			if (strlen($val)>0 &&
				(strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
720
721
722
723
724
725
726
727
				return $db->qstr($val);
				break;
			}
		default:
			return $val;
			break;
		}
	}
728

729
730
731
732
733
	// generate where clause for an UPDATE/SELECT
	function GenWhere(&$db, &$table)
	{
		$keys = $table->keys;
		$parr = array();
734

735
736
737
738
739
740
741
742
		foreach($keys as $k) {
			$f = $table->flds[$k];
			if ($f) {
				$parr[] = $k.' = '.$this->doquote($db,$this->$k,$db->MetaType($f->type));
			}
		}
		return implode(' and ', $parr);
	}
743
744


745
	//------------------------------------------------------------ Public functions below
746

747
748
749
750
	function Load($where=null,$bindarr=false)
	{
		$db = $this->DB(); if (!$db) return false;
		$this->_where = $where;
751

752
753
754
755
756
757
758
759
		$save = $db->SetFetchMode(ADODB_FETCH_NUM);
		$qry = "select * from ".$this->_table;
		$table =& $this->TableInfo();

		if(($k = reset($table->keys)))
			$hasManyId   = $k;
		else
			$hasManyId   = 'id';
760

761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
		foreach($table->_belongsTo as $foreignTable)
		{
			if(($k = reset($foreignTable->TableInfo()->keys)))
			{
				$belongsToId = $k;
			}
			else
			{
				$belongsToId = 'id';
			}
			$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
				$this->_table.'.'.$foreignTable->foreignKey.'='.
				$foreignTable->_table.'.'.$belongsToId;
		}
		foreach($table->_hasMany as $foreignTable)
		{
			$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
				$this->_table.'.'.$hasManyId.'='.
				$foreignTable->_table.'.'.$foreignTable->foreignKey;
		}
		if($where)
			$qry .= ' WHERE '.$where;
783

784
785
786
787
788
789
790
791
792
		// Simple case: no relations. Load row and return.
		if((count($table->_hasMany) + count($table->_belongsTo)) < 1)
		{
			$row = $db->GetRow($qry,$bindarr);
			if(!$row)
				return false;
			$db->SetFetchMode($save);
			return $this->Set($row);
		}
793

794
795
796
797
798
799
800
801
802
		// More complex case when relations have to be collated
		$rows = $db->GetAll($qry,$bindarr);
		if(!$rows)
			return false;
		$db->SetFetchMode($save);
		if(count($rows) < 1)
			return false;
		$class = get_class($this);
		$isFirstRow = true;
803

804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
		if(($k = reset($this->TableInfo()->keys)))
			$myId   = $k;
		else
			$myId   = 'id';
		$index = 0; $found = false;
		/** @todo Improve by storing once and for all in table metadata */
		/** @todo Also re-use info for hasManyId */
		foreach($this->TableInfo()->flds as $fld)
		{
			if($fld->name == $myId)
			{
				$found = true;
				break;
			}
			$index++;
		}
		if(!$found)
			$this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
822

823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
		foreach($rows as $row)
		{
			$rowId = intval($row[$index]);
			if($rowId > 0)
			{
				if($isFirstRow)
				{
					$isFirstRow = false;
					if(!$this->Set($row))
						return false;
				}
				$obj = new $class($table,false,$db);
				$obj->Set($row);
				// TODO Copy/paste code below: bad!
				if(count($table->_hasMany) > 0)
				{
					foreach($table->_hasMany as $foreignTable)
					{
						$foreignName = $foreignTable->foreignName;
						if(!empty($obj->$foreignName))
						{
							if(!is_array($this->$foreignName))
							{
								$foreignObj = $this->$foreignName;
								$this->$foreignName = array(clone($foreignObj));
							}
							else
							{
								$foreignObj = $obj->$foreignName;
								array_push($this->$foreignName, clone($foreignObj));
							}
						}
					}
				}
				if(count($table->_belongsTo) > 0)
				{
					foreach($table->_belongsTo as $foreignTable)
					{
						$foreignName = $foreignTable->foreignName;
						if(!empty($obj->$foreignName))
						{
							if(!is_array($this->$foreignName))
							{
								$foreignObj = $this->$foreignName;
								$this->$foreignName = array(clone($foreignObj));
							}
							else
							{
								$foreignObj = $obj->$foreignName;
								array_push($this->$foreignName, clone($foreignObj));
							}
						}
					}
876
				}
877
878
879
880
			}
		}
		return true;
	}
881

882
883
884
885
886
	// false on error
	function Save()
	{
		if ($this->_saved) $ok = $this->Update();
		else $ok = $this->Insert();
887

888
889
		return $ok;
	}
890

891
892
893
894
895
896
897
898
899
900
901
902
903
	// CFR: Sometimes we may wish to consider that an object is not to be replaced but inserted.
	// Sample use case: an 'undo' command object (after a delete())
	function Dirty()
	{
		$this->_saved = false;
	}

	// false on error
	function Insert()
	{
		$db = $this->DB(); if (!$db) return false;
		$cnt = 0;
		$table = $this->TableInfo();
904

905
906
907
908
909
910
911
912
913
914
915
916
917
		$valarr = array();
		$names = array();
		$valstr = array();

		foreach($table->flds as $name=>$fld) {
			$val = $this->$name;
			if(!is_null($val) || !array_key_exists($name, $table->keys)) {
				$valarr[] = $val;
				$names[] = $name;
				$valstr[] = $db->Param($cnt);
				$cnt += 1;
			}
		}
918

919
920
921
922
923
924
925
926
927
928
		if (empty($names)){
			foreach($table->flds as $name=>$fld) {
				$valarr[] = null;
				$names[] = $name;
				$valstr[] = $db->Param($cnt);
				$cnt += 1;
			}
		}
		$sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
		$ok = $db->Execute($sql,$valarr);
929

930
931
932
933
934
935
936
937
938
939
940
941
942
943
		if ($ok) {
			$this->_saved = true;
			$autoinc = false;
			foreach($table->keys as $k) {
				if (is_null($this->$k)) {
					$autoinc = true;
					break;
				}
			}
			if ($autoinc && sizeof($table->keys) == 1) {
				$k = reset($table->keys);
				$this->$k = $this->LastInsertID($db,$k);
			}
		}
944

945
946
947
		$this->_original = $valarr;
		return !empty($ok);
	}
948

949
950
951
952
	function Delete()
	{
		$db = $this->DB(); if (!$db) return false;
		$table = $this->TableInfo();
953

954
955
956
		$where = $this->GenWhere($db,$table);
		$sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
		$ok = $db->Execute($sql);
957

958
959
		return $ok ? true : false;
	}
960

961
962
963
964
965
966
967
968
969
	// returns an array of active record objects
	function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
	{
		$db = $this->DB(); if (!$db || empty($this->_table)) return false;
		$table =& $this->TableInfo();
		$arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
			array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
		return $arr;
	}
970

971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
	// CFR: In introduced this method to ensure that inner workings are not disturbed by
	// subclasses...for instance when GetActiveRecordsClass invokes Find()
	// Why am I not invoking parent::Find?
	// Shockingly because I want to preserve PHP4 compatibility.
	function packageFind($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
	{
		$db = $this->DB(); if (!$db || empty($this->_table)) return false;
		$table =& $this->TableInfo();
		$arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
			array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
		return $arr;
	}

	// returns 0 on error, 1 on update, 2 on insert
	function Replace()
	{
	global $ADODB_ASSOC_CASE;
988

989
990
		$db = $this->DB(); if (!$db) return false;
		$table = $this->TableInfo();
991

992
		$pkey = $table->keys;
993

994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
		foreach($table->flds as $name=>$fld) {
			$val = $this->$name;
			/*
			if (is_null($val)) {
				if (isset($fld->not_null) && $fld->not_null) {
					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
					else {
						$this->Error("Cannot update null into $name","Replace");
						return false;
					}
				}
			}*/
			if (is_null($val) && !empty($fld->auto_increment)) {
1007
            	continue;
1008
1009
1010
1011
1012
            }
			$t = $db->MetaType($fld->type);
			$arr[$name] = $this->doquote($db,$val,$t);
			$valarr[] = $val;
		}
1013

1014
		if (!is_array($pkey)) $pkey = array($pkey);
1015
1016
1017


		if ($ADODB_ASSOC_CASE == 0)
1018
1019
			foreach($pkey as $k => $v)
				$pkey[$k] = strtolower($v);
1020
		elseif ($ADODB_ASSOC_CASE == 1)
1021
1022
			foreach($pkey as $k => $v)
				$pkey[$k] = strtoupper($v);
1023

1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
		$ok = $db->Replace($this->_table,$arr,$pkey);
		if ($ok) {
			$this->_saved = true; // 1= update 2=insert
			if ($ok == 2) {
				$autoinc = false;
				foreach($table->keys as $k) {
					if (is_null($this->$k)) {
						$autoinc = true;
						break;
					}
				}
				if ($autoinc && sizeof($table->keys) == 1) {
					$k = reset($table->keys);
					$this->$k = $this->LastInsertID($db,$k);
				}
			}
1040

1041
			$this->_original = $valarr;
1042
		}
1043
1044
1045
1046
1047
1048
1049
1050
		return $ok;
	}

	// returns 0 on error, 1 on update, -1 if no change in data (no update)
	function Update()
	{
		$db = $this->DB(); if (!$db) return false;
		$table = $this->TableInfo();
1051

1052
		$where = $this->GenWhere($db, $table);
1053

1054
1055
1056
1057
		if (!$where) {
			$this->error("Where missing for table $table", "Update");
			return false;
		}
1058
		$valarr = array();
1059
1060
1061
1062
1063
1064
1065
1066
		$neworig = array();
		$pairs = array();
		$i = -1;
		$cnt = 0;
		foreach($table->flds as $name=>$fld) {
			$i += 1;
			$val = $this->$name;
			$neworig[] = $val;
1067

1068
1069
1070
			if (isset($table->keys[$name])) {
				continue;
			}
1071

1072
1073
1074
1075
1076
1077
1078
1079
1080
			if (is_null($val)) {
				if (isset($fld->not_null) && $fld->not_null) {
					if (isset($fld->default_value) && strlen($fld->default_value)) continue;
					else {
						$this->Error("Cannot set field $name to NULL","Update");
						return false;
					}
				}
			}
1081

1082
1083
			if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
				continue;
1084
			}
1085
1086
1087
1088
			$valarr[] = $val;
			$pairs[] = $name.'='.$db->Param($cnt);
			$cnt += 1;
		}
1089
1090


1091
1092
1093
1094
1095
1096
1097
1098
1099
		if (!$cnt) return -1;
		$sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
		$ok = $db->Execute($sql,$valarr);
		if ($ok) {
			$this->_original = $neworig;
			return 1;
		}
		return 0;
	}
1100

1101
1102
1103
1104
1105
1106
	function GetAttributeNames()
	{
		$table = $this->TableInfo();
		if (!$table) return false;
		return array_keys($table->flds);
	}
1107

1108
1109
1110
1111
1112
1113
};

function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bindarr, $primkeyArr,
			$extra, $relations)
{
	global $_ADODB_ACTIVE_DBS;
1114

1115
		if (empty($extra['loading'])) $extra['loading'] = ADODB_LAZY_AR;
1116

1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
		$save = $db->SetFetchMode(ADODB_FETCH_NUM);
		$table = &$tableObj->_table;
		$tableInfo =& $tableObj->TableInfo();
		if(($k = reset($tableInfo->keys)))
			$myId   = $k;
		else
			$myId   = 'id';
		$index = 0; $found = false;
		/** @todo Improve by storing once and for all in table metadata */
		/** @todo Also re-use info for hasManyId */
		foreach($tableInfo->flds as $fld)
		{
			if($fld->name == $myId)
			{
				$found = true;
				break;
			}
			$index++;
		}
		if(!$found)
			$db->outp_throw("Unable to locate key $myId for $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
1138

1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
		$qry = "select * from ".$table;
		if(ADODB_JOIN_AR == $extra['loading'])
		{
			if(!empty($relations['belongsTo']))
			{
				foreach($relations['belongsTo'] as $foreignTable)
				{
					if(($k = reset($foreignTable->TableInfo()->keys)))
					{
						$belongsToId = $k;
					}
					else
					{
						$belongsToId = 'id';
					}

					$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
						$table.'.'.$foreignTable->foreignKey.'='.
						$foreignTable->_table.'.'.$belongsToId;
				}
			}
			if(!empty($relations['hasMany']))
			{
				if(empty($relations['foreignName']))
					$db->outp_throw("Missing foreignName is relation specification in GetActiveRecordsClass()",'GetActiveRecordsClass');
				if(($k = reset($tableInfo->keys)))
					$hasManyId   = $k;
				else
					$hasManyId   = 'id';

				foreach($relations['hasMany'] as $foreignTable)
				{
					$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
						$table.'.'.$hasManyId.'='.
						$foreignTable->_table.'.'.$foreignTable->foreignKey;
				}
			}
		}
		if (!empty($whereOrderBy))
			$qry .= ' WHERE '.$whereOrderBy;
		if(isset($extra['limit']))
		{
			$rows = false;
			if(isset($extra['offset'])) {
				$rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset']);
			} else {
				$rs = $db->SelectLimit($qry, $extra['limit']);
			}
			if ($rs) {
				while (!$rs->EOF) {
					$rows[] = $rs->fields;
					$rs->MoveNext();
				}
			}
		} else
			$rows = $db->GetAll($qry,$bindarr);
1195

1196
		$db->SetFetchMode($save);
1197

1198
		$false = false;
1199
1200

		if ($rows === false) {
1201
1202
			return $false;
		}
1203
1204


1205
1206
		if (!isset($_ADODB_ACTIVE_DBS)) {
			include(ADODB_DIR.'/adodb-active-record.inc.php');
1207
		}
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
		if (!class_exists($class)) {
			$db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
			return $false;
		}
		$uniqArr = array(); // CFR Keep track of records for relations
		$arr = array();
		// arrRef will be the structure that knows about our objects.
		// It is an associative array.
		// We will, however, return arr, preserving regular 0.. order so that
		// obj[0] can be used by app developpers.
		$arrRef = array();
		$bTos = array(); // Will store belongTo's indices if any
		foreach($rows as $row) {
1221

1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
			$obj = new $class($table,$primkeyArr,$db);
			if ($obj->ErrorNo()){
				$db->_errorMsg = $obj->ErrorMsg();
				return $false;
			}
			$obj->Set($row);
			// CFR: FIXME: Insane assumption here:
			// If the first column returned is an integer, then it's a 'id' field
			// And to make things a bit worse, I use intval() rather than is_int() because, in fact,
			// $row[0] is not an integer.
			//
			// So, what does this whole block do?
			// When relationships are found, we perform JOINs. This is fast. But not accurate:
			// instead of returning n objects with their n' associated cousins,
			// we get n*n' objects. This code fixes this.
			// Note: to-many relationships mess around with the 'limit' parameter
			$rowId = intval($row[$index]);

			if(ADODB_WORK_AR == $extra['loading'])
			{
				$arrRef[$rowId] = $obj;
				$arr[] = &$arrRef[$rowId];
				if(!isset($indices))
					$indices = $rowId;
				else
					$indices .= ','.$rowId;
				if(!empty($relations['belongsTo']))
				{
					foreach($relations['belongsTo'] as $foreignTable)
					{
						$foreignTableRef = $foreignTable->foreignKey;
						// First array: list of foreign ids we are looking for
						if(empty($bTos[$foreignTableRef]))
							$bTos[$foreignTableRef] = array();
						// Second array: list of ids found
						if(empty($obj->$foreignTableRef))
							continue;
						if(empty($bTos[$foreignTableRef][$obj->$foreignTableRef]))
							$bTos[$foreignTableRef][$obj->$foreignTableRef] = array();
						$bTos[$foreignTableRef][$obj->$foreignTableRef][] = $obj;
					}
				}
				continue;
			}

			if($rowId>0)
			{
				if(ADODB_JOIN_AR == $extra['loading'])
				{
1271
					$isNewObj = !isset($uniqArr['_'.$row[0]]);
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
					if($isNewObj)
						$uniqArr['_'.$row[0]] = $obj;

					// TODO Copy/paste code below: bad!
					if(!empty($relations['hasMany']))
					{
						foreach($relations['hasMany'] as $foreignTable)
						{
							$foreignName = $foreignTable->foreignName;
							if(!empty($obj->$foreignName))
							{
								$masterObj = &$uniqArr['_'.$row[0]];
								// Assumption: this property exists in every object since they are instances of the same class
								if(!is_array($masterObj->$foreignName))
								{
									// Pluck!
									$foreignObj = $masterObj->$foreignName;
									$masterObj->$foreignName = array(clone($foreignObj));
								}
								else
								{
									// Pluck pluck!
									$foreignObj = $obj->$foreignName;
									array_push($masterObj->$foreignName, clone($foreignObj));
								}
							}
						}
					}
					if(!empty($relations['belongsTo']))
					{
						foreach($relations['belongsTo'] as $foreignTable)
						{
							$foreignName = $foreignTable->foreignName;
							if(!empty($obj->$foreignName))
							{
								$masterObj = &$uniqArr['_'.$row[0]];
								// Assumption: this property exists in every object since they are instances of the same class
								if(!is_array($masterObj->$foreignName))
								{
									// Pluck!
									$foreignObj = $masterObj->$foreignName;
									$masterObj->$foreignName = array(clone($foreignObj));
								}
								else
								{
									// Pluck pluck!
									$foreignObj = $obj->$foreignName;
									array_push($masterObj->$foreignName, clone($foreignObj));
								}
							}
						}
					}
					if(!$isNewObj)
1325
						unset($obj); // We do not need this object itself anymore and do not want it re-added to the main array
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
				}
				else if(ADODB_LAZY_AR == $extra['loading'])
				{
					// Lazy loading: we need to give AdoDb a hint that we have not really loaded
					// anything, all the while keeping enough information on what we wish to load.
					// Let's do this by keeping the relevant info in our relationship arrays
					// but get rid of the actual properties.
					// We will then use PHP's __get to load these properties on-demand.
					if(!empty($relations['hasMany']))
					{
						foreach($relations['hasMany'] as $foreignTable)
						{
							$foreignName = $foreignTable->foreignName;
							if(!empty($obj->$foreignName))
							{
								unset($obj->$foreignName);
							}
						}
					}
					if(!empty($relations['belongsTo']))
					{
						foreach($relations['belongsTo'] as $foreignTable)
						{
							$foreignName = $foreignTable->foreignName;
							if(!empty($obj->$foreignName))
							{
								unset($obj->$foreignName);
							}
						}
					}
				}
			}

			if(isset($obj))
				$arr[] = $obj;
		}

		if(ADODB_WORK_AR == $extra['loading'])
		{
			// The best of both worlds?
			// Here, the number of queries is constant: 1 + n*relationship.
			// The second query will allow us to perform a good join
			// while preserving LIMIT etc.
			if(!empty($relations['hasMany']))
			{
				foreach($relations['hasMany'] as $foreignTable)
				{
					$foreignName = $foreignTable->foreignName;
					$className = ucfirst($foreignTable->_singularize($foreignName));
					$obj = new $className();
					$dbClassRef = $foreignTable->foreignKey;
					$objs = $obj->packageFind($dbClassRef.' IN ('.$indices.')');
					foreach($objs as $obj)
					{
						if(!is_array($arrRef[$obj->$dbClassRef]->$foreignName))
							$arrRef[$obj->$dbClassRef]->$foreignName = array();
						array_push($arrRef[$obj->$dbClassRef]->$foreignName, $obj);
					}
				}
1385

1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
			}
			if(!empty($relations['belongsTo']))
			{
				foreach($relations['belongsTo'] as $foreignTable)
				{
					$foreignTableRef = $foreignTable->foreignKey;
					if(empty($bTos[$foreignTableRef]))
						continue;
					if(($k = reset($foreignTable->TableInfo()->keys)))
					{
						$belongsToId = $k;
					}
					else
					{
						$belongsToId = 'id';
1401
					}
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
					$origObjsArr = $bTos[$foreignTableRef];
					$bTosString = implode(',', array_keys($bTos[$foreignTableRef]));
					$foreignName = $foreignTable->foreignName;
					$className = ucfirst($foreignTable->_singularize($foreignName));
					$obj = new $className();
					$objs = $obj->packageFind($belongsToId.' IN ('.$bTosString.')');
					foreach($objs as $obj)
					{
						foreach($origObjsArr[$obj->$belongsToId] as $idx=>$origObj)
						{
							$origObj->$foreignName = $obj;
						}
					}
				}
			}
		}

		return $arr;
}