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

4
@version   v5.20.14  06-Jan-2019
5
6
@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
@copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
7
  Latest version is available at http://adodb.org/
8
9
10

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

13
  Active Record implementation. Superset of Zend Framework's.
14
15
16

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

17
  Version 0.9
18
19

  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
20
  	for info on Ruby on Rails Active Record implementation
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
66
67
*/


	// 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;
68

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

81
82
83
		$obj = new ADODB_Active_DB();
		$obj->db = $db;
		$obj->tables = array();
84

85
		$_ADODB_ACTIVE_DBS[] = $obj;
86

87
88
89
90
91
92
		return sizeof($_ADODB_ACTIVE_DBS)-1;
}


class ADODB_Active_Record {
	static $_changeNames = true; // dynamically pluralize table names
93
	static $_foreignSuffix = '_id'; //
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;
109
110
111
		if (isset($bool)) {
			$ADODB_ACTIVE_DEFVALS = $bool;
		}
112
113
114
115
		return $ADODB_ACTIVE_DEFVALS;
	}

	// should be static
116
	static function SetDatabaseAdapter(&$db)
117
118
119
	{
		return ADODB_SetDatabaseAdapter($db);
	}
120
121


122
123
124
125
126
	public function __set($name, $value)
	{
		$name = str_replace(' ', '_', $name);
		$this->$name = $value;
	}
127

128
129
130
131
132
133
134
135
136
137
138
139
140
	// 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;
141

142
143
144
145
		if ($db == false && is_object($pkeyarr)) {
			$db = $pkeyarr;
			$pkeyarr = false;
		}
146

147
		if($table) {
148
149
150
151
152
			// table argument exists. It is expected to be
			// already plural form.
			$this->_pTable = $table;
			$this->_sTable = $this->_singularize($this->_pTable);
		}
153
		else {
154
155
156
157
158
159
160
161
162
163
164
165
166
			// 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;
167
168


169
170
171
172
173
174
		if ($this->_dbat < 0) {
			$this->Error(
				"No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",
				'ADODB_Active_Record::__constructor'
			);
		}
175

176
177
178
179
180
181
		$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);
182
		if(isset($options['new']) && true === $options['new']) {
183
184
185
186
187
188
189
			$table =& $this->TableInfo();
			unset($table->_hasMany);
			unset($table->_belongsTo);
			$table->_hasMany = array();
			$table->_belongsTo = array();
		}
	}
190

