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['_delete']);
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, $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, $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         $x->whereAdd('id IN ('. implode(',', $bits) .')');
515         $x->find();
516         $errs = array();
517         while ($x->fetch()) {
518             $xx = clone($x);
519             
520             
521             foreach($affects as $k=> $true) {
522                 $ka = explode('.', $k);
523                 $chk = DB_DataObject::factory($ka[0]);
524                 $chk->{$ka[1]} =  $xx->id;
525                 if ($chk->count()) {
526                     $this->jerr('Delete Dependant records first');
527                 }
528             }
529             
530             
531             
532             if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
533                 $this->jerr("PERMISSION DENIED");
534             }
535             
536             $this->addEvent("DELETE", $x, $x->toEventString());
537             if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
538                 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
539                 continue;
540             }
541             $xx->delete();
542         }
543         if ($errs) {
544             $this->jerr(implode("\n<BR>", $errs));
545         }
546         $this->jok("Deleted");
547         
548     }
549    
550     
551     
552     
553     var $cols = array();
554     function loadMap($do, $filter=false) 
555     {
556         //DB_DataObject::debugLevel(1);
557         $conf = array();
558         
559         
560         $this->init();
561         $mods = explode(',',$this->appModules);
562         
563         $ff = HTML_FlexyFramework::geT();
564         //$db->databaseName();
565         
566         //$ff->DB_DataObject['ini_'. $db->database()];
567         //echo '<PRE>';print_r($do->links());exit;
568         //var_dump($mods);
569         
570         if (in_array('Builder', $mods) ) {
571             
572             foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
573                 
574                 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
575                     continue;
576                 }
577                 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
578                 if (!file_exists($ini)) {
579                     continue;
580                 }
581                 $conf = array_merge($conf, parse_ini_file($ini,true));
582                 if (!isset($conf[$do->tableName()])) {
583                     return;
584                 }
585                 $map = $conf[$do->tableName()];
586             } 
587         } else {
588             $map = $do->links();
589         }
590          
591         
592         
593         
594         // current table..
595         $tabdef = $do->table();
596         if (isset($tabdef['passwd'])) {
597             // prevent exposure of passwords..
598             unset($tabdef['passwd']);     
599         }
600         $xx = clone($do);
601         $xx = array_keys($tabdef);
602         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
603         
604         if ($filter) {
605             $cols = array();
606          
607             foreach($xx as $c) {
608                 if (in_array($c, $filter)) {
609                     $cols[] = $c;
610                 }
611             }
612             $do->selectAs($cols);
613         } else {
614             $do->selectAs($xx);
615         }
616         
617         
618         
619         
620         $this->cols = $xx;
621         
622         
623         
624          
625         
626         foreach($map as $ocl=>$info) {
627             
628             list($tab,$col) = explode(':', $info);
629             // what about multiple joins on the same table!!!
630             $xx = DB_DataObject::factory($tab);
631             if (!is_a($xx, 'DB_DataObject')) {
632                 continue;
633             }
634             // this is borked ... for multiple jions..
635             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
636             $tabdef = $xx->table();
637             $table = $xx->tableName();
638             if (isset($tabdef['passwd'])) {
639              
640                 unset($tabdef['passwd']);
641               
642             } 
643             $xx = array_keys($tabdef);
644             
645             
646             if ($filter) {
647                 $cols = array();
648                 foreach($xx as $c) {
649                     
650                     $tn = sprintf($ocl.'_%s', $c);
651                     if (in_array($tn, $filter)) {
652                         $cols[] = $c;
653                     }
654                 }
655                 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
656             } else {
657                 $do->selectAs($xx,  $ocl.'_%s', 'join_'.$ocl.'_'. $col);
658             }
659             
660              
661             
662             
663             
664             foreach($xx as $k) {
665                 $this->cols[] = sprintf($ocl.'_%s', $k);
666             }
667             
668             
669         }
670         //DB_DataObject::debugLevel(1);
671         
672         
673         
674     }
675     function setFilters($x, $q)
676     {
677         // if a column is type int, and we get ',' -> the it should be come an inc clause..
678        // DB_DataObject::debugLevel(1);
679         if (method_exists($x, 'applyFilters')) {
680            // DB_DataObject::debugLevel(1);
681             $x->applyFilters($q, $this->authUser);
682         }
683         $q_filtered = array();
684         
685         foreach($q as $key=>$val) {
686             
687             if (is_array($val)) {
688                 continue;
689             }
690             if ($key[0] == '!' && in_array(substr($key, 1), $this->cols)) {
691                     
692                 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
693                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
694                 );
695                 continue;
696                 
697             }
698             
699             
700             
701             switch($key) {
702                     
703                 // Events and remarks
704                 case 'on_id':  // where TF is this used...
705                     if (!empty($q['query']['original'])) {
706                       //  DB_DataObject::debugLevel(1);
707                         $o = (int) $q['query']['original'];
708                         $oid = (int) $val;
709                         $x->whereAdd("(on_id = $oid  OR 
710                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
711                             )");
712                         continue;
713                                 
714                     }
715                     $x->on_id = $val;
716                 
717                 
718                 default:
719                     if (strlen($val)) {
720                         $q_filtered[$key] = $val;
721                     }
722                     
723                     continue;
724             }
725         }
726         $x->setFrom($q_filtered);
727        
728         // nice generic -- let's get rid of it.. where is it used!!!!
729         // used by: 
730         // Person / Group
731         if (!empty($q['query']['name'])) {
732             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
733         }
734         
735         // - projectdirectory staff list - persn queuy
736       
737          
738        
739          
740           
741         
742         
743     }
744     
745 }