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 * 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 // DB_DataObject::debuglevel(1);
158 // sets map and countWhat
159 $this->loadMap($x, $_columns, empty($_REQUEST['_distinct']) ? false: $_REQUEST['_distinct']);
161 $this->setFilters($x,$_REQUEST);
164 // build join if req.
165 //DB_DataObject::debugLevel(1);
166 $total = $x->count($this->countWhat);
169 //var_dump($total);exit;
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, $sort = '', $dir ='')
267 // Db_DataObject::debugLevel(1);
268 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
269 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
270 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
275 if (method_exists($x, 'applySort')) {
276 $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
278 if ($sorted === false) {
281 $sort_ar = explode(',', $sort);
284 foreach($sort_ar as $sort) {
286 if (strlen($sort) && isset($cols[$sort]) ) {
287 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
289 } else if (in_array($sort, array_keys($this->cols))) {
290 $sort_str[] = $sort . ' ' . $dir ;
295 $x->orderBy(implode(', ', $sort_str ));
300 * POST method Roo/TABLENAME.php
301 * -- updates the data..
304 * _debug - forces debugging on.
305 * _get - forces a get request
306 * _ids - multiple update of records.
307 * {colid} - forces fetching
310 function post($tab) // update / insert (?? dleete??)
312 // DB_DataObject::debugLevel(1);
313 if (!empty($_REQUEST['_debug'])) {
314 DB_DataObject::debugLevel(1);
317 if (!empty($_REQUEST['_get'])) {
318 return $this->get($tab);
321 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
323 $tab = str_replace('/', '',$tab); // basic protection??
324 $x = DB_DataObject::factory($tab);
325 if (!is_a($x, 'DB_DataObject')) {
326 $this->jerr('invalid url');
328 // find the key and use that to get the thing..
331 $this->jerr('no key');
334 // delete should be here...
335 if (isset($_REQUEST['_delete'])) {
336 // do we really delete stuff!?!?!?
337 return $this->delete($x,$_REQUEST);
343 if (!empty($_REQUEST['_ids'])) {
344 $ids = explode(',',$_REQUEST['_ids']);
345 $x->whereAddIn($keys[0], $ids, 'int');
346 $ar = $x->fetchAll();
348 $this->update($x, $_REQUEST);
352 $this->jok("UPDATED");
358 if (!empty($_REQUEST[$keys[0]])) {
360 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
361 $this->jerr("Invalid request");
363 $this->jok($this->update($x, $_REQUEST));
367 $this->jerr("No data recieved for inserting");
370 $this->jok($this->insert($x, $_REQUEST));
377 function insert($x, $req)
381 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
382 $this->jerr("PERMISSION DENIED");
385 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
387 if (method_exists($x, 'setFromRoo')) {
388 $res = $x->setFromRoo($req, $this);
389 if (is_string($res)) {
399 if (isset($cols['created'])) {
400 $x->created = date('Y-m-d H:i:s');
402 if (isset($cols['created_dt'])) {
403 $x->created_dt = date('Y-m-d H:i:s');
405 if (isset($cols['created_by'])) {
406 $x->created_by = $this->authUser->id;
410 if (isset($cols['modified'])) {
411 $x->modified = date('Y-m-d H:i:s');
413 if (isset($cols['modified_dt'])) {
414 $x->modified_dt = date('Y-m-d H:i:s');
416 if (isset($cols['modified_by'])) {
417 $x->modified_by = $this->authUser->id;
420 if (isset($cols['updated'])) {
421 $x->updated = date('Y-m-d H:i:s');
423 if (isset($cols['updated_dt'])) {
424 $x->updated_dt = date('Y-m-d H:i:s');
426 if (isset($cols['updated_by'])) {
427 $x->updated_by = $this->authUser->id;
435 if (method_exists($x, 'onInsert')) {
436 $x->onInsert($_REQUEST, $this);
438 $this->addEvent("ADD", $x);
440 // note setFrom might handle this before hand...!??!
441 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
445 $r = DB_DataObject::factory($x->tableName());
447 // let's assume it has a key!!!
450 $this->loadMap($r, $_columns);
454 $rooar = method_exists($r, 'toRooArray');
455 //print_r(var_dump($rooar)); exit;
456 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
460 function update($x, $req)
462 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
463 $this->jerr("PERMISSION DENIED");
467 // only done if we recieve a lock_id.
468 // we are very trusing here.. that someone has not messed around with locks..
469 // the object might want to check in their checkPerm - if locking is essential..
471 $lock = DB_DataObjecT::factory('Core_locking');
472 if (is_a($lock,'DB_DataObject')) {
474 $lock->on_id = $x->id;
475 $lock->on_table= $x->tableName();
476 if (!empty($_REQUEST['_lock_id'])) {
477 $lock->whereAdd('id != ' . ((int)$_REQUEST['_lock_id']));
480 if ($lock->find(true)) {
481 // it's locked by someone else..
482 $p = $lock->person();
483 $this->jerr("Your lock is invalid, This record is locked by " . $p->name . " at " .$lock->created);
485 // check the users lock.. - no point.. ??? - if there are no other locks and it's not the users, then they can
486 // edit it anyways...
495 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
500 // this lot is generic.. needs moving
501 if (method_exists($x, 'setFromRoo')) {
502 $res = $x->setFromRoo($req, $this);
503 if (is_string($res)) {
509 $this->addEvent("EDIT", $x);
515 if (isset($cols['modified'])) {
516 $x->modified = date('Y-m-d H:i:s');
518 if (isset($cols['modified_dt'])) {
519 $x->modified_dt = date('Y-m-d H:i:s');
521 if (isset($cols['modified_by'])) {
522 $x->modified_by = $this->authUser->id;
525 if (isset($cols['updated'])) {
526 $x->updated = date('Y-m-d H:i:s');
528 if (isset($cols['updated_dt'])) {
529 $x->updated_dt = date('Y-m-d H:i:s');
531 if (isset($cols['updated_by'])) {
532 $x->updated_by = $this->authUser->id;
537 if (method_exists($x, 'onUpdate')) {
538 $x->onUpdate($old, $req, $this);
541 $r = DB_DataObject::factory($x->tableName());
543 // let's assume it has a key!!!
546 $this->loadMap($r, $_columns);
549 $rooar = method_exists($r, 'toRooArray');
550 //print_r(var_dump($rooar)); exit;
551 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
554 function delete($x, $req)
556 // do we really delete stuff!?!?!?
557 if (empty($req['_delete'])) {
558 $this->jerr("Delete Requested with no value");
561 // build a list of tables to queriy for dependant data..
566 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
567 foreach($all_links as $tbl => $links) {
568 foreach($links as $col => $totbl_col) {
569 $to = explode(':', $totbl_col);
570 if ($to[0] != $x->tableName()) {
574 $affects[$tbl .'.' . $col] = true;
579 // echo '<PRE>';print_r($affects);exit;
580 //DB_Dataobject::debugLevel(1);
583 $clean = create_function('$v', 'return (int)$v;');
585 $bits = array_map($clean, explode(',', $req['_delete']));
587 // print_r($bits);exit;
589 // let's assume it has a key!!!
592 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
594 $this->jerr("Nothing found to delete");
597 while ($x->fetch()) {
603 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
604 $this->jerr("PERMISSION DENIED");
607 // before delte = allows us to trash dependancies if needed..
608 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
609 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
615 foreach($affects as $k=> $true) {
616 $ka = explode('.', $k);
617 $chk = DB_DataObject::factory($ka[0]);
618 if (!is_a($chk,'DB_DataObject')) {
619 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
621 $chk->{$ka[1]} = $xx->$pk;
622 $matches = $chk->count();
625 $o = $chk->fetchAll();
626 $desc = $ka[0]. ':' . $ka[1] .'='.$xx->$pk;
627 if (method_exists($chk, 'toEventString')) {
628 $desc = $ka[0] . ' : ' . $o[0]->toEventString();
631 $this->jerr("Delete Dependant records ($matches found), first is ( $desc )");
636 $this->addEvent("DELETE", $x);
641 $this->jerr(implode("\n<BR>", $errs));
643 $this->jok("Deleted");
651 function loadMap($do, $filter=false, $distinct = false)
653 //DB_DataObject::debugLevel(1);
655 $this->countWhat = false;
661 $mods = explode(',',$this->appModules);
663 $ff = HTML_FlexyFramework::get();
664 //$db->databaseName();
666 //$ff->DB_DataObject['ini_'. $db->database()];
667 //echo '<PRE>';print_r($do->links());exit;
670 if (in_array('Builder', $mods) ) {
672 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
674 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
677 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
678 if (!file_exists($ini)) {
681 $conf = array_merge($conf, parse_ini_file($ini,true));
682 if (!isset($conf[$do->tableName()])) {
685 $map = $conf[$do->tableName()];
696 $tabdef = $do->table();
697 if (isset($tabdef['passwd'])) {
698 // prevent exposure of passwords..
699 unset($tabdef['passwd']);
702 $xx = array_keys($tabdef);
703 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
705 $selectAs = array(array( $xx , '%s', false));
707 $has_distinct = false;
708 if ($filter || $distinct) {
710 //echo '<PRE>' ;print_r($filter);exit;
712 if ($distinct && $distinct == $c) {
713 $has_distinct = 'DISTINCT( ' . $do->tableName() .'.'. $c .') as ' . $c;
714 $this->countWhat = 'DISTINCT ' . $do->tableName() .'.'. $c .'';
717 if (!$filter || in_array($c, $filter)) {
723 $selectAs = empty($cols) ? array() : array(array( $cols , '%s', false)) ;
729 $this->cols = array();
730 $this->colsJoinName =array();
732 $this->cols[$k] = $do->tableName(). '.' . $k;
740 foreach($map as $ocl=>$info) {
742 list($tab,$col) = explode(':', $info);
743 // what about multiple joins on the same table!!!
744 $xx = DB_DataObject::factory($tab);
745 if (!is_a($xx, 'DB_DataObject')) {
748 // this is borked ... for multiple jions..
749 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
750 $tabdef = $xx->table();
751 $table = $xx->tableName();
752 if (isset($tabdef['passwd'])) {
754 unset($tabdef['passwd']);
757 $xx = array_keys($tabdef);
760 if ($filter || $distinct) {
763 $tn = sprintf($ocl.'_%s', $c);
764 // echo '<PRE>'; var_dump($tn);
765 if ($distinct && $tn == $distinct) {
766 $has_distinct = 'DISTINCT( ' . 'join_'.$ocl.'_'.$col.'.'.$k .') as ' . $tn ;
767 $this->countWhat = 'DISTINCT join_'.$ocl.'_'.$col.'.'.$k;
772 if (!$filter || in_array($tn, $filter)) {
777 $selectAs[] = array($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
782 $selectAs[] = array($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
788 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
789 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
796 $do->selectAdd($has_distinct);
798 //DB_DataObject::debugLevel(1);
799 // we do select as after everything else as we need to plop distinct at the beginning??
801 // echo '<PRE>';print_r($this->colsJname);exit;
802 foreach($selectAs as $ar) {
803 $do->selectAs($ar[0], $ar[1], $ar[2]);
809 * generate the meta data neede by queries.
812 function meta($x, $data)
814 // this is not going to work on queries where the data does not match the database def..
815 // for unknown columns we send them as stirngs..
817 $cols = array_keys($data[0]);
822 //echo '<PRE>';print_r($this->cols); exit;
823 $options = &PEAR::getStaticProperty('DB_DataObject','options');
824 $reader = $options["ini_{$x->_database}"] .'.reader';
825 if (!file_exists( $reader )) {
829 $rdata = unserialize(file_get_contents($reader));
831 // echo '<PRE>';print_r($rdata);exit;
834 foreach($cols as $c ) {
835 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
839 $add = $rdata[$this->cols[$c]];
844 'totalProperty' => 'total',
845 'successProperty' => 'success',
854 function setFilters($x, $q)
856 // if a column is type int, and we get ',' -> the it should be come an inc clause..
857 // DB_DataObject::debugLevel(1);
858 if (method_exists($x, 'applyFilters')) {
859 // DB_DataObject::debugLevel(1);
860 $x->applyFilters($q, $this->authUser);
862 $q_filtered = array();
864 foreach($q as $key=>$val) {
866 // value is an array..
867 if (is_array($val) ) {
869 if (!in_array( $key, array_keys($this->cols))) {
873 // support a[0] a[1] ..... => whereAddIn(
876 foreach($val as $k=>$v) {
877 if (!is_numeric($k)) {
881 // FIXME: note this is not typesafe for anything other than mysql..
883 if (!is_numeric($v) || !is_long($v)) {
893 isset($this->colsJname[$key]) ?
894 $this->colsJname[$key] :
895 ($x->tableName(). '.'.$key),
896 $ar, $quote ? 'string' : 'int');
904 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
906 $key = substr($key, 1) ;
909 isset($this->colsJname[$key]) ?
910 $this->colsJname[$key] :
911 $x->tableName(). '.'.$key ) . ' != ' .
912 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
922 // Events and remarks -- fixme - move to events/remarsk...
923 case 'on_id': // where TF is this used...
924 if (!empty($q['query']['original'])) {
925 // DB_DataObject::debugLevel(1);
926 $o = (int) $q['query']['original'];
928 $x->whereAdd("(on_id = $oid OR
929 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
939 $q_filtered[$key] = $val;
942 // subjoined columns = check the values.
943 // note this is not typesafe for anything other than mysql..
945 if (isset($this->colsJname[$key])) {
947 if (!is_numeric($val) || !is_long($val)) {
950 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
959 $x->setFrom($q_filtered);
964 // nice generic -- let's get rid of it.. where is it used!!!!
966 // Person / Group / most of my queries noww...
967 if (!empty($q['query']['name'])) {
968 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
971 // - projectdirectory staff list - persn queuy