191
192
	function __wakeup()
	{
193
194
		$class = get_class($this);
		new $class;
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
	// 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)
	{
227
228
229
		if (!ADODB_Active_Record::$_changeNames) {
			return $table;
		}
230
		$ut = strtoupper($table);
231
		if(isset(self::$WeIsI[$ut])) {
232
233
			return $table;
		}
234
		if(isset(self::$IrregularP[$ut])) {
235
236
237
238
239
240
			return self::$IrregularP[$ut];
		}
		$len = strlen($table);
		$lastc = $ut[$len-1];
		$lastc2 = substr($ut,$len-2);
		switch ($lastc) {
241
			case 'S':
242
				return $table.'es';
243
244
245
246
247
248
249
250
251
252
			case 'Y':
				return substr($table,0,$len-1).'ies';
			case 'X':
				return $table.'es';
			case 'H':
				if ($lastc2 == 'CH' || $lastc2 == 'SH') {
					return $table.'es';
				}
			default:
				return $table.'s';
253
254
		}
	}
255

256
257
258
259
	// 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)
	{
260

261
262
263
		if (!ADODB_Active_Record::$_changeNames) {
		return $table;
	}
264
		$ut = strtoupper($table);
265
		if(isset(self::$WeIsI[$ut])) {
266
267
			return $table;
		}
268
		if(isset(self::$IrregularS[$ut])) {
269
270
271
			return self::$IrregularS[$ut];
		}
		$len = strlen($table);
272
		if($ut[$len-1] != 'S') {
273
			return $table; // I know...forget oxen
274
275
		}
		if($ut[$len-2] != 'E') {
276
			return substr($table, 0, $len-1);
277
278
		}
		switch($ut[$len-3]) {
279
280
281
282
283
284
			case 'S':
			case 'X':
				return substr($table, 0, $len-2);
			case 'I':
				return substr($table, 0, $len-3) . 'y';
			case 'H';
285
				if($ut[$len-4] == 'C' || $ut[$len-4] == 'S') {
286
					return substr($table, 0, $len-2);
287
				}
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
			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();
309
		if(!isset($table->_hasMany[$foreignRef])) {
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
			$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;
332

333
		$table =& $this->TableInfo();
334
		if(!isset($table->_belongsTo[$foreignRef])) {
335
336
337
338
339
340
341
342
			$table->_belongsTo[$foreignRef] = $ar;
			$table->updateColsCount();
		}
		$this->$foreignRef = $table->_belongsTo[$foreignRef];
	}

	/**
	 * __get Access properties - used for lazy loading
343
344
	 *
	 * @param mixed $name
345
346
347
348
349
350
351
352
353
354
355
	 * @access protected
	 * @return void
	 */
	function __get($name)
	{
		return $this->LoadRelations($name, '', -1. -1);
	}

	function LoadRelations($name, $whereOrderBy, $offset=-1, $limit=-1)
	{
		$extras = array();
356
357
358
359
360
361
		if($offset >= 0) {
			$extras['offset'] = $offset;
		}
		if($limit >= 0) {
			$extras['limit'] = $limit;
		}
362
		$table =& $this->TableInfo();
363

364
365
366
		if (strlen($whereOrderBy)) {
			if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy)) {
				if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy)) {
367
					$whereOrderBy = 'AND '.$whereOrderBy;
368
369
370
				}
			}
		}
371

372
		if(!empty($table->_belongsTo[$name])) {
373
374
			$obj = $table->_belongsTo[$name];
			$columnName = $obj->foreignKey;
375
			if(empty($this->$columnName)) {
376
				$this->$name = null;
377
378
379
			}
			else {
				if(($k = reset($obj->TableInfo()->keys))) {
380
					$belongsToId = $k;
381
382
				}
				else {
383
					$belongsToId = 'id';
384
				}
385

386
387
388
389
390
391
392
				$arrayOfOne =
					$obj->Find(
						$belongsToId.'='.$this->$columnName.' '.$whereOrderBy, false, false, $extras);
				$this->$name = $arrayOfOne[0];
			}
			return $this->$name;
		}
393
		if(!empty($table->_hasMany[$name])) {
394
			$obj = $table->_hasMany[$name];
395
			if(($k = reset($table->keys))) {
396
				$hasManyId   = $k;
397
398
			}
			else {
399
				$hasManyId   = 'id';
400
			}
401
402
403
404
405
406
407
408

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

410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
	// 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) {
425
426
427
428
429
430
				if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) {
					$this->$name = $fld->default_value;
				}
				else {
					$this->$name = null;
				}
431
432
433
			}
			return;
		}
434

435
436
437
438
439
440
441
		$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);
442
			if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) {
443
444
445
				// abs(rand()) randomizes deletion, reducing contention to delete/refresh file
				// ideally, you should cache at least 32 secs
				$activedb->tables[$table] = $acttab;
446

447
				//if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
448
					return;
449
450
451
452
453
454
			} else if ($db->debug) {
				ADOConnection::outp("Refreshing cached active record file: $fname");
			}
		}
		$activetab = new ADODB_Active_Table();
		$activetab->name = $table;
455

456
457
		$save = $ADODB_FETCH_MODE;
		$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
458
459
460
		if ($db->fetchMode !== false) {
			$savem = $db->SetFetchMode(false);
		}
461

462
		$cols = $db->MetaColumns($table);
463

