Updated adodb syysext to upstream version 5.0.8a.
[Packages/TYPO3.CMS.git] / typo3 / sysext / adodb / adodb / adodb-active-record.inc.php
1 <?php
2 /*
3
4 @version V5.08 6 Apr 2009 (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
5 Latest version is available at http://adodb.sourceforge.net
6
7 Released under both BSD license and Lesser GPL library license.
8 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 Version 0.92
14
15 See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
16 for info on Ruby on Rails Active Record implementation
17 */
18
19
20 global $_ADODB_ACTIVE_DBS;
21 global $ADODB_ACTIVE_CACHESECS; // set to true to enable caching of metadata such as field info
22 global $ACTIVE_RECORD_SAFETY; // set to false to disable safety checks
23 global $ADODB_ACTIVE_DEFVALS; // use default values of table definition when creating new active record.
24
25 // array of ADODB_Active_DB's, indexed by ADODB_Active_Record->_dbat
26 $_ADODB_ACTIVE_DBS = array();
27 $ACTIVE_RECORD_SAFETY = true;
28 $ADODB_ACTIVE_DEFVALS = false;
29
30 class ADODB_Active_DB {
31 var $db; // ADOConnection
32 var $tables; // assoc array of ADODB_Active_Table objects, indexed by tablename
33 }
34
35 class ADODB_Active_Table {
36 var $name; // table name
37 var $flds; // assoc array of adofieldobjs, indexed by fieldname
38 var $keys; // assoc array of primary keys, indexed by fieldname
39 var $_created; // only used when stored as a cached file
40 var $_belongsTo = array();
41 var $_hasMany = array();
42 }
43
44 // $db = database connection
45 // $index = name of index - can be associative, for an example see
46 // http://phplens.com/lens/lensforum/msgs.php?id=17790
47 // returns index into $_ADODB_ACTIVE_DBS
48 function ADODB_SetDatabaseAdapter(&$db, $index=false)
49 {
50 global $_ADODB_ACTIVE_DBS;
51
52 foreach($_ADODB_ACTIVE_DBS as $k => $d) {
53 if (PHP_VERSION >= 5) {
54 if ($d->db === $db) return $k;
55 } else {
56 if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database)
57 return $k;
58 }
59 }
60
61 $obj = new ADODB_Active_DB();
62 $obj->db = $db;
63 $obj->tables = array();
64
65 if ($index == false) $index = sizeof($_ADODB_ACTIVE_DBS);
66
67
68 $_ADODB_ACTIVE_DBS[$index] = $obj;
69
70 return sizeof($_ADODB_ACTIVE_DBS)-1;
71 }
72
73
74 class ADODB_Active_Record {
75 static $_changeNames = true; // dynamically pluralize table names
76 static $_foreignSuffix = '_id'; //
77 var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
78 var $_table; // tablename, if set in class definition then use it as table name
79 var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
80 var $_where; // where clause set in Load()
81 var $_saved = false; // indicates whether data is already inserted.
82 var $_lasterr = false; // last error message
83 var $_original = false; // the original values loaded or inserted, refreshed on update
84
85 var $foreignName; // CFR: class name when in a relationship
86
87 static function UseDefaultValues($bool=null)
88 {
89 global $ADODB_ACTIVE_DEFVALS;
90 if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
91 return $ADODB_ACTIVE_DEFVALS;
92 }
93
94 // should be static
95 static function SetDatabaseAdapter(&$db, $index=false)
96 {
97 return ADODB_SetDatabaseAdapter($db, $index);
98 }
99
100
101 public function __set($name, $value)
102 {
103 $name = str_replace(' ', '_', $name);
104 $this->$name = $value;
105 }
106
107 // php5 constructor
108 function __construct($table = false, $pkeyarr=false, $db=false)
109 {
110 global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS;
111
112 if ($db == false && is_object($pkeyarr)) {
113 $db = $pkeyarr;
114 $pkeyarr = false;
115 }
116
117 if (!$table) {
118 if (!empty($this->_table)) $table = $this->_table;
119 else $table = $this->_pluralize(get_class($this));
120 }
121 $this->foreignName = strtolower(get_class($this)); // CFR: default foreign name
122 if ($db) {
123 $this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
124 } else if (!isset($this->_dbat)) {
125 if (sizeof($_ADODB_ACTIVE_DBS) == 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
126 end($_ADODB_ACTIVE_DBS);
127 $this->_dbat = key($_ADODB_ACTIVE_DBS);
128 }
129
130 $this->_table = $table;
131 $this->_tableat = $table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
132
133 $this->UpdateActiveTable($pkeyarr);
134 }
135
136 function __wakeup()
137 {
138 $class = get_class($this);
139 new $class;
140 }
141
142 function _pluralize($table)
143 {
144 if (!ADODB_Active_Record::$_changeNames) return $table;
145
146 $ut = strtoupper($table);
147 $len = strlen($table);
148 $lastc = $ut[$len-1];
149 $lastc2 = substr($ut,$len-2);
150 switch ($lastc) {
151 case 'S':
152 return $table.'es';
153 case 'Y':
154 return substr($table,0,$len-1).'ies';
155 case 'X':
156 return $table.'es';
157 case 'H':
158 if ($lastc2 == 'CH' || $lastc2 == 'SH')
159 return $table.'es';
160 default:
161 return $table.'s';
162 }
163 }
164
165 // CFR Lamest singular inflector ever - @todo Make it real!
166 // Note: There is an assumption here...and it is that the argument's length >= 4
167 function _singularize($tables)
168 {
169
170 if (!ADODB_Active_Record::$_changeNames) return $table;
171
172 $ut = strtoupper($tables);
173 $len = strlen($tables);
174 if($ut[$len-1] != 'S')
175 return $tables; // I know...forget oxen
176 if($ut[$len-2] != 'E')
177 return substr($tables, 0, $len-1);
178 switch($ut[$len-3])
179 {
180 case 'S':
181 case 'X':
182 return substr($tables, 0, $len-2);
183 case 'I':
184 return substr($tables, 0, $len-3) . 'y';
185 case 'H';
186 if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
187 return substr($tables, 0, $len-2);
188 default:
189 return substr($tables, 0, $len-1); // ?
190 }
191 }
192
193 function hasMany($foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
194 {
195 $ar = new $foreignClass($foreignRef);
196 $ar->foreignName = $foreignRef;
197 $ar->UpdateActiveTable();
198 $ar->foreignKey = ($foreignKey) ? $foreignKey : $foreignRef.ADODB_Active_Record::$_foreignSuffix;
199 $table =& $this->TableInfo();
200 $table->_hasMany[$foreignRef] = $ar;
201 # $this->$foreignRef = $this->_hasMany[$foreignRef]; // WATCHME Removed assignment by ref. to please __get()
202 }
203
204 // use when you don't want ADOdb to auto-pluralize tablename
205 static function TableHasMany($table, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
206 {
207 $ar = new ADODB_Active_Record($table);
208 $ar->hasMany($foreignRef, $foreignKey, $foreignClass);
209 }
210
211 // use when you don't want ADOdb to auto-pluralize tablename
212 static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
213 {
214 if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
215 $ar = new ADODB_Active_Record($table,$tablePKey);
216 $ar->hasMany($foreignRef, $foreignKey, $foreignClass);
217 }
218
219
220 // use when you want ADOdb to auto-pluralize tablename for you. Note that the class must already be defined.
221 // e.g. class Person will generate relationship for table Persons
222 static function ClassHasMany($parentclass, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
223 {
224 $ar = new $parentclass();
225 $ar->hasMany($foreignRef, $foreignKey, $foreignClass);
226 }
227
228
229 function belongsTo($foreignRef,$foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
230 {
231 global $inflector;
232
233 $ar = new $parentClass($this->_pluralize($foreignRef));
234 $ar->foreignName = $foreignRef;
235 $ar->parentKey = $parentKey;
236 $ar->UpdateActiveTable();
237 $ar->foreignKey = ($foreignKey) ? $foreignKey : $foreignRef.ADODB_Active_Record::$_foreignSuffix;
238
239 $table =& $this->TableInfo();
240 $table->_belongsTo[$foreignRef] = $ar;
241 # $this->$foreignRef = $this->_belongsTo[$foreignRef];
242 }
243
244 static function ClassBelongsTo($class, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
245 {
246 $ar = new $class();
247 $ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
248 }
249
250 static function TableBelongsTo($table, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
251 {
252 $ar = new ADOdb_Active_Record($table);
253 $ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
254 }
255
256 static function TableKeyBelongsTo($table, $tablePKey, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
257 {
258 if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
259 $ar = new ADOdb_Active_Record($table, $tablePKey);
260 $ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
261 }
262
263
264 /**
265 * __get Access properties - used for lazy loading
266 *
267 * @param mixed $name
268 * @access protected
269 * @return mixed
270 */
271 function __get($name)
272 {
273 return $this->LoadRelations($name, '', -1, -1);
274 }
275
276 /**
277 * @param string $name
278 * @param string $whereOrderBy : eg. ' AND field1 = value ORDER BY field2'
279 * @param offset
280 * @param limit
281 * @return mixed
282 */
283 function LoadRelations($name, $whereOrderBy='', $offset=-1,$limit=-1)
284 {
285 $extras = array();
286 $table = $this->TableInfo();
287 if ($limit >= 0) $extras['limit'] = $limit;
288 if ($offset >= 0) $extras['offset'] = $offset;
289
290 if (strlen($whereOrderBy))
291 if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
292 if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
293 $whereOrderBy = 'AND '.$whereOrderBy;
294
295 if(!empty($table->_belongsTo[$name]))
296 {
297 $obj = $table->_belongsTo[$name];
298 $columnName = $obj->foreignKey;
299 if(empty($this->$columnName))
300 $this->$name = null;
301 else
302 {
303 if ($obj->parentKey) $key = $obj->parentKey;
304 else $key = reset($table->keys);
305
306 $arrayOfOne = $obj->Find($key.'='.$this->$columnName.' '.$whereOrderBy,false,false,$extras);
307 if ($arrayOfOne) {
308 $this->$name = $arrayOfOne[0];
309 return $arrayOfOne[0];
310 }
311 }
312 }
313 if(!empty($table->_hasMany[$name]))
314 {
315 $obj = $table->_hasMany[$name];
316 $key = reset($table->keys);
317 $id = @$this->$key;
318 if (!is_numeric($id)) {
319 $db = $this->DB();
320 $id = $db->qstr($id);
321 }
322 $objs = $obj->Find($obj->foreignKey.'='.$id. ' '.$whereOrderBy,false,false,$extras);
323 if (!$objs) $objs = array();
324 $this->$name = $objs;
325 return $objs;
326 }
327
328 return array();
329 }
330 //////////////////////////////////
331
332 // update metadata
333 function UpdateActiveTable($pkeys=false,$forceUpdate=false)
334 {
335 global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS , $ADODB_CACHE_DIR, $ADODB_ACTIVE_CACHESECS;
336 global $ADODB_ACTIVE_DEFVALS,$ADODB_FETCH_MODE;
337
338 $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
339
340 $table = $this->_table;
341 $tables = $activedb->tables;
342 $tableat = $this->_tableat;
343 if (!$forceUpdate && !empty($tables[$tableat])) {
344
345 $tobj = $tables[$tableat];
346 foreach($tobj->flds as $name => $fld) {
347 if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
348 $this->$name = $fld->default_value;
349 else
350 $this->$name = null;
351 }
352 return;
353 }
354 $db = $activedb->db;
355 $fname = $ADODB_CACHE_DIR . '/adodb_' . $db->databaseType . '_active_'. $table . '.cache';
356 if (!$forceUpdate && $ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR && file_exists($fname)) {
357 $fp = fopen($fname,'r');
358 @flock($fp, LOCK_SH);
359 $acttab = unserialize(fread($fp,100000));
360 fclose($fp);
361 if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) {
362 // abs(rand()) randomizes deletion, reducing contention to delete/refresh file
363 // ideally, you should cache at least 32 secs
364 $activedb->tables[$table] = $acttab;
365
366 //if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
367 return;
368 } else if ($db->debug) {
369 ADOConnection::outp("Refreshing cached active record file: $fname");
370 }
371 }
372 $activetab = new ADODB_Active_Table();
373 $activetab->name = $table;
374
375 $save = $ADODB_FETCH_MODE;
376 $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
377 if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
378
379 $cols = $db->MetaColumns($table);
380
381 if (isset($savem)) $db->SetFetchMode($savem);
382 $ADODB_FETCH_MODE = $save;
383
384 if (!$cols) {
385 $this->Error("Invalid table name: $table",'UpdateActiveTable');
386 return false;
387 }
388 $fld = reset($cols);
389 if (!$pkeys) {
390 if (isset($fld->primary_key)) {
391 $pkeys = array();
392 foreach($cols as $name => $fld) {
393 if (!empty($fld->primary_key)) $pkeys[] = $name;
394 }
395 } else
396 $pkeys = $this->GetPrimaryKeys($db, $table);
397 }
398 if (empty($pkeys)) {
399 $this->Error("No primary key found for table $table",'UpdateActiveTable');
400 return false;
401 }
402
403 $attr = array();
404 $keys = array();
405
406 switch($ADODB_ASSOC_CASE) {
407 case 0:
408 foreach($cols as $name => $fldobj) {
409 $name = strtolower($name);
410 if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
411 $this->$name = $fldobj->default_value;
412 else
413 $this->$name = null;
414 $attr[$name] = $fldobj;
415 }
416 foreach($pkeys as $k => $name) {
417 $keys[strtolower($name)] = strtolower($name);
418 }
419 break;
420
421 case 1:
422 foreach($cols as $name => $fldobj) {
423 $name = strtoupper($name);
424
425 if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
426 $this->$name = $fldobj->default_value;
427 else
428 $this->$name = null;
429 $attr[$name] = $fldobj;
430 }
431
432 foreach($pkeys as $k => $name) {
433 $keys[strtoupper($name)] = strtoupper($name);
434 }
435 break;
436 default:
437 foreach($cols as $name => $fldobj) {
438 $name = ($fldobj->name);
439
440 if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
441 $this->$name = $fldobj->default_value;
442 else
443 $this->$name = null;
444 $attr[$name] = $fldobj;
445 }
446 foreach($pkeys as $k => $name) {
447 $keys[$name] = $cols[$name]->name;
448 }
449 break;
450 }
451
452 $activetab->keys = $keys;
453 $activetab->flds = $attr;
454
455 if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
456 $activetab->_created = time();
457 $s = serialize($activetab);
458 if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
459 adodb_write_file($fname,$s);
460 }
461 if (isset($activedb->tables[$table])) {
462 $oldtab = $activedb->tables[$table];
463
464 if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
465 if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
466 }
467 $activedb->tables[$table] = $activetab;
468 }
469
470 function GetPrimaryKeys(&$db, $table)
471 {
472 return $db->MetaPrimaryKeys($table);
473 }
474
475 // error handler for both PHP4+5.
476 function Error($err,$fn)
477 {
478 global $_ADODB_ACTIVE_DBS;
479
480 $fn = get_class($this).'::'.$fn;
481 $this->_lasterr = $fn.': '.$err;
482
483 if ($this->_dbat < 0) $db = false;
484 else {
485 $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
486 $db = $activedb->db;
487 }
488
489 if (function_exists('adodb_throw')) {
490 if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
491 else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
492 } else
493 if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
494
495 }
496
497 // return last error message
498 function ErrorMsg()
499 {
500 if (!function_exists('adodb_throw')) {
501 if ($this->_dbat < 0) $db = false;
502 else $db = $this->DB();
503
504 // last error could be database error too
505 if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
506 }
507 return $this->_lasterr;
508 }
509
510 function ErrorNo()
511 {
512 if ($this->_dbat < 0) return -9999; // no database connection...
513 $db = $this->DB();
514
515 return (int) $db->ErrorNo();
516 }
517
518
519 // retrieve ADOConnection from _ADODB_Active_DBs
520 function DB()
521 {
522 global $_ADODB_ACTIVE_DBS;
523
524 if ($this->_dbat < 0) {
525 $false = false;
526 $this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
527 return $false;
528 }
529 $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
530 $db = $activedb->db;
531 return $db;
532 }
533
534 // retrieve ADODB_Active_Table
535 function &TableInfo()
536 {
537 global $_ADODB_ACTIVE_DBS;
538 $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
539 $table = $activedb->tables[$this->_tableat];
540 return $table;
541 }
542
543
544 // I have an ON INSERT trigger on a table that sets other columns in the table.
545 // So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
546 function Reload()
547 {
548 $db =& $this->DB(); if (!$db) return false;
549 $table =& $this->TableInfo();
550 $where = $this->GenWhere($db, $table);
551 return($this->Load($where));
552 }
553
554
555 // set a numeric array (using natural table field ordering) as object properties
556 function Set(&$row)
557 {
558 global $ACTIVE_RECORD_SAFETY;
559
560 $db = $this->DB();
561
562 if (!$row) {
563 $this->_saved = false;
564 return false;
565 }
566
567 $this->_saved = true;
568
569 $table = $this->TableInfo();
570 if ($ACTIVE_RECORD_SAFETY && sizeof($table->flds) != sizeof($row)) {
571 # <AP>
572 $bad_size = TRUE;
573 if (sizeof($row) == 2 * sizeof($table->flds)) {
574 // Only keep string keys
575 $keys = array_filter(array_keys($row), 'is_string');
576 if (sizeof($keys) == sizeof($table->flds))
577 $bad_size = FALSE;
578 }
579 if ($bad_size) {
580 $this->Error("Table structure of $this->_table has changed","Load");
581 return false;
582 }
583 # </AP>
584 }
585 else
586 $keys = array_keys($row);
587
588 # <AP>
589 reset($keys);
590 $this->_original = array();
591 foreach($table->flds as $name=>$fld) {
592 $value = $row[current($keys)];
593 $this->$name = $value;
594 $this->_original[] = $value;
595 next($keys);
596 }
597
598 # </AP>
599 return true;
600 }
601
602 // get last inserted id for INSERT
603 function LastInsertID(&$db,$fieldname)
604 {
605 if ($db->hasInsertID)
606 $val = $db->Insert_ID($this->_table,$fieldname);
607 else
608 $val = false;
609
610 if (is_null($val) || $val === false) {
611 // this might not work reliably in multi-user environment
612 return $db->GetOne("select max(".$fieldname.") from ".$this->_table);
613 }
614 return $val;
615 }
616
617 // quote data in where clause
618 function doquote(&$db, $val,$t)
619 {
620 switch($t) {
621 case 'D':
622 case 'T':
623 if (empty($val)) return 'null';
624
625 case 'B':
626 case 'N':
627 case 'C':
628 case 'X':
629 if (is_null($val)) return 'null';
630
631 if (strlen($val)>1 &&
632 (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
633 return $db->qstr($val);
634 break;
635 }
636 default:
637 return $val;
638 break;
639 }
640 }
641
642 // generate where clause for an UPDATE/SELECT
643 function GenWhere(&$db, &$table)
644 {
645 $keys = $table->keys;
646 $parr = array();
647
648 foreach($keys as $k) {
649 $f = $table->flds[$k];
650 if ($f) {
651 $parr[] = $k.' = '.$this->doquote($db,$this->$k,$db->MetaType($f->type));
652 }
653 }
654 return implode(' and ', $parr);
655 }
656
657
658 //------------------------------------------------------------ Public functions below
659
660 function Load($where=null,$bindarr=false)
661 {
662 global $ADODB_FETCH_MODE;
663
664 $db = $this->DB(); if (!$db) return false;
665 $this->_where = $where;
666
667 $save = $ADODB_FETCH_MODE;
668 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
669 if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
670
671 $qry = "select * from ".$this->_table;
672
673 if($where) {
674 $qry .= ' WHERE '.$where;
675 }
676 $row = $db->GetRow($qry,$bindarr);
677
678 if (isset($savem)) $db->SetFetchMode($savem);
679 $ADODB_FETCH_MODE = $save;
680
681 return $this->Set($row);
682 }
683
684 # useful for multiple record inserts
685 # see http://phplens.com/lens/lensforum/msgs.php?id=17795
686 function Reset()
687 {
688 $this->_where=null;
689 $this->_saved = false;
690 $this->_lasterr = false;
691 $this->_original = false;
692 $vars=get_object_vars($this);
693 foreach($vars as $k=>$v){
694 if(substr($k,0,1)!=='_'){
695 $this->{$k}=null;
696 }
697 }
698 $this->foreignName=strtolower(get_class($this));
699 return true;
700 }
701
702 // false on error
703 function Save()
704 {
705 if ($this->_saved) $ok = $this->Update();
706 else $ok = $this->Insert();
707
708 return $ok;
709 }
710
711 // false on error
712 function Insert()
713 {
714 $db = $this->DB(); if (!$db) return false;
715 $cnt = 0;
716 $table = $this->TableInfo();
717
718 $valarr = array();
719 $names = array();
720 $valstr = array();
721
722 foreach($table->flds as $name=>$fld) {
723 $val = $this->$name;
724 if(!is_array($val) || !is_null($val) || !array_key_exists($name, $table->keys)) {
725 $valarr[] = $val;
726 $names[] = $name;
727 $valstr[] = $db->Param($cnt);
728 $cnt += 1;
729 }
730 }
731
732 if (empty($names)){
733 foreach($table->flds as $name=>$fld) {
734 $valarr[] = null;
735 $names[] = $name;
736 $valstr[] = $db->Param($cnt);
737 $cnt += 1;
738 }
739 }
740 $sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
741 $ok = $db->Execute($sql,$valarr);
742
743 if ($ok) {
744 $this->_saved = true;
745 $autoinc = false;
746 foreach($table->keys as $k) {
747 if (is_null($this->$k)) {
748 $autoinc = true;
749 break;
750 }
751 }
752 if ($autoinc && sizeof($table->keys) == 1) {
753 $k = reset($table->keys);
754 $this->$k = $this->LastInsertID($db,$k);
755 }
756 }
757
758 $this->_original = $valarr;
759 return !empty($ok);
760 }
761
762 function Delete()
763 {
764 $db = $this->DB(); if (!$db) return false;
765 $table = $this->TableInfo();
766
767 $where = $this->GenWhere($db,$table);
768 $sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
769 $ok = $db->Execute($sql);
770
771 return $ok ? true : false;
772 }
773
774 // returns an array of active record objects
775 function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
776 {
777 $db = $this->DB(); if (!$db || empty($this->_table)) return false;
778 $arr = $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr,$extra);
779 return $arr;
780 }
781
782 // returns 0 on error, 1 on update, 2 on insert
783 function Replace()
784 {
785 global $ADODB_ASSOC_CASE;
786
787 $db = $this->DB(); if (!$db) return false;
788 $table = $this->TableInfo();
789
790 $pkey = $table->keys;
791
792 foreach($table->flds as $name=>$fld) {
793 $val = $this->$name;
794 /*
795 if (is_null($val)) {
796 if (isset($fld->not_null) && $fld->not_null) {
797 if (isset($fld->default_value) && strlen($fld->default_value)) continue;
798 else {
799 $this->Error("Cannot update null into $name","Replace");
800 return false;
801 }
802 }
803 }*/
804 if (is_null($val) && !empty($fld->auto_increment)) {
805 continue;
806 }
807
808 if (is_array($val)) continue;
809
810 $t = $db->MetaType($fld->type);
811 $arr[$name] = $this->doquote($db,$val,$t);
812 $valarr[] = $val;
813 }
814
815 if (!is_array($pkey)) $pkey = array($pkey);
816
817
818 if ($ADODB_ASSOC_CASE == 0)
819 foreach($pkey as $k => $v)
820 $pkey[$k] = strtolower($v);
821 elseif ($ADODB_ASSOC_CASE == 1)
822 foreach($pkey as $k => $v)
823 $pkey[$k] = strtoupper($v);
824
825 $ok = $db->Replace($this->_table,$arr,$pkey);
826 if ($ok) {
827 $this->_saved = true; // 1= update 2=insert
828 if ($ok == 2) {
829 $autoinc = false;
830 foreach($table->keys as $k) {
831 if (is_null($this->$k)) {
832 $autoinc = true;
833 break;
834 }
835 }
836 if ($autoinc && sizeof($table->keys) == 1) {
837 $k = reset($table->keys);
838 $this->$k = $this->LastInsertID($db,$k);
839 }
840 }
841
842 $this->_original = $valarr;
843 }
844 return $ok;
845 }
846
847 // returns 0 on error, 1 on update, -1 if no change in data (no update)
848 function Update()
849 {
850 $db = $this->DB(); if (!$db) return false;
851 $table = $this->TableInfo();
852
853 $where = $this->GenWhere($db, $table);
854
855 if (!$where) {
856 $this->error("Where missing for table $table", "Update");
857 return false;
858 }
859 $valarr = array();
860 $neworig = array();
861 $pairs = array();
862 $i = -1;
863 $cnt = 0;
864 foreach($table->flds as $name=>$fld) {
865 $i += 1;
866 $val = $this->$name;
867 $neworig[] = $val;
868
869 if (isset($table->keys[$name]) || is_array($val))
870 continue;
871
872 if (is_null($val)) {
873 if (isset($fld->not_null) && $fld->not_null) {
874 if (isset($fld->default_value) && strlen($fld->default_value)) continue;
875 else {
876 $this->Error("Cannot set field $name to NULL","Update");
877 return false;
878 }
879 }
880 }
881
882 if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
883 continue;
884 }
885 $valarr[] = $val;
886 $pairs[] = $name.'='.$db->Param($cnt);
887 $cnt += 1;
888 }
889
890
891 if (!$cnt) return -1;
892 $sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
893 $ok = $db->Execute($sql,$valarr);
894 if ($ok) {
895 $this->_original = $neworig;
896 return 1;
897 }
898 return 0;
899 }
900
901 function GetAttributeNames()
902 {
903 $table = $this->TableInfo();
904 if (!$table) return false;
905 return array_keys($table->flds);
906 }
907
908 };
909
910 function adodb_GetActiveRecordsClass(&$db, $class, $table,$whereOrderBy,$bindarr, $primkeyArr,
911 $extra)
912 {
913 global $_ADODB_ACTIVE_DBS;
914
915
916 $save = $db->SetFetchMode(ADODB_FETCH_NUM);
917 $qry = "select * from ".$table;
918
919 if (!empty($whereOrderBy))
920 $qry .= ' WHERE '.$whereOrderBy;
921 if(isset($extra['limit']))
922 {
923 $rows = false;
924 if(isset($extra['offset'])) {
925 $rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset']);
926 } else {
927 $rs = $db->SelectLimit($qry, $extra['limit']);
928 }
929 if ($rs) {
930 while (!$rs->EOF) {
931 $rows[] = $rs->fields;
932 $rs->MoveNext();
933 }
934 }
935 } else
936 $rows = $db->GetAll($qry,$bindarr);
937
938 $db->SetFetchMode($save);
939
940 $false = false;
941
942 if ($rows === false) {
943 return $false;
944 }
945
946
947 if (!class_exists($class)) {
948 $db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
949 return $false;
950 }
951 $arr = array();
952 // arrRef will be the structure that knows about our objects.
953 // It is an associative array.
954 // We will, however, return arr, preserving regular 0.. order so that
955 // obj[0] can be used by app developpers.
956 $arrRef = array();
957 $bTos = array(); // Will store belongTo's indices if any
958 foreach($rows as $row) {
959
960 $obj = new $class($table,$primkeyArr,$db);
961 if ($obj->ErrorNo()){
962 $db->_errorMsg = $obj->ErrorMsg();
963 return $false;
964 }
965 $obj->Set($row);
966 $arr[] = $obj;
967 } // foreach($rows as $row)
968
969 return $arr;
970 }
971 ?>