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 - 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 * 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));
76 //echo '<PRE>';print_R($_GET); DB_DataObject::debuglevel(1);
78 $this->init(); // from pnan.
80 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
82 if (!empty($_GET['_post'])) {
84 DB_DAtaObject::debuglevel(1);
85 return $this->post($tab);
87 $tab = str_replace('/', '',$tab); // basic protection??
88 $x = DB_DataObject::factory($tab);
89 if (!is_a($x, 'DB_DataObject')) {
90 $this->jerr('invalid url');
92 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
94 if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
95 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
96 $this->jerr("PERMISSION DENIED");
98 $this->loadMap($x, $_columns);
99 $x->setFrom($_REQUEST['lookup'] );
101 if (!$x->find(true)) {
104 $this->jok($x->toArray());
109 if (isset($_REQUEST['_id'])) { // single fetch
111 if (empty($_REQUEST['_id'])) {
112 $this->jok($x->toArray()); // return an empty array!
115 $this->loadMap($x, $_columns);
117 if (!$x->get($_REQUEST['_id'])) {
118 $this->jerr("no such record");
121 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
122 $this->jerr("PERMISSION DENIED");
125 $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser) : $x->toArray());
128 if (isset($_REQUEST['_delete'])) {
129 // do we really delete stuff!?!?!?
130 return $this->delete($x,$_REQUEST);
136 if (isset($_REQUEST['_toggleActive'])) {
137 // do we really delete stuff!?!?!?
138 if (!$this->hasPerm("Core.Staff", 'E')) {
139 $this->jerr("PERMISSION DENIED");
141 $clean = create_function('$v', 'return (int)$v;');
142 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
143 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
144 $this->jerr("you can not disable yourself");
146 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
147 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
148 $this->jok("Updated");
151 //DB_DataObject::debugLevel(1);
152 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
153 $this->jerr("PERMISSION DENIED");
156 // sets map and countWhat
157 $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct']);
159 $this->setFilters($x,$_REQUEST);
162 // build join if req.
163 //DB_DataObject::debugLevel(1);
164 $total = $x->count($this->countWhat);
167 //var_dump($total);exit;
168 $this->applySort($x);
173 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
174 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
177 $queryObj = clone($x);
182 if (!empty($_REQUEST['query']['add_blank'])) {
183 $ret[] = array( 'id' => 0, 'name' => '----');
188 //if (($tab == 'Groups') && ($_REQUEST['type'] != 0)) { // then it's a list of teams..
189 if ($tab == 'Groups') {
191 $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
192 $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
193 //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
199 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
200 header('Content-type: text/csv');
202 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
203 //header('Content-type: text/plain');
204 $fh = fopen('php://output', 'w');
205 fputcsv($fh, $_REQUEST['csvTitles']);
206 while ($x->fetch()) {
207 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
209 foreach($_REQUEST['csvCols'] as $k) {
210 $line[] = isset($x->$k) ? $x->$k : '';
221 $rooar = method_exists($x, 'toRooArray');
223 while ($x->fetch()) {
224 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
226 $ret[] = !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
228 //if ($x->tableName() == 'Documents_Tracking') {
229 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
233 if (method_exists($queryObj ,'postListExtra')) {
234 $extra = $queryObj->postListExtra($_REQUEST);
236 // filter results, and add any data that is needed...
237 if (method_exists($x,'postListFilter')) {
238 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
241 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
242 $meta = $this->meta($x, $ret);
244 $extra['metaData'] = $meta;
248 // echo "<PRE>"; print_r($ret);
249 $this->jdata($ret,$total, $extra );
256 * apply REQUEST[sort] and [dir]
257 * sort may be an array of columsn..
259 * @arg DB_DataObject $x
262 function applySort($x, $sort = '', $dir ='')
265 // Db_DataObject::debugLevel(1);
266 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
267 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
268 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
273 if (method_exists($x, 'applySort')) {
274 $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
276 if ($sorted === false) {
279 $sort_ar = explode(',', $sort);
282 foreach($sort_ar as $sort) {
284 if (strlen($sort) && isset($cols[$sort]) ) {
285 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
287 } else if (in_array($sort, array_keys($this->cols))) {
288 $sort_str[] = $sort . ' ' . $dir ;
293 $x->orderBy(implode(', ', $sort_str ));
298 * POST method Roo/TABLENAME.php
299 * -- updates the data..
302 * _debug - forces debugging on.
303 * _get - forces a get request
304 * _ids - multiple update of records.
305 * {colid} - forces fetching
308 function post($tab) // update / insert (?? dleete??)
310 // DB_DataObject::debugLevel(1);
311 if (!empty($_REQUEST['_debug'])) {
312 DB_DataObject::debugLevel(1);
315 if (!empty($_REQUEST['_get'])) {
316 return $this->get($tab);
319 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
321 $tab = str_replace('/', '',$tab); // basic protection??
322 $x = DB_DataObject::factory($tab);
323 if (!is_a($x, 'DB_DataObject')) {
324 $this->jerr('invalid url');
326 // find the key and use that to get the thing..
329 $this->jerr('no key');
332 // delete should be here...
333 if (isset($_REQUEST['_delete'])) {
334 // do we really delete stuff!?!?!?
335 return $this->delete($x,$_REQUEST);
341 if (!empty($_REQUEST['_ids'])) {
342 $ids = explode(',',$_REQUEST['_ids']);
343 $x->whereAddIn($keys[0], $ids, 'int');
344 $ar = $x->fetchAll();
346 $this->update($x, $_REQUEST);
350 $this->jok("UPDATED");
356 if (!empty($_REQUEST[$keys[0]])) {
358 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
359 $this->jerr("Invalid request");
361 $this->jok($this->update($x, $_REQUEST));
365 $this->jerr("No data recieved for inserting");
368 $this->jok($this->insert($x, $_REQUEST));
375 function insert($x, $req)
379 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
380 $this->jerr("PERMISSION DENIED");
383 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
385 if (method_exists($x, 'setFromRoo')) {
386 $res = $x->setFromRoo($req, $this);
387 if (is_string($res)) {
397 if (isset($cols['created'])) {
398 $x->created = date('Y-m-d H:i:s');
400 if (isset($cols['created_dt'])) {
401 $x->created_dt = date('Y-m-d H:i:s');
403 if (isset($cols['created_by'])) {
404 $x->created_by = $this->authUser->id;
408 if (isset($cols['modified'])) {
409 $x->modified = date('Y-m-d H:i:s');
411 if (isset($cols['modified_dt'])) {
412 $x->modified_dt = date('Y-m-d H:i:s');
414 if (isset($cols['modified_by'])) {
415 $x->modified_by = $this->authUser->id;
418 if (isset($cols['updated'])) {
419 $x->updated = date('Y-m-d H:i:s');
421 if (isset($cols['updated_dt'])) {
422 $x->updated_dt = date('Y-m-d H:i:s');
424 if (isset($cols['updated_by'])) {
425 $x->updated_by = $this->authUser->id;
433 if (method_exists($x, 'onInsert')) {
434 $x->onInsert($_REQUEST, $this);
436 $this->addEvent("ADD", $x);
438 // note setFrom might handle this before hand...!??!
439 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
443 $r = DB_DataObject::factory($x->tableName());
445 // let's assume it has a key!!!
448 $this->loadMap($r, $_columns);
452 $rooar = method_exists($r, 'toRooArray');
453 //print_r(var_dump($rooar)); exit;
454 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
458 function update($x, $req)
460 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
461 $this->jerr("PERMISSION DENIED");
464 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
469 // this lot is generic.. needs moving
470 if (method_exists($x, 'setFromRoo')) {
471 $res = $x->setFromRoo($req, $this);
472 if (is_string($res)) {
478 $this->addEvent("EDIT", $x);
484 if (isset($cols['modified'])) {
485 $x->modified = date('Y-m-d H:i:s');
487 if (isset($cols['modified_dt'])) {
488 $x->modified_dt = date('Y-m-d H:i:s');
490 if (isset($cols['modified_by'])) {
491 $x->modified_by = $this->authUser->id;
494 if (isset($cols['updated'])) {
495 $x->updated = date('Y-m-d H:i:s');
497 if (isset($cols['updated_dt'])) {
498 $x->updated_dt = date('Y-m-d H:i:s');
500 if (isset($cols['updated_by'])) {
501 $x->updated_by = $this->authUser->id;
506 if (method_exists($x, 'onUpdate')) {
507 $x->onUpdate($old, $req, $this);
510 $r = DB_DataObject::factory($x->tableName());
512 // let's assume it has a key!!!
515 $this->loadMap($r, $_columns);
518 $rooar = method_exists($r, 'toRooArray');
519 //print_r(var_dump($rooar)); exit;
520 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
523 function delete($x, $req)
525 // do we really delete stuff!?!?!?
526 if (empty($req['_delete'])) {
527 $this->jerr("Delete Requested with no value");
530 // build a list of tables to queriy for dependant data..
535 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
536 foreach($all_links as $tbl => $links) {
537 foreach($links as $col => $totbl_col) {
538 $to = explode(':', $totbl_col);
539 if ($to[0] != $x->tableName()) {
543 $affects[$tbl .'.' . $col] = true;
548 // echo '<PRE>';print_r($affects);exit;
549 //DB_Dataobject::debugLevel(1);
552 $clean = create_function('$v', 'return (int)$v;');
554 $bits = array_map($clean, explode(',', $req['_delete']));
556 // print_r($bits);exit;
558 // let's assume it has a key!!!
561 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
563 $this->jerr("Nothing found to delete");
566 while ($x->fetch()) {
572 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
573 $this->jerr("PERMISSION DENIED");
576 // before delte = allows us to trash dependancies if needed..
577 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
578 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
584 foreach($affects as $k=> $true) {
585 $ka = explode('.', $k);
586 $chk = DB_DataObject::factory($ka[0]);
587 if (!is_a($chk,'DB_DataObject')) {
588 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
590 $chk->{$ka[1]} = $xx->$pk;
592 $this->jerr('Delete Dependant records first ('. $ka[0]. ':' . $ka[1] .'='.$xx->$pk.')');
597 $this->addEvent("DELETE", $x);
602 $this->jerr(implode("\n<BR>", $errs));
604 $this->jok("Deleted");
612 function loadMap($do, $filter=false, $distinct = false)
614 //DB_DataObject::debugLevel(1);
619 $mods = explode(',',$this->appModules);
621 $ff = HTML_FlexyFramework::get();
622 //$db->databaseName();
624 //$ff->DB_DataObject['ini_'. $db->database()];
625 //echo '<PRE>';print_r($do->links());exit;
628 if (in_array('Builder', $mods) ) {
630 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
632 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
635 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
636 if (!file_exists($ini)) {
639 $conf = array_merge($conf, parse_ini_file($ini,true));
640 if (!isset($conf[$do->tableName()])) {
643 $map = $conf[$do->tableName()];
653 $tabdef = $do->table();
654 if (isset($tabdef['passwd'])) {
655 // prevent exposure of passwords..
656 unset($tabdef['passwd']);
659 $xx = array_keys($tabdef);
660 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
662 $selectAs = array(array( $xx , '%s', false));
663 $this->countWhat = false;
664 $has_distinct = false;
665 if ($filter || $distinct) {
667 //echo '<PRE>' ;print_r($filter);exit;
669 if ($distinct && $distinct == $c) {
670 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
671 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
674 if (!$filter || in_array($c, $filter)) {
680 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
686 $this->cols = array();
687 $this->colsJoinName =array();
689 $this->cols[$k] = $do->tableName(). '.' . $k;
697 foreach($map as $ocl=>$info) {
699 list($tab,$col) = explode(':', $info);
700 // what about multiple joins on the same table!!!
701 $xx = DB_DataObject::factory($tab);
702 if (!is_a($xx, 'DB_DataObject')) {
705 // this is borked ... for multiple jions..
706 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
707 $tabdef = $xx->table();
708 $table = $xx->tableName();
709 if (isset($tabdef['passwd'])) {
711 unset($tabdef['passwd']);
714 $xx = array_keys($tabdef);
717 if ($filter || $distinct) {
720 $tn = sprintf($ocl.'_%s', $c);
721 // echo '<PRE>'; var_dump($tn);
722 if ($distinct && $tn == $distinct) {
723 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
724 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
729 if (!$filter || in_array($tn, $filter)) {
734 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
739 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
745 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
746 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
753 $do->selectAdd($has_distinct);
755 //DB_DataObject::debugLevel(1);
756 // we do select as after everything else as we need to plop distinct at the beginning??
758 // echo '<PRE>';print_r($this->colsJname);exit;
759 foreach($selectAs as $ar) {
760 $do->selectAs($ar[0], $ar[1], $ar[2]);
766 * generate the meta data neede by queries.
769 function meta($x, $data)
771 // this is not going to work on queries where the data does not match the database def..
772 // for unknown columns we send them as stirngs..
774 $cols = array_keys($data[0]);
779 //echo '<PRE>';print_r($this->cols); exit;
780 $options = &PEAR::getStaticProperty('DB_DataObject','options');
781 $reader = $options["ini_{$x->_database}"] .'.reader';
782 if (!file_exists( $reader )) {
786 $rdata = unserialize(file_get_contents($reader));
788 // echo '<PRE>';print_r($rdata);exit;
791 foreach($cols as $c ) {
792 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
796 $add = $rdata[$this->cols[$c]];
801 'totalProperty' => 'total',
802 'successProperty' => 'success',
811 function setFilters($x, $q)
813 // if a column is type int, and we get ',' -> the it should be come an inc clause..
814 // DB_DataObject::debugLevel(1);
815 if (method_exists($x, 'applyFilters')) {
816 // DB_DataObject::debugLevel(1);
817 $x->applyFilters($q, $this->authUser);
819 $q_filtered = array();
821 foreach($q as $key=>$val) {
823 // value is an array..
824 if (is_array($val) ) {
826 if (!in_array( $key, array_keys($this->cols))) {
830 // support a[0] a[1] ..... => whereAddIn(
833 foreach($val as $k=>$v) {
834 if (!is_numeric($k)) {
838 // FIXME: note this is not typesafe for anything other than mysql..
840 if (!is_numeric($v) || !is_long($v)) {
850 isset($this->colsJname[$key]) ?
851 $this->colsJname[$key] :
852 ($x->tableName(). '.'.$key),
853 $ar, $quote ? 'string' : 'int');
861 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
863 $key = substr($key, 1) ;
866 isset($this->colsJname[$key]) ?
867 $this->colsJname[$key] :
868 $x->tableName(). '.'.$key ) . ' != ' .
869 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
879 // Events and remarks -- fixme - move to events/remarsk...
880 case 'on_id': // where TF is this used...
881 if (!empty($q['query']['original'])) {
882 // DB_DataObject::debugLevel(1);
883 $o = (int) $q['query']['original'];
885 $x->whereAdd("(on_id = $oid OR
886 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
896 $q_filtered[$key] = $val;
899 // subjoined columns = check the values.
900 // note this is not typesafe for anything other than mysql..
902 if (isset($this->colsJname[$key])) {
904 if (!is_numeric($val) || !is_long($val)) {
907 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
916 $x->setFrom($q_filtered);
921 // nice generic -- let's get rid of it.. where is it used!!!!
923 // Person / Group / most of my queries noww...
924 if (!empty($q['query']['name'])) {
925 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
928 // - projectdirectory staff list - persn queuy