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));
76 // 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");
155 $map = $this->loadMap($x, $_columns);
157 $this->setFilters($x,$_REQUEST);
161 // build join if req.
163 if (!empty($_REQUEST['_distinct'])) {
167 if (isset($cols[$_REQUEST['_distinct']])) {
168 $countWhat = 'distinct ' . $_REQUEST['_distinct'];
170 $x->selectAdd('distinct('.$_REQUEST['_distinct'].')');
171 $_columns = array( $_REQUEST['_distinct'] );
173 $this->jerr('invalid distinct');
177 $total = $x->count($countWhat);
179 // DB_DataObject::debugLevel(1);
181 $this->applySort($x);
186 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
187 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
190 $queryObj = clone($x);
195 if (!empty($_REQUEST['query']['add_blank'])) {
196 $ret[] = array( 'id' => 0, 'name' => '----');
201 //if (($tab == 'Groups') && ($_REQUEST['type'] != 0)) { // then it's a list of teams..
202 if ($tab == 'Groups') {
204 $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
205 $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
206 //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
212 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
213 header('Content-type: text/csv');
215 header('Content-Disposition: attachment; filename="list-export-'.date('Y-m-d') . '.csv"');
216 //header('Content-type: text/plain');
217 $fh = fopen('php://output', 'w');
218 fputcsv($fh, $_REQUEST['csvTitles']);
219 while ($x->fetch()) {
220 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
222 foreach($_REQUEST['csvCols'] as $k) {
223 $line[] = isset($x->$k) ? $x->$k : '';
234 $rooar = method_exists($x, 'toRooArray');
236 while ($x->fetch()) {
237 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
239 $ret[] = !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
241 //if ($x->tableName() == 'Documents_Tracking') {
242 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
246 if (method_exists($queryObj ,'postListExtra')) {
247 $extra = $queryObj->postListExtra($_REQUEST);
249 // filter results, and add any data that is needed...
250 if (method_exists($x,'postListFilter')) {
251 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
254 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
255 $meta = $this->meta($x, $ret);
257 $extra['metaData'] = $meta;
261 // echo "<PRE>"; print_r($ret);
262 $this->jdata($ret,$total, $extra );
269 * apply REQUEST[sort] and [dir]
270 * sort may be an array of columsn..
272 * @arg DB_DataObject $x
275 function applySort($x)
278 // Db_DataObject::debugLevel(1);
279 $sort = empty($_REQUEST['sort']) ? '' : $_REQUEST['sort'];
280 $dir = (empty($_REQUEST['dir']) || strtoupper($_REQUEST['dir']) == 'ASC' ? 'ASC' : 'DESC');
285 if (method_exists($x, 'applySort')) {
286 $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
288 if ($sorted === false) {
291 $sort_ar = explode(',', $sort);
294 foreach($sort_ar as $sort) {
296 if (strlen($sort) && isset($cols[$sort]) ) {
297 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
299 } else if (in_array($sort, array_keys($this->cols))) {
300 $sort_str[] = $sort . ' ' . $dir ;
305 $x->orderBy(implode(', ', $sort_str ));
310 * POST method Roo/TABLENAME.php
311 * -- updates the data..
314 * _debug - forces debugging on.
315 * _get - forces a get request
316 * _ids - multiple update of records.
317 * {colid} - forces fetching
320 function post($tab) // update / insert (?? dleete??)
322 // DB_DataObject::debugLevel(1);
323 if (!empty($_REQUEST['_debug'])) {
324 DB_DataObject::debugLevel(1);
327 if (!empty($_REQUEST['_get'])) {
328 return $this->get($tab);
331 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
333 $tab = str_replace('/', '',$tab); // basic protection??
334 $x = DB_DataObject::factory($tab);
335 if (!is_a($x, 'DB_DataObject')) {
336 $this->jerr('invalid url');
338 // find the key and use that to get the thing..
341 $this->jerr('no key');
344 // delete should be here...
345 if (isset($_REQUEST['_delete'])) {
346 // do we really delete stuff!?!?!?
347 return $this->delete($x,$_REQUEST);
353 if (!empty($_REQUEST['_ids'])) {
354 $ids = explode(',',$_REQUEST['_ids']);
355 $x->whereAddIn($keys[0], $ids, 'int');
356 $ar = $x->fetchAll();
358 $this->update($x, $_REQUEST);
362 $this->jok("UPDATED");
368 if (!empty($_REQUEST[$keys[0]])) {
370 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
371 $this->jerr("Invalid request");
373 $this->jok($this->update($x, $_REQUEST));
377 $this->jerr("No data recieved for inserting");
380 $this->jok($this->insert($x, $_REQUEST));
387 function insert($x, $req)
391 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
392 $this->jerr("PERMISSION DENIED");
395 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
397 if (method_exists($x, 'setFromRoo')) {
398 $res = $x->setFromRoo($req, $this);
399 if (is_string($res)) {
409 if (isset($cols['created'])) {
410 $x->created = date('Y-m-d H:i:s');
412 if (isset($cols['created_dt'])) {
413 $x->created_dt = date('Y-m-d H:i:s');
415 if (isset($cols['created_by'])) {
416 $x->created_by = $this->authUser->id;
420 if (isset($cols['modified'])) {
421 $x->modified = date('Y-m-d H:i:s');
423 if (isset($cols['modified_dt'])) {
424 $x->modified_dt = date('Y-m-d H:i:s');
426 if (isset($cols['modified_by'])) {
427 $x->modified_by = $this->authUser->id;
430 if (isset($cols['updated'])) {
431 $x->updated = date('Y-m-d H:i:s');
433 if (isset($cols['updated_dt'])) {
434 $x->updated_dt = date('Y-m-d H:i:s');
436 if (isset($cols['updated_by'])) {
437 $x->updated_by = $this->authUser->id;
445 if (method_exists($x, 'onInsert')) {
446 $x->onInsert($_REQUEST, $this);
448 $this->addEvent("ADD", $x, $x->toEventString());
450 // note setFrom might handle this before hand...!??!
451 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
455 $r = DB_DataObject::factory($x->tableName());
457 // let's assume it has a key!!!
460 $this->loadMap($r, $_columns);
464 $rooar = method_exists($r, 'toRooArray');
465 //print_r(var_dump($rooar)); exit;
466 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
470 function update($x, $req)
472 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
473 $this->jerr("PERMISSION DENIED");
476 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
481 // this lot is generic.. needs moving
482 if (method_exists($x, 'setFromRoo')) {
483 $res = $x->setFromRoo($req, $this);
484 if (is_string($res)) {
490 $this->addEvent("EDIT", $x, $x->toEventString());
496 if (isset($cols['modified'])) {
497 $x->modified = date('Y-m-d H:i:s');
499 if (isset($cols['modified_dt'])) {
500 $x->modified_dt = date('Y-m-d H:i:s');
502 if (isset($cols['modified_by'])) {
503 $x->modified_by = $this->authUser->id;
506 if (isset($cols['updated'])) {
507 $x->updated = date('Y-m-d H:i:s');
509 if (isset($cols['updated_dt'])) {
510 $x->updated_dt = date('Y-m-d H:i:s');
512 if (isset($cols['updated_by'])) {
513 $x->updated_by = $this->authUser->id;
518 if (method_exists($x, 'onUpdate')) {
519 $x->onUpdate($old, $req, $this);
522 $r = DB_DataObject::factory($x->tableName());
524 // let's assume it has a key!!!
527 $this->loadMap($r, $_columns);
530 $rooar = method_exists($r, 'toRooArray');
531 //print_r(var_dump($rooar)); exit;
532 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
535 function delete($x, $req)
537 // do we really delete stuff!?!?!?
538 if (empty($req['_delete'])) {
539 $this->jerr("Delete Requested with no value");
542 // build a list of tables to queriy for dependant data..
547 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
548 foreach($all_links as $tbl => $links) {
549 foreach($links as $col => $totbl_col) {
550 $to = explode(':', $totbl_col);
551 if ($to[0] != $x->tableName()) {
555 $affects[$tbl .'.' . $col] = true;
560 // echo '<PRE>';print_r($affects);exit;
561 //DB_Dataobject::debugLevel(1);
564 $clean = create_function('$v', 'return (int)$v;');
566 $bits = array_map($clean, explode(',', $req['_delete']));
568 // print_r($bits);exit;
570 // let's assume it has a key!!!
573 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
575 $this->jerr("Nothing found to delete");
578 while ($x->fetch()) {
582 foreach($affects as $k=> $true) {
583 $ka = explode('.', $k);
584 $chk = DB_DataObject::factory($ka[0]);
585 if (!is_a($chk,'DB_DataObject')) {
586 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
588 $chk->{$ka[1]} = $xx->$pk;
590 $this->jerr('Delete Dependant records first ('. $ka[0]. ':' . $ka[1] .'='.$xx->$pk.')');
596 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
597 $this->jerr("PERMISSION DENIED");
600 $this->addEvent("DELETE", $x, $x->toEventString());
601 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
602 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
608 $this->jerr(implode("\n<BR>", $errs));
610 $this->jok("Deleted");
618 function loadMap($do, $filter=false)
620 //DB_DataObject::debugLevel(1);
625 $mods = explode(',',$this->appModules);
627 $ff = HTML_FlexyFramework::geT();
628 //$db->databaseName();
630 //$ff->DB_DataObject['ini_'. $db->database()];
631 //echo '<PRE>';print_r($do->links());exit;
634 if (in_array('Builder', $mods) ) {
636 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
638 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
641 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
642 if (!file_exists($ini)) {
645 $conf = array_merge($conf, parse_ini_file($ini,true));
646 if (!isset($conf[$do->tableName()])) {
649 $map = $conf[$do->tableName()];
659 $tabdef = $do->table();
660 if (isset($tabdef['passwd'])) {
661 // prevent exposure of passwords..
662 unset($tabdef['passwd']);
665 $xx = array_keys($tabdef);
666 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
672 if (in_array($c, $filter)) {
676 $do->selectAs($cols);
682 $this->cols = array();
683 $this->colsJoinName =array();
685 $this->cols[$k] = $do->tableName(). '.' . $k;
693 foreach($map as $ocl=>$info) {
695 list($tab,$col) = explode(':', $info);
696 // what about multiple joins on the same table!!!
697 $xx = DB_DataObject::factory($tab);
698 if (!is_a($xx, 'DB_DataObject')) {
701 // this is borked ... for multiple jions..
702 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
703 $tabdef = $xx->table();
704 $table = $xx->tableName();
705 if (isset($tabdef['passwd'])) {
707 unset($tabdef['passwd']);
710 $xx = array_keys($tabdef);
717 $tn = sprintf($ocl.'_%s', $c);
718 if (in_array($tn, $filter)) {
722 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
724 $do->selectAs($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
729 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
730 $this->colsJname[sprintf($ocl.'_%s', $k)] = 'join_'.$ocl.'_'.$col.'.'.$k;
735 //DB_DataObject::debugLevel(1);
741 * generate the meta data neede by queries.
744 function meta($x, $data)
746 // this is not going to work on queries where the data does not match the database def..
747 // for unknown columns we send them as stirngs..
749 $cols = array_keys($data[0]);
754 //echo '<PRE>';print_r($this->cols); exit;
755 $options = &PEAR::getStaticProperty('DB_DataObject','options');
756 $reader = $options["ini_{$x->_database}"] .'.reader';
757 if (!file_exists( $reader )) {
761 $rdata = unserialize(file_get_contents($reader));
763 // echo '<PRE>';print_r($rdata);exit;
766 foreach($cols as $c ) {
767 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
771 $add = $rdata[$this->cols[$c]];
776 'totalProperty' => 'total',
777 'successProperty' => 'success',
786 function setFilters($x, $q)
788 // if a column is type int, and we get ',' -> the it should be come an inc clause..
789 // DB_DataObject::debugLevel(1);
790 if (method_exists($x, 'applyFilters')) {
791 // DB_DataObject::debugLevel(1);
792 $x->applyFilters($q, $this->authUser);
794 $q_filtered = array();
796 foreach($q as $key=>$val) {
798 // value is an array..
799 if (is_array($val) ) {
801 if (!in_array( $key, array_keys($this->cols))) {
805 // support a[0] a[1] ..... => whereAddIn(
808 foreach($val as $k=>$v) {
809 if (!is_numeric($k)) {
813 // FIXME: note this is not typesafe for anything other than mysql..
815 if (!is_numeric($v) || !is_long($v)) {
825 isset($this->colsJoinName[$key]) ?
826 $this->colsJoinName[$key] :
827 $x->tableName(). '.'.$key,
828 $ar, $quote ? 'string' : 'int');
836 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
839 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
840 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
850 // Events and remarks
851 case 'on_id': // where TF is this used...
852 if (!empty($q['query']['original'])) {
853 // DB_DataObject::debugLevel(1);
854 $o = (int) $q['query']['original'];
856 $x->whereAdd("(on_id = $oid OR
857 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
867 $q_filtered[$key] = $val;
870 // subjoined columns = check the values.
871 // note this is not typesafe for anything other than mysql..
873 if (isset($this->colsJname[$key])) {
875 if (!is_numeric($val) || !is_long($val)) {
878 $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
887 $x->setFrom($q_filtered);
892 // nice generic -- let's get rid of it.. where is it used!!!!
894 // Person / Group / most of my queries noww...
895 if (!empty($q['query']['name'])) {
896 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
899 // - projectdirectory staff list - persn queuy