464
465
466
		if (isset($savem)) {
			$db->SetFetchMode($savem);
		}
467
		$ADODB_FETCH_MODE = $save;
468

469
		if (!$cols) {
470
			$this->Error("Invalid table name: $table",'UpdateActiveTable');
471
472
473
474
475
476
477
			return false;
		}
		$fld = reset($cols);
		if (!$pkeys) {
			if (isset($fld->primary_key)) {
				$pkeys = array();
				foreach($cols as $name => $fld) {
478
479
480
					if (!empty($fld->primary_key)) {
						$pkeys[] = $name;
					}
481
				}
482
			} else {
483
				$pkeys = $this->GetPrimaryKeys($db, $table);
484
			}
485
486
487
488
489
		}
		if (empty($pkeys)) {
			$this->Error("No primary key found for table $table",'UpdateActiveTable');
			return false;
		}
490

491
492
		$attr = array();
		$keys = array();
493

494
495
496
497
		switch($ADODB_ASSOC_CASE) {
		case 0:
			foreach($cols as $name => $fldobj) {
				$name = strtolower($name);
498
499
500
501
				if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
					$this->$name = $fldobj->default_value;
				}
				else {
502
					$this->$name = null;
503
				}
504
505
506
507
508
509
				$attr[$name] = $fldobj;
			}
			foreach($pkeys as $k => $name) {
				$keys[strtolower($name)] = strtolower($name);
			}
			break;
510
511

		case 1:
512
513
			foreach($cols as $name => $fldobj) {
				$name = strtoupper($name);
514

515
516
517
518
				if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
					$this->$name = $fldobj->default_value;
				}
				else {
519
					$this->$name = null;
520
				}
521
522
				$attr[$name] = $fldobj;
			}
523

524
525
526
527
528
529
530
			foreach($pkeys as $k => $name) {
				$keys[strtoupper($name)] = strtoupper($name);
			}
			break;
		default:
			foreach($cols as $name => $fldobj) {
				$name = ($fldobj->name);
531

532
533
534
535
				if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
					$this->$name = $fldobj->default_value;
				}
				else {
536
					$this->$name = null;
537
				}
538
539
540
541
542
543
544
				$attr[$name] = $fldobj;
			}
			foreach($pkeys as $k => $name) {
				$keys[$name] = $cols[$name]->name;
			}
			break;
		}
545

546
547
548
549
550
551
552
		$activetab->keys = $keys;
		$activetab->flds = $attr;
		$activetab->updateColsCount();

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

561
562
563
564
			if ($oldtab) {
				$activetab->_belongsTo = $oldtab->_belongsTo;
				$activetab->_hasMany = $oldtab->_hasMany;
			}
565
566
567
		}
		$activedb->tables[$table] = $activetab;
	}
568

569
570
571
572
	function GetPrimaryKeys(&$db, $table)
	{
		return $db->MetaPrimaryKeys($table);
	}
573
574

	// error handler for both PHP4+5.
575
576
577
	function Error($err,$fn)
	{
	global $_ADODB_ACTIVE_DBS;
578

579
580
		$fn = get_class($this).'::'.$fn;
		$this->_lasterr = $fn.': '.$err;
581

582
583
584
		if ($this->_dbat < 0) {
			$db = false;
		}
585
586
587
588
		else {
			$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
			$db = $activedb->db;
		}
589
590

		if (function_exists('adodb_throw')) {
591
592
593
594
595
596
597
598
599
600
601
			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);
			}
		}
602

603
	}
604

605
606
607
608
	// return last error message
	function ErrorMsg()
	{
		if (!function_exists('adodb_throw')) {
609
610
611
612
613
614
			if ($this->_dbat < 0) {
				$db = false;
			}
			else {
				$db = $this->DB();
			}
615

616
			// last error could be database error too
617
618
619
			if ($db && $db->ErrorMsg()) {
				return $db->ErrorMsg();
			}
620
621
622
		}
		return $this->_lasterr;
	}
