4 require_once 'Pman.php';
10 * Uses these methods of the dataobjects:
12 * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
14 * - applySort($au, $sortcol, $direction, $array_of_columns, $multisort) -- does not support multisort at present..
15 * - applyFilters($_REQUEST, $authUser, $roo) -- apply any query filters on data. and hide stuff not to be seen.
16 * - postListExtra($_REQUEST) : array(extra_name => data) - add extra column data on the results (like new messages etc.)
17 * - postListFilter($data, $authUser, $request) return $data - add extra data to an object
19 * - toRooSingleArray($authUser, $request) // single fetch, add data..
20 * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
23 * CRUD - before/after handlers..
24 * - setFromRoo($ar, $roo) - values from post (deal with dates etc.) - return true|error string.
25 * ... call $roo->jerr() on failure...
28 * - beforeDelete($dependants_array, $roo) Argument is an array of un-find/fetched dependant items.
29 * - jerr() will stop insert.. (Prefered)
30 * - return false for fail and set DO->err;
31 * - beforeUpdate($old, $request,$roo) - after update - jerr() will stop insert..
32 * - beforeInsert($request,$roo) - before insert - jerr() will stop insert..
35 * - onUpdate($old, $request,$roo) - after update // return value ignored
36 * - onInsert($request,$roo) - after insert
41 * - toEventString (for logging - this is generically prefixed to all database operations.)
44 class Pman_Roo extends Pman
47 * if set to an array (when extending this, then you can restrict which tables are available
49 var $validTables = false;
51 var $key; // used by update currenly to store primary key.
54 parent::getAuth(); // load company!
55 $au = $this->getAuthUser();
57 $this->jerr("Not authenticated", array('authFailure' => true));
59 $this->authUser = $au;
63 * GET method Roo/TABLENAME.php
65 * Generally for SELECT or Single SELECT
68 * _id=value single fetch based on primary id.
69 * lookup[key]=value single fetch based on a single key value lookup.
70 * multiple key/value can be used. eg. ontable+onid..
71 * _columns what to return.
76 * _columns=a,b,c,d comma seperated list of columns.
77 * _distinct=name a distinct column lookup.
80 * !colname=.... => colname != ....
81 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
82 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
85 * sort=name what to sort.
86 * sort=a,b,d can support multiple columns
87 * dir=ASC what direction
88 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
92 * limit=25 limit number
96 * csvCols[0] csvCols[1].... = .... column titles for CSV output
97 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
100 * _toggleActive !:!:!:! - this hsould not really be here..
101 * query[add_blank] - add a line in with an empty option... - not really needed???
104 * _post = simulate a post with debuggin on.
105 * _delete = delete a list of ids element. (depricated.. this will be removed...)
106 * _debug = turn on DB_dataobject deubbing, must be admin at present..
109 * CALLS methods on dataobjects if they exist
110 * checkPerm('S' , $authuser)
111 * - can we list the stuff
112 * - return false to disallow...
113 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
114 * -- does not support multisort at present..
115 * applyFilters($_REQUEST, $authUser, $roo)
116 * -- apply any query filters on data. and hide stuff not to be seen.
117 * -- can exit by calling $roo->jerr()
118 * postListExtra($_REQUEST) : array(extra_name => data)
119 * - add extra column data on the results (like new messages etc.)
120 * postListFilter($data, $authUser, $request) return $data
121 * - add extra data to an object
123 * toRooSingleArray($authUser, $request) : array
124 * - called on single fetch only, add or maniuplate returned array data.
125 * toRooArray($request) : array
126 * - called if singleArray is unavailable on single fetch.
127 * - always tried for mutiple results.
129 * - standard DataObject feature - causes all results to show all
134 // $this->jerr("Not authenticated", array('authFailure' => true));
135 //echo '<PRE>';print_R($_GET);
136 //DB_DataObject::debuglevel(1);
138 $this->init(); // from pman.
139 //DB_DataObject::debuglevel(1);
140 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
146 if (!empty($_GET['_post'])) {
148 //DB_DAtaObject::debuglevel(1);
149 return $this->post($tab);
152 if (isset($_REQUEST['_debug']) && in_array('Administrators', $this->authUser->groups('name'))) {
153 DB_DAtaObject::debuglevel(1);
156 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
159 $x = $this->dataObject($tab);
161 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
163 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
164 $this->jok($this->selectSingle($x, $_REQUEST['lookup']));
169 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) { // single fetch
170 $this->jok($this->selectSingle($x, $_REQUEST['_id']));
175 if (isset($_REQUEST['_delete'])) {
179 $this->jerr('no key');
182 $this->key = $keys[0];
185 // do we really delete stuff!?!?!?
186 return $this->delete($x,$_REQUEST);
192 if (isset($_REQUEST['_toggleActive'])) {
193 // do we really delete stuff!?!?!?
194 if (!$this->hasPerm("Core.Staff", 'E')) {
195 $this->jerr("PERMISSION DENIED");
197 $clean = create_function('$v', 'return (int)$v;');
198 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
199 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
200 $this->jerr("you can not disable yourself");
202 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
203 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
204 $this->jok("Updated");
207 //DB_DataObject::debugLevel(1);
208 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
209 $this->jerr("PERMISSION DENIED");
212 // sets map and countWhat
213 $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct']);
215 $this->setFilters($x,$_REQUEST);
218 // build join if req.
219 //DB_DataObject::debugLevel(1);
220 $total = $x->count($this->countWhat);
223 //var_dump($total);exit;
224 $this->applySort($x);
229 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
230 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 5000)
233 $queryObj = clone($x);
234 //DB_DataObject::debuglevel(1);
235 if (false === $x->find()) {
236 $this->jerr($x->_lastError->toString());
244 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
247 if (!empty($_REQUEST['query']['add_blank'])) {
248 $ret[] = array( 'id' => 0, 'name' => '----');
252 $rooar = method_exists($x, 'toRooArray');
253 $_columnsf = $_columns ? array_flip($_columns) : false;
254 while ($x->fetch()) {
256 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
258 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
261 if (method_exists($queryObj ,'postListExtra')) {
262 $extra = $queryObj->postListExtra($_REQUEST, $this);
266 // filter results, and add any data that is needed...
267 if (method_exists($x,'postListFilter')) {
268 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
273 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
274 header('Content-type: text/csv');
276 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
277 //header('Content-type: text/plain');
278 $fh = fopen('php://output', 'w');
279 fputcsv($fh, $_REQUEST['csvTitles']);
282 foreach($ret as $x) {
283 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
285 foreach($_REQUEST['csvCols'] as $k) {
286 $line[] = isset($x[$k]) ? $x[$k] : '';
297 //if ($x->tableName() == 'Documents_Tracking') {
298 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
303 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
304 $meta = $this->meta($x, $ret);
306 $extra['metaData'] = $meta;
310 // echo "<PRE>"; print_r($ret);
311 $this->jdata($ret, max(count($ret), $total), $extra );
317 * POST method Roo/TABLENAME
318 * -- creates, updates, or deletes data.
321 * if the primary key is empty, this happens
322 * will automatically set these to current date and authUser->id
323 * created, created_by, created_dt
324 * updated, update_by, updated_dt
325 * modified, modified_by, modified_dt
327 * will return a GET request SINGLE SELECT (and accepts same)
330 * _delete=1,2,3 delete a set of data.
332 * if the primary key value is set, then update occurs.
333 * will automatically set these to current date and authUser->id
334 * updated, update_by, updated_dt
335 * modified, modified_by, modified_dt
339 * _delete=1,2,3 causes a delete to occur.
340 * _ids=1,2,3,4 causes update to occur on all primary ids.
343 * = same as single SELECT GET request..
348 * _debug=1 forces debug
349 * _get=1 - causes a get request to occur when doing a POST..
353 * these methods on dataobjects if they exist
355 * checkPerm('E' / 'D' , $authuser)
356 * - can we list the stuff
357 * - return false to disallow...
359 * toRooSingleArray($authUser, $request) : array
360 * - called on single fetch only, add or maniuplate returned array data.
361 * toRooArray($request) : array
362 * - Called if toSingleArray does not exist.
363 * - if you need to return different data than toArray..
366 * (for logging - this is generically prefixed to all database operations.)
370 * called when $_FILES is not empty
373 * setFromRoo($ar, $roo)
374 * - alternative to setFrom() which is called if this method does not exist
375 * - values from post (deal with dates etc.) - return true|error string.
376 * - call $roo->jerr() on failure...
378 * CALLS BEFORE change occurs:
380 * beforeDelete($dependants_array, $roo)
381 * Argument is an array of un-find/fetched dependant items.
382 * - jerr() will stop insert.. (Prefered)
383 * - return false for fail and set DO->err;
385 * beforeUpdate($old, $request,$roo)
386 * - after update - jerr() will stop insert..
387 * beforeInsert($request,$roo)
388 * - before insert - jerr() will stop insert..
390 * CALLS AFTER change occured
392 * onUpdate($old, $request,$roo)
393 * - after update // return value ignored
395 * onInsert($request,$roo)
402 function post($tab) // update / insert (?? delete??)
405 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
408 //DB_DataObject::debugLevel(1);
409 if (!empty($_REQUEST['_debug'])) {
410 DB_DataObject::debugLevel(1);
413 if (!empty($_REQUEST['_get'])) {
414 return $this->get($tab);
418 $x = $this->dataObject($tab);
419 // find the key and use that to get the thing..
422 $this->jerr('no key');
425 $this->key = $keys[0];
427 // delete should be here...
428 if (isset($_REQUEST['_delete'])) {
429 // do we really delete stuff!?!?!?
430 return $this->delete($x,$_REQUEST);
436 // not sure if this is a good idea here...
438 if (!empty($_REQUEST['_ids'])) {
439 $ids = explode(',',$_REQUEST['_ids']);
440 $x->whereAddIn($this->key, $ids, 'int');
441 $ar = $x->fetchAll();
443 $this->update($x, $_REQUEST);
447 $this->jok("UPDATED");
452 if (!empty($_REQUEST[$this->key])) {
454 if (!$x->get($this->key, $_REQUEST[$this->key])) {
455 $this->jerr("Invalid request");
457 $this->jok($this->update($x, $_REQUEST));
461 $this->jerr("No data recieved for inserting");
464 $this->jok($this->insert($x, $_REQUEST));
476 * apply REQUEST[sort] and [dir]
477 * sort may be an array of columsn..
479 * @arg DB_DataObject $x
482 function applySort($x, $sort = '', $dir ='')
485 // Db_DataObject::debugLevel(1);
486 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
487 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
488 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
490 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
492 if (method_exists($x, 'applySort')) {
493 $sorted = $x->applySort(
497 array_keys($this->cols),
498 $ms ? json_decode($ms) : false
502 return $this->multiSort($x);
505 if ($sorted === false) {
508 $sort_ar = explode(',', $sort);
511 foreach($sort_ar as $sort) {
513 if (strlen($sort) && isset($cols[$sort]) ) {
514 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
516 } else if (in_array($sort, array_keys($this->cols))) {
517 $sort_str[] = $sort . ' ' . $dir ;
522 $x->orderBy(implode(', ', $sort_str ));
527 function multiSort($x)
529 //DB_DataObject::debugLevel(1);
530 $ms = json_decode($_REQUEST['_multisort']);
535 foreach($ms->order as $col) {
536 if (!isset($ms->sort->{$col})) {
537 continue; // no direction..
539 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
541 if (strlen($col) && isset($cols[$col]) ) {
542 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
544 } else if (in_array($col, array_keys($this->cols))) {
545 $sort_str[] = $col. ' ' . $ms->sort->{$col};
550 $x->orderBy(implode(', ', $sort_str ));
559 function selectSingle($x, $id)
565 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
567 if (!is_array($id) && empty($id)) {
568 $this->jok($x->toArray()); // return an empty array!
571 $this->loadMap($x, $_columns);
575 $x->setFrom($_REQUEST['lookup'] );
577 if (!$x->find(true)) {
581 } else if (!$x->get($id)) {
582 $this->jerr("no such record");
585 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
586 $this->jerr("PERMISSION DENIED");
589 $m = method_exists($x, 'toRooSingleArray') ? 'toRooSingleArray' : false;
590 $m = !$m && method_exists($x, 'toRooArray') ? 'toRooArray' : $m;
591 $m = $m ? $m : 'toArray';
593 $this->jok($m == 'toArray' ? $x->toArray() : $x->$m($this->authUser, $_REQUEST) );
598 function insert($x, $req)
605 if (method_exists($x, 'setFromRoo')) {
606 $res = $x->setFromRoo($req, $this);
607 if (is_string($res)) {
614 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
615 $this->jerr("PERMISSION DENIED");
619 if (isset($cols['created'])) {
620 $x->created = date('Y-m-d H:i:s');
622 if (isset($cols['created_dt'])) {
623 $x->created_dt = date('Y-m-d H:i:s');
625 if (isset($cols['created_by'])) {
626 $x->created_by = $this->authUser->id;
630 if (isset($cols['modified'])) {
631 $x->modified = date('Y-m-d H:i:s');
633 if (isset($cols['modified_dt'])) {
634 $x->modified_dt = date('Y-m-d H:i:s');
636 if (isset($cols['modified_by'])) {
637 $x->modified_by = $this->authUser->id;
640 if (isset($cols['updated'])) {
641 $x->updated = date('Y-m-d H:i:s');
643 if (isset($cols['updated_dt'])) {
644 $x->updated_dt = date('Y-m-d H:i:s');
646 if (isset($cols['updated_by'])) {
647 $x->updated_by = $this->authUser->id;
651 if (method_exists($x, 'beforeInsert')) {
652 $x->beforeInsert($_REQUEST, $this);
657 if ($res === false) {
658 $this->jerr($x->_lastError->toString());
660 if (method_exists($x, 'onInsert')) {
661 $x->onInsert($_REQUEST, $this);
663 $ev = $this->addEvent("ADD", $x);
668 // note setFrom might handle this before hand...!??!
669 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
673 return $this->selectSingle(
674 DB_DataObject::factory($x->tableName()),
681 function update($x, $req)
683 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
684 $this->jerr("PERMISSION DENIED");
688 // only done if we recieve a lock_id.
689 // we are very trusing here.. that someone has not messed around with locks..
690 // the object might want to check in their checkPerm - if locking is essential..
691 $lock_warning = false;
692 $lock = DB_DataObjecT::factory('Core_locking');
693 if (is_a($lock,'DB_DataObject')) {
695 $lock->on_id = $x->{$this->key};
696 $lock->on_table= $x->tableName();
697 if (!empty($_REQUEST['_lock_id'])) {
698 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
700 $lock->whereAdd('person_id !=' . $this->authUser->id);
704 if ($lock->find(true)) {
705 // it's locked by someone else..
706 $p = $lock->person();
707 $lock_warning = "Record was locked by " . $p->name . " at " .$lock->created.
708 " - Your changes have been saved - you may like to warn them if " .
709 " they are editing now";
711 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
712 // edit it anyways...
725 // this lot is generic.. needs moving
726 if (method_exists($x, 'setFromRoo')) {
727 $res = $x->setFromRoo($req, $this);
728 if (is_string($res)) {
734 $ev = $this->addEvent("EDIT", $x);
735 $ev->audit($x, $old);
741 if (isset($cols['modified'])) {
742 $x->modified = date('Y-m-d H:i:s');
744 if (isset($cols['modified_dt'])) {
745 $x->modified_dt = date('Y-m-d H:i:s');
747 if (isset($cols['modified_by'])) {
748 $x->modified_by = $this->authUser->id;
751 if (isset($cols['updated'])) {
752 $x->updated = date('Y-m-d H:i:s');
754 if (isset($cols['updated_dt'])) {
755 $x->updated_dt = date('Y-m-d H:i:s');
757 if (isset($cols['updated_by'])) {
758 $x->updated_by = $this->authUser->id;
761 if (method_exists($x, 'beforeUpdate')) {
762 $x->beforeUpdate($old, $req, $this);
765 //DB_DataObject::DebugLevel(1);
766 $res = $x->update($old);
767 if ($res === false) {
768 $this->jerr($x->_lastError->toString());
771 if (method_exists($x, 'onUpdate')) {
772 $x->onUpdate($old, $req, $this);
777 $this->jerr($lock_warning);
780 return $this->selectSingle(
781 DB_DataObject::factory($x->tableName()),
787 * Delete a number of records.
788 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects)
792 function delete($x, $req)
794 // do we really delete stuff!?!?!?
795 if (empty($req['_delete'])) {
796 $this->jerr("Delete Requested with no value");
798 // build a list of tables to queriy for dependant data..
803 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
804 foreach($all_links as $tbl => $links) {
805 foreach($links as $col => $totbl_col) {
806 $to = explode(':', $totbl_col);
807 if ($to[0] != $x->tableName()) {
811 $affects[$tbl .'.' . $col] = true;
816 // echo '<PRE>';print_r($affects);exit;
817 //DB_Dataobject::debugLevel(1);
820 $clean = create_function('$v', 'return (int)$v;');
822 $bits = array_map($clean, explode(',', $req['_delete']));
824 // print_r($bits);exit;
826 // let's assume it has a key!!!
829 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
831 $this->jerr("Nothing found to delete");
834 while ($x->fetch()) {
840 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
841 $this->jerr("PERMISSION DENIED");
845 foreach($affects as $k=> $true) {
846 $ka = explode('.', $k);
848 $chk = DB_DataObject::factory($ka[0]);
849 if (!is_a($chk,'DB_DataObject')) {
850 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
852 $chk->{$ka[1]} = $xx->{$this->key};
854 if (count($chk->keys())) {
855 $matches = $chk->count();
857 //DB_DataObject::DebugLevel(1);
858 $matches = $chk->count($ka[1]);
862 $match_ar[] = clone($chk);
867 $has_beforeDelete = method_exists($xx, 'beforeDelete');
868 // before delte = allows us to trash dependancies if needed..
871 if ( method_exists($xx, 'beforeDelete') ) {
872 if ($xx->beforeDelete($match_ar, $this) === false) {
873 $errs[] = "Delete failed ({$xx->id})\n".
874 (isset($xx->err) ? $xx->err : '');
880 foreach($affects as $k=> $true) {
881 $ka = explode('.', $k);
882 $chk = DB_DataObject::factory($ka[0]);
883 if (!is_a($chk,'DB_DataObject')) {
884 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
886 $chk->{$ka[1]} = $xx->{$this->key};
887 $matches = $chk->count();
888 $match_total += $matches;
890 $match_ar[] = clone($chk);
900 if (!empty($match_ar)) {
903 $o = $chk->fetchAll();
905 $desc = $chk->tableName(). '.' . $key .'='.$xx->$key ;
906 if (method_exists($chk, 'toEventString')) {
907 $desc .= ' : ' . $o[0]->toEventString();
910 $this->jerr("Delete Dependant records ($match_total found), " .
911 "first is ( $desc )");
918 $this->addEvent("DELETE", $x);
923 $this->jerr(implode("\n<BR>", $errs));
925 $this->jok("Deleted");
933 function loadMap($do, $filter=false, $distinct = false)
935 //DB_DataObject::debugLevel(1);
937 $this->countWhat = false;
943 $mods = explode(',',$this->appModules);
945 $ff = HTML_FlexyFramework::get();
952 $tabdef = $do->table();
953 if (isset($tabdef['passwd'])) {
954 // prevent exposure of passwords..
955 unset($tabdef['passwd']);
958 $xx = array_keys($tabdef);
959 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
961 $selectAs = array(array( $xx , '%s', false));
963 $has_distinct = false;
964 if ($filter || $distinct) {
966 //echo '<PRE>' ;print_r($filter);exit;
968 if ($distinct && $distinct == $c) {
969 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
970 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
973 if (!$filter || in_array($c, $filter)) {
979 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
985 $this->cols = array();
986 $this->colsJoinName =array();
988 $this->cols[$k] = $do->tableName(). '.' . $k;
996 foreach($map as $ocl=>$info) {
998 list($tab,$col) = explode(':', $info);
999 // what about multiple joins on the same table!!!
1000 $xx = DB_DataObject::factory($tab);
1001 if (!is_a($xx, 'DB_DataObject')) {
1004 // this is borked ... for multiple jions..
1005 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
1006 $tabdef = $xx->table();
1007 $table = $xx->tableName();
1008 if (isset($tabdef['passwd'])) {
1010 unset($tabdef['passwd']);
1013 $xx = array_keys($tabdef);
1016 if ($filter || $distinct) {
1018 foreach($xx as $c) {
1019 $tn = sprintf($ocl.'_%s', $c);
1020 // echo '<PRE>'; var_dump($tn);
1021 if ($distinct && $tn == $distinct) {
1022 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
1023 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
1028 if (!$filter || in_array($tn, $filter)) {
1032 if (!empty($cols)) {
1033 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
1038 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
1043 foreach($xx as $k) {
1044 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
1045 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
1051 if ($has_distinct) {
1052 $do->selectAdd($has_distinct);
1055 // we do select as after everything else as we need to plop distinct at the beginning??
1057 // echo '<PRE>';print_r($this->colsJname);exit;
1058 foreach($selectAs as $ar) {
1059 $do->selectAs($ar[0], $ar[1], $ar[2]);
1065 * generate the meta data neede by queries.
1068 function meta($x, $data)
1070 // this is not going to work on queries where the data does not match the database def..
1071 // for unknown columns we send them as stirngs..
1073 $cols = array_keys($data[0]);
1078 //echo '<PRE>';print_r($this->cols); exit;
1079 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1080 $reader = $options["ini_{$x->_database}"] .'.reader';
1081 if (!file_exists( $reader )) {
1085 $rdata = unserialize(file_get_contents($reader));
1087 // echo '<PRE>';print_r($rdata);exit;
1090 foreach($cols as $c ) {
1091 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1095 $add = $rdata[$this->cols[$c]];
1100 'totalProperty' => 'total',
1101 'successProperty' => 'success',
1110 function setFilters($x, $q)
1112 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1113 // DB_DataObject::debugLevel(1);
1114 if (method_exists($x, 'applyFilters')) {
1115 // DB_DataObject::debugLevel(1);
1116 $x->applyFilters($q, $this->authUser, $this);
1118 $q_filtered = array();
1120 foreach($q as $key=>$val) {
1122 // value is an array..
1123 if (is_array($val) ) {
1127 if ($key[0] == '!') {
1129 $key = substr($key,1);
1132 if (!in_array( $key, array_keys($this->cols))) {
1136 // support a[0] a[1] ..... => whereAddIn(
1139 foreach($val as $k=>$v) {
1140 if (!is_numeric($k)) {
1144 // FIXME: note this is not typesafe for anything other than mysql..
1146 if (!is_numeric($v) || !is_long($v)) {
1155 $x->whereAddIn($pref . (
1156 isset($this->colsJname[$key]) ?
1157 $this->colsJname[$key] :
1158 ($x->tableName(). '.'.$key)),
1159 $ar, $quote ? 'string' : 'int');
1167 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1169 $key = substr($key, 1) ;
1172 isset($this->colsJname[$key]) ?
1173 $this->colsJname[$key] :
1174 $x->tableName(). '.'.$key ) . ' != ' .
1175 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1185 // Events and remarks -- fixme - move to events/remarsk...
1186 case 'on_id': // where TF is this used...
1187 if (!empty($q['query']['original'])) {
1188 // DB_DataObject::debugLevel(1);
1189 $o = (int) $q['query']['original'];
1191 $x->whereAdd("(on_id = $oid OR
1192 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1202 $q_filtered[$key] = $val;
1205 // subjoined columns = check the values.
1206 // note this is not typesafe for anything other than mysql..
1208 if (isset($this->colsJname[$key])) {
1210 if (!is_numeric($val) || !is_long($val)) {
1213 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1222 $x->setFrom($q_filtered);
1227 // nice generic -- let's get rid of it.. where is it used!!!!
1229 // Person / Group / most of my queries noww...
1230 if (!empty($q['query']['name'])) {
1231 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1234 // - projectdirectory staff list - persn queuy
1239 * create the dataobject from (usually the url)
1240 * This uses $this->validTables
1241 * $this->validPrefix (later..)
1242 * to determine if class can be created..
1246 function dataObject($tab)
1248 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1249 $this->jerr("Invalid url");
1251 $tab = str_replace('/', '',$tab); // basic protection??
1253 $x = DB_DataObject::factory($tab);
1255 if (!is_a($x, 'DB_DataObject')) {
1256 $this->jerr('invalid url');
1263 function onPearError($err)
1265 static $reported = false;
1270 $out = $err->toString();
1273 //print_R($bt); exit;
1276 foreach($err->backtrace as $b) {
1277 $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' . @$b['class'] . '::' . @$b['function'];
1283 //convert the huge backtrace into something that is readable..
1284 $out .= "\n" . implode("\n", $ret);