Pman/Roo.php
[Pman.Base] / Pman / Roo.php
1 <?php
2
3
4 require_once 'Pman.php';
5 /**
6  * 
7  * 
8  * not really sure how save our factory method is....!!!
9  * 
10  * 
11  * Uses these methods of the dataobjects:
12  * - checkPerm('L'/'E'/'A', $authuser) - can we list the stuff
13  * 
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
18  * 
19  * - toRooSingleArray() // single fetch, add data..
20  * - toRooArray($request) /// toArray if you need to return different data.. for a list fetch.
21  * 
22  * 
23  * - beforeDelete() -- return false for fail and set DO->err;
24  * - onUpdate($old, $request,$roo) - after update
25  * - onInsert($request,$roo) - after insert
26  * - onUpload($roo)
27  * - setFromRoo($ar) - values from post (deal with dates etc.) - return true|error string.
28  * 
29  * - toEventString (for logging)
30  */
31
32 class Pman_Roo extends Pman
33 {
34     
35    function getAuth() {
36         parent::getAuth(); // load company!
37         $au = $this->getAuthUser();
38         if (!$au) {
39             $this->jerr("Not authenticated", array('authFailure' => true));
40         }
41         $this->authUser = $au;
42         return true;
43     }
44     /**
45      * GET method   Roo/TABLENAME.php 
46      * -- defaults to listing data. with args.
47      * 
48      * other opts:
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      * 
56      * csvCols    = return data as csv
57      * 
58      * csvTitles  = return data as csv
59      *
60      * sort        = sort column
61      * dir         = sort direction
62      * start       = limit start
63      * limit       = limit number 
64      * 
65      * _toggleActive !:!:!:! - this hsould not really be here..
66      * query[add_blank] - add a line in with an empty option...  - not really needed???
67      * 
68      */
69     function get($tab)
70     {
71          //  $this->jerr("Not authenticated", array('authFailure' => true));
72          //DB_DataObject::debuglevel(1);
73         
74         // debugging...
75         if (!empty($_GET['_post'])) {
76             $_POST  = $_GET;
77             DB_DAtaObject::debuglevel(1);
78             return $this->post($tab);
79         }
80         $tab = str_replace('/', '',$tab); // basic protection??
81         $x = DB_DataObject::factory($tab);
82         if (!is_a($x, 'DB_DataObject')) {
83             $this->jerr('invalid url');
84         }
85         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
86         
87         if (isset( $_REQUEST['lookup'] )) { // single fetch based on key/value pairs
88             if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
89                 $this->jerr("PERMISSION DENIED");
90             }
91             $this->loadMap($x, $_columns);
92             $x->setFrom($_REQUEST['lookup'] );
93             $x->limit(1);
94             if (!$x->find(true)) {
95                 $this->jok(false);
96             }
97             $this->jok($x->toArray());
98         }
99         
100         
101         
102         if (isset($_REQUEST['_id'])) { // single fetch
103             
104             if (empty($_REQUEST['_id'])) {
105                 $this->jok($x->toArray());  // return an empty array!
106             }
107            
108             $this->loadMap($x, $_columns);
109             
110             if (!$x->get($_REQUEST['_id'])) {
111                 $this->jerr("no such record");
112             }
113             
114             if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
115                 $this->jerr("PERMISSION DENIED");
116             }
117             
118             $this->jok(method_exists($x, 'toRooSingleArray') ? $x->toRooSingleArray($this->authUser) : $x->toArray());
119             
120         }
121         if (isset($_REQUEST['_delete'])) {
122             // do we really delete stuff!?!?!?
123             return $this->delete($x,$_REQUEST);
124         } 
125         
126         
127         
128         
129         if (isset($_REQUEST['_toggleActive'])) {
130             // do we really delete stuff!?!?!?
131             if (!$this->hasPerm("Core.Staff", 'E'))  {
132                 $this->jerr("PERMISSION DENIED");
133             }
134             $clean = create_function('$v', 'return (int)$v;');
135             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
136             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
137                 $this->jerr("you can not disable yourself");
138             }
139             $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
140             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
141             $this->jok("Updated");
142             
143         }
144       // DB_DataObject::debugLevel(1);
145         if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
146             $this->jerr("PERMISSION DENIED");
147         }
148         $map = $this->loadMap($x, $_columns);
149         
150         $this->setFilters($x,$_REQUEST);
151         
152          
153         
154         // build join if req.
155         $countWhat = false;
156         if (!empty($_REQUEST['_distinct'])) {
157             $cols = $x->table();
158            // print_r($cols);
159           
160             if (isset($cols[$_REQUEST['_distinct']])) {
161                 $countWhat = 'distinct ' . $_REQUEST['_distinct'];
162                 $x->selectAdd();
163                 $x->selectAdd('distinct('.$_REQUEST['_distinct'].')');
164                 $_columns = array( $_REQUEST['_distinct'] );
165             } else {
166                 $this->jerr('invalid distinct');
167             }
168              
169         }
170         $total = $x->count($countWhat);
171         // sorting..
172       //   DB_DataObject::debugLevel(1);
173         
174         $sort = empty($_REQUEST['sort']) ? '' : $_REQUEST['sort'];
175         $dir = (empty($_REQUEST['dir']) || strtoupper($_REQUEST['dir']) == 'ASC' ? 'ASC' : 'DESC');
176         
177         $sorted = false;
178         if (method_exists($x, 'applySort')) {
179             $sorted = $x->applySort($this->authUser, $sort, $dir, array_values($this->cols));
180         }
181         if ($sorted === false) {
182             
183             $cols = $x->table();
184            // echo '<PRE>';print_r(array($sort, $this->cols));
185             // other sorts??? 
186            // $otherSorts = array('person_id_name');
187             
188             if (strlen($sort) && isset($cols[$sort]) ) {
189                 $sort = $x->tableName() .'.'.$sort . ' ' . $dir ;
190                 $x->orderBy($sort );
191             } else if (in_array($sort, array_values($this->cols))) {
192                 $sort = $sort . ' ' . $dir ;
193                 $x->orderBy($sort );
194             }// else other formatas?
195             //if ( in_array($sort, $otherSorts)) {
196             //    $x->orderBy($sort . ' ' . $dir);
197             ////}
198         }
199         
200         
201  
202         $x->limit(
203             empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
204             min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
205         );
206         
207         $queryObj = clone($x);
208         
209         $x->find();
210         $ret = array();
211         
212         if (!empty($_REQUEST['query']['add_blank'])) {
213             $ret[] = array( 'id' => 0, 'name' => '----');
214             $total+=1;
215         }
216         // MOVE ME...
217         
218         //if (($tab == 'Groups') && ($_REQUEST['type'] != 0))  { // then it's a list of teams..
219         if ($tab == 'Groups') {
220             
221             $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
222             $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
223             //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
224             $total+=2;
225         }
226         
227         // DOWNLOAD...
228         
229         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
230             header('Content-type: text/csv');
231             
232             header('Content-Disposition: attachment; filename="documentlist-export-'.date('Y-m-d') . '.csv"');
233             //header('Content-type: text/plain');
234             $fh = fopen('php://output', 'w');
235             fputcsv($fh, $_REQUEST['csvTitles']);
236             while ($x->fetch()) {
237                 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
238                 $line = array();
239                 foreach($_REQUEST['csvCols'] as $k) {
240                     $line[] = isset($x->$k) ? $x->$k : '';
241                 }
242                 fputcsv($fh, $line);
243             }
244             fclose($fh);
245             exit;
246             
247         
248         }
249         //die("DONE?");
250         
251         $rooar = method_exists($x, 'toRooArray');
252         
253         while ($x->fetch()) {
254             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
255             
256             $ret[] =  !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
257         }
258         //if ($x->tableName() == 'Documents_Tracking') {
259         //    $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
260        // }
261         
262         $extra = false;
263         if (method_exists($queryObj ,'postListExtra')) {
264             $extra = $queryObj->postListExtra($_REQUEST);
265         }
266         // filter results, and add any data that is needed...
267         if (method_exists($x,'postListFilter')) {
268             $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
269         }
270         
271         
272         
273        // echo "<PRE>"; print_r($ret);
274         $this->jdata($ret,$total, $extra );
275
276     
277     }
278      /**
279      * POST method   Roo/TABLENAME.php 
280      * -- updates the data..
281      * 
282      * other opts:
283      * _debug - forces debugging on.
284      * _get - forces a get request
285      * _ids - multiple update of records.
286      * {colid} - forces fetching
287      * 
288      */
289     function post($tab) // update / insert (?? dleete??)
290     {
291        // DB_DataObject::debugLevel(1);
292         if (!empty($_REQUEST['_debug'])) {
293             DB_DataObject::debugLevel(1);
294         }
295         
296         if (!empty($_REQUEST['_get'])) {
297             return $this->get($tab);
298         }
299         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
300         
301         $tab = str_replace('/', '',$tab); // basic protection??
302         $x = DB_DataObject::factory($tab);
303         if (!is_a($x, 'DB_DataObject')) {
304             $this->jerr('invalid url');
305         }
306         // find the key and use that to get the thing..
307         $keys = $x->keys();
308         if (empty($keys) ) {
309             $this->jerr('no key');
310         }
311         $old = false;
312         
313         if (!empty($_REQUEST['_ids'])) {
314             $ids = explode(',',$_REQUEST['_ids']);
315             $x->whereAddIn($keys[0], $ids, 'int');
316             $ar = $x->fetchAll();
317             foreach($ar as $x) {
318                 $this->update($x, $_REQUEST);
319                 
320             }
321             // all done..
322             $this->jok("UPDATED");
323             
324             
325         }
326         
327         
328         if (!empty($_REQUEST[$keys[0]])) {
329             // it's a create..
330             if (!$x->get($keys[0], $_REQUEST[$keys[0]]))  {
331                 $this->jerr("Invalid request");
332             }
333             $this->jok($this->update($x, $_REQUEST));
334         } else {
335             $this->jok($this->insert($x, $_REQUEST));
336             
337         }
338         
339         
340         
341     }
342     function insert($x, $req)
343     {
344         
345     
346         if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req))  {
347             $this->jerr("PERMISSION DENIED");
348         }
349         
350         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
351    
352         if (method_exists($x, 'setFromRoo')) {
353             $res = $x->setFromRoo($req, $this);
354             if (is_string($res)) {
355                 $this->jerr($res);
356             }
357         } else {
358             $x->setFrom($req);
359         }
360         
361          
362         $cols = $x->table();
363      
364         if (isset($cols['created'])) {
365             $x->created = date('Y-m-d H:i:s');
366         }
367         if (isset($cols['created_dt'])) {
368             $x->created_dt = date('Y-m-d H:i:s');
369         }
370         if (isset($cols['created_by'])) {
371             $x->created_by = $this->authUser->id;
372         }
373         
374      
375          if (isset($cols['modified'])) {
376             $x->modified = date('Y-m-d H:i:s');
377         }
378         if (isset($cols['modified_dt'])) {
379             $x->modified_dt = date('Y-m-d H:i:s');
380         }
381         if (isset($cols['modified_by'])) {
382             $x->modified_by = $this->authUser->id;
383         }
384         
385         if (isset($cols['updated'])) {
386             $x->updated = date('Y-m-d H:i:s');
387         }
388         if (isset($cols['updated_dt'])) {
389             $x->updated_dt = date('Y-m-d H:i:s');
390         }
391         if (isset($cols['updated_by'])) {
392             $x->updated_by = $this->authUser->id;
393         }
394         
395      
396         
397         
398         
399         $x->insert();
400         if (method_exists($x, 'onInsert')) {
401             $x->onInsert($_REQUEST, $this);
402         }
403         $this->addEvent("ADD", $x, $x->toEventString());
404         
405         // note setFrom might handle this before hand...!??!
406         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
407             $x->onUpload($this);
408         }
409         
410         $r = DB_DataObject::factory($x->tableName());
411         $r->id = $x->id;
412         $this->loadMap($r, $_columns);
413         $r->limit(1);
414         $r->find(true);
415         
416         $rooar = method_exists($r, 'toRooArray');
417         //print_r(var_dump($rooar)); exit;
418         return $rooar  ? $r->toRooArray() : $r->toArray();
419     }
420     
421     
422     function update($x, $req)
423     {
424         if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST))  {
425             $this->jerr("PERMISSION DENIED");
426         }
427        
428         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
429
430        
431         $old = clone($x);
432         $this->old = $x;
433         // this lot is generic.. needs moving 
434         if (method_exists($x, 'setFromRoo')) {
435             $res = $x->setFromRoo($req, $this);
436             if (is_string($res)) {
437                 $this->jerr($res);
438             }
439         } else {
440             $x->setFrom($req);
441         }
442         $this->addEvent("EDIT", $x, $x->toEventString());
443         //print_r($x);
444         //print_r($old);
445         
446         $cols = $x->table();
447         
448         if (isset($cols['modified'])) {
449             $x->modified = date('Y-m-d H:i:s');
450         }
451         if (isset($cols['modified_dt'])) {
452             $x->modified_dt = date('Y-m-d H:i:s');
453         }
454         if (isset($cols['modified_by'])) {
455             $x->modified_by = $this->authUser->id;
456         }
457         
458         if (isset($cols['updated'])) {
459             $x->updated = date('Y-m-d H:i:s');
460         }
461         if (isset($cols['updated_dt'])) {
462             $x->updated_dt = date('Y-m-d H:i:s');
463         }
464         if (isset($cols['updated_by'])) {
465             $x->updated_by = $this->authUser->id;
466         }
467         
468         
469         $x->update($old);
470         if (method_exists($x, 'onUpdate')) {
471             $x->onUpdate($old, $req, $this);
472         }
473         
474         $r = DB_DataObject::factory($x->tableName());
475         $r->id = $x->id;
476         $this->loadMap($r, $_columns);
477         $r->limit(1);
478         $r->find(true);
479         $rooar = method_exists($r, 'toRooArray');
480         //print_r(var_dump($rooar)); exit;
481         return $rooar  ? $r->toRooArray() : $r->toArray();
482     }
483     
484     function delete($x, $req)
485     {
486         // do we really delete stuff!?!?!?
487        
488        
489         // build a list of tables to queriy for dependant data..
490         $map = $x->links();
491         
492         $affects  = array();
493         
494         $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
495         foreach($all_links as $tbl => $links) {
496             foreach($links as $col => $totbl_col) {
497                 $to = explode(':', $totbl_col);
498                 if ($to[0] != $x->tableName()) {
499                     continue;
500                 }
501                 
502                 $affects[$tbl .'.' . $col] = true;
503             }
504         }
505         // collect tables
506         
507        // echo '<PRE>';print_r($affects);exit;
508         //DB_Dataobject::debugLevel(1);
509        
510         
511         $clean = create_function('$v', 'return (int)$v;');
512         
513         $bits = array_map($clean, explode(',', $req['_delete']));
514         
515        // print_r($bits);exit;
516         
517         $x->whereAdd('id IN ('. implode(',', $bits) .')');
518         $x->find();
519         $errs = array();
520         while ($x->fetch()) {
521             $xx = clone($x);
522             
523             
524             foreach($affects as $k=> $true) {
525                 $ka = explode('.', $k);
526                 $chk = DB_DataObject::factory($ka[0]);
527                 $chk->{$ka[1]} =  $xx->id;
528                 if ($chk->count()) {
529                     $this->jerr('Delete Dependant records first');
530                 }
531             }
532             
533             
534             
535             if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
536                 $this->jerr("PERMISSION DENIED");
537             }
538             
539             $this->addEvent("DELETE", $x, $x->toEventString());
540             if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
541                 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
542                 continue;
543             }
544             $xx->delete();
545         }
546         if ($errs) {
547             $this->jerr(implode("\n<BR>", $errs));
548         }
549         $this->jok("Deleted");
550         
551     }
552    
553     
554     
555     
556     var $cols = array();
557     function loadMap($do, $filter=false) 
558     {
559         //DB_DataObject::debugLevel(1);
560         $conf = array();
561         
562         
563         $this->init();
564         $mods = explode(',',$this->appModules);
565         
566         $ff = HTML_FlexyFramework::geT();
567         //$db->databaseName();
568         
569         //$ff->DB_DataObject['ini_'. $db->database()];
570         //echo '<PRE>';print_r($do->links());exit;
571         //var_dump($mods);
572         
573         if (in_array('Builder', $mods) ) {
574             
575             foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
576                 
577                 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
578                     continue;
579                 }
580                 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
581                 if (!file_exists($ini)) {
582                     continue;
583                 }
584                 $conf = array_merge($conf, parse_ini_file($ini,true));
585                 if (!isset($conf[$do->tableName()])) {
586                     return;
587                 }
588                 $map = $conf[$do->tableName()];
589             } 
590         } else {
591             $map = $do->links();
592         }
593          
594         
595         
596         
597         // current table..
598         $tabdef = $do->table();
599         if (isset($tabdef['passwd'])) {
600             // prevent exposure of passwords..
601             unset($tabdef['passwd']);     
602         }
603         $xx = clone($do);
604         $xx = array_keys($tabdef);
605         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
606         
607         if ($filter) {
608             $cols = array();
609          
610             foreach($xx as $c) {
611                 if (in_array($c, $filter)) {
612                     $cols[] = $c;
613                 }
614             }
615             $do->selectAs($cols);
616         } else {
617             $do->selectAs($xx);
618         }
619         
620         
621         $this->cols = array();
622         foreach($xx as $k) {
623             $this->cols[$do->tableName(). '.' . $k] = $k;
624         }
625         
626         
627         
628         
629          
630         
631         foreach($map as $ocl=>$info) {
632             
633             list($tab,$col) = explode(':', $info);
634             // what about multiple joins on the same table!!!
635             $xx = DB_DataObject::factory($tab);
636             if (!is_a($xx, 'DB_DataObject')) {
637                 continue;
638             }
639             // this is borked ... for multiple jions..
640             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
641             $tabdef = $xx->table();
642             $table = $xx->tableName();
643             if (isset($tabdef['passwd'])) {
644              
645                 unset($tabdef['passwd']);
646               
647             } 
648             $xx = array_keys($tabdef);
649             
650             
651             if ($filter) {
652                 $cols = array();
653                 foreach($xx as $c) {
654                     
655                     $tn = sprintf($ocl.'_%s', $c);
656                     if (in_array($tn, $filter)) {
657                         $cols[] = $c;
658                     }
659                 }
660                 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
661             } else {
662                 $do->selectAs($xx,  $ocl.'_%s', 'join_'.$ocl.'_'. $col);
663             }
664             
665              
666             
667             
668             
669             foreach($xx as $k) {
670                 $this->cols[$tab.'.'.$k] = sprintf($ocl.'_%s', $k);
671             }
672             
673             
674         }
675         //DB_DataObject::debugLevel(1);
676         
677         
678         
679     }
680     /**
681      * generate the meta data neede by queries.
682      * 
683      */
684     function meta($x)
685     {
686         
687         
688         
689         
690     }
691     
692     function setFilters($x, $q)
693     {
694         // if a column is type int, and we get ',' -> the it should be come an inc clause..
695        // DB_DataObject::debugLevel(1);
696         if (method_exists($x, 'applyFilters')) {
697            // DB_DataObject::debugLevel(1);
698             $x->applyFilters($q, $this->authUser);
699         }
700         $q_filtered = array();
701         
702         foreach($q as $key=>$val) {
703             
704             if (is_array($val)) {
705                 continue;
706             }
707             if ($key[0] == '!' && in_array(substr($key, 1), array_values($this->cols))) {
708                     
709                 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
710                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
711                 );
712                 continue;
713                 
714             }
715             
716             
717             
718             switch($key) {
719                     
720                 // Events and remarks
721                 case 'on_id':  // where TF is this used...
722                     if (!empty($q['query']['original'])) {
723                       //  DB_DataObject::debugLevel(1);
724                         $o = (int) $q['query']['original'];
725                         $oid = (int) $val;
726                         $x->whereAdd("(on_id = $oid  OR 
727                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
728                             )");
729                         continue;
730                                 
731                     }
732                     $x->on_id = $val;
733                 
734                 
735                 default:
736                     if (strlen($val)) {
737                         $q_filtered[$key] = $val;
738                     }
739                     
740                     continue;
741             }
742         }
743         $x->setFrom($q_filtered);
744        
745         // nice generic -- let's get rid of it.. where is it used!!!!
746         // used by: 
747         // Person / Group
748         if (!empty($q['query']['name'])) {
749             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
750         }
751         
752         // - projectdirectory staff list - persn queuy
753       
754          
755        
756          
757           
758         
759         
760     }
761     
762 }