4 require_once 'Pman.php';
8 * not really sure how save our factory method is....!!!
11 * Uses these methods of the dataobjects:
12 * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
14 * - applySort($au, $sortcol, $direction) -- return false to let system do default sort code.
15 * - applyFilters($_REQUEST, $authUser) -- apply any query filters on data. and hide stuff not to be seen.
16 * - postListExtra($_REQUEST) : array(extra_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 * - beforeDelete() -- return false for fail and set DO->err;
24 * - onUpdate($old, $request,$roo) - after update // return value ignored
25 * - onInsert($request,$roo) - after insert
27 * - setFromRoo($ar) - values from post (deal with dates etc.) - return true|error string.
29 * - toEventString (for logging - this is generically prefixed to all database operations.)
32 class Pman_Roo extends Pman
36 parent::getAuth(); // load company!
37 $au = $this->getAuthUser();
39 $this->jerr("Not authenticated", array('authFailure' => true));
41 $this->authUser = $au;
45 * GET method Roo/TABLENAME.php
46 * -- defaults to listing data. with args.
49 * !colname=.... => colname != ....
50 * !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
51 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
54 * _post = simulate a post with debuggin on.
55 * lookup = array( k=>v) single fetch based on a key/value pair
56 * _id = single fetch based on id.
57 * _delete = delete a list of ids element. (seperated by ,);
58 * _columns = comma seperated list of columns.
59 * _distinct = a distinct column lookup.
60 * _requestMeta = default behaviour of Roo stores.. on first query..
62 * csvCols[0] csvCols[1].... = .... column titles for CSV output
64 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
66 * sort = sort column (',' comma delimited)
67 * dir = sort direction ?? in future comma delimited...
69 * limit = limit number
71 * _toggleActive !:!:!:! - this hsould not really be here..
72 * query[add_blank] - add a line in with an empty option... - not really needed???
77 // $this->jerr("Not authenticated", array('authFailure' => true));
78 //echo '<PRE>';print_R($_GET);
79 //DB_DataObject::debuglevel(1);
81 $this->init(); // from pnan.
83 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
85 if (!empty($_GET['_post'])) {
87 //DB_DAtaObject::debuglevel(1);
88 return $this->post($tab);
90 $tab = str_replace('/', '',$tab); // basic protection??
91 $x = DB_DataObject::factory($tab);
92 if (!is_a($x, 'DB_DataObject')) {
93 $this->jerr('invalid url');
95 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
97 if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
98 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
99 $this->jerr("PERMISSION DENIED");
101 $this->loadMap($x, $_columns);
102 $x->setFrom($_REQUEST['lookup'] );
104 if (!$x->find(true)) {
107 $this->jok($x->toArray());
112 if (isset($_REQUEST['_id'])) { // single fetch
114 if (empty($_REQUEST['_id'])) {
115 $this->jok($x->toArray()); // return an empty array!
118 $this->loadMap($x, $_columns);
120 if (!$x->get($_REQUEST['_id'])) {
121 $this->jerr("no such record");
124 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
125 $this->jerr("PERMISSION DENIED");
128 $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser, $_REQUEST) : $x->toArray());
131 if (isset($_REQUEST['_delete'])) {
132 // do we really delete stuff!?!?!?
133 return $this->delete($x,$_REQUEST);
139 if (isset($_REQUEST['_toggleActive'])) {
140 // do we really delete stuff!?!?!?
141 if (!$this->hasPerm("Core.Staff", 'E')) {
142 $this->jerr("PERMISSION DENIED");
144 $clean = create_function('$v', 'return (int)$v;');
145 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
146 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
147 $this->jerr("you can not disable yourself");
149 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
150 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
151 $this->jok("Updated");
154 //DB_DataObject::debugLevel(1);
155 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
156 $this->jerr("PERMISSION DENIED");
159 // sets map and countWhat
160 $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct']);
162 $this->setFilters($x,$_REQUEST);
165 // build join if req.
166 //DB_DataObject::debugLevel(1);
167 $total = $x->count($this->countWhat);
170 //var_dump($total);exit;
171 $this->applySort($x);
176 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
177 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 5000)
180 $queryObj = clone($x);
185 if (!empty($_REQUEST['query']['add_blank'])) {
186 $ret[] = array( 'id' => 0, 'name' => '----');
191 //if (($tab == 'Groups') && ($_REQUEST['type'] != 0)) { // then it's a list of teams..
192 if ($tab == 'Groups') {
194 $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
195 $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
196 //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
202 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
203 header('Content-type: text/csv');
205 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
206 //header('Content-type: text/plain');
207 $fh = fopen('php://output', 'w');
208 fputcsv($fh, $_REQUEST['csvTitles']);
209 while ($x->fetch()) {
210 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
212 foreach($_REQUEST['csvCols'] as $k) {
213 $line[] = isset($x->$k) ? $x->$k : '';
224 $rooar = method_exists($x, 'toRooArray');
226 while ($x->fetch()) {
227 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
229 $ret[] = !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
231 //if ($x->tableName() == 'Documents_Tracking') {
232 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
236 if (method_exists($queryObj ,'postListExtra')) {
237 $extra = $queryObj->postListExtra($_REQUEST);
239 // filter results, and add any data that is needed...
240 if (method_exists($x,'postListFilter')) {
241 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
244 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
245 $meta = $this->meta($x, $ret);
247 $extra['metaData'] = $meta;
251 // echo "<PRE>"; print_r($ret);
252 $this->jdata($ret,$total, $extra );
259 * apply REQUEST[sort] and [dir]
260 * sort may be an array of columsn..
262 * @arg DB_DataObject $x
265 function applySort($x, $sort = '', $dir ='')
268 // Db_DataObject::debugLevel(1);
269 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
270 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
271 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
276 if (method_exists($x, 'applySort')) {
277 $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
279 if ($sorted === false) {
282 $sort_ar = explode(',', $sort);
285 foreach($sort_ar as $sort) {
287 if (strlen($sort) && isset($cols[$sort]) ) {
288 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
290 } else if (in_array($sort, array_keys($this->cols))) {
291 $sort_str[] = $sort . ' ' . $dir ;
296 $x->orderBy(implode(', ', $sort_str ));
301 * POST method Roo/TABLENAME.php
302 * -- updates the data..
305 * _debug - forces debugging on.
306 * _get - forces a get request
307 * _ids - multiple update of records.
308 * {colid} - forces fetching
311 function post($tab) // update / insert (?? dleete??)
313 // DB_DataObject::debugLevel(1);
314 if (!empty($_REQUEST['_debug'])) {
315 DB_DataObject::debugLevel(1);
318 if (!empty($_REQUEST['_get'])) {
319 return $this->get($tab);
322 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
324 $tab = str_replace('/', '',$tab); // basic protection??
325 $x = DB_DataObject::factory($tab);
326 if (!is_a($x, 'DB_DataObject')) {
327 $this->jerr('invalid url');
329 // find the key and use that to get the thing..
332 $this->jerr('no key');
335 // delete should be here...
336 if (isset($_REQUEST['_delete'])) {
337 // do we really delete stuff!?!?!?
338 return $this->delete($x,$_REQUEST);
344 if (!empty($_REQUEST['_ids'])) {
345 $ids = explode(',',$_REQUEST['_ids']);
346 $x->whereAddIn($keys[0], $ids, 'int');
347 $ar = $x->fetchAll();
349 $this->update($x, $_REQUEST);
353 $this->jok("UPDATED");
359 if (!empty($_REQUEST[$keys[0]])) {
361 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
362 $this->jerr("Invalid request");
364 $this->jok($this->update($x, $_REQUEST));
368 $this->jerr("No data recieved for inserting");
371 $this->jok($this->insert($x, $_REQUEST));
378 function insert($x, $req)
382 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
383 $this->jerr("PERMISSION DENIED");
386 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
388 if (method_exists($x, 'setFromRoo')) {
389 $res = $x->setFromRoo($req, $this);
390 if (is_string($res)) {
400 if (isset($cols['created'])) {
401 $x->created = date('Y-m-d H:i:s');
403 if (isset($cols['created_dt'])) {
404 $x->created_dt = date('Y-m-d H:i:s');
406 if (isset($cols['created_by'])) {
407 $x->created_by = $this->authUser->id;
411 if (isset($cols['modified'])) {
412 $x->modified = date('Y-m-d H:i:s');
414 if (isset($cols['modified_dt'])) {
415 $x->modified_dt = date('Y-m-d H:i:s');
417 if (isset($cols['modified_by'])) {
418 $x->modified_by = $this->authUser->id;
421 if (isset($cols['updated'])) {
422 $x->updated = date('Y-m-d H:i:s');
424 if (isset($cols['updated_dt'])) {
425 $x->updated_dt = date('Y-m-d H:i:s');
427 if (isset($cols['updated_by'])) {
428 $x->updated_by = $this->authUser->id;
436 if (method_exists($x, 'onInsert')) {
437 $x->onInsert($_REQUEST, $this);
439 $this->addEvent("ADD", $x);
441 // note setFrom might handle this before hand...!??!
442 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
446 $r = DB_DataObject::factory($x->tableName());
448 // let's assume it has a key!!!
451 $this->loadMap($r, $_columns);
455 $rooar = method_exists($r, 'toRooArray');
456 //print_r(var_dump($rooar)); exit;
457 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
461 function update($x, $req)
463 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
464 $this->jerr("PERMISSION DENIED");
468 // only done if we recieve a lock_id.
469 // we are very trusing here.. that someone has not messed around with locks..
470 // the object might want to check in their checkPerm - if locking is essential..
472 $lock = DB_DataObjecT::factory('Core_locking');
473 if (is_a($lock,'DB_DataObject')) {
475 $lock->on_id = $x->id;
476 $lock->on_table= $x->tableName();
477 if (!empty($_REQUEST['_lock_id'])) {
478 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
481 if ($lock->find(true)) {
482 // it's locked by someone else..
483 $p = $lock->person();
484 $this->jerr("Your lock is invalid, This record is locked by " . $p->name . " at " .$lock->created);
486 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
487 // edit it anyways...
496 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
501 // this lot is generic.. needs moving
502 if (method_exists($x, 'setFromRoo')) {
503 $res = $x->setFromRoo($req, $this);
504 if (is_string($res)) {
510 $this->addEvent("EDIT", $x);
516 if (isset($cols['modified'])) {
517 $x->modified = date('Y-m-d H:i:s');
519 if (isset($cols['modified_dt'])) {
520 $x->modified_dt = date('Y-m-d H:i:s');
522 if (isset($cols['modified_by'])) {
523 $x->modified_by = $this->authUser->id;
526 if (isset($cols['updated'])) {
527 $x->updated = date('Y-m-d H:i:s');
529 if (isset($cols['updated_dt'])) {
530 $x->updated_dt = date('Y-m-d H:i:s');
532 if (isset($cols['updated_by'])) {
533 $x->updated_by = $this->authUser->id;
538 if (method_exists($x, 'onUpdate')) {
539 $x->onUpdate($old, $req, $this);
542 $r = DB_DataObject::factory($x->tableName());
544 // let's assume it has a key!!!
547 $this->loadMap($r, $_columns);
550 $rooar = method_exists($r, 'toRooArray');
551 //print_r(var_dump($rooar)); exit;
552 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
555 function delete($x, $req)
557 // do we really delete stuff!?!?!?
558 if (empty($req['_delete'])) {
559 $this->jerr("Delete Requested with no value");
562 // build a list of tables to queriy for dependant data..
567 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
568 foreach($all_links as $tbl => $links) {
569 foreach($links as $col => $totbl_col) {
570 $to = explode(':', $totbl_col);
571 if ($to[0] != $x->tableName()) {
575 $affects[$tbl .'.' . $col] = true;
580 // echo '<PRE>';print_r($affects);exit;
581 //DB_Dataobject::debugLevel(1);
584 $clean = create_function('$v', 'return (int)$v;');
586 $bits = array_map($clean, explode(',', $req['_delete']));
588 // print_r($bits);exit;
590 // let's assume it has a key!!!
593 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
595 $this->jerr("Nothing found to delete");
598 while ($x->fetch()) {
604 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
605 $this->jerr("PERMISSION DENIED");
608 // before delte = allows us to trash dependancies if needed..
609 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
610 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
616 foreach($affects as $k=> $true) {
617 $ka = explode('.', $k);
618 $chk = DB_DataObject::factory($ka[0]);
619 if (!is_a($chk,'DB_DataObject')) {
620 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
622 $chk->{$ka[1]} = $xx->$pk;
623 $matches = $chk->count();
626 $o = $chk->fetchAll();
627 $desc = $ka[0]. ':' . $ka[1] .'='.$xx->$pk;
628 if (method_exists($chk, 'toEventString')) {
629 $desc = $ka[0] . ' : ' . $o[0]->toEventString();
632 $this->jerr("Delete Dependant records ($matches found), first is ( $desc )");
637 $this->addEvent("DELETE", $x);
642 $this->jerr(implode("\n<BR>", $errs));
644 $this->jok("Deleted");
652 function loadMap($do, $filter=false, $distinct = false)
654 //DB_DataObject::debugLevel(1);
656 $this->countWhat = false;
662 $mods = explode(',',$this->appModules);
664 $ff = HTML_FlexyFramework::get();
665 //$db->databaseName();
667 //$ff->DB_DataObject['ini_'. $db->database()];
668 //echo '<PRE>';print_r($do->links());exit;
671 if (in_array('Builder', $mods) ) {
673 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
675 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
678 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
679 if (!file_exists($ini)) {
682 $conf = array_merge($conf, parse_ini_file($ini,true));
683 if (!isset($conf[$do->tableName()])) {
686 $map = $conf[$do->tableName()];
697 $tabdef = $do->table();
698 if (isset($tabdef['passwd'])) {
699 // prevent exposure of passwords..
700 unset($tabdef['passwd']);
703 $xx = array_keys($tabdef);
704 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
706 $selectAs = array(array( $xx , '%s', false));
708 $has_distinct = false;
709 if ($filter || $distinct) {
711 //echo '<PRE>' ;print_r($filter);exit;
713 if ($distinct && $distinct == $c) {
714 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
715 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
718 if (!$filter || in_array($c, $filter)) {
724 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
730 $this->cols = array();
731 $this->colsJoinName =array();
733 $this->cols[$k] = $do->tableName(). '.' . $k;
741 foreach($map as $ocl=>$info) {
743 list($tab,$col) = explode(':', $info);
744 // what about multiple joins on the same table!!!
745 $xx = DB_DataObject::factory($tab);
746 if (!is_a($xx, 'DB_DataObject')) {
749 // this is borked ... for multiple jions..
750 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
751 $tabdef = $xx->table();
752 $table = $xx->tableName();
753 if (isset($tabdef['passwd'])) {
755 unset($tabdef['passwd']);
758 $xx = array_keys($tabdef);
761 if ($filter || $distinct) {
764 $tn = sprintf($ocl.'_%s', $c);
765 // echo '<PRE>'; var_dump($tn);
766 if ($distinct && $tn == $distinct) {
767 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
768 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
773 if (!$filter || in_array($tn, $filter)) {
778 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
783 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
789 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
790 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
797 $do->selectAdd($has_distinct);
799 //DB_DataObject::debugLevel(1);
800 // we do select as after everything else as we need to plop distinct at the beginning??
802 // echo '<PRE>';print_r($this->colsJname);exit;
803 foreach($selectAs as $ar) {
804 $do->selectAs($ar[0], $ar[1], $ar[2]);
810 * generate the meta data neede by queries.
813 function meta($x, $data)
815 // this is not going to work on queries where the data does not match the database def..
816 // for unknown columns we send them as stirngs..
818 $cols = array_keys($data[0]);
823 //echo '<PRE>';print_r($this->cols); exit;
824 $options = &PEAR::getStaticProperty('DB_DataObject','options');
825 $reader = $options["ini_{$x->_database}"] .'.reader';
826 if (!file_exists( $reader )) {
830 $rdata = unserialize(file_get_contents($reader));
832 // echo '<PRE>';print_r($rdata);exit;
835 foreach($cols as $c ) {
836 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
840 $add = $rdata[$this->cols[$c]];
845 'totalProperty' => 'total',
846 'successProperty' => 'success',
855 function setFilters($x, $q)
857 // if a column is type int, and we get ',' -> the it should be come an inc clause..
858 // DB_DataObject::debugLevel(1);
859 if (method_exists($x, 'applyFilters')) {
860 // DB_DataObject::debugLevel(1);
861 $x->applyFilters($q, $this->authUser);
863 $q_filtered = array();
865 foreach($q as $key=>$val) {
867 // value is an array..
868 if (is_array($val) ) {
872 if ($key[0] == '!') {
874 $key = substr($key,1);
877 if (!in_array( $key, array_keys($this->cols))) {
881 // support a[0] a[1] ..... => whereAddIn(
884 foreach($val as $k=>$v) {
885 if (!is_numeric($k)) {
889 // FIXME: note this is not typesafe for anything other than mysql..
891 if (!is_numeric($v) || !is_long($v)) {
900 $x->whereAddIn($pref . (
901 isset($this->colsJname[$key]) ?
902 $this->colsJname[$key] :
903 ($x->tableName(). '.'.$key)),
904 $ar, $quote ? 'string' : 'int');
912 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
914 $key = substr($key, 1) ;
917 isset($this->colsJname[$key]) ?
918 $this->colsJname[$key] :
919 $x->tableName(). '.'.$key ) . ' != ' .
920 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
930 // Events and remarks -- fixme - move to events/remarsk...
931 case 'on_id': // where TF is this used...
932 if (!empty($q['query']['original'])) {
933 // DB_DataObject::debugLevel(1);
934 $o = (int) $q['query']['original'];
936 $x->whereAdd("(on_id = $oid OR
937 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
947 $q_filtered[$key] = $val;
950 // subjoined columns = check the values.
951 // note this is not typesafe for anything other than mysql..
953 if (isset($this->colsJname[$key])) {
955 if (!is_numeric($val) || !is_long($val)) {
958 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
967 $x->setFrom($q_filtered);
972 // nice generic -- let's get rid of it.. where is it used!!!!
974 // Person / Group / most of my queries noww...
975 if (!empty($q['query']['name'])) {
976 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
979 // - projectdirectory staff list - persn queuy