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 - 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) // 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)
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 * csvTitle[0], csvTitle[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));
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) : $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);
164 // build join if req.
166 $total = $x->count($this->countWhat);
168 // DB_DataObject::debugLevel(1);
170 $this->applySort($x);
175 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
176 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
179 $queryObj = clone($x);
184 if (!empty($_REQUEST['query']['add_blank'])) {
185 $ret[] = array( 'id' => 0, 'name' => '----');
190 //if (($tab == 'Groups') && ($_REQUEST['type'] != 0)) { // then it's a list of teams..
191 if ($tab == 'Groups') {
193 $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
194 $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
195 //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
201 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
202 header('Content-type: text/csv');
204 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
205 //header('Content-type: text/plain');
206 $fh = fopen('php://output', 'w');
207 fputcsv($fh, $_REQUEST['csvTitles']);
208 while ($x->fetch()) {
209 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
211 foreach($_REQUEST['csvCols'] as $k) {
212 $line[] = isset($x->$k) ? $x->$k : '';
223 $rooar = method_exists($x, 'toRooArray');
225 while ($x->fetch()) {
226 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
228 $ret[] = !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
230 //if ($x->tableName() == 'Documents_Tracking') {
231 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
235 if (method_exists($queryObj ,'postListExtra')) {
236 $extra = $queryObj->postListExtra($_REQUEST);
238 // filter results, and add any data that is needed...
239 if (method_exists($x,'postListFilter')) {
240 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
243 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
244 $meta = $this->meta($x, $ret);
246 $extra['metaData'] = $meta;
250 // echo "<PRE>"; print_r($ret);
251 $this->jdata($ret,$total, $extra );
258 * apply REQUEST[sort] and [dir]
259 * sort may be an array of columsn..
261 * @arg DB_DataObject $x
264 function applySort($x)
267 // Db_DataObject::debugLevel(1);
268 $sort = empty($_REQUEST['sort']) ? '' : $_REQUEST['sort'];
269 $dir = (empty($_REQUEST['dir']) || strtoupper($_REQUEST['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, $x->toEventString());
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");
465 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
470 // this lot is generic.. needs moving
471 if (method_exists($x, 'setFromRoo')) {
472 $res = $x->setFromRoo($req, $this);
473 if (is_string($res)) {
479 $this->addEvent("EDIT", $x, $x->toEventString());
485 if (isset($cols['modified'])) {
486 $x->modified = date('Y-m-d H:i:s');
488 if (isset($cols['modified_dt'])) {
489 $x->modified_dt = date('Y-m-d H:i:s');
491 if (isset($cols['modified_by'])) {
492 $x->modified_by = $this->authUser->id;
495 if (isset($cols['updated'])) {
496 $x->updated = date('Y-m-d H:i:s');
498 if (isset($cols['updated_dt'])) {
499 $x->updated_dt = date('Y-m-d H:i:s');
501 if (isset($cols['updated_by'])) {
502 $x->updated_by = $this->authUser->id;
507 if (method_exists($x, 'onUpdate')) {
508 $x->onUpdate($old, $req, $this);
511 $r = DB_DataObject::factory($x->tableName());
513 // let's assume it has a key!!!
516 $this->loadMap($r, $_columns);
519 $rooar = method_exists($r, 'toRooArray');
520 //print_r(var_dump($rooar)); exit;
521 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
524 function delete($x, $req)
526 // do we really delete stuff!?!?!?
527 if (empty($req['_delete'])) {
528 $this->jerr("Delete Requested with no value");
531 // build a list of tables to queriy for dependant data..
536 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
537 foreach($all_links as $tbl => $links) {
538 foreach($links as $col => $totbl_col) {
539 $to = explode(':', $totbl_col);
540 if ($to[0] != $x->tableName()) {
544 $affects[$tbl .'.' . $col] = true;
549 // echo '<PRE>';print_r($affects);exit;
550 //DB_Dataobject::debugLevel(1);
553 $clean = create_function('$v', 'return (int)$v;');
555 $bits = array_map($clean, explode(',', $req['_delete']));
557 // print_r($bits);exit;
559 // let's assume it has a key!!!
562 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
564 $this->jerr("Nothing found to delete");
567 while ($x->fetch()) {
571 foreach($affects as $k=> $true) {
572 $ka = explode('.', $k);
573 $chk = DB_DataObject::factory($ka[0]);
574 if (!is_a($chk,'DB_DataObject')) {
575 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
577 $chk->{$ka[1]} = $xx->$pk;
579 $this->jerr('Delete Dependant records first ('. $ka[0]. ':' . $ka[1] .'='.$xx->$pk.')');
585 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
586 $this->jerr("PERMISSION DENIED");
589 $this->addEvent("DELETE", $x, $x->toEventString());
590 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
591 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
597 $this->jerr(implode("\n<BR>", $errs));
599 $this->jok("Deleted");
607 function loadMap($do, $filter=false, $distinct = false)
609 //DB_DataObject::debugLevel(1);
614 $mods = explode(',',$this->appModules);
616 $ff = HTML_FlexyFramework::get();
617 //$db->databaseName();
619 //$ff->DB_DataObject['ini_'. $db->database()];
620 //echo '<PRE>';print_r($do->links());exit;
623 if (in_array('Builder', $mods) ) {
625 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
627 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
630 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
631 if (!file_exists($ini)) {
634 $conf = array_merge($conf, parse_ini_file($ini,true));
635 if (!isset($conf[$do->tableName()])) {
638 $map = $conf[$do->tableName()];
648 $tabdef = $do->table();
649 if (isset($tabdef['passwd'])) {
650 // prevent exposure of passwords..
651 unset($tabdef['passwd']);
654 $xx = array_keys($tabdef);
655 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
657 $selectAs = array(array( $xx , '%s', false));
658 $this->countWhat = false;
659 $has_distinct = false;
660 if ($filter || $distinct) {
662 //echo '<PRE>' ;print_r($filter);exit;
664 if ($distinct && $distinct == $c) {
665 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
666 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
669 if (!$filter || in_array($c, $filter)) {
675 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
681 $this->cols = array();
682 $this->colsJoinName =array();
684 $this->cols[$k] = $do->tableName(). '.' . $k;
692 foreach($map as $ocl=>$info) {
694 list($tab,$col) = explode(':', $info);
695 // what about multiple joins on the same table!!!
696 $xx = DB_DataObject::factory($tab);
697 if (!is_a($xx, 'DB_DataObject')) {
700 // this is borked ... for multiple jions..
701 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
702 $tabdef = $xx->table();
703 $table = $xx->tableName();
704 if (isset($tabdef['passwd'])) {
706 unset($tabdef['passwd']);
709 $xx = array_keys($tabdef);
712 if ($filter || $distinct) {
715 $tn = sprintf($ocl.'_%s', $c);
716 // echo '<PRE>'; var_dump($tn);
717 if ($distinct && $tn == $distinct) {
718 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
719 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
724 if (!$filter || in_array($tn, $filter)) {
729 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
734 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
740 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
741 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
748 $do->selectAdd($has_distinct);
750 //DB_DataObject::debugLevel(1);
751 // we do select as after everything else as we need to plop distinct at the beginning??
753 // echo '<PRE>';print_r($selectAs );exit;
754 foreach($selectAs as $ar) {
755 $do->selectAs($ar[0], $ar[1], $ar[2]);
761 * generate the meta data neede by queries.
764 function meta($x, $data)
766 // this is not going to work on queries where the data does not match the database def..
767 // for unknown columns we send them as stirngs..
769 $cols = array_keys($data[0]);
774 //echo '<PRE>';print_r($this->cols); exit;
775 $options = &PEAR::getStaticProperty('DB_DataObject','options');
776 $reader = $options["ini_{$x->_database}"] .'.reader';
777 if (!file_exists( $reader )) {
781 $rdata = unserialize(file_get_contents($reader));
783 // echo '<PRE>';print_r($rdata);exit;
786 foreach($cols as $c ) {
787 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
791 $add = $rdata[$this->cols[$c]];
796 'totalProperty' => 'total',
797 'successProperty' => 'success',
806 function setFilters($x, $q)
808 // if a column is type int, and we get ',' -> the it should be come an inc clause..
809 // DB_DataObject::debugLevel(1);
810 if (method_exists($x, 'applyFilters')) {
811 // DB_DataObject::debugLevel(1);
812 $x->applyFilters($q, $this->authUser);
814 $q_filtered = array();
816 foreach($q as $key=>$val) {
818 // value is an array..
819 if (is_array($val) ) {
821 if (!in_array( $key, array_keys($this->cols))) {
825 // support a[0] a[1] ..... => whereAddIn(
828 foreach($val as $k=>$v) {
829 if (!is_numeric($k)) {
833 // FIXME: note this is not typesafe for anything other than mysql..
835 if (!is_numeric($v) || !is_long($v)) {
845 isset($this->colsJoinName[$key]) ?
846 $this->colsJoinName[$key] :
847 $x->tableName(). '.'.$key,
848 $ar, $quote ? 'string' : 'int');
856 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
858 $key = substr($key, 1) ;
861 isset($this->colsJoinName[$key]) ?
862 $this->colsJoinName[$key] :
863 $x->tableName(). '.'.$key ) . ' != ' .
864 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
874 // Events and remarks -- fixme - move to events/remarsk...
875 case 'on_id': // where TF is this used...
876 if (!empty($q['query']['original'])) {
877 // DB_DataObject::debugLevel(1);
878 $o = (int) $q['query']['original'];
880 $x->whereAdd("(on_id = $oid OR
881 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
891 $q_filtered[$key] = $val;
894 // subjoined columns = check the values.
895 // note this is not typesafe for anything other than mysql..
897 if (isset($this->colsJname[$key])) {
899 if (!is_numeric($val) || !is_long($val)) {
902 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
911 $x->setFrom($q_filtered);
916 // nice generic -- let's get rid of it.. where is it used!!!!
918 // Person / Group / most of my queries noww...
919 if (!empty($q['query']['name'])) {
920 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
923 // - projectdirectory staff list - persn queuy