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            
124             
125             $clean = create_function('$v', 'return (int)$v;');
126             
127             $bits = array_map($clean, explode(',', $_REQUEST['_delete']));
128             $x->whereAdd('id IN ('. implode(',', $bits) .')');
129             $x->find();
130             $errs = array();
131             while ($x->fetch()) {
132                 $xx = clone($x);
133                 
134                 if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
135                     $this->jerr("PERMISSION DENIED");
136                 }
137                 
138                 $this->addEvent("DELETE", $x, $x->toEventString());
139                 if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
140                     $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
141                     continue;
142                 }
143                 $xx->delete();
144             }
145             if ($errs) {
146                 $this->jerr(implode("\n<BR>", $errs));
147             }
148             $this->jok("Deleted");
149             
150         }
151         if (isset($_REQUEST['_toggleActive'])) {
152             // do we really delete stuff!?!?!?
153             if (!$this->hasPerm("Core.Staff", 'E'))  {
154                 $this->jerr("PERMISSION DENIED");
155             }
156             $clean = create_function('$v', 'return (int)$v;');
157             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
158             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
159                 $this->jerr("you can not disable yourself");
160             }
161             $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
162             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
163             $this->jok("Updated");
164             
165         }
166       // DB_DataObject::debugLevel(1);
167         if (method_exists($x, 'checkPerm') && !$x->checkPerm('S', $this->authUser))  {
168             $this->jerr("PERMISSION DENIED");
169         }
170         $map = $this->loadMap($x, $_columns);
171         
172         $this->setFilters($x,$_REQUEST);
173         
174          
175         
176         // build join if req.
177         $countWhat = false;
178         if (!empty($_REQUEST['_distinct'])) {
179             $cols = $x->table();
180            // print_r($cols);
181           
182             if (isset($cols[$_REQUEST['_distinct']])) {
183                 $countWhat = 'distinct ' . $_REQUEST['_distinct'];
184                 $x->selectAdd();
185                 $x->selectAdd('distinct('.$_REQUEST['_distinct'].')');
186                 $_columns = array( $_REQUEST['_distinct'] );
187             } else {
188                 $this->jerr('invalid distinct');
189             }
190              
191         }
192         $total = $x->count($countWhat);
193         // sorting..
194       //   DB_DataObject::debugLevel(1);
195         
196         $sort = empty($_REQUEST['sort']) ? '' : $_REQUEST['sort'];
197         $dir = (empty($_REQUEST['dir']) || strtoupper($_REQUEST['dir']) == 'ASC' ? 'ASC' : 'DESC');
198         
199         $sorted = false;
200         if (method_exists($x, 'applySort')) {
201             $sorted = $x->applySort($this->authUser, $sort, $dir, $this->cols);
202         }
203         if ($sorted === false) {
204             
205             $cols = $x->table();
206            // echo '<PRE>';print_r(array($sort, $this->cols));
207             // other sorts??? 
208            // $otherSorts = array('person_id_name');
209             
210             if (strlen($sort) && isset($cols[$sort]) ) {
211                 $sort = $x->tableName() .'.'.$sort . ' ' . $dir ;
212                 $x->orderBy($sort );
213             } else if (in_array($sort, $this->cols)) {
214                 $sort = $sort . ' ' . $dir ;
215                 $x->orderBy($sort );
216             }// else other formatas?
217             //if ( in_array($sort, $otherSorts)) {
218             //    $x->orderBy($sort . ' ' . $dir);
219             ////}
220         }
221         
222         
223  
224         $x->limit(
225             empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
226             min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 1000)
227         );
228         
229         $queryObj = clone($x);
230         
231         $x->find();
232         $ret = array();
233         
234         if (!empty($_REQUEST['query']['add_blank'])) {
235             $ret[] = array( 'id' => 0, 'name' => '----');
236             $total+=1;
237         }
238         // MOVE ME...
239         
240         //if (($tab == 'Groups') && ($_REQUEST['type'] != 0))  { // then it's a list of teams..
241         if ($tab == 'Groups') {
242             
243             $ret[] = array( 'id' => 0, 'name' => 'EVERYONE');
244             $ret[] = array( 'id' => -1, 'name' => 'NOT_IN_GROUP');
245             //$ret[] = array( 'id' => 999999, 'name' => 'ADMINISTRATORS');
246             $total+=2;
247         }
248         
249         // DOWNLOAD...
250         
251         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
252             header('Content-type: text/csv');
253             
254             header('Content-Disposition: attachment; filename="documentlist-export-'.date('Y-m-d') . '.csv"');
255             //header('Content-type: text/plain');
256             $fh = fopen('php://output', 'w');
257             fputcsv($fh, $_REQUEST['csvTitles']);
258             while ($x->fetch()) {
259                 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
260                 $line = array();
261                 foreach($_REQUEST['csvCols'] as $k) {
262                     $line[] = isset($x->$k) ? $x->$k : '';
263                 }
264                 fputcsv($fh, $line);
265             }
266             fclose($fh);
267             exit;
268             
269         
270         }
271         //die("DONE?");
272         
273         $rooar = method_exists($x, 'toRooArray');
274         
275         while ($x->fetch()) {
276             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
277             
278             $ret[] =  !$_columns ? $add : array_intersect_key($add, array_flip($_columns));
279         }
280         //if ($x->tableName() == 'Documents_Tracking') {
281         //    $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
282        // }
283         
284         $extra = false;
285         if (method_exists($queryObj ,'postListExtra')) {
286             $extra = $queryObj->postListExtra($_REQUEST);
287         }
288         // filter results, and add any data that is needed...
289         if (method_exists($x,'postListFilter')) {
290             $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
291         }
292         
293         
294         
295        // echo "<PRE>"; print_r($ret);
296         $this->jdata($ret,$total, $extra );
297
298     
299     }
300      /**
301      * POST method   Roo/TABLENAME.php 
302      * -- updates the data..
303      * 
304      * other opts:
305      * _debug - forces debugging on.
306      * _get - forces a get request
307      * _ids - multiple update of records.
308      * {colid} - forces fetching
309      * 
310      */
311     function post($tab) // update / insert (?? dleete??)
312     {
313        // DB_DataObject::debugLevel(1);
314         if (!empty($_REQUEST['_debug'])) {
315             DB_DataObject::debugLevel(1);
316         }
317         
318         if (!empty($_REQUEST['_get'])) {
319             return $this->get($tab);
320         }
321         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
322         
323         $tab = str_replace('/', '',$tab); // basic protection??
324         $x = DB_DataObject::factory($tab);
325         if (!is_a($x, 'DB_DataObject')) {
326             $this->jerr('invalid url');
327         }
328         // find the key and use that to get the thing..
329         $keys = $x->keys();
330         if (empty($keys) ) {
331             $this->jerr('no key');
332         }
333         $old = false;
334         
335         if (!empty($_REQUEST['_ids'])) {
336             $ids = explode(',',$_REQUEST['_ids']);
337             $x->whereAddIn($keys[0], $ids, 'int');
338             $ar = $x->fetchAll();
339             foreach($ar as $x) {
340                 $this->update($x, $_REQUEST);
341                 
342             }
343             // all done..
344             $this->jok("UPDATED");
345             
346             
347         }
348         
349         
350         if (!empty($_REQUEST[$keys[0]])) {
351             // it's a create..
352             if (!$x->get($keys[0], $_REQUEST[$keys[0]]))  {
353                 $this->jerr("Invalid request");
354             }
355             $this->jok($this->update($x, $_REQUEST));
356         } else {
357             $this->jok($this->insert($x, $_REQUEST));
358             
359         }
360         
361         
362         
363     }
364     function insert($x, $req)
365     {
366         
367     
368         if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req))  {
369             $this->jerr("PERMISSION DENIED");
370         }
371         
372         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
373    
374         if (method_exists($x, 'setFromRoo')) {
375             $res = $x->setFromRoo($req, $this);
376             if (is_string($res)) {
377                 $this->jerr($res);
378             }
379         } else {
380             $x->setFrom($req);
381         }
382         
383          
384         $cols = $x->table();
385      
386         if (isset($cols['created'])) {
387             $x->created = date('Y-m-d H:i:s');
388         }
389         if (isset($cols['created_dt'])) {
390             $x->created_dt = date('Y-m-d H:i:s');
391         }
392         if (isset($cols['created_by'])) {
393             $x->created_by = $this->authUser->id;
394         }
395         
396      
397          if (isset($cols['modified'])) {
398             $x->modified = date('Y-m-d H:i:s');
399         }
400         if (isset($cols['modified_dt'])) {
401             $x->modified_dt = date('Y-m-d H:i:s');
402         }
403         if (isset($cols['modified_by'])) {
404             $x->modified_by = $this->authUser->id;
405         }
406         
407         if (isset($cols['updated'])) {
408             $x->updated = date('Y-m-d H:i:s');
409         }
410         if (isset($cols['updated_dt'])) {
411             $x->updated_dt = date('Y-m-d H:i:s');
412         }
413         if (isset($cols['updated_by'])) {
414             $x->updated_by = $this->authUser->id;
415         }
416         
417      
418         
419         
420         
421         $x->insert();
422         if (method_exists($x, 'onInsert')) {
423             $x->onInsert($_REQUEST, $this);
424         }
425         $this->addEvent("ADD", $x, $x->toEventString());
426         
427         // note setFrom might handle this before hand...!??!
428         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
429             $x->onUpload($this);
430         }
431         
432         $r = DB_DataObject::factory($x->tableName());
433         $r->id = $x->id;
434         $this->loadMap($r, $_columns);
435         $r->limit(1);
436         $r->find(true);
437         
438         $rooar = method_exists($r, 'toRooArray');
439         //print_r(var_dump($rooar)); exit;
440         return $rooar  ? $r->toRooArray() : $r->toArray();
441     }
442     
443     
444     function update($x, $req)
445     {
446         if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST))  {
447             $this->jerr("PERMISSION DENIED");
448         }
449        
450         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
451
452        
453         $old = clone($x);
454         $this->old = $x;
455         // this lot is generic.. needs moving 
456         if (method_exists($x, 'setFromRoo')) {
457             $res = $x->setFromRoo($req, $this);
458             if (is_string($res)) {
459                 $this->jerr($res);
460             }
461         } else {
462             $x->setFrom($req);
463         }
464         $this->addEvent("EDIT", $x, $x->toEventString());
465         //print_r($x);
466         //print_r($old);
467         
468         $cols = $x->table();
469         
470         if (isset($cols['modified'])) {
471             $x->modified = date('Y-m-d H:i:s');
472         }
473         if (isset($cols['modified_dt'])) {
474             $x->modified_dt = date('Y-m-d H:i:s');
475         }
476         if (isset($cols['modified_by'])) {
477             $x->modified_by = $this->authUser->id;
478         }
479         
480         if (isset($cols['updated'])) {
481             $x->updated = date('Y-m-d H:i:s');
482         }
483         if (isset($cols['updated_dt'])) {
484             $x->updated_dt = date('Y-m-d H:i:s');
485         }
486         if (isset($cols['updated_by'])) {
487             $x->updated_by = $this->authUser->id;
488         }
489         
490         
491         $x->update($old);
492         if (method_exists($x, 'onUpdate')) {
493             $x->onUpdate($old, $req, $this);
494         }
495         
496         $r = DB_DataObject::factory($x->tableName());
497         $r->id = $x->id;
498         $this->loadMap($r, $_columns);
499         $r->limit(1);
500         $r->find(true);
501         $rooar = method_exists($r, 'toRooArray');
502         //print_r(var_dump($rooar)); exit;
503         return $rooar  ? $r->toRooArray() : $r->toArray();
504     }
505     
506     
507     
508     var $cols = array();
509     function loadMap($do, $filter=false) 
510     {
511         //DB_DataObject::debugLevel(1);
512         $conf = array();
513         
514         
515         $this->init();
516         $mods = explode(',',$this->appModules);
517         
518         $ff = HTML_FlexyFramework::geT();
519         //$db->databaseName();
520         
521         //$ff->DB_DataObject['ini_'. $db->database()];
522         //echo '<PRE>';print_r($do->links());exit;
523         //var_dump($mods);
524         
525         if (in_array('Builder', $mods) ) {
526             
527             foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
528                 
529                 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
530                     continue;
531                 }
532                 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
533                 if (!file_exists($ini)) {
534                     continue;
535                 }
536                 $conf = array_merge($conf, parse_ini_file($ini,true));
537                 if (!isset($conf[$do->tableName()])) {
538                     return;
539                 }
540                 $map = $conf[$do->tableName()];
541             } 
542         } else {
543             $map = $do->links();
544         }
545          
546         
547         
548         
549         // current table..
550         $tabdef = $do->table();
551         if (isset($tabdef['passwd'])) {
552             // prevent exposure of passwords..
553             unset($tabdef['passwd']);     
554         }
555         $xx = clone($do);
556         $xx = array_keys($tabdef);
557         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
558         
559         if ($filter) {
560             $cols = array();
561          
562             foreach($xx as $c) {
563                 if (in_array($c, $filter)) {
564                     $cols[] = $c;
565                 }
566             }
567             $do->selectAs($cols);
568         } else {
569             $do->selectAs($xx);
570         }
571         
572         
573         
574         
575         $this->cols = $xx;
576         
577         
578         
579          
580         
581         foreach($map as $ocl=>$info) {
582             
583             list($tab,$col) = explode(':', $info);
584             // what about multiple joins on the same table!!!
585             $xx = DB_DataObject::factory($tab);
586             if (!is_a($xx, 'DB_DataObject')) {
587                 continue;
588             }
589             // this is borked ... for multiple jions..
590             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
591             $tabdef = $xx->table();
592             $table = $xx->tableName();
593             if (isset($tabdef['passwd'])) {
594              
595                 unset($tabdef['passwd']);
596               
597             } 
598             $xx = array_keys($tabdef);
599             
600             
601             if ($filter) {
602                 $cols = array();
603                 foreach($xx as $c) {
604                     
605                     $tn = sprintf($ocl.'_%s', $c);
606                     if (in_array($tn, $filter)) {
607                         $cols[] = $c;
608                     }
609                 }
610                 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
611             } else {
612                 $do->selectAs($xx,  $ocl.'_%s', 'join_'.$ocl.'_'. $col);
613             }
614             
615              
616             
617             
618             
619             foreach($xx as $k) {
620                 $this->cols[] = sprintf($ocl.'_%s', $k);
621             }
622             
623             
624         }
625         //DB_DataObject::debugLevel(1);
626         
627         
628         
629     }
630     function setFilters($x, $q)
631     {
632         // if a column is type int, and we get ',' -> the it should be come an inc clause..
633        // DB_DataObject::debugLevel(1);
634         if (method_exists($x, 'applyFilters')) {
635            // DB_DataObject::debugLevel(1);
636             $x->applyFilters($q, $this->authUser);
637         }
638         $q_filtered = array();
639         
640         foreach($q as $key=>$val) {
641             
642             if (is_array($val)) {
643                 continue;
644             }
645             if ($key[0] == '!' && in_array(substr($key, 1), $this->cols)) {
646                     
647                 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
648                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
649                 );
650                 continue;
651                 
652             }
653             
654             
655             
656             switch($key) {
657                     
658                 // Events and remarks
659                 case 'on_id':  // where TF is this used...
660                     if (!empty($q['query']['original'])) {
661                       //  DB_DataObject::debugLevel(1);
662                         $o = (int) $q['query']['original'];
663                         $oid = (int) $val;
664                         $x->whereAdd("(on_id = $oid  OR 
665                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
666                             )");
667                         continue;
668                                 
669                     }
670                     $x->on_id = $val;
671                 
672                 
673                 default:
674                     if (strlen($val)) {
675                         $q_filtered[$key] = $val;
676                     }
677                     
678                     continue;
679             }
680         }
681         $x->setFrom($q_filtered);
682        
683         // nice generic -- let's get rid of it.. where is it used!!!!
684         // used by: 
685         // Person / Group
686         if (!empty($q['query']['name'])) {
687             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
688         }
689         
690         // - projectdirectory staff list - persn queuy
691       
692          
693        
694          
695           
696         
697         
698     }
699     
700 }