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() // 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
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.
49 * _post = simulate a post with debuggin on.
50 * lookup = array( k=>v) single fetch based on a key/value pair
51 * _id = single fetch based on id.
52 * _delete = delete a list of ids element. (seperated by ,);
53 * _columns = comma seperated list of columns.
54 * _distinct = a distinct column lookup.
55 * _requestMeta = default behaviour of Roo stores.. on first query..
57 * csvCols = return data as csv
59 * csvTitles = return data as csv
62 * dir = sort direction
64 * limit = limit number
66 * _toggleActive !:!:!:! - this hsould not really be here..
67 * query[add_blank] - add a line in with an empty option... - not really needed???
72 // $this->jerr("Not authenticated", array('authFailure' => true));
73 //DB_DataObject::debuglevel(1);
76 if (!empty($_GET['_post'])) {
78 DB_DAtaObject::debuglevel(1);
79 return $this->post($tab);
81 $tab = str_replace('/', '',$tab); // basic protection??
82 $x = DB_DataObject::factory($tab);
83 if (!is_a($x, 'DB_DataObject')) {
84 $this->jerr('invalid url');
86 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
88 if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
89 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
90 $this->jerr("PERMISSION DENIED");
92 $this->loadMap($x, $_columns);
93 $x->setFrom($_REQUEST['lookup'] );
95 if (!$x->find(true)) {
98 $this->jok($x->toArray());
103 if (isset($_REQUEST['_id'])) { // single fetch
105 if (empty($_REQUEST['_id'])) {
106 $this->jok($x->toArray()); // return an empty array!
109 $this->loadMap($x, $_columns);
111 if (!$x->get($_REQUEST['_id'])) {
112 $this->jerr("no such record");
115 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
116 $this->jerr("PERMISSION DENIED");
119 $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser) : $x->toArray());
122 if (isset($_REQUEST['_delete'])) {
123 // do we really delete stuff!?!?!?
124 return $this->delete($x,$_REQUEST);
130 if (isset($_REQUEST['_toggleActive'])) {
131 // do we really delete stuff!?!?!?
132 if (!$this->hasPerm("Core.Staff", 'E')) {
133 $this->jerr("PERMISSION DENIED");
135 $clean = create_function('$v', 'return (int)$v;');
136 $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
137 if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
138 $this->jerr("you can not disable yourself");
140 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
141 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
142 $this->jok("Updated");
145 // DB_DataObject::debugLevel(1);
146 if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser)) {
147 $this->jerr("PERMISSION DENIED");
149 $map = $this->loadMap($x, $_columns);
151 $this->setFilters($x,$_REQUEST);
155 // build join if req.
157 if (!empty($_REQUEST['_distinct'])) {
161 if (isset($cols[$_REQUEST['_distinct']])) {
162 $countWhat = 'distinct ' . $_REQUEST['_distinct'];
164 $x->selectAdd('distinct('.$_REQUEST['_distinct'].')');
165 $_columns = array( $_REQUEST['_distinct'] );
167 $this->jerr('invalid distinct');
171 $total = $x->count($countWhat);
173 // DB_DataObject::debugLevel(1);
175 $sort = empty($_REQUEST['sort']) ? '' : $_REQUEST['sort'];
176 $dir = (empty($_REQUEST['dir']) || strtoupper($_REQUEST['dir']) == 'ASC' ? 'ASC' : 'DESC');
179 if (method_exists($x, 'applySort')) {
180 $sorted = $x->applySort($this->authUser, $sort, $dir, array_keys($this->cols));
182 if ($sorted === false) {
185 // echo '<PRE>';print_r(array($sort, $this->cols));
187 // $otherSorts = array('person_id_name');
189 if (strlen($sort) && isset($cols[$sort]) ) {
190 $sort = $x->tableName() .'.'.$sort . ' ' . $dir ;
192 } else if (in_array($sort, array_keys($this->cols))) {
193 $sort = $sort . ' ' . $dir ;
195 }// else other formatas?
196 //if ( in_array($sort, $otherSorts)) {
197 // $x->orderBy($sort . ' ' . $dir);
204 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
205 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
208 $queryObj = clone($x);
213 if (!empty($_REQUEST['query']['add_blank'])) {
214 $ret[] = array( 'id' => 0, 'name' => '----');
219 //if (($tab == 'Groups') && ($_REQUEST['type'] != 0)) { // then it's a list of teams..
220 if ($tab == 'Groups') {
222 $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
223 $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
224 //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
230 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
231 header('Content-type: text/csv');
233 header('Content-Disposition: attachment; filename="documentlist-export-'.date('Y-m-d') . '.csv"');
234 //header('Content-type: text/plain');
235 $fh = fopen('php://output', 'w');
236 fputcsv($fh, $_REQUEST['csvTitles']);
237 while ($x->fetch()) {
238 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
240 foreach($_REQUEST['csvCols'] as $k) {
241 $line[] = isset($x->$k) ? $x->$k : '';
252 $rooar = method_exists($x, 'toRooArray');
254 while ($x->fetch()) {
255 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
257 $ret[] = !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
259 //if ($x->tableName() == 'Documents_Tracking') {
260 // $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
264 if (method_exists($queryObj ,'postListExtra')) {
265 $extra = $queryObj->postListExtra($_REQUEST);
267 // filter results, and add any data that is needed...
268 if (method_exists($x,'postListFilter')) {
269 $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
272 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
273 $meta = $this->meta($x, $ret);
275 $extra['metaData'] = $meta;
279 // echo "<PRE>"; print_r($ret);
280 $this->jdata($ret,$total, $extra );
285 * POST method Roo/TABLENAME.php
286 * -- updates the data..
289 * _debug - forces debugging on.
290 * _get - forces a get request
291 * _ids - multiple update of records.
292 * {colid} - forces fetching
295 function post($tab) // update / insert (?? dleete??)
297 // DB_DataObject::debugLevel(1);
298 if (!empty($_REQUEST['_debug'])) {
299 DB_DataObject::debugLevel(1);
302 if (!empty($_REQUEST['_get'])) {
303 return $this->get($tab);
305 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
307 $tab = str_replace('/', '',$tab); // basic protection??
308 $x = DB_DataObject::factory($tab);
309 if (!is_a($x, 'DB_DataObject')) {
310 $this->jerr('invalid url');
312 // find the key and use that to get the thing..
315 $this->jerr('no key');
319 if (!empty($_REQUEST['_ids'])) {
320 $ids = explode(',',$_REQUEST['_ids']);
321 $x->whereAddIn($keys[0], $ids, 'int');
322 $ar = $x->fetchAll();
324 $this->update($x, $_REQUEST);
328 $this->jok("UPDATED");
334 if (!empty($_REQUEST[$keys[0]])) {
336 if (!$x->get($keys[0], $_REQUEST[$keys[0]])) {
337 $this->jerr("Invalid request");
339 $this->jok($this->update($x, $_REQUEST));
341 $this->jok($this->insert($x, $_REQUEST));
348 function insert($x, $req)
352 if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req)) {
353 $this->jerr("PERMISSION DENIED");
356 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
358 if (method_exists($x, 'setFromRoo')) {
359 $res = $x->setFromRoo($req, $this);
360 if (is_string($res)) {
370 if (isset($cols['created'])) {
371 $x->created = date('Y-m-d H:i:s');
373 if (isset($cols['created_dt'])) {
374 $x->created_dt = date('Y-m-d H:i:s');
376 if (isset($cols['created_by'])) {
377 $x->created_by = $this->authUser->id;
381 if (isset($cols['modified'])) {
382 $x->modified = date('Y-m-d H:i:s');
384 if (isset($cols['modified_dt'])) {
385 $x->modified_dt = date('Y-m-d H:i:s');
387 if (isset($cols['modified_by'])) {
388 $x->modified_by = $this->authUser->id;
391 if (isset($cols['updated'])) {
392 $x->updated = date('Y-m-d H:i:s');
394 if (isset($cols['updated_dt'])) {
395 $x->updated_dt = date('Y-m-d H:i:s');
397 if (isset($cols['updated_by'])) {
398 $x->updated_by = $this->authUser->id;
406 if (method_exists($x, 'onInsert')) {
407 $x->onInsert($_REQUEST, $this);
409 $this->addEvent("ADD", $x, $x->toEventString());
411 // note setFrom might handle this before hand...!??!
412 if (!empty($_FILES) && method_exists($x, 'onUpload')) {
416 $r = DB_DataObject::factory($x->tableName());
418 $this->loadMap($r, $_columns);
422 $rooar = method_exists($r, 'toRooArray');
423 //print_r(var_dump($rooar)); exit;
424 return $rooar ? $r->toRooArray() : $r->toArray();
428 function update($x, $req)
430 if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST)) {
431 $this->jerr("PERMISSION DENIED");
434 $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
439 // this lot is generic.. needs moving
440 if (method_exists($x, 'setFromRoo')) {
441 $res = $x->setFromRoo($req, $this);
442 if (is_string($res)) {
448 $this->addEvent("EDIT", $x, $x->toEventString());
454 if (isset($cols['modified'])) {
455 $x->modified = date('Y-m-d H:i:s');
457 if (isset($cols['modified_dt'])) {
458 $x->modified_dt = date('Y-m-d H:i:s');
460 if (isset($cols['modified_by'])) {
461 $x->modified_by = $this->authUser->id;
464 if (isset($cols['updated'])) {
465 $x->updated = date('Y-m-d H:i:s');
467 if (isset($cols['updated_dt'])) {
468 $x->updated_dt = date('Y-m-d H:i:s');
470 if (isset($cols['updated_by'])) {
471 $x->updated_by = $this->authUser->id;
476 if (method_exists($x, 'onUpdate')) {
477 $x->onUpdate($old, $req, $this);
480 $r = DB_DataObject::factory($x->tableName());
482 $this->loadMap($r, $_columns);
485 $rooar = method_exists($r, 'toRooArray');
486 //print_r(var_dump($rooar)); exit;
487 return $rooar ? $r->toRooArray() : $r->toArray();
490 function delete($x, $req)
492 // do we really delete stuff!?!?!?
495 // build a list of tables to queriy for dependant data..
500 $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
501 foreach($all_links as $tbl => $links) {
502 foreach($links as $col => $totbl_col) {
503 $to = explode(':', $totbl_col);
504 if ($to[0] != $x->tableName()) {
508 $affects[$tbl .'.' . $col] = true;
513 // echo '<PRE>';print_r($affects);exit;
514 //DB_Dataobject::debugLevel(1);
517 $clean = create_function('$v', 'return (int)$v;');
519 $bits = array_map($clean, explode(',', $req['_delete']));
521 // print_r($bits);exit;
523 $x->whereAdd('id IN ('. implode(',', $bits) .')');
526 while ($x->fetch()) {
530 foreach($affects as $k=> $true) {
531 $ka = explode('.', $k);
532 $chk = DB_DataObject::factory($ka[0]);
533 $chk->{$ka[1]} = $xx->id;
535 $this->jerr('Delete Dependant records first');
541 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser)) {
542 $this->jerr("PERMISSION DENIED");
545 $this->addEvent("DELETE", $x, $x->toEventString());
546 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
547 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
553 $this->jerr(implode("\n<BR>", $errs));
555 $this->jok("Deleted");
563 function loadMap($do, $filter=false)
565 //DB_DataObject::debugLevel(1);
570 $mods = explode(',',$this->appModules);
572 $ff = HTML_FlexyFramework::geT();
573 //$db->databaseName();
575 //$ff->DB_DataObject['ini_'. $db->database()];
576 //echo '<PRE>';print_r($do->links());exit;
579 if (in_array('Builder', $mods) ) {
581 foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
583 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
586 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
587 if (!file_exists($ini)) {
590 $conf = array_merge($conf, parse_ini_file($ini,true));
591 if (!isset($conf[$do->tableName()])) {
594 $map = $conf[$do->tableName()];
604 $tabdef = $do->table();
605 if (isset($tabdef['passwd'])) {
606 // prevent exposure of passwords..
607 unset($tabdef['passwd']);
610 $xx = array_keys($tabdef);
611 $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
617 if (in_array($c, $filter)) {
621 $do->selectAs($cols);
627 $this->cols = array();
629 $this->cols[$k] = $do->tableName(). '.' . $k;
637 foreach($map as $ocl=>$info) {
639 list($tab,$col) = explode(':', $info);
640 // what about multiple joins on the same table!!!
641 $xx = DB_DataObject::factory($tab);
642 if (!is_a($xx, 'DB_DataObject')) {
645 // this is borked ... for multiple jions..
646 $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
647 $tabdef = $xx->table();
648 $table = $xx->tableName();
649 if (isset($tabdef['passwd'])) {
651 unset($tabdef['passwd']);
654 $xx = array_keys($tabdef);
661 $tn = sprintf($ocl.'_%s', $c);
662 if (in_array($tn, $filter)) {
666 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
668 $do->selectAs($xx, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
673 $this->cols[sprintf($ocl.'_%s', $k)] = $tab.'.'.$k;
678 //DB_DataObject::debugLevel(1);
684 * generate the meta data neede by queries.
687 function meta($x, $data)
689 // this is not going to work on queries where the data does not match the database def..
690 // for unknown columns we send them as stirngs..
692 $cols = array_keys($data[0]);
697 //echo '<PRE>';print_r($this->cols); exit;
698 $options = &PEAR::getStaticProperty('DB_DataObject','options');
699 $reader = $options["ini_{$x->_database}"] .'.reader';
700 if (!file_exists( $reader )) {
704 $rdata = unserialize(file_get_contents($reader));
706 // echo '<PRE>';print_r($rdata);exit;
709 foreach($cols as $c ) {
710 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
714 $add = $rdata[$this->cols[$c]];
719 'totalProperty' => 'total',
720 'successProperty' => 'success',
729 function setFilters($x, $q)
731 // if a column is type int, and we get ',' -> the it should be come an inc clause..
732 // DB_DataObject::debugLevel(1);
733 if (method_exists($x, 'applyFilters')) {
734 // DB_DataObject::debugLevel(1);
735 $x->applyFilters($q, $this->authUser);
737 $q_filtered = array();
739 foreach($q as $key=>$val) {
741 if (is_array($val)) {
744 if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
746 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
747 (is_numeric($val) ? $val : "'". $x->escape($val) . "'")
757 // Events and remarks
758 case 'on_id': // where TF is this used...
759 if (!empty($q['query']['original'])) {
760 // DB_DataObject::debugLevel(1);
761 $o = (int) $q['query']['original'];
763 $x->whereAdd("(on_id = $oid OR
764 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o )
774 $q_filtered[$key] = $val;
780 $x->setFrom($q_filtered);
782 // nice generic -- let's get rid of it.. where is it used!!!!
785 if (!empty($q['query']['name'])) {
786 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
789 // - projectdirectory staff list - persn queuy