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((int)$_REQUEST['_debug']);
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);
262 if (method_exists($queryObj ,'postListExtra')) {
263 $extra = $queryObj->postListExtra($_REQUEST, $this);
267 // filter results, and add any data that is needed...
268 if (method_exists($x,'postListFilter')) {
269 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
274 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
275 header('Content-type: text/csv');
277 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
278 //header('Content-type: text/plain');
279 $fh = fopen('php://output', 'w');
280 fputcsv($fh, $_REQUEST['csvTitles']);
283 foreach($ret as $x) {
284 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
286 foreach($_REQUEST['csvCols'] as $k) {
287 $line[] = isset($x[$k]) ? $x[$k] : '';
298 //if ($x->tableName() == 'Documents_Tracking') {
299 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
304 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
305 $meta = $this->meta($x, $ret);
307 $extra['metaData'] = $meta;
311 // echo "<PRE>"; print_r($ret);
312 $this->jdata($ret, max(count($ret), $total), $extra );
318 * POST method Roo/TABLENAME
319 * -- creates, updates, or deletes data.
322 * if the primary key is empty, this happens
323 * will automatically set these to current date and authUser->id
324 * created, created_by, created_dt
325 * updated, update_by, updated_dt
326 * modified, modified_by, modified_dt
328 * will return a GET request SINGLE SELECT (and accepts same)
331 * _delete=1,2,3 delete a set of data.
333 * if the primary key value is set, then update occurs.
334 * will automatically set these to current date and authUser->id
335 * updated, update_by, updated_dt
336 * modified, modified_by, modified_dt
340 * _delete=1,2,3 causes a delete to occur.
341 * _ids=1,2,3,4 causes update to occur on all primary ids.
344 * = same as single SELECT GET request..
349 * _debug=1 forces debug
350 * _get=1 - causes a get request to occur when doing a POST..
354 * these methods on dataobjects if they exist
356 * checkPerm('E' / 'D' , $authuser)
357 * - can we list the stuff
358 * - return false to disallow...
360 * toRooSingleArray($authUser, $request) : array
361 * - called on single fetch only, add or maniuplate returned array data.
362 * toRooArray($request) : array
363 * - Called if toSingleArray does not exist.
364 * - if you need to return different data than toArray..
367 * (for logging - this is generically prefixed to all database operations.)
371 * called when $_FILES is not empty
374 * setFromRoo($ar, $roo)
375 * - alternative to setFrom() which is called if this method does not exist
376 * - values from post (deal with dates etc.) - return true|error string.
377 * - call $roo->jerr() on failure...
379 * CALLS BEFORE change occurs:
381 * beforeDelete($dependants_array, $roo)
382 * Argument is an array of un-find/fetched dependant items.
383 * - jerr() will stop insert.. (Prefered)
384 * - return false for fail and set DO->err;
386 * beforeUpdate($old, $request,$roo)
387 * - after update - jerr() will stop insert..
388 * beforeInsert($request,$roo)
389 * - before insert - jerr() will stop insert..
391 * CALLS AFTER change occured
393 * onUpdate($old, $request,$roo)
394 * - after update // return value ignored
396 * onInsert($request,$roo)
403 function post($tab) // update / insert (?? delete??)
406 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
409 //DB_DataObject::debugLevel(1);
410 if (!empty($_REQUEST['_debug'])) {
411 DB_DataObject::debugLevel(1);
414 if (!empty($_REQUEST['_get'])) {
415 return $this->get($tab);
419 $x = $this->dataObject($tab);
420 // find the key and use that to get the thing..
423 $this->jerr('no key');
426 $this->key = $keys[0];
428 // delete should be here...
429 if (isset($_REQUEST['_delete'])) {
430 // do we really delete stuff!?!?!?
431 return $this->delete($x,$_REQUEST);
437 // not sure if this is a good idea here...
439 if (!empty($_REQUEST['_ids'])) {
440 $ids = explode(',',$_REQUEST['_ids']);
441 $x->whereAddIn($this->key, $ids, 'int');
442 $ar = $x->fetchAll();
444 $this->update($x, $_REQUEST);
448 $this->jok("UPDATED");
453 if (!empty($_REQUEST[$this->key])) {
455 if (!$x->get($this->key, $_REQUEST[$this->key])) {
456 $this->jerr("Invalid request");
458 $this->jok($this->update($x, $_REQUEST));
462 $this->jerr("No data recieved for inserting");
465 $this->jok($this->insert($x, $_REQUEST));
477 * apply REQUEST[sort] and [dir]
478 * sort may be an array of columsn..
480 * @arg DB_DataObject $x
483 function applySort($x, $sort = '', $dir ='')
486 // Db_DataObject::debugLevel(1);
487 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
488 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
489 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
491 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
493 if (method_exists($x, 'applySort')) {
494 $sorted = $x->applySort(
498 array_keys($this->cols),
499 $ms ? json_decode($ms) : false
503 return $this->multiSort($x);
506 if ($sorted === false) {
509 $sort_ar = explode(',', $sort);
512 foreach($sort_ar as $sort) {
514 if (strlen($sort) && isset($cols[$sort]) ) {
515 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
517 } else if (in_array($sort, array_keys($this->cols))) {
518 $sort_str[] = $sort . ' ' . $dir ;
523 $x->orderBy(implode(', ', $sort_str ));
528 function multiSort($x)
530 //DB_DataObject::debugLevel(1);
531 $ms = json_decode($_REQUEST['_multisort']);
536 foreach($ms->order as $col) {
537 if (!isset($ms->sort->{$col})) {
538 continue; // no direction..
540 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
542 if (strlen($col) && isset($cols[$col]) ) {
543 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
545 } else if (in_array($col, array_keys($this->cols))) {
546 $sort_str[] = $col. ' ' . $ms->sort->{$col};
551 $x->orderBy(implode(', ', $sort_str ));
560 function selectSingle($x, $id)
566 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
568 if (!is_array($id) && empty($id)) {
569 $this->jok($x->toArray()); // return an empty array!
572 $this->loadMap($x, $_columns);
574 $this->setFilters($x, $_REQUEST);
578 $x->setFrom($_REQUEST['lookup'] );
580 if (!$x->find(true)) {
584 } else if (!$x->get($id)) {
585 $this->jerr("no such record");
588 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
589 $this->jerr("PERMISSION DENIED");
592 $m = method_exists($x, 'toRooSingleArray') ? 'toRooSingleArray' : false;
593 $m = !$m && method_exists($x, 'toRooArray') ? 'toRooArray' : $m;
594 $m = $m ? $m : 'toArray';
596 $this->jok($m == 'toArray' ? $x->toArray() : $x->$m($this->authUser, $_REQUEST) );
601 function insert($x, $req)
608 if (method_exists($x, 'setFromRoo')) {
609 $res = $x->setFromRoo($req, $this);
610 if (is_string($res)) {
617 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
618 $this->jerr("PERMISSION DENIED");
622 if (isset($cols['created'])) {
623 $x->created = date('Y-m-d H:i:s');
625 if (isset($cols['created_dt'])) {
626 $x->created_dt = date('Y-m-d H:i:s');
628 if (isset($cols['created_by'])) {
629 $x->created_by = $this->authUser->id;
633 if (isset($cols['modified'])) {
634 $x->modified = date('Y-m-d H:i:s');
636 if (isset($cols['modified_dt'])) {
637 $x->modified_dt = date('Y-m-d H:i:s');
639 if (isset($cols['modified_by'])) {
640 $x->modified_by = $this->authUser->id;
643 if (isset($cols['updated'])) {
644 $x->updated = date('Y-m-d H:i:s');
646 if (isset($cols['updated_dt'])) {
647 $x->updated_dt = date('Y-m-d H:i:s');
649 if (isset($cols['updated_by'])) {
650 $x->updated_by = $this->authUser->id;
654 if (method_exists($x, 'beforeInsert')) {
655 $x->beforeInsert($_REQUEST, $this);
660 if ($res === false) {
661 $this->jerr($x->_lastError->toString());
663 if (method_exists($x, 'onInsert')) {
664 $x->onInsert($_REQUEST, $this);
666 $ev = $this->addEvent("ADD", $x);
671 // note setFrom might handle this before hand...!??!
672 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
676 return $this->selectSingle(
677 DB_DataObject::factory($x->tableName()),
684 function update($x, $req)
686 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
687 $this->jerr("PERMISSION DENIED");
691 // only done if we recieve a lock_id.
692 // we are very trusing here.. that someone has not messed around with locks..
693 // the object might want to check in their checkPerm - if locking is essential..
694 $lock_warning = false;
695 $lock = DB_DataObjecT::factory('Core_locking');
696 if (is_a($lock,'DB_DataObject')) {
698 $lock->on_id = $x->{$this->key};
699 $lock->on_table= $x->tableName();
700 if (!empty($_REQUEST['_lock_id'])) {
701 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
703 $lock->whereAdd('person_id !=' . $this->authUser->id);
707 if ($lock->find(true)) {
708 // it's locked by someone else..
709 $p = $lock->person();
710 $lock_warning = "Record was locked by " . $p->name . " at " .$lock->created.
711 " - Your changes have been saved - you may like to warn them if " .
712 " they are editing now";
714 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
715 // edit it anyways...
728 // this lot is generic.. needs moving
729 if (method_exists($x, 'setFromRoo')) {
730 $res = $x->setFromRoo($req, $this);
731 if (is_string($res)) {
737 $ev = $this->addEvent("EDIT", $x);
738 $ev->audit($x, $old);
744 if (isset($cols['modified'])) {
745 $x->modified = date('Y-m-d H:i:s');
747 if (isset($cols['modified_dt'])) {
748 $x->modified_dt = date('Y-m-d H:i:s');
750 if (isset($cols['modified_by'])) {
751 $x->modified_by = $this->authUser->id;
754 if (isset($cols['updated'])) {
755 $x->updated = date('Y-m-d H:i:s');
757 if (isset($cols['updated_dt'])) {
758 $x->updated_dt = date('Y-m-d H:i:s');
760 if (isset($cols['updated_by'])) {
761 $x->updated_by = $this->authUser->id;
764 if (method_exists($x, 'beforeUpdate')) {
765 $x->beforeUpdate($old, $req, $this);
768 //DB_DataObject::DebugLevel(1);
769 $res = $x->update($old);
770 if ($res === false) {
771 $this->jerr($x->_lastError->toString());
774 if (method_exists($x, 'onUpdate')) {
775 $x->onUpdate($old, $req, $this);
780 $this->jerr($lock_warning);
783 return $this->selectSingle(
784 DB_DataObject::factory($x->tableName()),
790 * Delete a number of records.
791 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects)
795 function delete($x, $req)
797 // do we really delete stuff!?!?!?
798 if (empty($req['_delete'])) {
799 $this->jerr("Delete Requested with no value");
801 // build a list of tables to queriy for dependant data..
806 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
807 foreach($all_links as $tbl => $links) {
808 foreach($links as $col => $totbl_col) {
809 $to = explode(':', $totbl_col);
810 if ($to[0] != $x->tableName()) {
814 $affects[$tbl .'.' . $col] = true;
819 // echo '<PRE>';print_r($affects);exit;
820 //DB_Dataobject::debugLevel(1);
823 $clean = create_function('$v', 'return (int)$v;');
825 $bits = array_map($clean, explode(',', $req['_delete']));
827 // print_r($bits);exit;
829 // let's assume it has a key!!!
832 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
834 $this->jerr("Nothing found to delete");
837 while ($x->fetch()) {
843 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
844 $this->jerr("PERMISSION DENIED");
848 foreach($affects as $k=> $true) {
849 $ka = explode('.', $k);
851 $chk = DB_DataObject::factory($ka[0]);
852 if (!is_a($chk,'DB_DataObject')) {
853 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
855 $chk->{$ka[1]} = $xx->{$this->key};
857 if (count($chk->keys())) {
858 $matches = $chk->count();
860 //DB_DataObject::DebugLevel(1);
861 $matches = $chk->count($ka[1]);
865 $match_ar[] = clone($chk);
870 $has_beforeDelete = method_exists($xx, 'beforeDelete');
871 // before delte = allows us to trash dependancies if needed..
874 if ( method_exists($xx, 'beforeDelete') ) {
875 if ($xx->beforeDelete($match_ar, $this) === false) {
876 $errs[] = "Delete failed ({$xx->id})\n".
877 (isset($xx->err) ? $xx->err : '');
883 foreach($affects as $k=> $true) {
884 $ka = explode('.', $k);
885 $chk = DB_DataObject::factory($ka[0]);
886 if (!is_a($chk,'DB_DataObject')) {
887 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
889 $chk->{$ka[1]} = $xx->{$this->key};
890 $matches = $chk->count();
891 $match_total += $matches;
893 $match_ar[] = clone($chk);
903 if (!empty($match_ar)) {
906 $o = $chk->fetchAll();
908 $desc = $chk->tableName(). '.' . $key .'='.$xx->$key ;
909 if (method_exists($chk, 'toEventString')) {
910 $desc .= ' : ' . $o[0]->toEventString();
913 $this->jerr("Delete Dependant records ($match_total found), " .
914 "first is ( $desc )");
921 $this->addEvent("DELETE", $x);
926 $this->jerr(implode("\n<BR>", $errs));
928 $this->jok("Deleted");
936 function loadMap($do, $filter=false, $distinct = false)
938 //DB_DataObject::debugLevel(1);
940 $this->countWhat = false;
946 $mods = explode(',',$this->appModules);
948 $ff = HTML_FlexyFramework::get();
955 $tabdef = $do->table();
956 if (isset($tabdef['passwd'])) {
957 // prevent exposure of passwords..
958 unset($tabdef['passwd']);
961 $xx = array_keys($tabdef);
962 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
964 $selectAs = array(array( $xx , '%s', false));
966 $has_distinct = false;
967 if ($filter || $distinct) {
969 //echo '<PRE>' ;print_r($filter);exit;
971 if ($distinct && $distinct == $c) {
972 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
973 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
976 if (!$filter || in_array($c, $filter)) {
982 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
988 $this->cols = array();
989 $this->colsJoinName =array();
991 $this->cols[$k] = $do->tableName(). '.' . $k;
999 foreach($map as $ocl=>$info) {
1001 list($tab,$col) = explode(':', $info);
1002 // what about multiple joins on the same table!!!
1003 $xx = DB_DataObject::factory($tab);
1004 if (!is_a($xx, 'DB_DataObject')) {
1007 // this is borked ... for multiple jions..
1008 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
1009 $tabdef = $xx->table();
1010 $table = $xx->tableName();
1011 if (isset($tabdef['passwd'])) {
1013 unset($tabdef['passwd']);
1016 $xx = array_keys($tabdef);
1019 if ($filter || $distinct) {
1021 foreach($xx as $c) {
1022 $tn = sprintf($ocl.'_%s', $c);
1023 // echo '<PRE>'; var_dump($tn);
1024 if ($distinct && $tn == $distinct) {
1025 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
1026 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
1031 if (!$filter || in_array($tn, $filter)) {
1035 if (!empty($cols)) {
1036 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
1041 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
1046 foreach($xx as $k) {
1047 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
1048 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
1054 if ($has_distinct) {
1055 $do->selectAdd($has_distinct);
1058 // we do select as after everything else as we need to plop distinct at the beginning??
1060 // echo '<PRE>';print_r($this->colsJname);exit;
1061 foreach($selectAs as $ar) {
1062 $do->selectAs($ar[0], $ar[1], $ar[2]);
1068 * generate the meta data neede by queries.
1071 function meta($x, $data)
1073 // this is not going to work on queries where the data does not match the database def..
1074 // for unknown columns we send them as stirngs..
1076 $cols = array_keys($data[0]);
1081 //echo '<PRE>';print_r($this->cols); exit;
1082 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1083 $reader = $options["ini_{$x->_database}"] .'.reader';
1084 if (!file_exists( $reader )) {
1088 $rdata = unserialize(file_get_contents($reader));
1090 // echo '<PRE>';print_r($rdata);exit;
1093 foreach($cols as $c ) {
1094 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1098 $add = $rdata[$this->cols[$c]];
1103 'totalProperty' => 'total',
1104 'successProperty' => 'success',
1113 function setFilters($x, $q)
1115 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1116 // DB_DataObject::debugLevel(1);
1117 if (method_exists($x, 'applyFilters')) {
1118 // DB_DataObject::debugLevel(1);
1119 $x->applyFilters($q, $this->authUser, $this);
1121 $q_filtered = array();
1123 foreach($q as $key=>$val) {
1125 // value is an array..
1126 if (is_array($val) ) {
1130 if ($key[0] == '!') {
1132 $key = substr($key,1);
1135 if (!in_array( $key, array_keys($this->cols))) {
1139 // support a[0] a[1] ..... => whereAddIn(
1142 foreach($val as $k=>$v) {
1143 if (!is_numeric($k)) {
1147 // FIXME: note this is not typesafe for anything other than mysql..
1149 if (!is_numeric($v) || !is_long($v)) {
1158 $x->whereAddIn($pref . (
1159 isset($this->colsJname[$key]) ?
1160 $this->colsJname[$key] :
1161 ($x->tableName(). '.'.$key)),
1162 $ar, $quote ? 'string' : 'int');
1170 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1172 $key = substr($key, 1) ;
1175 isset($this->colsJname[$key]) ?
1176 $this->colsJname[$key] :
1177 $x->tableName(). '.'.$key ) . ' != ' .
1178 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1188 // Events and remarks -- fixme - move to events/remarsk...
1189 case 'on_id': // where TF is this used...
1190 if (!empty($q['query']['original'])) {
1191 // DB_DataObject::debugLevel(1);
1192 $o = (int) $q['query']['original'];
1194 $x->whereAdd("(on_id = $oid OR
1195 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1205 $q_filtered[$key] = $val;
1208 // subjoined columns = check the values.
1209 // note this is not typesafe for anything other than mysql..
1211 if (isset($this->colsJname[$key])) {
1213 if (!is_numeric($val) || !is_long($val)) {
1216 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1225 $x->setFrom($q_filtered);
1230 // nice generic -- let's get rid of it.. where is it used!!!!
1232 // Person / Group / most of my queries noww...
1233 if (!empty($q['query']['name'])) {
1234 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1237 // - projectdirectory staff list - persn queuy
1242 * create the dataobject from (usually the url)
1243 * This uses $this->validTables
1244 * $this->validPrefix (later..)
1245 * to determine if class can be created..
1249 function dataObject($tab)
1251 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1252 $this->jerr("Invalid url");
1254 $tab = str_replace('/', '',$tab); // basic protection??
1256 $x = DB_DataObject::factory($tab);
1258 if (!is_a($x, 'DB_DataObject')) {
1259 $this->jerr('invalid url');
1266 function onPearError($err)
1268 static $reported = false;
1273 $out = $err->toString();
1276 //print_R($bt); exit;
1279 foreach($err->backtrace as $b) {
1280 $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' . @$b['class'] . '::' . @$b['function'];
1286 //convert the huge backtrace into something that is readable..
1287 $out .= "\n" . implode("\n", $ret);