623
624

	function ErrorNo()
625
	{
626
627
628
		if ($this->_dbat < 0) {
			return -9999; // no database connection...
		}
629
		$db = $this->DB();
630

631
632
633
634
635
636
637
638
		return (int) $db->ErrorNo();
	}


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

640
641
642
643
644
645
646
647
648
		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;
	}
649

650
651
652
653
	// retrieve ADODB_Active_Table
	function &TableInfo()
	{
	global $_ADODB_ACTIVE_DBS;
654

655
656
657
658
		$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
		$table = $activedb->tables[$this->_tableat];
		return $table;
	}
659
660


661
662
663
664
	// 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()
	{
665
666
667
668
		$db =& $this->DB();
		if (!$db) {
			return false;
		}
669
670
671
672
673
		$table =& $this->TableInfo();
		$where = $this->GenWhere($db, $table);
		return($this->Load($where));
	}

674

675
676
677
678
	// set a numeric array (using natural table field ordering) as object properties
	function Set(&$row)
	{
	global $ACTIVE_RECORD_SAFETY;
679

680
		$db = $this->DB();
681

682
		if (!$row) {
683
			$this->_saved = false;
684
685
			return false;
		}
686

687
		$this->_saved = true;
688

689
690
691
692
		$table = $this->TableInfo();
		$sizeofFlds = sizeof($table->flds);
		$sizeofRow  = sizeof($row);
		if ($ACTIVE_RECORD_SAFETY && $table->_colsCount != $sizeofRow && $sizeofFlds != $sizeofRow) {
693
694
695
696
697
698
699
700
701
702
703
704
705
706
			# <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>
707
		}
708
709
		else {
			$keys = array_keys($row);
710
		}
711
712
713
714
715
716

		# <AP>
		reset($keys);
		$this->_original = array();
		foreach($table->flds as $name=>$fld) {
			$value = $row[current($keys)];
717
			$this->$name = $value;
718
719
720
721
			$this->_original[] = $value;
			if(!next($keys)) {
				break;
			}
722
723
		}
		$table =& $this->TableInfo();
724
		foreach($table->_belongsTo as $foreignTable) {
725
726
			$ft = $foreignTable->TableInfo();
			$propertyName = $ft->name;
727
			foreach($ft->flds as $name=>$fld) {
728
729
730
				$value = $row[current($keys)];
				$foreignTable->$name = $value;
				$foreignTable->_original[] = $value;
731
732
733
				if(!next($keys)) {
					break;
				}
734
735
			}
		}
736
		foreach($table->_hasMany as $foreignTable) {
737
			$ft = $foreignTable->TableInfo();
738
			foreach($ft->flds as $name=>$fld) {
739
740
741
				$value = $row[current($keys)];
				$foreignTable->$name = $value;
				$foreignTable->_original[] = $value;
742
743
744
				if(!next($keys)) {
					break;
				}
745
746
			}
		}
747
748
		# </AP>

749
750
		return true;
	}
751

752
753
754
	// get last inserted id for INSERT
	function LastInsertID(&$db,$fieldname)
	{
755
		if ($db->hasInsertID) {
756
			$val = $db->Insert_ID($this->_table,$fieldname);
757
758
		}
		else {
759
			$val = false;
760
		}
761

762
763
764
765
766
767
		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;
	}
768

769
770
771
772
773
774
	// quote data in where clause
	function doquote(&$db, $val,$t)
	{
		switch($t) {
		case 'D':
		case 'T':
775
776
777
			if (empty($val)) {
				return 'null';
			}
778
779
		case 'C':
		case 'X':
780
781
782
			if (is_null($val)) {
				return 'null';
			}
783
			if (strlen($val)>0 &&
784
785
				(strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")
			) {
786
787
788
789
790
791
792
793
				return $db->qstr($val);
				break;
			}
		default:
			return $val;
			break;
		}
	}
794

795
796
797
798
799
	// generate where clause for an UPDATE/SELECT
	function GenWhere(&$db, &$table)
	{
		$keys = $table->keys;
		$parr = array();
800

801
802
803
804
805
806
807
808
		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);
	}
