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, $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 * 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, $_REQUEST) : $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");
465 // only done if we recieve a lock_id.
466 // we are very trusing here.. that someone has not messed around with locks..
467 // the object might want to check in their checkPerm - if locking is essential..
469 $lock = DB_DataObjecT::factory('Core_locking');
470 if (is_a($lock,'DB_DataObject')) {
472 $lock->on_id = $x->id;
473 $lock->on_table= $x->tableName();
474 if (!empty($_REQUEST['_lock_id'])) {
475 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
478 if ($lock->find(true)) {
479 // it's locked by someone else..
480 $p = $lock->person();
481 $this->jerr("Your lock is invalid, This record is locked by " . $p->name . " at " .$lock->created);
483 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
484 // edit it anyways...
493 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
498 // this lot is generic.. needs moving
499 if (method_exists($x, 'setFromRoo')) {
500 $res = $x->setFromRoo($req, $this);
501 if (is_string($res)) {
507 $this->addEvent("EDIT", $x);
513 if (isset($cols['modified'])) {
514 $x->modified = date('Y-m-d H:i:s');
516 if (isset($cols['modified_dt'])) {
517 $x->modified_dt = date('Y-m-d H:i:s');
519 if (isset($cols['modified_by'])) {
520 $x->modified_by = $this->authUser->id;
523 if (isset($cols['updated'])) {
524 $x->updated = date('Y-m-d H:i:s');
526 if (isset($cols['updated_dt'])) {
527 $x->updated_dt = date('Y-m-d H:i:s');
529 if (isset($cols['updated_by'])) {
530 $x->updated_by = $this->authUser->id;
535 if (method_exists($x, 'onUpdate')) {
536 $x->onUpdate($old, $req, $this);
539 $r = DB_DataObject::factory($x->tableName());
541 // let's assume it has a key!!!
544 $this->loadMap($r, $_columns);
547 $rooar = method_exists($r, 'toRooArray');
548 //print_r(var_dump($rooar)); exit;
549 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
552 function delete($x, $req)
554 // do we really delete stuff!?!?!?
555 if (empty($req['_delete'])) {
556 $this->jerr("Delete Requested with no value");
559 // build a list of tables to queriy for dependant data..
564 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
565 foreach($all_links as $tbl => $links) {
566 foreach($links as $col => $totbl_col) {
567 $to = explode(':', $totbl_col);
568 if ($to[0] != $x->tableName()) {
572 $affects[$tbl .'.' . $col] = true;
577 // echo '<PRE>';print_r($affects);exit;
578 //DB_Dataobject::debugLevel(1);
581 $clean = create_function('$v', 'return (int)$v;');
583 $bits = array_map($clean, explode(',', $req['_delete']));
585 // print_r($bits);exit;
587 // let's assume it has a key!!!
590 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
592 $this->jerr("Nothing found to delete");
595 while ($x->fetch()) {
601 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
602 $this->jerr("PERMISSION DENIED");
605 // before delte = allows us to trash dependancies if needed..
606 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
607 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
613 foreach($affects as $k=> $true) {
614 $ka = explode('.', $k);
615 $chk = DB_DataObject::factory($ka[0]);
616 if (!is_a($chk,'DB_DataObject')) {
617 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
619 $chk->{$ka[1]} = $xx->$pk;
620 $matches = $chk->count();
623 $o = $chk->fetchAll();
624 $desc = $ka[0]. ':' . $ka[1] .'='.$xx->$pk;
625 if (method_exists($chk, 'toEventString')) {
626 $desc = $ka[0] . ' : ' . $o[0]->toEventString();
629 $this->jerr("Delete Dependant records first ($matches found) first is ('. $desc.')');
634 $this->addEvent("DELETE", $x);
639 $this->jerr(implode("\n<BR>", $errs));
641 $this->jok("Deleted");
649 function loadMap($do, $filter=false, $distinct = false)
651 //DB_DataObject::debugLevel(1);
653 $this->countWhat = false;
659 $mods = explode(',',$this->appModules);
661 $ff = HTML_FlexyFramework::get();
662 //$db->databaseName();
664 //$ff->DB_DataObject['ini_'. $db->database()];
665 //echo '<PRE>';print_r($do->links());exit;
668 if (in_array('Builder', $mods) ) {
670 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
672 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
675 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
676 if (!file_exists($ini)) {
679 $conf = array_merge($conf, parse_ini_file($ini,true));
680 if (!isset($conf[$do->tableName()])) {
683 $map = $conf[$do->tableName()];
694 $tabdef = $do->table();
695 if (isset($tabdef['passwd'])) {
696 // prevent exposure of passwords..
697 unset($tabdef['passwd']);
700 $xx = array_keys($tabdef);
701 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
703 $selectAs = array(array( $xx , '%s', false));
705 $has_distinct = false;
706 if ($filter || $distinct) {
708 //echo '<PRE>' ;print_r($filter);exit;
710 if ($distinct && $distinct == $c) {
711 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
712 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
715 if (!$filter || in_array($c, $filter)) {
721 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
727 $this->cols = array();
728 $this->colsJoinName =array();
730 $this->cols[$k] = $do->tableName(). '.' . $k;
738 foreach($map as $ocl=>$info) {
740 list($tab,$col) = explode(':', $info);
741 // what about multiple joins on the same table!!!
742 $xx = DB_DataObject::factory($tab);
743 if (!is_a($xx, 'DB_DataObject')) {
746 // this is borked ... for multiple jions..
747 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
748 $tabdef = $xx->table();
749 $table = $xx->tableName();
750 if (isset($tabdef['passwd'])) {
752 unset($tabdef['passwd']);
755 $xx = array_keys($tabdef);
758 if ($filter || $distinct) {
761 $tn = sprintf($ocl.'_%s', $c);
762 // echo '<PRE>'; var_dump($tn);
763 if ($distinct && $tn == $distinct) {
764 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
765 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
770 if (!$filter || in_array($tn, $filter)) {
775 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
780 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
786 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
787 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
794 $do->selectAdd($has_distinct);
796 //DB_DataObject::debugLevel(1);
797 // we do select as after everything else as we need to plop distinct at the beginning??
799 // echo '<PRE>';print_r($this->colsJname);exit;
800 foreach($selectAs as $ar) {
801 $do->selectAs($ar[0], $ar[1], $ar[2]);
807 * generate the meta data neede by queries.
810 function meta($x, $data)
812 // this is not going to work on queries where the data does not match the database def..
813 // for unknown columns we send them as stirngs..
815 $cols = array_keys($data[0]);
820 //echo '<PRE>';print_r($this->cols); exit;
821 $options = &PEAR::getStaticProperty('DB_DataObject','options');
822 $reader = $options["ini_{$x->_database}"] .'.reader';
823 if (!file_exists( $reader )) {
827 $rdata = unserialize(file_get_contents($reader));
829 // echo '<PRE>';print_r($rdata);exit;
832 foreach($cols as $c ) {
833 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
837 $add = $rdata[$this->cols[$c]];
842 'totalProperty' => 'total',
843 'successProperty' => 'success',
852 function setFilters($x, $q)
854 // if a column is type int, and we get ',' -> the it should be come an inc clause..
855 // DB_DataObject::debugLevel(1);
856 if (method_exists($x, 'applyFilters')) {
857 // DB_DataObject::debugLevel(1);
858 $x->applyFilters($q, $this->authUser);
860 $q_filtered = array();
862 foreach($q as $key=>$val) {
864 // value is an array..
865 if (is_array($val) ) {
867 if (!in_array( $key, array_keys($this->cols))) {
871 // support a[0] a[1] ..... => whereAddIn(
874 foreach($val as $k=>$v) {
875 if (!is_numeric($k)) {
879 // FIXME: note this is not typesafe for anything other than mysql..
881 if (!is_numeric($v) || !is_long($v)) {
891 isset($this->colsJname[$key]) ?
892 $this->colsJname[$key] :
893 ($x->tableName(). '.'.$key),
894 $ar, $quote ? 'string' : 'int');
902 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
904 $key = substr($key, 1) ;
907 isset($this->colsJname[$key]) ?
908 $this->colsJname[$key] :
909 $x->tableName(). '.'.$key ) . ' != ' .
910 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
920 // Events and remarks -- fixme - move to events/remarsk...
921 case 'on_id': // where TF is this used...
922 if (!empty($q['query']['original'])) {
923 // DB_DataObject::debugLevel(1);
924 $o = (int) $q['query']['original'];
926 $x->whereAdd("(on_id = $oid OR
927 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
937 $q_filtered[$key] = $val;
940 // subjoined columns = check the values.
941 // note this is not typesafe for anything other than mysql..
943 if (isset($this->colsJname[$key])) {
945 if (!is_numeric($val) || !is_long($val)) {
948 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
957 $x->setFrom($q_filtered);
962 // nice generic -- let's get rid of it.. where is it used!!!!
964 // Person / Group / most of my queries noww...
965 if (!empty($q['query']['name'])) {
966 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
969 // - projectdirectory staff list - persn queuy