RooGetTrait.php
[Pman.Core] / RooGetTrait.php
1 <?php
2
3 trait Pman_Core_RooGetTrait {
4     /**
5      * GET method   Roo/TABLENAME.php
6      *
7      * Generally for SELECT or Single SELECT
8      *
9      * Single SELECT:
10      *    _id=value          single fetch based on primary id.
11      *                       can be '0' if you want to fetch a set of defaults
12      *                       Use in conjuntion with toRooSingleArray()
13      *                      
14      *    lookup[key]=value  single fetch based on a single key value lookup.
15      *                       multiple key/value can be used. eg. ontable+onid..
16      *    _columns           what to return.
17      *
18      *    
19      * JOINS:
20      *  - all tables are always autojoined.
21      * 
22      * Search SELECT
23      *    COLUMNS to fetch
24      *      _columns=a,b,c,d     comma seperated list of columns.
25      *      _columns_exclude=a,b,c,d   comma seperated list of columns.
26      *      _distinct=name        a distinct column lookup. you also have to use _columns with this.
27      *
28      *    WHERE (searches)
29      *       colname = ...              => colname = ....
30      *       !colname=....                 => colname != ....
31      *       !colname[0]=... !colname[1]=... => colname NOT IN (.....) ** only supports main table at present..
32      *       colname[0]=... colname[1]=... => colname IN (.....) ** only supports main table at present..
33      *
34      *    ORDER BY
35      *       sort=name          what to sort.
36      *       sort=a,b,d         can support multiple columns
37      *       dir=ASC            what direction
38      *       _multisort ={...}  JSON encoded { sort : { row : direction }, order : [ row, row, row ] }
39      *
40      *    LIMIT
41      *      start=0         limit start
42      *      limit=25        limit number 
43      * 
44      * 
45      *    Simple CSV support
46      *      csvCols[0] csvCols[1]....    = .... column titles for CSV output
47      *      csvTitles[0], csvTitles[1] ....  = columns to use for CSV output
48      *
49      *  Depricated  
50      *      _toggleActive !:!:!:! - this hsould not really be here..
51      *      query[add_blank] - add a line in with an empty option...  - not really needed???
52      *      _delete    = delete a list of ids element. (depricated.. this will be removed...)
53      * 
54      * DEBUGGING
55      *  _post   =1    = simulate a post with debuggin on.
56      *  _debug_post << This is prefered, as _post may overlap with accouting posts..
57      *  
58      *  _debug     = turn on DB_dataobject deubbing, must be admin at present..
59      *
60      *
61      * CALLS methods on dataobjects if they exist
62      *
63      * 
64      *   checkPerm('S' , $authuser)
65      *                      - can we list the stuff
66      *                      - return false to disallow...
67      *   applySort($au, $sortcol, $direction, $array_of_columns, $multisort)
68      *                     -- does not support multisort at present..
69      *   applyFilters($_REQUEST, $authUser, $roo)
70      *                     -- apply any query filters on data. and hide stuff not to be seen.
71      *                     -- can exit by calling $roo->jerr()
72      *   postListExtra($_REQUEST) : array(extra_name => data)
73      *                     - add extra column data on the results (like new messages etc.)
74      *   postListFilter($data, $authUser, $request) return $data
75      *                      - add extra data to an object
76      * 
77      *   
78      *   toRooSingleArray($authUser, $request) : array
79      *                       - called on single fetch only, add or maniuplate returned array data.
80      *                       - is also called when _id=0 is used (for fetching a default set.)
81      *   toRooArray($request) : array
82      *                      - called if singleArray is unavailable on single fetch.
83      *                      - always tried for mutiple results.
84      *   toArray()          - the default method if none of the others are found. 
85      *   
86      *   autoJoin($request) 
87      *                      - standard DataObject feature - causes all results to show all
88      *                        referenced data.
89      *
90      * PROPERTIES:
91      *    _extra_cols  -- if set, then filtering by column etc. will use them.
92      *
93      
94      */
95     function get($tab)
96     {
97         $this->init();
98         
99         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
100         
101         if ( $this->checkDebugPost()) {
102             $_POST  = $_GET;
103             return $this->post($tab);
104         }
105         
106         $this->checkDebug();
107         
108         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
109    
110         $tab = array_shift(explode('/', $tab));
111         
112         $x = $this->dataObject($tab);
113         
114         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
115         
116         if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
117              $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
118              // actually exits.
119         }
120         
121         
122         // single fetch (use '0' to fetch an empty object..)
123         if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
124              
125              $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
126              // actually exits.
127         }
128         
129         // Depricated...
130
131        
132         if (isset($_REQUEST['_delete'])) {
133             $this->jerr("DELETE by GET has been removed - update the code to use POST");
134         } 
135         
136         
137         // Depricated...
138         
139         if (isset($_REQUEST['_toggleActive'])) {
140             // do we really delete stuff!?!?!?
141             if (!$this->hasPerm("Core.Staff", 'E'))  {
142                 $this->jerr("PERMISSION DENIED (ta)");
143             }
144             $clean = create_function('$v', 'return (int)$v;');
145             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
146             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
147                 $this->jerr("you can not disable yourself");
148             }
149             $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
150             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
151             $this->jok("Updated");
152             
153         }
154        //DB_DataObject::debugLevel(1);
155        
156         
157         // sets map and countWhat
158         $this->loadMap($x, array(
159             'columns' => $_columns,
160             'distinct' => empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct'],
161             'exclude' => empty($_REQUEST['_exclude_columns']) ? false:  explode(',', $_REQUEST['_exclude_columns'])
162         ));
163         
164         
165         $this->setFilters($x,$_REQUEST);
166         
167         if (!$this->checkPerm($x,'S', $_REQUEST))  {
168             $this->jerr("PERMISSION DENIED (g)");
169         }
170         
171         $total = $x->count($this->countWhat);
172         // sorting..
173       //   
174         //var_dump($total);exit;
175         $this->applySort($x);
176         
177         $fake_limit = false;
178         
179         if (!empty($_REQUEST['_distinct']) && $total < 400) {
180             $fake_limit  = true;
181         }
182         
183         if (!$fake_limit) {
184  
185             $x->limit(
186                 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
187                 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
188             );
189         } 
190         $queryObj = clone($x);
191         //DB_DataObject::debuglevel(1);
192         
193         $this->sessionState(0);
194         $res = $x->find();
195         $this->sessionState(1);
196         
197         if (false === $res) {
198             $this->jerr($x->_lastError->toString());
199         }
200         
201         $ret = array();
202         
203         // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
204         
205         
206         if (!empty($_REQUEST['query']['add_blank'])) {
207             $ret[] = array( 'id' => 0, 'name' => '----');
208             $total+=1;
209         }
210          
211         $rooar = method_exists($x, 'toRooArray');
212         $_columnsf = $_columns  ? array_flip($_columns) : false;
213         while ($x->fetch()) {
214             //print_R($x);exit;
215             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
216             if ($add === false) {
217                 continue;
218             }
219             $ret[] =  !$_columns ? $add : array_intersect_key($add, $_columnsf);
220         }
221         
222         if ($fake_limit) {
223             $ret = array_slice($ret,
224                    empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
225                     min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
226             );
227             
228         }
229         
230         
231         $extra = false;
232         if (method_exists($queryObj ,'postListExtra')) {
233             $extra = $queryObj->postListExtra($_REQUEST, $this);
234         }
235         
236         
237         // filter results, and add any data that is needed...
238         if (method_exists($x,'postListFilter')) {
239             $ret = $x->postListFilter($ret, $this->getAuthUser(), $_REQUEST);
240         }
241         
242         
243         
244         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
245             
246             
247             $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
248                         empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
249                          );
250             
251             
252         
253         }
254         
255         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
256             $meta = $this->meta($x, $ret);
257             if ($meta) {
258                 $extra['metaData'] = $meta;
259             }
260         }
261         // this make take some time...
262         $this->sessionState(0);
263        // echo "<PRE>"; print_r($ret);
264         $this->jdata($ret, max(count($ret), $total), $extra );
265
266     
267     }
268     
269     function checkDebugPost()
270     {
271         return (!empty($_GET['_post']) || !empty($_GET['_debug_post'])) && 
272                     $this->authUser && 
273                     method_exists($this->authUser,'groups') &&
274                     in_array('Administrators', $this->authUser->groups('name')); 
275         
276     }
277     
278     function selectSingle($x, $id, $req=false)
279     {
280         $_columns = !empty($req['_columns']) ? explode(',', $req['_columns']) : false;
281
282         if (!is_array($id) && empty($id)) {
283             
284             if (method_exists($x, 'toRooSingleArray')) {
285                 $this->jok($x->toRooSingleArray($this->getAuthUser(), $req));
286             }
287             
288             if (method_exists($x, 'toRooArray')) {
289                 $this->jok($x->toRooArray($req));
290             }
291             
292             $this->jok($x->toArray());
293         }
294         
295         $this->loadMap($x, array(
296             'columns' => $_columns,
297         ));
298         
299         if ($req !== false) { 
300             $this->setFilters($x, $req);
301         }
302         
303         if (is_array($id)) {
304             // lookup...
305             $x->setFrom($req['lookup'] );
306             $x->limit(1);
307             if (!$x->find(true)) {
308                 if (!empty($id['_id'])) {
309                     // standardize this?
310                     $this->jok($x->toArray());
311                 }
312                 $this->jok(false);
313             }
314             
315         } else if (!$x->get($id)) {
316             $this->jerr("selectSingle: no such record ($id)");
317         }
318         
319         // ignore perms if comming from update/insert - as it's already done...
320         if ($req !== false && !$this->checkPerm($x,'S'))  {
321             $this->jerr("PERMISSION DENIED - si");
322         }
323         // different symantics on all these calls??
324         if (method_exists($x, 'toRooSingleArray')) {
325             $this->jok($x->toRooSingleArray($this->getAuthUser(), $req));
326         }
327         if (method_exists($x, 'toRooArray')) {
328             $this->jok($x->toRooArray($req));
329         }
330         
331         $this->jok($x->toArray());
332         
333         
334     }
335     
336     function setFilters($x, $q)
337     {
338         if (method_exists($x, 'applyFilters')) {
339            // DB_DataObject::debugLevel(1);
340             if (false === $x->applyFilters($q, $this->getAuthUser(), $this)) {
341                 return; 
342             } 
343         }
344         $q_filtered = array();
345         
346         $keys = $x->keys();
347         // var_dump($keys);exit;
348         foreach($q as $key=>$val) {
349             
350             if (in_array($key,$keys) && !is_array($val)) {
351                
352                 $x->$key  = $val;
353             }
354             
355              // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
356             // value is an array..
357             if (is_array($val) ) {
358                 
359                 $pref = '';
360                 
361                 if ($key[0] == '!') {
362                     $pref = '!';
363                     $key = substr($key,1);
364                 }
365                 
366                 if (!in_array( $key,  array_keys($this->cols))) {
367                     continue;
368                 }
369                 
370                 // support a[0] a[1] ..... => whereAddIn(
371                 $ar = array();
372                 $quote = false;
373                 foreach($val as $k=>$v) {
374                     if (!is_numeric($k)) {
375                         $ar = array();
376                         break;
377                     }
378                     // FIXME: note this is not typesafe for anything other than mysql..
379                     
380                     if (!is_numeric($v) || !is_long($v)) {
381                         $quote = true;
382                     }
383                     $ar[] = $v;
384                     
385                 }
386                 if (count($ar)) {
387                     
388                     
389                     $x->whereAddIn($pref . (
390                         isset($this->colsJname[$key]) ? 
391                             $this->colsJname[$key] :
392                             ($x->tableName(). '.'.$key)),
393                         $ar, $quote ? 'string' : 'int');
394                 }
395                 
396                 continue;
397             }
398             
399             
400             // handles !name=fred => name not equal fred.
401             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
402                 
403                 $key  = substr($key, 1) ;
404                 
405                 $x->whereAdd(   (
406                         isset($this->colsJname[$key]) ? 
407                             $this->colsJname[$key] :
408                             $x->tableName(). '.'.$key ) . ' != ' .
409                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
410                 );
411                 continue;
412                 
413             }
414
415             switch($key) {
416                     
417                 // Events and remarks -- fixme - move to events/remarsk...
418                 case 'on_id':  // where TF is this used...
419                     if (!empty($q['query']['original'])) {
420                       //  DB_DataObject::debugLevel(1);
421                         $o = (int) $q['query']['original'];
422                         $oid = (int) $val;
423                         $x->whereAdd("(on_id = $oid  OR 
424                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
425                             )");
426                         continue;
427                                 
428                     }
429                     $x->on_id = $val;
430                 
431                 
432                 default:
433                     if (strlen($val) && $key[0] != '_') {
434                         $q_filtered[$key] = $val;
435                     }
436                     
437                     // subjoined columns = check the values.
438                     // note this is not typesafe for anything other than mysql..
439                     
440                     if (isset($this->colsJname[$key])) {
441                         $quote = false;
442                         if (!is_numeric($val) || !is_long($val)) {
443                             $quote = true;
444                         }
445                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
446                         
447                     }
448                     
449                     
450                     continue;
451             }
452         }
453         if (!empty($q_filtered)) {
454             $x->setFrom($q_filtered);
455         }
456         
457         if (!empty($q['query']['name'])) {
458             if (in_array( 'name',  array_keys($x->table()))) {
459                 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
460             }
461         }
462         
463     }
464     
465     function applySort($x, $sort = '', $dir ='')
466     {
467         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
468         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
469         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
470          
471         $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
472         //var_Dump($ms);exit;
473         $sorted = false;
474         if (method_exists($x, 'applySort')) {
475             $sorted = $x->applySort(
476                     $this->getAuthUser(),
477                     $sort,
478                     $dir,
479                     array_keys($this->cols),
480                     $ms ? json_decode($ms) : false
481             );
482         }
483         if ($ms !== false) {
484             return $this->multiSort($x);
485         }
486         
487         if ($sorted === false) {
488             
489             $cols = $x->table();
490             $excols = array_keys($this->cols);
491             
492             if (isset($x->_extra_cols)) {
493                 $excols = array_merge($excols, $x->_extra_cols);
494             }
495             $sort_ar = explode(',', $sort);
496             $sort_str = array();
497           
498             foreach($sort_ar as $sort) {
499                 
500                 if (strlen($sort) && isset($cols[$sort]) ) {
501                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
502                     
503                 } else if (in_array($sort, $excols)) {
504                     $sort_str[] = $sort . ' ' . $dir ;
505                 }
506             }
507              
508             if ($sort_str) {
509                 $x->orderBy(implode(', ', $sort_str ));
510             }
511         }
512     }
513     
514     function toCsv($data, $cols, $titles, $filename, $addDate = true)
515     {
516         $this->sessionState(0); // turn off sessions  - no locking..
517
518         require_once 'Pman/Core/SimpleExcel.php';
519         
520         $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
521         
522         
523         $se_config=  array(
524             'workbook' => substr($fn, 0, 31),
525             'cols' => array(),
526             'leave_open' => true
527         );
528         
529         
530         $se = false;
531         if (is_object($data)) {
532             $rooar = method_exists($data, 'toRooArray');
533             while($data->fetch()) {
534                 $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
535                 
536                 
537                 if ($cols == '*') {  /// did we get cols sent to us?
538                     $cols = array_keys($x);
539                 }
540                 if ($titles== '*') {
541                     $titles= array_keys($x);
542                 }
543                 if ($titles !== false) {
544                     
545                     foreach($cols as $i=>$col) {
546                         $se_config['cols'][] = array(
547                             'header'=> isset($titles[$i]) ? $titles[$i] : $col,
548                             'dataIndex'=> $col,
549                             'width'=>  100
550                         );
551                          $se = new Pman_Core_SimpleExcel(array(), $se_config);
552        
553                         
554                     }
555                     
556                     
557                     //fputcsv($fh, $titles);
558                     $titles = false;
559                 }
560                 
561
562                 $se->addLine($se_config['workbook'], $x);
563                     
564                 
565             }
566             if(!$se){
567                 
568                 $this->jerr('no data found', false, 'text/plain');
569             }
570             $se->send($fn .'.xls');
571             exit;
572             
573         } 
574         
575         
576         foreach($data as $x) {
577             //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
578             $line = array();
579             if ($titles== '*') {
580                 $titles= array_keys($x);
581             }
582             if ($cols== '*') {
583                 $cols= array_keys($x);
584             }
585             if ($titles !== false) {
586                 foreach($cols as $i=>$col) {
587                     $se_config['cols'][] = array(
588                         'header'=> isset($titles[$i]) ? $titles[$i] : $col,
589                         'dataIndex'=> $col,
590                         'width'=>  100,
591                        //     'renderer' => array($this, 'getThumb'),
592                          //   'color' => 'yellow', // set color for the cell which is a header element
593                           // 'fillBlank' => 'gray', // set 
594                     );
595                     $se = new Pman_Core_SimpleExcel(array(),$se_config);
596    
597                     
598                 }
599                 
600                 
601                 //fputcsv($fh, $titles);
602                 $titles = false;
603             }
604             
605             
606             
607             $se->addLine($se_config['workbook'], $x);
608         }
609         if(!$se){
610             $this->jerr('no data found');
611         }
612         $se->send($fn .'.xls');
613         exit;
614         
615     }
616     
617     var $cols = array();
618     
619     function loadMap($do, $cfg =array())
620     {
621         $onlycolumns    = !empty($cfg['columns']) ? $cfg['columns'] : false;
622         $distinct       = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
623         $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
624           
625         $excludecolumns[] = 'passwd'; // we never expose passwords
626        
627         $ret = $do->autoJoin(array(
628             'include' => $onlycolumns,
629             'exclude' => $excludecolumns,
630             'distinct' => $distinct
631         ));
632         
633         $this->countWhat = $ret['count'];
634         $this->cols = $ret['cols'];
635         $this->colsJname = $ret['join_names'];
636         
637         return;
638         
639     }
640     
641     function meta($x, $data)
642     {
643         $lost = 0;
644         $cols  = array_keys($data[0]);
645      
646         $options = &PEAR::getStaticProperty('DB_DataObject','options');
647         $reader = $options["ini_{$x->_database}"] .'.reader';
648         if (!file_exists( $reader )) {
649             return;
650         }
651         
652         $rdata = unserialize(file_get_contents($reader));
653         
654         $keys = $x->keys();
655         $key = empty($keys) ? 'id' : $keys[0];
656         
657         
658         $meta = array();
659         foreach($cols as $c ) {
660             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
661                 $meta[] = $c;
662                 continue;    
663             }
664             $add = $rdata[$this->cols[$c]];
665             $add['name'] = $c;
666             $meta[] = $add;
667         }
668         return array(
669             'totalProperty' =>  'total',
670             'successProperty' => 'success',
671             'root' => 'data',
672             'id' => $key, // was 'id'...
673             'fields' => $meta
674         );
675          
676         
677     }
678 }