809
810


811
	//------------------------------------------------------------ Public functions below
812

813
814
	function Load($where=null,$bindarr=false)
	{
815
816
817
818
		$db = $this->DB();
		if (!$db) {
			return false;
		}
819
		$this->_where = $where;
820

821
822
823
824
		$save = $db->SetFetchMode(ADODB_FETCH_NUM);
		$qry = "select * from ".$this->_table;
		$table =& $this->TableInfo();

825
		if(($k = reset($table->keys))) {
826
			$hasManyId   = $k;
827
828
		}
		else {
829
			$hasManyId   = 'id';
830
		}
831

832
833
		foreach($table->_belongsTo as $foreignTable) {
			if(($k = reset($foreignTable->TableInfo()->keys))) {
834
835
				$belongsToId = $k;
			}
836
			else {
837
838
839
840
841
842
843
844
845
846
847
848
				$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;
		}
849
		if($where) {
850
			$qry .= ' WHERE '.$where;
851
		}
852

853
		// Simple case: no relations. Load row and return.
854
		if((count($table->_hasMany) + count($table->_belongsTo)) < 1) {
855
			$row = $db->GetRow($qry,$bindarr);
856
			if(!$row) {
857
				return false;
858
			}
859
860
861
			$db->SetFetchMode($save);
			return $this->Set($row);
		}
862

863
864
		// More complex case when relations have to be collated
		$rows = $db->GetAll($qry,$bindarr);
865
		if(!$rows) {
866
			return false;
867
		}
868
		$db->SetFetchMode($save);
869
		if(count($rows) < 1) {
870
			return false;
871
		}
872
873
		$class = get_class($this);
		$isFirstRow = true;
874

875
		if(($k = reset($this->TableInfo()->keys))) {
876
			$myId   = $k;
877
878
		}
		else {
879
			$myId   = 'id';
880
		}
881
882
883
		$index = 0; $found = false;
		/** @todo Improve by storing once and for all in table metadata */
		/** @todo Also re-use info for hasManyId */
884
885
		foreach($this->TableInfo()->flds as $fld) {
			if($fld->name == $myId) {
886
887
888
889
890
				$found = true;
				break;
			}
			$index++;
		}
891
		if(!$found) {
892
			$this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
893
		}
894

895
		foreach($rows as $row) {
896
			$rowId = intval($row[$index]);
897
898
			if($rowId > 0) {
				if($isFirstRow) {
899
					$isFirstRow = false;
900
					if(!$this->Set($row)) {
901
						return false;
902
					}
903
904
905
906
				}
				$obj = new $class($table,false,$db);
				$obj->Set($row);
				// TODO Copy/paste code below: bad!
907
908
				if(count($table->_hasMany) > 0) {
					foreach($table->_hasMany as $foreignTable) {
909
						$foreignName = $foreignTable->foreignName;
910
911
						if(!empty($obj->$foreignName)) {
							if(!is_array($this->$foreignName)) {
912
913
914
								$foreignObj = $this->$foreignName;
								$this->$foreignName = array(clone($foreignObj));
							}
915
							else {
916
917
918
919
920
921
								$foreignObj = $obj->$foreignName;
								array_push($this->$foreignName, clone($foreignObj));
							}
						}
					}
				}
922
923
				if(count($table->_belongsTo) > 0) {
					foreach($table->_belongsTo as $foreignTable) {
924
						$foreignName = $foreignTable->foreignName;
925
926
						if(!empty($obj->$foreignName)) {
							if(!is_array($this->$foreignName)) {
927
928
929
								$foreignObj = $this->$foreignName;
								$this->$foreignName = array(clone($foreignObj));
							}
930
							else {
931
932
933
934
935
								$foreignObj = $obj->$foreignName;
								array_push($this->$foreignName, clone($foreignObj));
							}
						}
					}
936
				}
937
938
939
940
			}
		}
		return true;
	}
941

942
943
944
	// false on error
	function Save()
	{
945
946
947
948
949
950
		if ($this->_saved) {
			$ok = $this->Update();
		}
		else {
			$ok = $this->Insert();
		}
951

952
953
		return $ok;
	}
954

955
956
957
958
959
960
961
962
963
964
	// 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()
	{
965
966
967
968
		$db = $this->DB();
		if (!$db) {
			return false;
		}
969
970
		$cnt = 0;
		$table = $this->TableInfo();
971

972
973
974
975
976
977
978
979
980
981
982
983
984
		$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;
			}
		}
