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