bfc370bceae9924dff3c6762472292b12fd0b922
[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 setFilters($x, $q)
279     {
280         if (method_exists($x, 'applyFilters')) {
281            // DB_DataObject::debugLevel(1);
282             if (false === $x->applyFilters($q, $this->getAuthUser(), $this)) {
283                 return; 
284             } 
285         }
286         $q_filtered = array();
287         
288         $keys = $x->keys();
289         // var_dump($keys);exit;
290         foreach($q as $key=>$val) {
291             
292             if (in_array($key,$keys) && !is_array($val)) {
293                
294                 $x->$key  = $val;
295             }
296             
297              // handles name[]=fred&name[]=brian => name in ('fred', 'brian').
298             // value is an array..
299             if (is_array($val) ) {
300                 
301                 $pref = '';
302                 
303                 if ($key[0] == '!') {
304                     $pref = '!';
305                     $key = substr($key,1);
306                 }
307                 
308                 if (!in_array( $key,  array_keys($this->cols))) {
309                     continue;
310                 }
311                 
312                 // support a[0] a[1] ..... => whereAddIn(
313                 $ar = array();
314                 $quote = false;
315                 foreach($val as $k=>$v) {
316                     if (!is_numeric($k)) {
317                         $ar = array();
318                         break;
319                     }
320                     // FIXME: note this is not typesafe for anything other than mysql..
321                     
322                     if (!is_numeric($v) || !is_long($v)) {
323                         $quote = true;
324                     }
325                     $ar[] = $v;
326                     
327                 }
328                 if (count($ar)) {
329                     
330                     
331                     $x->whereAddIn($pref . (
332                         isset($this->colsJname[$key]) ? 
333                             $this->colsJname[$key] :
334                             ($x->tableName(). '.'.$key)),
335                         $ar, $quote ? 'string' : 'int');
336                 }
337                 
338                 continue;
339             }
340             
341             
342             // handles !name=fred => name not equal fred.
343             if ($key[0] == '!' && in_array(substr($key, 1), array_keys($this->cols))) {
344                 
345                 $key  = substr($key, 1) ;
346                 
347                 $x->whereAdd(   (
348                         isset($this->colsJname[$key]) ? 
349                             $this->colsJname[$key] :
350                             $x->tableName(). '.'.$key ) . ' != ' .
351                     (is_numeric($val) ? $val : "'".  $x->escape($val) . "'")
352                 );
353                 continue;
354                 
355             }
356
357             switch($key) {
358                     
359                 // Events and remarks -- fixme - move to events/remarsk...
360                 case 'on_id':  // where TF is this used...
361                     if (!empty($q['query']['original'])) {
362                       //  DB_DataObject::debugLevel(1);
363                         $o = (int) $q['query']['original'];
364                         $oid = (int) $val;
365                         $x->whereAdd("(on_id = $oid  OR 
366                                 on_id IN ( SELECT distinct(id) FROM Documents WHERE original = $o ) 
367                             )");
368                         continue;
369                                 
370                     }
371                     $x->on_id = $val;
372                 
373                 
374                 default:
375                     if (strlen($val) && $key[0] != '_') {
376                         $q_filtered[$key] = $val;
377                     }
378                     
379                     // subjoined columns = check the values.
380                     // note this is not typesafe for anything other than mysql..
381                     
382                     if (isset($this->colsJname[$key])) {
383                         $quote = false;
384                         if (!is_numeric($val) || !is_long($val)) {
385                             $quote = true;
386                         }
387                         $x->whereAdd( "{$this->colsJname[$key]} = " . ($quote ? "'". $x->escape($val) ."'" : $val));
388                         
389                     }
390                     
391                     
392                     continue;
393             }
394         }
395         if (!empty($q_filtered)) {
396             $x->setFrom($q_filtered);
397         }
398         
399         if (!empty($q['query']['name'])) {
400             if (in_array( 'name',  array_keys($x->table()))) {
401                 $x->whereAdd($x->tableName().".name LIKE '". $x->escape($q['query']['name']) . "%'");
402             }
403         }
404         
405     }
406     
407     function applySort($x, $sort = '', $dir ='')
408     {
409         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
410         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
411         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
412          
413         $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
414         //var_Dump($ms);exit;
415         $sorted = false;
416         if (method_exists($x, 'applySort')) {
417             $sorted = $x->applySort(
418                     $this->getAuthUser(),
419                     $sort,
420                     $dir,
421                     array_keys($this->cols),
422                     $ms ? json_decode($ms) : false
423             );
424         }
425         if ($ms !== false) {
426             return $this->multiSort($x);
427         }
428         
429         if ($sorted === false) {
430             
431             $cols = $x->table();
432             $excols = array_keys($this->cols);
433             
434             if (isset($x->_extra_cols)) {
435                 $excols = array_merge($excols, $x->_extra_cols);
436             }
437             $sort_ar = explode(',', $sort);
438             $sort_str = array();
439           
440             foreach($sort_ar as $sort) {
441                 
442                 if (strlen($sort) && isset($cols[$sort]) ) {
443                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
444                     
445                 } else if (in_array($sort, $excols)) {
446                     $sort_str[] = $sort . ' ' . $dir ;
447                 }
448             }
449              
450             if ($sort_str) {
451                 $x->orderBy(implode(', ', $sort_str ));
452             }
453         }
454     }
455     
456     function toCsv($data, $cols, $titles, $filename, $addDate = true)
457     {
458         $this->sessionState(0); // turn off sessions  - no locking..
459
460         require_once 'Pman/Core/SimpleExcel.php';
461         
462         $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
463         
464         
465         $se_config=  array(
466             'workbook' => substr($fn, 0, 31),
467             'cols' => array(),
468             'leave_open' => true
469         );
470         
471         
472         $se = false;
473         if (is_object($data)) {
474             $rooar = method_exists($data, 'toRooArray');
475             while($data->fetch()) {
476                 $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
477                 
478                 
479                 if ($cols == '*') {  /// did we get cols sent to us?
480                     $cols = array_keys($x);
481                 }
482                 if ($titles== '*') {
483                     $titles= array_keys($x);
484                 }
485                 if ($titles !== false) {
486                     
487                     foreach($cols as $i=>$col) {
488                         $se_config['cols'][] = array(
489                             'header'=> isset($titles[$i]) ? $titles[$i] : $col,
490                             'dataIndex'=> $col,
491                             'width'=>  100
492                         );
493                          $se = new Pman_Core_SimpleExcel(array(), $se_config);
494        
495                         
496                     }
497                     
498                     
499                     //fputcsv($fh, $titles);
500                     $titles = false;
501                 }
502                 
503
504                 $se->addLine($se_config['workbook'], $x);
505                     
506                 
507             }
508             if(!$se){
509                 
510                 $this->jerr('no data found', false, 'text/plain');
511             }
512             $se->send($fn .'.xls');
513             exit;
514             
515         } 
516         
517         
518         foreach($data as $x) {
519             //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
520             $line = array();
521             if ($titles== '*') {
522                 $titles= array_keys($x);
523             }
524             if ($cols== '*') {
525                 $cols= array_keys($x);
526             }
527             if ($titles !== false) {
528                 foreach($cols as $i=>$col) {
529                     $se_config['cols'][] = array(
530                         'header'=> isset($titles[$i]) ? $titles[$i] : $col,
531                         'dataIndex'=> $col,
532                         'width'=>  100,
533                        //     'renderer' => array($this, 'getThumb'),
534                          //   'color' => 'yellow', // set color for the cell which is a header element
535                           // 'fillBlank' => 'gray', // set 
536                     );
537                     $se = new Pman_Core_SimpleExcel(array(),$se_config);
538    
539                     
540                 }
541                 
542                 
543                 //fputcsv($fh, $titles);
544                 $titles = false;
545             }
546             
547             
548             
549             $se->addLine($se_config['workbook'], $x);
550         }
551         if(!$se){
552             $this->jerr('no data found');
553         }
554         $se->send($fn .'.xls');
555         exit;
556         
557     }
558     
559     var $cols = array();
560     
561     function loadMap($do, $cfg =array())
562     {
563         $onlycolumns    = !empty($cfg['columns']) ? $cfg['columns'] : false;
564         $distinct       = !empty($cfg['distinct']) ? $cfg['distinct'] : false;
565         $excludecolumns = !empty($cfg['exclude']) ? $cfg['exclude'] : array();
566           
567         $excludecolumns[] = 'passwd'; // we never expose passwords
568        
569         $ret = $do->autoJoin(array(
570             'include' => $onlycolumns,
571             'exclude' => $excludecolumns,
572             'distinct' => $distinct
573         ));
574         
575         $this->countWhat = $ret['count'];
576         $this->cols = $ret['cols'];
577         $this->colsJname = $ret['join_names'];
578         
579         return;
580         
581     }
582     
583     function meta($x, $data)
584     {
585         $lost = 0;
586         $cols  = array_keys($data[0]);
587      
588         $options = &PEAR::getStaticProperty('DB_DataObject','options');
589         $reader = $options["ini_{$x->_database}"] .'.reader';
590         if (!file_exists( $reader )) {
591             return;
592         }
593         
594         $rdata = unserialize(file_get_contents($reader));
595         
596         $keys = $x->keys();
597         $key = empty($keys) ? 'id' : $keys[0];
598         
599         
600         $meta = array();
601         foreach($cols as $c ) {
602             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
603                 $meta[] = $c;
604                 continue;    
605             }
606             $add = $rdata[$this->cols[$c]];
607             $add['name'] = $c;
608             $meta[] = $add;
609         }
610         return array(
611             'totalProperty' =>  'total',
612             'successProperty' => 'success',
613             'root' => 'data',
614             'id' => $key, // was 'id'...
615             'fields' => $meta
616         );
617          
618         
619     }
620 }