985

986
987
988
989
990
991
992
993
994
995
		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);
996

997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
		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);
			}
		}
1011

1012
1013
1014
		$this->_original = $valarr;
		return !empty($ok);
	}
1015

1016
1017
	function Delete()
	{
1018
1019
1020
1021
		$db = $this->DB();
		if (!$db) {
			return false;
		}
1022
		$table = $this->TableInfo();
1023

1024
1025
1026
		$where = $this->GenWhere($db,$table);
		$sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
		$ok = $db->Execute($sql);
1027

1028
1029
		return $ok ? true : false;
	}
1030

1031
1032
1033
	// returns an array of active record objects
	function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
	{
1034
1035
1036
1037
		$db = $this->DB();
		if (!$db || empty($this->_table)) {
			return false;
		}
1038
1039
1040
1041
1042
		$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;
	}
1043

1044
1045
1046
1047
1048
1049
	// 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())
	{
1050
1051
1052
1053
		$db = $this->DB();
		if (!$db || empty($this->_table)) {
			return false;
		}
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
		$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;
1064

1065
1066
1067
1068
		$db = $this->DB();
		if (!$db) {
			return false;
		}
1069
		$table = $this->TableInfo();
1070

1071
		$pkey = $table->keys;
1072

1073
1074
1075
1076
1077
		foreach($table->flds as $name=>$fld) {
			$val = $this->$name;
			/*
			if (is_null($val)) {
				if (isset($fld->not_null) && $fld->not_null) {
1078
1079
1080
					if (isset($fld->default_value) && strlen($fld->default_value)) {
						continue;
					}
1081
1082
1083
1084
1085
1086
1087
					else {
						$this->Error("Cannot update null into $name","Replace");
						return false;
					}
				}
			}*/
			if (is_null($val) && !empty($fld->auto_increment)) {
1088
1089
				continue;
			}
1090
1091
1092
1093
			$t = $db->MetaType($fld->type);
			$arr[$name] = $this->doquote($db,$val,$t);
			$valarr[] = $val;
		}
1094

1095
1096
1097
		if (!is_array($pkey)) {
			$pkey = array($pkey);
		}
1098
1099


1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
		switch ($ADODB_ASSOC_CASE == 0) {
			case ADODB_ASSOC_CASE_LOWER:
				foreach($pkey as $k => $v) {
					$pkey[$k] = strtolower($v);
				}
				break;
			case ADODB_ASSOC_CASE_UPPER:
				foreach($pkey as $k => $v) {
					$pkey[$k] = strtoupper($v);
				}
				break;
		}
1112

1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
		$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);
				}
			}
1129

1130
			$this->_original = $valarr;
1131
		}
1132
1133
1134
1135
1136
1137
		return $ok;
	}

	// returns 0 on error, 1 on update, -1 if no change in data (no update)
	function Update()
	{
1138
1139
1140
1141
		$db = $this->DB();
		if (!$db) {
			return false;
		}
1142
		$table = $this->TableInfo();
1143

1144
		$where = $this->GenWhere($db, $table);
Robert Lyon's avatar