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 = return data as csv
62 * csvTitles = return data as csv
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);
79 if (!empty($_GET['_post'])) {
81 DB_DAtaObject::debuglevel(1);
82 return $this->post($tab);
84 $tab = str_replace('/', '',$tab); // basic protection??
85 $x = DB_DataObject::factory($tab);
86 if (!is_a($x, 'DB_DataObject')) {
87 $this->jerr('invalid url');
89 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
91 if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
92 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
93 $this->jerr("PERMISSION DENIED");
95 $this->loadMap($x, $_columns);
96 $x->setFrom($_REQUEST['lookup'] );
98 if (!$x->find(true)) {
101 $this->jok($x->toArray());
106 if (isset($_REQUEST['_id'])) { // single fetch
108 if (empty($_REQUEST['_id'])) {
109 $this->jok($x->toArray()); // return an empty array!
112 $this->loadMap($x, $_columns);
114 if (!$x->get($_REQUEST['_id'])) {
115 $this->jerr("no such record");
118 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
119 $this->jerr("PERMISSION DENIED");
122 $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser) : $x->toArray());
125 if (isset($_REQUEST['_delete'])) {
126 // do we really delete stuff!?!?!?
127 return $this->delete($x,$_REQUEST);
133 if (isset($_REQUEST['_toggleActive'])) {
134 // do we really delete stuff!?!?!?
135 if (!$this->hasPerm("Core.Staff", 'E')) {
136 $this->jerr("PERMISSION DENIED");
138 $clean = create_function('$v', 'return (int)$v;');
139 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
140 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
141 $this->jerr("you can not disable yourself");
143 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
144 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
145 $this->jok("Updated");
148 // DB_DataObject::debugLevel(1);
149 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
150 $this->jerr("PERMISSION DENIED");
152 $map = $this->loadMap($x, $_columns);
154 $this->setFilters($x,$_REQUEST);
158 // build join if req.
160 if (!empty($_REQUEST['_distinct'])) {
164 if (isset($cols[$_REQUEST['_distinct']])) {
165 $countWhat = 'distinct ' . $_REQUEST['_distinct'];
167 $x->selectAdd('distinct('.$_REQUEST['_distinct'].')');
168 $_columns = array( $_REQUEST['_distinct'] );
170 $this->jerr('invalid distinct');
174 $total = $x->count($countWhat);
176 // DB_DataObject::debugLevel(1);
178 $this->applySort($x);
183 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
184 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
187 $queryObj = clone($x);
192 if (!empty($_REQUEST['query']['add_blank'])) {
193 $ret[] = array( 'id' => 0, 'name' => '----');
198 //if (($tab == 'Groups') && ($_REQUEST['type'] != 0)) { // then it's a list of teams..
199 if ($tab == 'Groups') {
201 $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
202 $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
203 //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
209 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
210 header('Content-type: text/csv');
212 header('Content-Disposition: attachment; filename="documentlist-export-'.date('Y-m-d') . '.csv"');
213 //header('Content-type: text/plain');
214 $fh = fopen('php://output', 'w');
215 fputcsv($fh, $_REQUEST['csvTitles']);
216 while ($x->fetch()) {
217 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
219 foreach($_REQUEST['csvCols'] as $k) {
220 $line[] = isset($x->$k) ? $x->$k : '';
231 $rooar = method_exists($x, 'toRooArray');
233 while ($x->fetch()) {
234 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
236 $ret[] = !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
238 //if ($x->tableName() == 'Documents_Tracking') {
239 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
243 if (method_exists($queryObj ,'postListExtra')) {
244 $extra = $queryObj->postListExtra($_REQUEST);
246 // filter results, and add any data that is needed...
247 if (method_exists($x,'postListFilter')) {
248 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
251 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
252 $meta = $this->meta($x, $ret);
254 $extra['metaData'] = $meta;
258 // echo "<PRE>"; print_r($ret);
259 $this->jdata($ret,$total, $extra );
266 * apply REQUEST[sort] and [dir]
267 * sort may be an array of columsn..
269 * @arg DB_DataObject $x
272 function applySort($x)
275 // Db_DataObject::debugLevel(1);
276 $sort = empty($_REQUEST['sort']) ? '' : $_REQUEST['sort'];
277 $dir = (empty($_REQUEST['dir']) || strtoupper($_REQUEST['dir']) == 'ASC' ? 'ASC' : 'DESC');
282 if (method_exists($x, 'applySort')) {
283 $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
285 if ($sorted === false) {
288 $sort_ar = explode(',', $sort);
291 foreach($sort_ar as $sort) {
293 if (strlen($sort) && isset($cols[$sort]) ) {
294 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
296 } else if (in_array($sort, array_keys($this->cols))) {
297 $sort_str[] = $sort . ' ' . $dir ;
302 $x->orderBy(implode(', ', $sort_str ));
307 * POST method Roo/TABLENAME.php
308 * -- updates the data..
311 * _debug - forces debugging on.
312 * _get - forces a get request
313 * _ids - multiple update of records.
314 * {colid} - forces fetching
317 function post($tab) // update / insert (?? dleete??)
319 // DB_DataObject::debugLevel(1);
320 if (!empty($_REQUEST['_debug'])) {
321 DB_DataObject::debugLevel(1);
324 if (!empty($_REQUEST['_get'])) {
325 return $this->get($tab);
328 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
330 $tab = str_replace('/', '',$tab); // basic protection??
331 $x = DB_DataObject::factory($tab);
332 if (!is_a($x, 'DB_DataObject')) {
333 $this->jerr('invalid url');
335 // find the key and use that to get the thing..
338 $this->jerr('no key');
341 // delete should be here...
342 if (isset($_REQUEST['_delete'])) {
343 // do we really delete stuff!?!?!?
344 return $this->delete($x,$_REQUEST);
350 if (!empty($_REQUEST['_ids'])) {
351 $ids = explode(',',$_REQUEST['_ids']);
352 $x->whereAddIn($keys[0], $ids, 'int');
353 $ar = $x->fetchAll();
355 $this->update($x, $_REQUEST);
359 $this->jok("UPDATED");
365 if (!empty($_REQUEST[$keys[0]])) {
367 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
368 $this->jerr("Invalid request");
370 $this->jok($this->update($x, $_REQUEST));
374 $this->jerr("No data recieved for inserting");
377 $this->jok($this->insert($x, $_REQUEST));
384 function insert($x, $req)
388 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
389 $this->jerr("PERMISSION DENIED");
392 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
394 if (method_exists($x, 'setFromRoo')) {
395 $res = $x->setFromRoo($req, $this);
396 if (is_string($res)) {
406 if (isset($cols['created'])) {
407 $x->created = date('Y-m-d H:i:s');
409 if (isset($cols['created_dt'])) {
410 $x->created_dt = date('Y-m-d H:i:s');
412 if (isset($cols['created_by'])) {
413 $x->created_by = $this->authUser->id;
417 if (isset($cols['modified'])) {
418 $x->modified = date('Y-m-d H:i:s');
420 if (isset($cols['modified_dt'])) {
421 $x->modified_dt = date('Y-m-d H:i:s');
423 if (isset($cols['modified_by'])) {
424 $x->modified_by = $this->authUser->id;
427 if (isset($cols['updated'])) {
428 $x->updated = date('Y-m-d H:i:s');
430 if (isset($cols['updated_dt'])) {
431 $x->updated_dt = date('Y-m-d H:i:s');
433 if (isset($cols['updated_by'])) {
434 $x->updated_by = $this->authUser->id;
442 if (method_exists($x, 'onInsert')) {
443 $x->onInsert($_REQUEST, $this);
445 $this->addEvent("ADD", $x, $x->toEventString());
447 // note setFrom might handle this before hand...!??!
448 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
452 $r = DB_DataObject::factory($x->tableName());
454 // let's assume it has a key!!!
457 $this->loadMap($r, $_columns);
461 $rooar = method_exists($r, 'toRooArray');
462 //print_r(var_dump($rooar)); exit;
463 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
467 function update($x, $req)
469 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
470 $this->jerr("PERMISSION DENIED");
473 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
478 // this lot is generic.. needs moving
479 if (method_exists($x, 'setFromRoo')) {
480 $res = $x->setFromRoo($req, $this);
481 if (is_string($res)) {
487 $this->addEvent("EDIT", $x, $x->toEventString());
493 if (isset($cols['modified'])) {
494 $x->modified = date('Y-m-d H:i:s');
496 if (isset($cols['modified_dt'])) {
497 $x->modified_dt = date('Y-m-d H:i:s');
499 if (isset($cols['modified_by'])) {
500 $x->modified_by = $this->authUser->id;
503 if (isset($cols['updated'])) {
504 $x->updated = date('Y-m-d H:i:s');
506 if (isset($cols['updated_dt'])) {
507 $x->updated_dt = date('Y-m-d H:i:s');
509 if (isset($cols['updated_by'])) {
510 $x->updated_by = $this->authUser->id;
515 if (method_exists($x, 'onUpdate')) {
516 $x->onUpdate($old, $req, $this);
519 $r = DB_DataObject::factory($x->tableName());
521 // let's assume it has a key!!!
524 $this->loadMap($r, $_columns);
527 $rooar = method_exists($r, 'toRooArray');
528 //print_r(var_dump($rooar)); exit;
529 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
532 function delete($x, $req)
534 // do we really delete stuff!?!?!?
535 if (empty($req['_delete'])) {
536 $this->jerr("Delete Requested with no value");
539 // build a list of tables to queriy for dependant data..
544 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
545 foreach($all_links as $tbl => $links) {
546 foreach($links as $col => $totbl_col) {
547 $to = explode(':', $totbl_col);
548 if ($to[0] != $x->tableName()) {
552 $affects[$tbl .'.' . $col] = true;
557 // echo '<PRE>';print_r($affects);exit;
558 //DB_Dataobject::debugLevel(1);
561 $clean = create_function('$v', 'return (int)$v;');
563 $bits = array_map($clean, explode(',', $req['_delete']));
565 // print_r($bits);exit;
567 // let's assume it has a key!!!
570 $x->whereAdd($pk .' IN ('. implode(',', $bits) .')');
572 $this->jerr("Nothing found to delete");
575 while ($x->fetch()) {
579 foreach($affects as $k=> $true) {
580 $ka = explode('.', $k);
581 $chk = DB_DataObject::factory($ka[0]);
582 if (!is_a($chk,'DB_DataObject')) {
583 $this->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
585 $chk->{$ka[1]} = $xx->$pk;
587 $this->jerr('Delete Dependant records first ('. $ka[0]. ':' . $ka[1] .'='.$xx->$pk.')');
593 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
594 $this->jerr("PERMISSION DENIED");
597 $this->addEvent("DELETE", $x, $x->toEventString());
598 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
599 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
605 $this->jerr(implode("\n<BR>", $errs));
607 $this->jok("Deleted");
615 function loadMap($do, $filter=false)
617 //DB_DataObject::debugLevel(1);
622 $mods = explode(',',$this->appModules);
624 $ff = HTML_FlexyFramework::geT();
625 //$db->databaseName();
627 //$ff->DB_DataObject['ini_'. $db->database()];
628 //echo '<PRE>';print_r($do->links());exit;
631 if (in_array('Builder', $mods) ) {
633 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
635 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
638 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
639 if (!file_exists($ini)) {
642 $conf = array_merge($conf, parse_ini_file($ini,true));
643 if (!isset($conf[$do->tableName()])) {
646 $map = $conf[$do->tableName()];
656 $tabdef = $do->table();
657 if (isset($tabdef['passwd'])) {
658 // prevent exposure of passwords..
659 unset($tabdef['passwd']);
662 $xx = array_keys($tabdef);
663 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
669 if (in_array($c, $filter)) {
673 $do->selectAs($cols);
679 $this->cols = array();
681 $this->cols[$k] = $do->tableName(). '.' . $k;
689 foreach($map as $ocl=>$info) {
691 list($tab,$col) = explode(':', $info);
692 // what about multiple joins on the same table!!!
693 $xx = DB_DataObject::factory($tab);
694 if (!is_a($xx, 'DB_DataObject')) {
697 // this is borked ... for multiple jions..
698 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
699 $tabdef = $xx->table();
700 $table = $xx->tableName();
701 if (isset($tabdef['passwd'])) {
703 unset($tabdef['passwd']);
706 $xx = array_keys($tabdef);
713 $tn = sprintf($ocl.'_%s', $c);
714 if (in_array($tn, $filter)) {
718 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
720 $do->selectAs($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
725 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
730 //DB_DataObject::debugLevel(1);
736 * generate the meta data neede by queries.
739 function meta($x, $data)
741 // this is not going to work on queries where the data does not match the database def..
742 // for unknown columns we send them as stirngs..
744 $cols = array_keys($data[0]);
749 //echo '<PRE>';print_r($this->cols); exit;
750 $options = &PEAR::getStaticProperty('DB_DataObject','options');
751 $reader = $options["ini_{$x->_database}"] .'.reader';
752 if (!file_exists( $reader )) {
756 $rdata = unserialize(file_get_contents($reader));
758 // echo '<PRE>';print_r($rdata);exit;
761 foreach($cols as $c ) {
762 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
766 $add = $rdata[$this->cols[$c]];
771 'totalProperty' => 'total',
772 'successProperty' => 'success',
781 function setFilters($x, $q)
783 // if a column is type int, and we get ',' -> the it should be come an inc clause..
784 // DB_DataObject::debugLevel(1);
785 if (method_exists($x, 'applyFilters')) {
786 // DB_DataObject::debugLevel(1);
787 $x->applyFilters($q, $this->authUser);
789 $q_filtered = array();
791 foreach($q as $key=>$val) {
793 if (is_array($val) ) {
795 if (!in_array( $key, array_keys($this->cols))) {
799 // support a[0] a[1] ..... => whereAddIn(
802 foreach($val as $k=>$v) {
803 if (!is_numeric($k)) {
807 if (!is_numeric($v) || !is_long($v)) {
814 $x->whereAddIn($x->tableName(). '.'.$key,$ar, $quote ? 'string' : 'int');
822 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
824 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
825 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
835 // Events and remarks
836 case 'on_id': // where TF is this used...
837 if (!empty($q['query']['original'])) {
838 // DB_DataObject::debugLevel(1);
839 $o = (int) $q['query']['original'];
841 $x->whereAdd("(on_id = $oid OR
842 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
852 $q_filtered[$key] = $val;
858 $x->setFrom($q_filtered);
860 // nice generic -- let's get rid of it.. where is it used!!!!
863 if (!empty($q['query']['name'])) {
864 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
867 // - projectdirectory staff list - persn queuy