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.
53 var $transObj = false ; // the transaction BEGIN / ROLLBACK / COMMIT Dataobject.
57 parent::getAuth(); // load company!
58 $au = $this->getAuthUser();
60 $this->jerr("Not authenticated", array('authFailure' => true));
62 $this->authUser = $au;
66 * GET method Roo/TABLENAME.php
68 * Generally for SELECT or Single SELECT
71 * _id=value single fetch based on primary id.
72 * can be '0' if you want to fetch a set of defaults
73 * Use in conjuntion with toRooSingleArray()
75 * lookup[key]=value single fetch based on a single key value lookup.
76 * multiple key/value can be used. eg. ontable+onid..
77 * _columns what to return.
82 * _columns=a,b,c,d comma seperated list of columns.
83 * _distinct=name a distinct column lookup.
86 * !colname=.... => colname != ....
87 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
88 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
91 * sort=name what to sort.
92 * sort=a,b,d can support multiple columns
93 * dir=ASC what direction
94 * _multisort ={...} JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
98 * limit=25 limit number
102 * csvCols[0] csvCols[1].... = .... column titles for CSV output
103 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
106 * _toggleActive !:!:!:! - this hsould not really be here..
107 * query[add_blank] - add a line in with an empty option... - not really needed???
110 * _post = simulate a post with debuggin on.
111 * _delete = delete a list of ids element. (depricated.. this will be removed...)
112 * _debug = turn on DB_dataobject deubbing, must be admin at present..
115 * CALLS methods on dataobjects if they exist
118 * checkPerm('S' , $authuser)
119 * - can we list the stuff
120 * - return false to disallow...
121 * applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
122 * -- does not support multisort at present..
123 * applyFilters($_REQUEST, $authUser, $roo)
124 * -- apply any query filters on data. and hide stuff not to be seen.
125 * -- can exit by calling $roo->jerr()
126 * postListExtra($_REQUEST) : array(extra_name => data)
127 * - add extra column data on the results (like new messages etc.)
128 * postListFilter($data, $authUser, $request) return $data
129 * - add extra data to an object
131 * toRooSingleArray($authUser, $request) : array
132 * - called on single fetch only, add or maniuplate returned array data.
133 * - is also called when _id=0 is used (for fetching a default set.)
134 * toRooArray($request) : array
135 * - called if singleArray is unavailable on single fetch.
136 * - always tried for mutiple results.
138 * - standard DataObject feature - causes all results to show all
142 * _extra_cols -- if set, then filtering by column etc. will use them.
148 // $this->jerr("Not authenticated", array('authFailure' => true));
149 //echo '<PRE>';print_R($_GET);
150 //DB_DataObject::debuglevel(1);
152 $this->init(); // from pman.
153 //DB_DataObject::debuglevel(1);
154 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
160 if (!empty($_GET['_post'])) {
162 //DB_DAtaObject::debuglevel(1);
163 return $this->post($tab);
166 if (isset($_REQUEST['_debug']) && in_array('Administrators', $this->authUser->groups('name'))) {
167 DB_DAtaObject::debuglevel((int)$_REQUEST['_debug']);
170 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
173 $x = $this->dataObject($tab);
175 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
177 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
178 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
183 // single fetch (use '0' to fetch an empty object..)
184 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
186 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
193 if (isset($_REQUEST['_delete'])) {
197 $this->jerr('no key');
200 $this->key = $keys[0];
203 // do we really delete stuff!?!?!?
204 return $this->delete($x,$_REQUEST);
210 if (isset($_REQUEST['_toggleActive'])) {
211 // do we really delete stuff!?!?!?
212 if (!$this->hasPerm("Core.Staff", 'E')) {
213 $this->jerr("PERMISSION DENIED");
215 $clean = create_function('$v', 'return (int)$v;');
216 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
217 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
218 $this->jerr("you can not disable yourself");
220 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
221 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
222 $this->jok("Updated");
225 //DB_DataObject::debugLevel(1);
228 // sets map and countWhat
229 $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct']);
231 $this->setFilters($x,$_REQUEST);
233 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
234 $this->jerr("PERMISSION DENIED");
238 // build join if req.
239 //DB_DataObject::debugLevel(1);
240 $total = $x->count($this->countWhat);
243 //var_dump($total);exit;
244 $this->applySort($x);
249 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
250 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 5000)
253 $queryObj = clone($x);
254 //DB_DataObject::debuglevel(1);
255 if (false === $x->find()) {
256 $this->jerr($x->_lastError->toString());
264 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
267 if (!empty($_REQUEST['query']['add_blank'])) {
268 $ret[] = array( 'id' => 0, 'name' => '----');
272 $rooar = method_exists($x, 'toRooArray');
273 $_columnsf = $_columns ? array_flip($_columns) : false;
274 while ($x->fetch()) {
276 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
278 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
282 if (method_exists($queryObj ,'postListExtra')) {
283 $extra = $queryObj->postListExtra($_REQUEST, $this);
287 // filter results, and add any data that is needed...
288 if (method_exists($x,'postListFilter')) {
289 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
294 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
295 header('Content-type: text/csv');
297 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
298 //header('Content-type: text/plain');
299 $fh = fopen('php://output', 'w');
300 fputcsv($fh, $_REQUEST['csvTitles']);
303 foreach($ret as $x) {
304 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
306 foreach($_REQUEST['csvCols'] as $k) {
307 $line[] = isset($x[$k]) ? $x[$k] : '';
318 //if ($x->tableName() == 'Documents_Tracking') {
319 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
324 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
325 $meta = $this->meta($x, $ret);
327 $extra['metaData'] = $meta;
331 // echo "<PRE>"; print_r($ret);
332 $this->jdata($ret, max(count($ret), $total), $extra );
338 * POST method Roo/TABLENAME
339 * -- creates, updates, or deletes data.
342 * if the primary key is empty, this happens
343 * will automatically set these to current date and authUser->id
344 * created, created_by, created_dt
345 * updated, update_by, updated_dt
346 * modified, modified_by, modified_dt
348 * will return a GET request SINGLE SELECT (and accepts same)
351 * _delete=1,2,3 delete a set of data.
353 * if the primary key value is set, then update occurs.
354 * will automatically set these to current date and authUser->id
355 * updated, update_by, updated_dt
356 * modified, modified_by, modified_dt
360 * _delete=1,2,3 causes a delete to occur.
361 * _ids=1,2,3,4 causes update to occur on all primary ids.
364 * = same as single SELECT GET request..
369 * _debug=1 forces debug
370 * _get=1 - causes a get request to occur when doing a POST..
374 * these methods on dataobjects if they exist
376 * checkPerm('E' / 'D' , $authuser)
377 * - can we list the stuff
378 * - return false to disallow...
380 * toRooSingleArray($authUser, $request) : array
381 * - called on single fetch only, add or maniuplate returned array data.
382 * toRooArray($request) : array
383 * - Called if toSingleArray does not exist.
384 * - if you need to return different data than toArray..
387 * (for logging - this is generically prefixed to all database operations.)
391 * called when $_FILES is not empty
394 * setFromRoo($ar, $roo)
395 * - alternative to setFrom() which is called if this method does not exist
396 * - values from post (deal with dates etc.) - return true|error string.
397 * - call $roo->jerr() on failure...
399 * CALLS BEFORE change occurs:
401 * beforeDelete($dependants_array, $roo)
402 * Argument is an array of un-find/fetched dependant items.
403 * - jerr() will stop insert.. (Prefered)
404 * - return false for fail and set DO->err;
406 * beforeUpdate($old, $request,$roo)
407 * - after update - jerr() will stop insert..
408 * beforeInsert($request,$roo)
409 * - before insert - jerr() will stop insert..
411 * CALLS AFTER change occured
413 * onUpdate($old, $request,$roo)
414 * - after update // return value ignored
416 * onInsert($request,$roo)
423 function post($tab) // update / insert (?? delete??)
426 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
429 //DB_DataObject::debugLevel(1);
430 if (!empty($_REQUEST['_debug'])) {
431 DB_DataObject::debugLevel(1);
434 if (!empty($_REQUEST['_get'])) {
435 return $this->get($tab);
439 $x = $this->dataObject($tab);
441 $this->transObj = clone($x);
443 $this->transObj->query('BEGIN');
444 // find the key and use that to get the thing..
447 $this->jerr('no key');
450 $this->key = $keys[0];
452 // delete should be here...
453 if (isset($_REQUEST['_delete'])) {
454 // do we really delete stuff!?!?!?
455 return $this->delete($x,$_REQUEST);
461 // not sure if this is a good idea here...
463 if (!empty($_REQUEST['_ids'])) {
464 $ids = explode(',',$_REQUEST['_ids']);
465 $x->whereAddIn($this->key, $ids, 'int');
466 $ar = $x->fetchAll();
468 $this->update($x, $_REQUEST);
472 $this->jok("UPDATED");
477 if (!empty($_REQUEST[$this->key])) {
479 if (!$x->get($this->key, $_REQUEST[$this->key])) {
480 $this->jerr("Invalid request");
482 $this->jok($this->update($x, $_REQUEST));
486 $this->jerr("No data recieved for inserting");
489 $this->jok($this->insert($x, $_REQUEST));
501 * apply REQUEST[sort] and [dir]
502 * sort may be an array of columsn..
504 * @arg DB_DataObject $x
507 function applySort($x, $sort = '', $dir ='')
510 // Db_DataObject::debugLevel(1);
511 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
512 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
513 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
515 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
517 if (method_exists($x, 'applySort')) {
518 $sorted = $x->applySort(
522 array_keys($this->cols),
523 $ms ? json_decode($ms) : false
527 return $this->multiSort($x);
530 if ($sorted === false) {
533 $excols = array_keys($this->cols);
534 if (isset($x->_extra_cols)) {
535 $excols = array_merge($excols, $x->_extra_cols);
537 $sort_ar = explode(',', $sort);
540 foreach($sort_ar as $sort) {
542 if (strlen($sort) && isset($cols[$sort]) ) {
543 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
545 } else if (in_array($sort, $excols)) {
546 $sort_str[] = $sort . ' ' . $dir ;
551 $x->orderBy(implode(', ', $sort_str ));
556 function multiSort($x)
558 //DB_DataObject::debugLevel(1);
559 $ms = json_decode($_REQUEST['_multisort']);
564 foreach($ms->order as $col) {
565 if (!isset($ms->sort->{$col})) {
566 continue; // no direction..
568 $ms->sort->{$col} = $ms->sort->{$col} == 'ASC' ? 'ASC' : 'DESC';
570 if (strlen($col) && isset($cols[$col]) ) {
571 $sort_str[] = $x->tableName() .'.'.$col . ' ' . $ms->sort->{$col};
573 } else if (in_array($col, array_keys($this->cols))) {
574 $sort_str[] = $col. ' ' . $ms->sort->{$col};
579 $x->orderBy(implode(', ', $sort_str ));
586 * - used when _id is set, or after insert or update
588 * @param DataObject $x the dataobject to use
589 * @param int $id the pid of the object
590 * @param array $req the request, or false if it comes from insert/update.
593 function selectSingle($x, $id, $req=false)
597 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
598 //var_dump(array(!is_array($id) , empty($id)));
599 if (!is_array($id) && empty($id)) {
602 if (method_exists($x, 'toRooSingleArray')) {
603 $this->jok($x->toRooSingleArray($this->authUser, $req));
605 if (method_exists($x, 'toRooArray')) {
606 $this->jok($x->toRooArray($req));
609 $this->jok($x->toArray());
612 $this->loadMap($x, $_columns);
614 if ($req !== false) {
615 $this->setFilters($x, $req);
618 // DB_DataObject::DebugLevel(1);
621 $x->setFrom($req['lookup'] );
623 if (!$x->find(true)) {
627 } else if (!$x->get($id)) {
628 $this->jerr("selectSingle: no such record ($id)");
631 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
632 $this->jerr("PERMISSION DENIED");
634 // different symantics on all these calls??
635 if (method_exists($x, 'toRooSingleArray')) {
636 $this->jok($x->toRooSingleArray($this->authUser, $req));
638 if (method_exists($x, 'toRooArray')) {
639 $this->jok($x->toRooArray($req));
642 $this->jok($x->toArray());
647 function insert($x, $req)
650 if (method_exists($x, 'setFromRoo')) {
651 $res = $x->setFromRoo($req, $this);
652 if (is_string($res)) {
659 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
660 $this->jerr("PERMISSION DENIED");
664 if (isset($cols['created'])) {
665 $x->created = date('Y-m-d H:i:s');
667 if (isset($cols['created_dt'])) {
668 $x->created_dt = date('Y-m-d H:i:s');
670 if (isset($cols['created_by'])) {
671 $x->created_by = $this->authUser->id;
675 if (isset($cols['modified'])) {
676 $x->modified = date('Y-m-d H:i:s');
678 if (isset($cols['modified_dt'])) {
679 $x->modified_dt = date('Y-m-d H:i:s');
681 if (isset($cols['modified_by'])) {
682 $x->modified_by = $this->authUser->id;
685 if (isset($cols['updated'])) {
686 $x->updated = date('Y-m-d H:i:s');
688 if (isset($cols['updated_dt'])) {
689 $x->updated_dt = date('Y-m-d H:i:s');
691 if (isset($cols['updated_by'])) {
692 $x->updated_by = $this->authUser->id;
696 if (method_exists($x, 'beforeInsert')) {
697 $x->beforeInsert($_REQUEST, $this);
702 if ($res === false) {
703 $this->jerr($x->_lastError->toString());
705 if (method_exists($x, 'onInsert')) {
706 $x->onInsert($_REQUEST, $this);
708 $ev = $this->addEvent("ADD", $x);
713 // note setFrom might handle this before hand...!??!
714 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
718 return $this->selectSingle(
719 DB_DataObject::factory($x->tableName()),
726 function update($x, $req)
728 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
729 $this->jerr("PERMISSION DENIED - No Edit permissions on this element");
733 // only done if we recieve a lock_id.
734 // we are very trusing here.. that someone has not messed around with locks..
735 // the object might want to check in their checkPerm - if locking is essential..
737 $lock = DB_DataObjecT::factory('Core_locking');
738 if (is_a($lock,'DB_DataObject')) {
740 $lock->on_id = $x->{$this->key};
741 $lock->on_table= strtolower($x->tableName());
742 if (!empty($_REQUEST['_lock_id'])) {
743 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
745 $lock->whereAdd('person_id !=' . $this->authUser->id);
749 if ($lock->find(true)) {
750 // it's locked by someone else..
751 $p = $lock->person();
754 $this->jerr( "Record was locked by " . $p->name . " at " .$lock->created.
755 " - Please confirm you wish to save"
756 , array('needs_confirm' => true));
760 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
761 // edit it anyways...
763 // can we find the user's lock.
764 $lock = DB_DataObjecT::factory('Core_locking');
765 $lock->on_id = $x->{$this->key};
766 $lock->on_table= strtolower($x->tableName());
767 $lock->person_id = $this->authUser->id;
768 $lock->orderBy('created DESC');
773 isset($x->modified_dt) &&
774 strtotime($x->modified_dt) > strtotime($lock->created) &&
775 empty($req['_submit_confirmed'])
778 $p = DB_DataObject::factory('Person');
779 $p->get($x->modified_by);
780 $this->jerr($p->name . " saved the record since you started editing,\nDo you really want to update it?", array('needs_confirm' => true));
797 // this lot is generic.. needs moving
798 if (method_exists($x, 'setFromRoo')) {
799 $res = $x->setFromRoo($req, $this);
800 if (is_string($res)) {
806 $ev = $this->addEvent("EDIT", $x);
807 $ev->audit($x, $old);
813 if (isset($cols['modified'])) {
814 $x->modified = date('Y-m-d H:i:s');
816 if (isset($cols['modified_dt'])) {
817 $x->modified_dt = date('Y-m-d H:i:s');
819 if (isset($cols['modified_by'])) {
820 $x->modified_by = $this->authUser->id;
823 if (isset($cols['updated'])) {
824 $x->updated = date('Y-m-d H:i:s');
826 if (isset($cols['updated_dt'])) {
827 $x->updated_dt = date('Y-m-d H:i:s');
829 if (isset($cols['updated_by'])) {
830 $x->updated_by = $this->authUser->id;
833 if (method_exists($x, 'beforeUpdate')) {
834 $x->beforeUpdate($old, $req, $this);
837 //DB_DataObject::DebugLevel(1);
838 $res = $x->update($old);
839 if ($res === false) {
840 $this->jerr($x->_lastError->toString());
843 if (method_exists($x, 'onUpdate')) {
844 $x->onUpdate($old, $req, $this);
849 return $this->selectSingle(
850 DB_DataObject::factory($x->tableName()),
856 * Delete a number of records.
857 * calls $delete_obj->beforeDelete($array_of_dependant_dataobjects, $this)
861 function delete($x, $req)
863 // do we really delete stuff!?!?!?
864 if (empty($req['_delete'])) {
865 $this->jerr("Delete Requested with no value");
867 // build a list of tables to queriy for dependant data..
872 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
873 foreach($all_links as $tbl => $links) {
874 foreach($links as $col => $totbl_col) {
875 $to = explode(':', $totbl_col);
876 if ($to[0] != $x->tableName()) {
880 $affects[$tbl .'.' . $col] = true;
885 // echo '<PRE>';print_r($affects);exit;
886 //DB_Dataobject::debugLevel(1);
889 $clean = create_function('$v', 'return (int)$v;');
891 $bits = array_map($clean, explode(',', $req['_delete']));
893 // print_r($bits);exit;
895 // let's assume it has a key!!!
898 $x->whereAdd($this->key .' IN ('. implode(',', $bits) .')');
900 $this->jerr("Nothing found to delete");
903 while ($x->fetch()) {
909 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
910 $this->jerr("PERMISSION DENIED");
914 foreach($affects as $k=> $true) {
915 $ka = explode('.', $k);
917 $chk = DB_DataObject::factory($ka[0]);
918 if (!is_a($chk,'DB_DataObject')) {
919 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
921 $chk->{$ka[1]} = $xx->{$this->key};
923 if (count($chk->keys())) {
924 $matches = $chk->count();
926 //DB_DataObject::DebugLevel(1);
927 $matches = $chk->count($ka[1]);
931 $match_ar[] = clone($chk);
936 $has_beforeDelete = method_exists($xx, 'beforeDelete');
937 // before delte = allows us to trash dependancies if needed..
940 if ( method_exists($xx, 'beforeDelete') ) {
941 if ($xx->beforeDelete($match_ar, $this) === false) {
942 $errs[] = "Delete failed ({$xx->id})\n".
943 (isset($xx->err) ? $xx->err : '');
949 foreach($affects as $k=> $true) {
950 $ka = explode('.', $k);
951 $chk = DB_DataObject::factory($ka[0]);
952 if (!is_a($chk,'DB_DataObject')) {
953 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
955 $chk->{$ka[1]} = $xx->{$this->key};
956 $matches = $chk->count();
957 $match_total += $matches;
959 $match_ar[] = clone($chk);
969 if (!empty($match_ar)) {
972 $o = $chk->fetchAll();
974 $desc = $chk->tableName(). '.' . $key .'='.$xx->$key ;
975 if (method_exists($chk, 'toEventString')) {
976 $desc .= ' : ' . $o[0]->toEventString();
979 $this->jerr("Delete Dependant records ($match_total found), " .
980 "first is ( $desc )");
987 $this->addEvent("DELETE", $x);
992 $this->jerr(implode("\n<BR>", $errs));
994 $this->jok("Deleted");
1000 * cols stores the list of columns that are available from the query.
1005 var $cols = array();
1009 function loadMap($do, $filter=false, $distinct = false)
1011 //DB_DataObject::debugLevel(1);
1013 $this->countWhat = false;
1019 $mods = explode(',',$this->appModules);
1021 $ff = HTML_FlexyFramework::get();
1023 $map = $do->links();
1028 $tabdef = $do->table();
1029 if (isset($tabdef['passwd'])) {
1030 // prevent exposure of passwords..
1031 unset($tabdef['passwd']);
1034 $xx = array_keys($tabdef);
1035 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
1037 $selectAs = array(array( $xx , '%s', false));
1039 $has_distinct = false;
1040 if ($filter || $distinct) {
1042 //echo '<PRE>' ;print_r($filter);exit;
1043 foreach($xx as $c) {
1044 if ($distinct && $distinct == $c) {
1045 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
1046 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
1049 if (!$filter || in_array($c, $filter)) {
1055 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
1061 $this->cols = array();
1062 $this->colsJoinName =array();
1063 foreach($xx as $k) {
1064 $this->cols[$k] = $do->tableName(). '.' . $k;
1072 foreach($map as $ocl=>$info) {
1074 list($tab,$col) = explode(':', $info);
1075 // what about multiple joins on the same table!!!
1076 $xx = DB_DataObject::factory($tab);
1077 if (!is_a($xx, 'DB_DataObject')) {
1080 // this is borked ... for multiple jions..
1081 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
1082 $tabdef = $xx->table();
1083 $table = $xx->tableName();
1084 if (isset($tabdef['passwd'])) {
1086 unset($tabdef['passwd']);
1089 $xx = array_keys($tabdef);
1092 if ($filter || $distinct) {
1094 foreach($xx as $c) {
1095 $tn = sprintf($ocl.'_%s', $c);
1096 // echo '<PRE>'; var_dump($tn);
1097 if ($distinct && $tn == $distinct) {
1098 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
1099 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
1104 if (!$filter || in_array($tn, $filter)) {
1108 if (!empty($cols)) {
1109 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
1114 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
1119 foreach($xx as $k) {
1120 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
1121 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
1127 if ($has_distinct) {
1128 $do->selectAdd($has_distinct);
1131 // we do select as after everything else as we need to plop distinct at the beginning??
1133 // echo '<PRE>';print_r($this->colsJname);exit;
1134 foreach($selectAs as $ar) {
1135 $do->selectAs($ar[0], $ar[1], $ar[2]);
1141 * generate the meta data neede by queries.
1144 function meta($x, $data)
1146 // this is not going to work on queries where the data does not match the database def..
1147 // for unknown columns we send them as stirngs..
1149 $cols = array_keys($data[0]);
1154 //echo '<PRE>';print_r($this->cols); exit;
1155 $options = &PEAR::getStaticProperty('DB_DataObject','options');
1156 $reader = $options["ini_{$x->_database}"] .'.reader';
1157 if (!file_exists( $reader )) {
1161 $rdata = unserialize(file_get_contents($reader));
1163 // echo '<PRE>';print_r($rdata);exit;
1166 foreach($cols as $c ) {
1167 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
1171 $add = $rdata[$this->cols[$c]];
1176 'totalProperty' => 'total',
1177 'successProperty' => 'success',
1186 function setFilters($x, $q)
1188 // if a column is type int, and we get ',' -> the it should be come an inc clause..
1189 // DB_DataObject::debugLevel(1);
1190 if (method_exists($x, 'applyFilters')) {
1191 // DB_DataObject::debugLevel(1);
1192 $x->applyFilters($q, $this->authUser, $this);
1194 $q_filtered = array();
1196 foreach($q as $key=>$val) {
1198 // value is an array..
1199 if (is_array($val) ) {
1203 if ($key[0] == '!') {
1205 $key = substr($key,1);
1208 if (!in_array( $key, array_keys($this->cols))) {
1212 // support a[0] a[1] ..... => whereAddIn(
1215 foreach($val as $k=>$v) {
1216 if (!is_numeric($k)) {
1220 // FIXME: note this is not typesafe for anything other than mysql..
1222 if (!is_numeric($v) || !is_long($v)) {
1231 $x->whereAddIn($pref . (
1232 isset($this->colsJname[$key]) ?
1233 $this->colsJname[$key] :
1234 ($x->tableName(). '.'.$key)),
1235 $ar, $quote ? 'string' : 'int');
1243 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
1245 $key = substr($key, 1) ;
1248 isset($this->colsJname[$key]) ?
1249 $this->colsJname[$key] :
1250 $x->tableName(). '.'.$key ) . ' != ' .
1251 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
1261 // Events and remarks -- fixme - move to events/remarsk...
1262 case 'on_id': // where TF is this used...
1263 if (!empty($q['query']['original'])) {
1264 // DB_DataObject::debugLevel(1);
1265 $o = (int) $q['query']['original'];
1267 $x->whereAdd("(on_id = $oid OR
1268 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
1278 $q_filtered[$key] = $val;
1281 // subjoined columns = check the values.
1282 // note this is not typesafe for anything other than mysql..
1284 if (isset($this->colsJname[$key])) {
1286 if (!is_numeric($val) || !is_long($val)) {
1289 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
1298 $x->setFrom($q_filtered);
1303 // nice generic -- let's get rid of it.. where is it used!!!!
1305 // Person / Group / most of my queries noww...
1306 if (!empty($q['query']['name'])) {
1309 if (in_array( 'name', array_keys($x->table()))) {
1310 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
1314 // - projectdirectory staff list - persn queuy
1319 * create the dataobject from (usually the url)
1320 * This uses $this->validTables
1321 * $this->validPrefix (later..)
1322 * to determine if class can be created..
1326 function dataObject($tab)
1328 if (is_array($this->validTables) && !in_array($tab,$this->validTables)) {
1329 $this->jerr("Invalid url");
1331 $tab = str_replace('/', '',$tab); // basic protection??
1333 $x = DB_DataObject::factory($tab);
1335 if (!is_a($x, 'DB_DataObject')) {
1336 $this->jerr('invalid url');
1343 function onPearError($err)
1345 static $reported = false;
1350 $out = $err->toString();
1353 //print_R($bt); exit;
1356 foreach($err->backtrace as $b) {
1357 $ret[] = @$b['file'] . '(' . @$b['line'] . ')@' . @$b['class'] . '::' . @$b['function'];
1363 //convert the huge backtrace into something that is readable..
1364 $out .= "\n" . implode("\n", $ret);
1372 // our handlers to commit / rollback.
1376 if ($this->transObj) {
1377 $this->transObj->query('COMMIT');
1379 return parent::jok($str);
1383 function jerr($str, $errors=array())
1385 // standard error reporting..
1386 if ($this->transObj) {
1387 $this->transObj->query('ROLLBACK');
1389 return parent::jerr($str);