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)
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.
48 * !colname=.... => colname != ....
49 * colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
52 * _post = simulate a post with debuggin on.
53 * lookup = array( k=>v) single fetch based on a key/value pair
54 * _id = single fetch based on id.
55 * _delete = delete a list of ids element. (seperated by ,);
56 * _columns = comma seperated list of columns.
57 * _distinct = a distinct column lookup.
58 * _requestMeta = default behaviour of Roo stores.. on first query..
60 * csvCols[0] csvCols[1].... = .... column titles for CSV output
62 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
64 * sort = sort column (',' comma delimited)
65 * dir = sort direction ?? in future comma delimited...
67 * limit = limit number
69 * _toggleActive !:!:!:! - this hsould not really be here..
70 * query[add_blank] - add a line in with an empty option... - not really needed???
75 // $this->jerr("Not authenticated", array('authFailure' => true));
76 //echo '<PRE>';print_R($_GET);
77 //DB_DataObject::debuglevel(1);
79 $this->init(); // from pnan.
81 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
83 if (!empty($_GET['_post'])) {
85 //DB_DAtaObject::debuglevel(1);
86 return $this->post($tab);
88 $tab = str_replace('/', '',$tab); // basic protection??
89 $x = DB_DataObject::factory($tab);
90 if (!is_a($x, 'DB_DataObject')) {
91 $this->jerr('invalid url');
93 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
95 if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
96 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
97 $this->jerr("PERMISSION DENIED");
99 $this->loadMap($x, $_columns);
100 $x->setFrom($_REQUEST['lookup'] );
102 if (!$x->find(true)) {
105 $this->jok($x->toArray());
110 if (isset($_REQUEST['_id'])) { // single fetch
112 if (empty($_REQUEST['_id'])) {
113 $this->jok($x->toArray()); // return an empty array!
116 $this->loadMap($x, $_columns);
118 if (!$x->get($_REQUEST['_id'])) {
119 $this->jerr("no such record");
122 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
123 $this->jerr("PERMISSION DENIED");
126 $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser, $_REQUEST) : $x->toArray());
129 if (isset($_REQUEST['_delete'])) {
130 // do we really delete stuff!?!?!?
131 return $this->delete($x,$_REQUEST);
137 if (isset($_REQUEST['_toggleActive'])) {
138 // do we really delete stuff!?!?!?
139 if (!$this->hasPerm("Core.Staff", 'E')) {
140 $this->jerr("PERMISSION DENIED");
142 $clean = create_function('$v', 'return (int)$v;');
143 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
144 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
145 $this->jerr("you can not disable yourself");
147 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
148 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
149 $this->jok("Updated");
152 //DB_DataObject::debugLevel(1);
153 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
154 $this->jerr("PERMISSION DENIED");
157 // sets map and countWhat
158 $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct']);
160 $this->setFilters($x,$_REQUEST);
163 // build join if req.
164 //DB_DataObject::debugLevel(1);
165 $total = $x->count($this->countWhat);
168 //var_dump($total);exit;
169 $this->applySort($x);
174 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
175 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 5000)
178 $queryObj = clone($x);
183 if (!empty($_REQUEST['query']['add_blank'])) {
184 $ret[] = array( 'id' => 0, 'name' => '----');
189 //if (($tab == 'Groups') && ($_REQUEST['type'] != 0)) { // then it's a list of teams..
190 if ($tab == 'Groups') {
192 $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
193 $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
194 //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
200 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
201 header('Content-type: text/csv');
203 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
204 //header('Content-type: text/plain');
205 $fh = fopen('php://output', 'w');
206 fputcsv($fh, $_REQUEST['csvTitles']);
207 while ($x->fetch()) {
208 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
210 foreach($_REQUEST['csvCols'] as $k) {
211 $line[] = isset($x->$k) ? $x->$k : '';
222 $rooar = method_exists($x, 'toRooArray');
224 while ($x->fetch()) {
225 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
227 $ret[] = !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
229 //if ($x->tableName() == 'Documents_Tracking') {
230 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
234 if (method_exists($queryObj ,'postListExtra')) {
235 $extra = $queryObj->postListExtra($_REQUEST);
237 // filter results, and add any data that is needed...
238 if (method_exists($x,'postListFilter')) {
239 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
242 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
243 $meta = $this->meta($x, $ret);
245 $extra['metaData'] = $meta;
249 // echo "<PRE>"; print_r($ret);
250 $this->jdata($ret,$total, $extra );
257 * apply REQUEST[sort] and [dir]
258 * sort may be an array of columsn..
260 * @arg DB_DataObject $x
263 function applySort($x, $sort = '', $dir ='')
266 // Db_DataObject::debugLevel(1);
267 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
268 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
269 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
274 if (method_exists($x, 'applySort')) {
275 $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
277 if ($sorted === false) {
280 $sort_ar = explode(',', $sort);
283 foreach($sort_ar as $sort) {
285 if (strlen($sort) && isset($cols[$sort]) ) {
286 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
288 } else if (in_array($sort, array_keys($this->cols))) {
289 $sort_str[] = $sort . ' ' . $dir ;
294 $x->orderBy(implode(', ', $sort_str ));
299 * POST method Roo/TABLENAME.php
300 * -- updates the data..
303 * _debug - forces debugging on.
304 * _get - forces a get request
305 * _ids - multiple update of records.
306 * {colid} - forces fetching
309 function post($tab) // update / insert (?? dleete??)
311 // DB_DataObject::debugLevel(1);
312 if (!empty($_REQUEST['_debug'])) {
313 DB_DataObject::debugLevel(1);
316 if (!empty($_REQUEST['_get'])) {
317 return $this->get($tab);
320 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
322 $tab = str_replace('/', '',$tab); // basic protection??
323 $x = DB_DataObject::factory($tab);
324 if (!is_a($x, 'DB_DataObject')) {
325 $this->jerr('invalid url');
327 // find the key and use that to get the thing..
330 $this->jerr('no key');
333 // delete should be here...
334 if (isset($_REQUEST['_delete'])) {
335 // do we really delete stuff!?!?!?
336 return $this->delete($x,$_REQUEST);
342 if (!empty($_REQUEST['_ids'])) {
343 $ids = explode(',',$_REQUEST['_ids']);
344 $x->whereAddIn($keys[0], $ids, 'int');
345 $ar = $x->fetchAll();
347 $this->update($x, $_REQUEST);
351 $this->jok("UPDATED");
357 if (!empty($_REQUEST[$keys[0]])) {
359 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
360 $this->jerr("Invalid request");
362 $this->jok($this->update($x, $_REQUEST));
366 $this->jerr("No data recieved for inserting");
369 $this->jok($this->insert($x, $_REQUEST));
376 function insert($x, $req)
380 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
381 $this->jerr("PERMISSION DENIED");
384 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
386 if (method_exists($x, 'setFromRoo')) {
387 $res = $x->setFromRoo($req, $this);
388 if (is_string($res)) {
398 if (isset($cols['created'])) {
399 $x->created = date('Y-m-d H:i:s');
401 if (isset($cols['created_dt'])) {
402 $x->created_dt = date('Y-m-d H:i:s');
404 if (isset($cols['created_by'])) {
405 $x->created_by = $this->authUser->id;
409 if (isset($cols['modified'])) {
410 $x->modified = date('Y-m-d H:i:s');
412 if (isset($cols['modified_dt'])) {
413 $x->modified_dt = date('Y-m-d H:i:s');
415 if (isset($cols['modified_by'])) {
416 $x->modified_by = $this->authUser->id;
419 if (isset($cols['updated'])) {
420 $x->updated = date('Y-m-d H:i:s');
422 if (isset($cols['updated_dt'])) {
423 $x->updated_dt = date('Y-m-d H:i:s');
425 if (isset($cols['updated_by'])) {
426 $x->updated_by = $this->authUser->id;
434 if (method_exists($x, 'onInsert')) {
435 $x->onInsert($_REQUEST, $this);
437 $this->addEvent("ADD", $x);
439 // note setFrom might handle this before hand...!??!
440 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
444 $r = DB_DataObject::factory($x->tableName());
446 // let's assume it has a key!!!
449 $this->loadMap($r, $_columns);
453 $rooar = method_exists($r, 'toRooArray');
454 //print_r(var_dump($rooar)); exit;
455 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
459 function update($x, $req)
461 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
462 $this->jerr("PERMISSION DENIED");
466 // only done if we recieve a lock_id.
467 // we are very trusing here.. that someone has not messed around with locks..
468 // the object might want to check in their checkPerm - if locking is essential..
470 $lock = DB_DataObjecT::factory('Core_locking');
471 if (is_a($lock,'DB_DataObject')) {
473 $lock->on_id = $x->id;
474 $lock->on_table= $x->tableName();
475 if (!empty($_REQUEST['_lock_id'])) {
476 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
479 if ($lock->find(true)) {
480 // it's locked by someone else..
481 $p = $lock->person();
482 $this->jerr("Your lock is invalid, This record is locked by " . $p->name . " at " .$lock->created);
484 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
485 // edit it anyways...
494 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
499 // this lot is generic.. needs moving
500 if (method_exists($x, 'setFromRoo')) {
501 $res = $x->setFromRoo($req, $this);
502 if (is_string($res)) {
508 $this->addEvent("EDIT", $x);
514 if (isset($cols['modified'])) {
515 $x->modified = date('Y-m-d H:i:s');
517 if (isset($cols['modified_dt'])) {
518 $x->modified_dt = date('Y-m-d H:i:s');
520 if (isset($cols['modified_by'])) {
521 $x->modified_by = $this->authUser->id;
524 if (isset($cols['updated'])) {
525 $x->updated = date('Y-m-d H:i:s');
527 if (isset($cols['updated_dt'])) {
528 $x->updated_dt = date('Y-m-d H:i:s');
530 if (isset($cols['updated_by'])) {
531 $x->updated_by = $this->authUser->id;
536 if (method_exists($x, 'onUpdate')) {
537 $x->onUpdate($old, $req, $this);
540 $r = DB_DataObject::factory($x->tableName());
542 // let's assume it has a key!!!
545 $this->loadMap($r, $_columns);
548 $rooar = method_exists($r, 'toRooArray');
549 //print_r(var_dump($rooar)); exit;
550 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
553 function delete($x, $req)
555 // do we really delete stuff!?!?!?
556 if (empty($req['_delete'])) {
557 $this->jerr("Delete Requested with no value");
560 // build a list of tables to queriy for dependant data..
565 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
566 foreach($all_links as $tbl => $links) {
567 foreach($links as $col => $totbl_col) {
568 $to = explode(':', $totbl_col);
569 if ($to[0] != $x->tableName()) {
573 $affects[$tbl .'.' . $col] = true;
578 // echo '<PRE>';print_r($affects);exit;
579 //DB_Dataobject::debugLevel(1);
582 $clean = create_function('$v', 'return (int)$v;');
584 $bits = array_map($clean, explode(',', $req['_delete']));
586 // print_r($bits);exit;
588 // let's assume it has a key!!!
591 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
593 $this->jerr("Nothing found to delete");
596 while ($x->fetch()) {
602 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
603 $this->jerr("PERMISSION DENIED");
606 // before delte = allows us to trash dependancies if needed..
607 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
608 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
614 foreach($affects as $k=> $true) {
615 $ka = explode('.', $k);
616 $chk = DB_DataObject::factory($ka[0]);
617 if (!is_a($chk,'DB_DataObject')) {
618 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
620 $chk->{$ka[1]} = $xx->$pk;
621 $matches = $chk->count();
624 $o = $chk->fetchAll();
625 $desc = $ka[0]. ':' . $ka[1] .'='.$xx->$pk;
626 if (method_exists($chk, 'toEventString')) {
627 $desc = $ka[0] . ' : ' . $o[0]->toEventString();
630 $this->jerr("Delete Dependant records ($matches found), first is ( $desc )");
635 $this->addEvent("DELETE", $x);
640 $this->jerr(implode("\n<BR>", $errs));
642 $this->jok("Deleted");
650 function loadMap($do, $filter=false, $distinct = false)
652 //DB_DataObject::debugLevel(1);
654 $this->countWhat = false;
660 $mods = explode(',',$this->appModules);
662 $ff = HTML_FlexyFramework::get();
663 //$db->databaseName();
665 //$ff->DB_DataObject['ini_'. $db->database()];
666 //echo '<PRE>';print_r($do->links());exit;
669 if (in_array('Builder', $mods) ) {
671 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
673 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
676 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
677 if (!file_exists($ini)) {
680 $conf = array_merge($conf, parse_ini_file($ini,true));
681 if (!isset($conf[$do->tableName()])) {
684 $map = $conf[$do->tableName()];
695 $tabdef = $do->table();
696 if (isset($tabdef['passwd'])) {
697 // prevent exposure of passwords..
698 unset($tabdef['passwd']);
701 $xx = array_keys($tabdef);
702 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
704 $selectAs = array(array( $xx , '%s', false));
706 $has_distinct = false;
707 if ($filter || $distinct) {
709 //echo '<PRE>' ;print_r($filter);exit;
711 if ($distinct && $distinct == $c) {
712 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
713 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
716 if (!$filter || in_array($c, $filter)) {
722 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
728 $this->cols = array();
729 $this->colsJoinName =array();
731 $this->cols[$k] = $do->tableName(). '.' . $k;
739 foreach($map as $ocl=>$info) {
741 list($tab,$col) = explode(':', $info);
742 // what about multiple joins on the same table!!!
743 $xx = DB_DataObject::factory($tab);
744 if (!is_a($xx, 'DB_DataObject')) {
747 // this is borked ... for multiple jions..
748 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
749 $tabdef = $xx->table();
750 $table = $xx->tableName();
751 if (isset($tabdef['passwd'])) {
753 unset($tabdef['passwd']);
756 $xx = array_keys($tabdef);
759 if ($filter || $distinct) {
762 $tn = sprintf($ocl.'_%s', $c);
763 // echo '<PRE>'; var_dump($tn);
764 if ($distinct && $tn == $distinct) {
765 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
766 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
771 if (!$filter || in_array($tn, $filter)) {
776 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
781 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
787 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
788 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
795 $do->selectAdd($has_distinct);
797 //DB_DataObject::debugLevel(1);
798 // we do select as after everything else as we need to plop distinct at the beginning??
800 // echo '<PRE>';print_r($this->colsJname);exit;
801 foreach($selectAs as $ar) {
802 $do->selectAs($ar[0], $ar[1], $ar[2]);
808 * generate the meta data neede by queries.
811 function meta($x, $data)
813 // this is not going to work on queries where the data does not match the database def..
814 // for unknown columns we send them as stirngs..
816 $cols = array_keys($data[0]);
821 //echo '<PRE>';print_r($this->cols); exit;
822 $options = &PEAR::getStaticProperty('DB_DataObject','options');
823 $reader = $options["ini_{$x->_database}"] .'.reader';
824 if (!file_exists( $reader )) {
828 $rdata = unserialize(file_get_contents($reader));
830 // echo '<PRE>';print_r($rdata);exit;
833 foreach($cols as $c ) {
834 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
838 $add = $rdata[$this->cols[$c]];
843 'totalProperty' => 'total',
844 'successProperty' => 'success',
853 function setFilters($x, $q)
855 // if a column is type int, and we get ',' -> the it should be come an inc clause..
856 // DB_DataObject::debugLevel(1);
857 if (method_exists($x, 'applyFilters')) {
858 // DB_DataObject::debugLevel(1);
859 $x->applyFilters($q, $this->authUser);
861 $q_filtered = array();
863 foreach($q as $key=>$val) {
865 // value is an array..
866 if (is_array($val) ) {
870 if ($key[0] == '!') {
872 $key = substr($key,1);
875 if (!in_array( $key, array_keys($this->cols))) {
879 // support a[0] a[1] ..... => whereAddIn(
882 foreach($val as $k=>$v) {
883 if (!is_numeric($k)) {
887 // FIXME: note this is not typesafe for anything other than mysql..
889 if (!is_numeric($v) || !is_long($v)) {
898 $x->whereAddIn($pref . (
899 isset($this->colsJname[$key]) ?
900 $this->colsJname[$key] :
901 ($x->tableName(). '.'.$key)),
902 $ar, $quote ? 'string' : 'int');
910 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
912 $key = substr($key, 1) ;
915 isset($this->colsJname[$key]) ?
916 $this->colsJname[$key] :
917 $x->tableName(). '.'.$key ) . ' != ' .
918 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
928 // Events and remarks -- fixme - move to events/remarsk...
929 case 'on_id': // where TF is this used...
930 if (!empty($q['query']['original'])) {
931 // DB_DataObject::debugLevel(1);
932 $o = (int) $q['query']['original'];
934 $x->whereAdd("(on_id = $oid OR
935 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
945 $q_filtered[$key] = $val;
948 // subjoined columns = check the values.
949 // note this is not typesafe for anything other than mysql..
951 if (isset($this->colsJname[$key])) {
953 if (!is_numeric($val) || !is_long($val)) {
956 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
965 $x->setFrom($q_filtered);
970 // nice generic -- let's get rid of it.. where is it used!!!!
972 // Person / Group / most of my queries noww...
973 if (!empty($q['query']['name'])) {
974 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
977 // - projectdirectory staff list - persn queuy