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 (.....)
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);
351 if (!empty($_REQUEST['_ids'])) {
352 $ids = explode(',',$_REQUEST['_ids']);
353 $x->whereAddIn($keys[0], $ids, 'int');
354 $ar = $x->fetchAll();
356 $this->update($x, $_REQUEST);
360 $this->jok("UPDATED");
366 if (!empty($_REQUEST[$keys[0]])) {
368 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
369 $this->jerr("Invalid request");
371 $this->jok($this->update($x, $_REQUEST));
373 $this->jok($this->insert($x, $_REQUEST));
380 function insert($x, $req)
384 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
385 $this->jerr("PERMISSION DENIED");
388 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
390 if (method_exists($x, 'setFromRoo')) {
391 $res = $x->setFromRoo($req, $this);
392 if (is_string($res)) {
402 if (isset($cols['created'])) {
403 $x->created = date('Y-m-d H:i:s');
405 if (isset($cols['created_dt'])) {
406 $x->created_dt = date('Y-m-d H:i:s');
408 if (isset($cols['created_by'])) {
409 $x->created_by = $this->authUser->id;
413 if (isset($cols['modified'])) {
414 $x->modified = date('Y-m-d H:i:s');
416 if (isset($cols['modified_dt'])) {
417 $x->modified_dt = date('Y-m-d H:i:s');
419 if (isset($cols['modified_by'])) {
420 $x->modified_by = $this->authUser->id;
423 if (isset($cols['updated'])) {
424 $x->updated = date('Y-m-d H:i:s');
426 if (isset($cols['updated_dt'])) {
427 $x->updated_dt = date('Y-m-d H:i:s');
429 if (isset($cols['updated_by'])) {
430 $x->updated_by = $this->authUser->id;
438 if (method_exists($x, 'onInsert')) {
439 $x->onInsert($_REQUEST, $this);
441 $this->addEvent("ADD", $x, $x->toEventString());
443 // note setFrom might handle this before hand...!??!
444 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
448 $r = DB_DataObject::factory($x->tableName());
450 // let's assume it has a key!!!
453 $this->loadMap($r, $_columns);
457 $rooar = method_exists($r, 'toRooArray');
458 //print_r(var_dump($rooar)); exit;
459 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
463 function update($x, $req)
465 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
466 $this->jerr("PERMISSION DENIED");
469 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
474 // this lot is generic.. needs moving
475 if (method_exists($x, 'setFromRoo')) {
476 $res = $x->setFromRoo($req, $this);
477 if (is_string($res)) {
483 $this->addEvent("EDIT", $x, $x->toEventString());
489 if (isset($cols['modified'])) {
490 $x->modified = date('Y-m-d H:i:s');
492 if (isset($cols['modified_dt'])) {
493 $x->modified_dt = date('Y-m-d H:i:s');
495 if (isset($cols['modified_by'])) {
496 $x->modified_by = $this->authUser->id;
499 if (isset($cols['updated'])) {
500 $x->updated = date('Y-m-d H:i:s');
502 if (isset($cols['updated_dt'])) {
503 $x->updated_dt = date('Y-m-d H:i:s');
505 if (isset($cols['updated_by'])) {
506 $x->updated_by = $this->authUser->id;
511 if (method_exists($x, 'onUpdate')) {
512 $x->onUpdate($old, $req, $this);
515 $r = DB_DataObject::factory($x->tableName());
517 // let's assume it has a key!!!
520 $this->loadMap($r, $_columns);
523 $rooar = method_exists($r, 'toRooArray');
524 //print_r(var_dump($rooar)); exit;
525 return $rooar ? $r->toRooArray($_REQUEST) : $r->toArray();
528 function delete($x, $req)
530 // do we really delete stuff!?!?!?
532 // build a list of tables to queriy for dependant data..
537 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
538 foreach($all_links as $tbl => $links) {
539 foreach($links as $col => $totbl_col) {
540 $to = explode(':', $totbl_col);
541 if ($to[0] != $x->tableName()) {
545 $affects[$tbl .'.' . $col] = true;
550 // echo '<PRE>';print_r($affects);exit;
551 //DB_Dataobject::debugLevel(1);
554 $clean = create_function('$v', 'return (int)$v;');
556 $bits = array_map($clean, explode(',', $req['_delete']));
558 // print_r($bits);exit;
560 $x->whereAdd('id IN ('. implode(',', $bits) .')');
563 while ($x->fetch()) {
567 foreach($affects as $k=> $true) {
568 $ka = explode('.', $k);
569 $chk = DB_DataObject::factory($ka[0]);
570 $chk->{$ka[1]} = $xx->id;
572 $this->jerr('Delete Dependant records first');
578 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
579 $this->jerr("PERMISSION DENIED");
582 $this->addEvent("DELETE", $x, $x->toEventString());
583 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
584 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
590 $this->jerr(implode("\n<BR>", $errs));
592 $this->jok("Deleted");
600 function loadMap($do, $filter=false)
602 //DB_DataObject::debugLevel(1);
607 $mods = explode(',',$this->appModules);
609 $ff = HTML_FlexyFramework::geT();
610 //$db->databaseName();
612 //$ff->DB_DataObject['ini_'. $db->database()];
613 //echo '<PRE>';print_r($do->links());exit;
616 if (in_array('Builder', $mods) ) {
618 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
620 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
623 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
624 if (!file_exists($ini)) {
627 $conf = array_merge($conf, parse_ini_file($ini,true));
628 if (!isset($conf[$do->tableName()])) {
631 $map = $conf[$do->tableName()];
641 $tabdef = $do->table();
642 if (isset($tabdef['passwd'])) {
643 // prevent exposure of passwords..
644 unset($tabdef['passwd']);
647 $xx = array_keys($tabdef);
648 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
654 if (in_array($c, $filter)) {
658 $do->selectAs($cols);
664 $this->cols = array();
666 $this->cols[$k] = $do->tableName(). '.' . $k;
674 foreach($map as $ocl=>$info) {
676 list($tab,$col) = explode(':', $info);
677 // what about multiple joins on the same table!!!
678 $xx = DB_DataObject::factory($tab);
679 if (!is_a($xx, 'DB_DataObject')) {
682 // this is borked ... for multiple jions..
683 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
684 $tabdef = $xx->table();
685 $table = $xx->tableName();
686 if (isset($tabdef['passwd'])) {
688 unset($tabdef['passwd']);
691 $xx = array_keys($tabdef);
698 $tn = sprintf($ocl.'_%s', $c);
699 if (in_array($tn, $filter)) {
703 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
705 $do->selectAs($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
710 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
715 //DB_DataObject::debugLevel(1);
721 * generate the meta data neede by queries.
724 function meta($x, $data)
726 // this is not going to work on queries where the data does not match the database def..
727 // for unknown columns we send them as stirngs..
729 $cols = array_keys($data[0]);
734 //echo '<PRE>';print_r($this->cols); exit;
735 $options = &PEAR::getStaticProperty('DB_DataObject','options');
736 $reader = $options["ini_{$x->_database}"] .'.reader';
737 if (!file_exists( $reader )) {
741 $rdata = unserialize(file_get_contents($reader));
743 // echo '<PRE>';print_r($rdata);exit;
746 foreach($cols as $c ) {
747 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
751 $add = $rdata[$this->cols[$c]];
756 'totalProperty' => 'total',
757 'successProperty' => 'success',
766 function setFilters($x, $q)
768 // if a column is type int, and we get ',' -> the it should be come an inc clause..
769 // DB_DataObject::debugLevel(1);
770 if (method_exists($x, 'applyFilters')) {
771 // DB_DataObject::debugLevel(1);
772 $x->applyFilters($q, $this->authUser);
774 $q_filtered = array();
776 foreach($q as $key=>$val) {
778 if (is_array($val) ) {
780 if (!in_array( $key, array_keys($this->cols))) {
784 // support a[0] a[1] ..... => whereAddIn(
787 foreach($val as $k=>$v) {
788 if (!is_numeric($k)) {
792 if (!is_numeric($v) || !is_long($v)) {
799 $x->whereAddIn($key,$ar, $quote ? 'string' : 'int');
807 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
809 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
810 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
820 // Events and remarks
821 case 'on_id': // where TF is this used...
822 if (!empty($q['query']['original'])) {
823 // DB_DataObject::debugLevel(1);
824 $o = (int) $q['query']['original'];
826 $x->whereAdd("(on_id = $oid OR
827 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
837 $q_filtered[$key] = $val;
843 $x->setFrom($q_filtered);
845 // nice generic -- let's get rid of it.. where is it used!!!!
848 if (!empty($q['query']['name'])) {
849 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
852 // - projectdirectory staff list - persn queuy