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         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
272             $meta = $this->meta($x, $ret);
273         }
274         
275        // echo "<PRE>"; print_r($ret);
276         $this->jdata($ret,$total, $extra );
277
278     
279     }
280      /**
281      * POST method   Roo/TABLENAME.php 
282      * -- updates the data..
283      * 
284      * other opts:
285      * _debug - forces debugging on.
286      * _get - forces a get request
287      * _ids - multiple update of records.
288      * {colid} - forces fetching
289      * 
290      */
291     function post($tab) // update / insert (?? dleete??)
292     {
293        // DB_DataObject::debugLevel(1);
294         if (!empty($_REQUEST['_debug'])) {
295             DB_DataObject::debugLevel(1);
296         }
297         
298         if (!empty($_REQUEST['_get'])) {
299             return $this->get($tab);
300         }
301         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
302         
303         $tab = str_replace('/', '',$tab); // basic protection??
304         $x = DB_DataObject::factory($tab);
305         if (!is_a($x, 'DB_DataObject')) {
306             $this->jerr('invalid url');
307         }
308         // find the key and use that to get the thing..
309         $keys = $x->keys();
310         if (empty($keys) ) {
311             $this->jerr('no key');
312         }
313         $old = false;
314         
315         if (!empty($_REQUEST['_ids'])) {
316             $ids = explode(',',$_REQUEST['_ids']);
317             $x->whereAddIn($keys[0], $ids, 'int');
318             $ar = $x->fetchAll();
319             foreach($ar as $x) {
320                 $this->update($x, $_REQUEST);
321                 
322             }
323             // all done..
324             $this->jok("UPDATED");
325             
326             
327         }
328         
329         
330         if (!empty($_REQUEST[$keys[0]])) {
331             // it's a create..
332             if (!$x->get($keys[0], $_REQUEST[$keys[0]]))  {
333                 $this->jerr("Invalid request");
334             }
335             $this->jok($this->update($x, $_REQUEST));
336         } else {
337             $this->jok($this->insert($x, $_REQUEST));
338             
339         }
340         
341         
342         
343     }
344     function insert($x, $req)
345     {
346         
347     
348         if (method_exists($x, 'checkPerm') && !$x->checkPerm('A', $this->authUser, $req))  {
349             $this->jerr("PERMISSION DENIED");
350         }
351         
352         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
353    
354         if (method_exists($x, 'setFromRoo')) {
355             $res = $x->setFromRoo($req, $this);
356             if (is_string($res)) {
357                 $this->jerr($res);
358             }
359         } else {
360             $x->setFrom($req);
361         }
362         
363          
364         $cols = $x->table();
365      
366         if (isset($cols['created'])) {
367             $x->created = date('Y-m-d H:i:s');
368         }
369         if (isset($cols['created_dt'])) {
370             $x->created_dt = date('Y-m-d H:i:s');
371         }
372         if (isset($cols['created_by'])) {
373             $x->created_by = $this->authUser->id;
374         }
375         
376      
377          if (isset($cols['modified'])) {
378             $x->modified = date('Y-m-d H:i:s');
379         }
380         if (isset($cols['modified_dt'])) {
381             $x->modified_dt = date('Y-m-d H:i:s');
382         }
383         if (isset($cols['modified_by'])) {
384             $x->modified_by = $this->authUser->id;
385         }
386         
387         if (isset($cols['updated'])) {
388             $x->updated = date('Y-m-d H:i:s');
389         }
390         if (isset($cols['updated_dt'])) {
391             $x->updated_dt = date('Y-m-d H:i:s');
392         }
393         if (isset($cols['updated_by'])) {
394             $x->updated_by = $this->authUser->id;
395         }
396         
397      
398         
399         
400         
401         $x->insert();
402         if (method_exists($x, 'onInsert')) {
403             $x->onInsert($_REQUEST, $this);
404         }
405         $this->addEvent("ADD", $x, $x->toEventString());
406         
407         // note setFrom might handle this before hand...!??!
408         if (!empty($_FILES) && method_exists($x, 'onUpload')) {
409             $x->onUpload($this);
410         }
411         
412         $r = DB_DataObject::factory($x->tableName());
413         $r->id = $x->id;
414         $this->loadMap($r, $_columns);
415         $r->limit(1);
416         $r->find(true);
417         
418         $rooar = method_exists($r, 'toRooArray');
419         //print_r(var_dump($rooar)); exit;
420         return $rooar  ? $r->toRooArray() : $r->toArray();
421     }
422     
423     
424     function update($x, $req)
425     {
426         if (method_exists($x, 'checkPerm') && !$x->checkPerm('E', $this->authUser, $_REQUEST))  {
427             $this->jerr("PERMISSION DENIED");
428         }
429        
430         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
431
432        
433         $old = clone($x);
434         $this->old = $x;
435         // this lot is generic.. needs moving 
436         if (method_exists($x, 'setFromRoo')) {
437             $res = $x->setFromRoo($req, $this);
438             if (is_string($res)) {
439                 $this->jerr($res);
440             }
441         } else {
442             $x->setFrom($req);
443         }
444         $this->addEvent("EDIT", $x, $x->toEventString());
445         //print_r($x);
446         //print_r($old);
447         
448         $cols = $x->table();
449         
450         if (isset($cols['modified'])) {
451             $x->modified = date('Y-m-d H:i:s');
452         }
453         if (isset($cols['modified_dt'])) {
454             $x->modified_dt = date('Y-m-d H:i:s');
455         }
456         if (isset($cols['modified_by'])) {
457             $x->modified_by = $this->authUser->id;
458         }
459         
460         if (isset($cols['updated'])) {
461             $x->updated = date('Y-m-d H:i:s');
462         }
463         if (isset($cols['updated_dt'])) {
464             $x->updated_dt = date('Y-m-d H:i:s');
465         }
466         if (isset($cols['updated_by'])) {
467             $x->updated_by = $this->authUser->id;
468         }
469         
470         
471         $x->update($old);
472         if (method_exists($x, 'onUpdate')) {
473             $x->onUpdate($old, $req, $this);
474         }
475         
476         $r = DB_DataObject::factory($x->tableName());
477         $r->id = $x->id;
478         $this->loadMap($r, $_columns);
479         $r->limit(1);
480         $r->find(true);
481         $rooar = method_exists($r, 'toRooArray');
482         //print_r(var_dump($rooar)); exit;
483         return $rooar  ? $r->toRooArray() : $r->toArray();
484     }
485     
486     function delete($x, $req)
487     {
488         // do we really delete stuff!?!?!?
489        
490        
491         // build a list of tables to queriy for dependant data..
492         $map = $x->links();
493         
494         $affects  = array();
495         
496         $all_links = $GLOBALS['_DB_DATAOBJECT']['LINKS'][$x->_database];
497         foreach($all_links as $tbl => $links) {
498             foreach($links as $col => $totbl_col) {
499                 $to = explode(':', $totbl_col);
500                 if ($to[0] != $x->tableName()) {
501                     continue;
502                 }
503                 
504                 $affects[$tbl .'.' . $col] = true;
505             }
506         }
507         // collect tables
508         
509        // echo '<PRE>';print_r($affects);exit;
510         //DB_Dataobject::debugLevel(1);
511        
512         
513         $clean = create_function('$v', 'return (int)$v;');
514         
515         $bits = array_map($clean, explode(',', $req['_delete']));
516         
517        // print_r($bits);exit;
518         
519         $x->whereAdd('id IN ('. implode(',', $bits) .')');
520         $x->find();
521         $errs = array();
522         while ($x->fetch()) {
523             $xx = clone($x);
524             
525             
526             foreach($affects as $k=> $true) {
527                 $ka = explode('.', $k);
528                 $chk = DB_DataObject::factory($ka[0]);
529                 $chk->{$ka[1]} =  $xx->id;
530                 if ($chk->count()) {
531                     $this->jerr('Delete Dependant records first');
532                 }
533             }
534             
535             
536             
537             if (method_exists($x, 'checkPerm') && !$x->checkPerm('D', $this->authUser))  {
538                 $this->jerr("PERMISSION DENIED");
539             }
540             
541             $this->addEvent("DELETE", $x, $x->toEventString());
542             if ( method_exists($xx, 'beforeDelete') && ($xx->beforeDelete() === false)) {
543                 $errs[] = "Delete failed ({$xx->id})\n". (isset($xx->err) ? $xx->err : '');
544                 continue;
545             }
546             $xx->delete();
547         }
548         if ($errs) {
549             $this->jerr(implode("\n<BR>", $errs));
550         }
551         $this->jok("Deleted");
552         
553     }
554    
555     
556     
557     
558     var $cols = array();
559     function loadMap($do, $filter=false) 
560     {
561         //DB_DataObject::debugLevel(1);
562         $conf = array();
563         
564         
565         $this->init();
566         $mods = explode(',',$this->appModules);
567         
568         $ff = HTML_FlexyFramework::geT();
569         //$db->databaseName();
570         
571         //$ff->DB_DataObject['ini_'. $db->database()];
572         //echo '<PRE>';print_r($do->links());exit;
573         //var_dump($mods);
574         
575         if (in_array('Builder', $mods) ) {
576             
577             foreach(in_array('Builder', $mods) ? scandir($this->rootDir.'/Pman') : $mods as $m) {
578                 
579                 if (!strlen($m) || $m[0] == '.' || !is_dir($this->rootDir."/Pman/$m")) {
580                     continue;
581                 }
582                 $ini = $this->rootDir."/Pman/$m/DataObjects/pman.links.ini";
583                 if (!file_exists($ini)) {
584                     continue;
585                 }
586                 $conf = array_merge($conf, parse_ini_file($ini,true));
587                 if (!isset($conf[$do->tableName()])) {
588                     return;
589                 }
590                 $map = $conf[$do->tableName()];
591             } 
592         } else {
593             $map = $do->links();
594         }
595          
596         
597         
598         
599         // current table..
600         $tabdef = $do->table();
601         if (isset($tabdef['passwd'])) {
602             // prevent exposure of passwords..
603             unset($tabdef['passwd']);     
604         }
605         $xx = clone($do);
606         $xx = array_keys($tabdef);
607         $do->selectAdd(); // we need thsi as normally it's only cleared by an empty selectAs call.
608         
609         if ($filter) {
610             $cols = array();
611          
612             foreach($xx as $c) {
613                 if (in_array($c, $filter)) {
614                     $cols[] = $c;
615                 }
616             }
617             $do->selectAs($cols);
618         } else {
619             $do->selectAs($xx);
620         }
621         
622         
623         $this->cols = array();
624         foreach($xx as $k) {
625             $this->cols[$do->tableName(). '.' . $k] = $k;
626         }
627         
628         
629         
630         
631          
632         
633         foreach($map as $ocl=>$info) {
634             
635             list($tab,$col) = explode(':', $info);
636             // what about multiple joins on the same table!!!
637             $xx = DB_DataObject::factory($tab);
638             if (!is_a($xx, 'DB_DataObject')) {
639                 continue;
640             }
641             // this is borked ... for multiple jions..
642             $do->joinAdd($xx, 'LEFT', 'join_'.$ocl.'_'. $col, $ocl);
643             $tabdef = $xx->table();
644             $table = $xx->tableName();
645             if (isset($tabdef['passwd'])) {
646              
647                 unset($tabdef['passwd']);
648               
649             } 
650             $xx = array_keys($tabdef);
651             
652             
653             if ($filter) {
654                 $cols = array();
655                 foreach($xx as $c) {
656                     
657                     $tn = sprintf($ocl.'_%s', $c);
658                     if (in_array($tn, $filter)) {
659                         $cols[] = $c;
660                     }
661                 }
662                 $do->selectAs($cols, $ocl.'_%s', 'join_'.$ocl.'_'. $col);
663             } else {
664                 $do->selectAs($xx,  $ocl.'_%s', 'join_'.$ocl.'_'. $col);
665             }
666              
667             
668             foreach($xx as $k) {
669                 $this->cols[$tab.'.'.$k] = sprintf($ocl.'_%s', $k);
670             }
671             
672             
673         }
674         //DB_DataObject::debugLevel(1);
675         
676         
677         
678     }
679     /**
680      * generate the meta data neede by queries.
681      * 
682      */
683     function meta($x)
684     {
685         
686         
687         
688         
689     }
690     
691     function setFilters($x, $q)
692     {
693         // if a column is type int, and we get ',' -> the it should be come an inc clause..
694        // DB_DataObject::debugLevel(1);
695         if (method_exists($x, 'applyFilters')) {
696            // DB_DataObject::debugLevel(1);
697             $x->applyFilters($q, $this->authUser);
698         }
699         $q_filtered = array();
700         
701         foreach($q as $key=>$val) {
702             
703             if (is_array($val)) {
704                 continue;
705             }
706             if ($key[0] == '!' && in_array(substr($key, 1), array_values($this->cols))) {
707                     
708                 $x->whereAdd( $x->tableName() .'.' .substr($key, 1) . ' != ' .
709                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
710                 );
711                 continue;
712                 
713             }
714             
715             
716             
717             switch($key) {
718                     
719                 // Events and remarks
720                 case 'on_id':  // where TF is this used...
721                     if (!empty($q['query']['original'])) {
722                       //  DB_DataObject::debugLevel(1);
723                         $o = (int) $q['query']['original'];
724                         $oid = (int) $val;
725                         $x->whereAdd("(on_id = $oid  OR 
726                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
727                             )");
728                         continue;
729                                 
730                     }
731                     $x->on_id = $val;
732                 
733                 
734                 default:
735                     if (strlen($val)) {
736                         $q_filtered[$key] = $val;
737                     }
738                     
739                     continue;
740             }
741         }
742         $x->setFrom($q_filtered);
743        
744         // nice generic -- let's get rid of it.. where is it used!!!!
745         // used by: 
746         // Person / Group
747         if (!empty($q['query']['name'])) {
748             $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
749         }
750         
751         // - projectdirectory staff list - persn queuy
752       
753          
754        
755          
756           
757         
758         
759     }
760     
761 }