Pman.js
[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         $explode_tab = explode('/', $tab);
111         $tab = array_shift($explode_tab);
112         
113         $x = $this->dataObject($tab);
114         
115         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
116         
117         if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
118              $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
119              // actually exits.
120         }
121         
122         
123         // single fetch (use '0' to fetch an empty object..)
124         if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
125              
126              $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
127              // actually exits.
128         }
129         
130         // Depricated...
131
132        
133         if (isset($_REQUEST['_delete'])) {
134             $this->jerr("DELETE by GET has been removed - update the code to use POST");
135         } 
136         
137         
138         // Depricated...
139         
140         if (isset($_REQUEST['_toggleActive'])) {
141             // do we really delete stuff!?!?!?
142             if (!$this->hasPerm("Core.Staff", 'E'))  {
143                 $this->jerr("PERMISSION DENIED (ta)");
144             }
145             $clean = create_function('$v', 'return (int)$v;');
146             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
147             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
148                 $this->jerr("you can not disable yourself");
149             }
150             $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
151             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
152             $this->jok("Updated");
153             
154         }
155        //DB_DataObject::debugLevel(1);
156        
157         
158         // sets map and countWhat
159         $this->loadMap($x, array(
160             'columns' => $_columns,
161             'distinct' => empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct'],
162             'exclude' => empty($_REQUEST['_exclude_columns']) ? false:  explode(',', $_REQUEST['_exclude_columns'])
163         ));
164         
165         
166         $this->setFilters($x,$_REQUEST);
167         
168         if (!$this->checkPerm($x,'S', $_REQUEST))  {
169             $this->jerr("PERMISSION DENIED (g)");
170         }
171         
172         $total = $x->count($this->countWhat);
173         // sorting..
174       //   
175         //var_dump($total);exit;
176         $this->applySort($x);
177         
178         $fake_limit = false;
179         
180         if (!empty($_REQUEST['_distinct']) && $total < 400) {
181             $fake_limit  = true;
182         }
183         
184         if (!$fake_limit) {
185  
186             $x->limit(
187                 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
188                 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
189             );
190         } 
191         $queryObj = clone($x);
192         //DB_DataObject::debuglevel(1);
193         
194         $this->sessionState(0);
195         $res = $x->find();
196         $this->sessionState(1);
197         
198         if (false === $res) {
199             $this->jerr($x->_lastError->toString());
200         }
201         
202         $ret = array();
203         
204         // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
205         
206         
207         if (!empty($_REQUEST['query']['add_blank'])) {
208             $ret[] = array( 'id' => 0, 'name' => '----');
209             $total+=1;
210         }
211          
212         $rooar = method_exists($x, 'toRooArray');
213         $_columnsf = $_columns  ? array_flip($_columns) : false;
214         while ($x->fetch()) {
215             //print_R($x);exit;
216             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
217             if ($add === false) {
218                 continue;
219             }
220             $ret[] =  !$_columns ? $add : array_intersect_key($add, $_columnsf);
221         }
222         
223         if ($fake_limit) {
224             $ret = array_slice($ret,
225                    empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
226                     min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
227             );
228             
229         }
230         
231         
232         $extra = false;
233         if (method_exists($queryObj ,'postListExtra')) {
234             $extra = $queryObj->postListExtra($_REQUEST, $this);
235         }
236         
237         
238         // filter results, and add any data that is needed...
239         if (method_exists($x,'postListFilter')) {
240             $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
241         }
242         
243         
244         
245         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
246             
247             
248             $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
249                         empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
250                          );
251             
252             
253         
254         }
255         
256         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
257             $meta = $this->meta($x, $ret);
258             if ($meta) {
259                 $extra['metaData'] = $meta;
260             }
261         }
262         // this make take some time...
263         $this->sessionState(0);
264        // echo "<PRE>"; print_r($ret);
265         $this->jdata($ret, max(count($ret), $total), $extra );
266
267     
268     }
269     
270     function checkDebugPost()
271     {
272         return (!empty($_GET['_post']) || !empty($_GET['_debug_post'])) && 
273                     $this->authUser && 
274                     method_exists($this->authUser,'groups') &&
275                     in_array('Administrators', $this->authUser->groups('name')); 
276         
277     }
278     
279     function applySort($x, $sort = '', $dir ='')
280     {
281         $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
282         $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
283         $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
284          
285         $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
286         //var_Dump($ms);exit;
287         $sorted = false;
288         if (method_exists($x, 'applySort')) {
289             $sorted = $x->applySort(
290                     $this->authUser,
291                     $sort,
292                     $dir,
293                     array_keys($this->cols),
294                     $ms ? json_decode($ms) : false
295             );
296         }
297         if ($ms !== false) {
298             return $this->multiSort($x);
299         }
300         
301         if ($sorted === false) {
302             
303             $cols = $x->table();
304             $excols = array_keys($this->cols);
305             //print_R($excols);
306             
307             if (isset($x->_extra_cols)) {
308                 $excols = array_merge($excols, $x->_extra_cols);
309             }
310             $sort_ar = explode(',', $sort);
311             $sort_str = array();
312           
313             foreach($sort_ar as $sort) {
314                 
315                 if (strlen($sort) && isset($cols[$sort]) ) {
316                     $sort_str[] =  $x->tableName() .'.'.$sort . ' ' . $dir ;
317                     
318                 } else if (in_array($sort, $excols)) {
319                     $sort_str[] = $sort . ' ' . $dir ;
320                 }
321             }
322              
323             if ($sort_str) {
324                 $x->orderBy(implode(', ', $sort_str ));
325             }
326         }
327     }
328     
329     function toCsv($data, $cols, $titles, $filename, $addDate = true)
330     {
331         $this->sessionState(0); // turn off sessions  - no locking..
332
333         require_once 'Pman/Core/SimpleExcel.php';
334         
335         $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
336         
337         
338         $se_config=  array(
339             'workbook' => substr($fn, 0, 31),
340             'cols' => array(),
341             'leave_open' => true
342         );
343         
344         
345         $se = false;
346         if (is_object($data)) {
347             $rooar = method_exists($data, 'toRooArray');
348             while($data->fetch()) {
349                 $x = $rooar  ? $data->toRooArray($q) : $data->toArray();
350                 
351                 
352                 if ($cols == '*') {  /// did we get cols sent to us?
353                     $cols = array_keys($x);
354                 }
355                 if ($titles== '*') {
356                     $titles= array_keys($x);
357                 }
358                 if ($titles !== false) {
359                     
360                     foreach($cols as $i=>$col) {
361                         $se_config['cols'][] = array(
362                             'header'=> isset($titles[$i]) ? $titles[$i] : $col,
363                             'dataIndex'=> $col,
364                             'width'=>  100
365                         );
366                          $se = new Pman_Core_SimpleExcel(array(), $se_config);
367        
368                         
369                     }
370                     
371                     
372                     //fputcsv($fh, $titles);
373                     $titles = false;
374                 }
375                 
376
377                 $se->addLine($se_config['workbook'], $x);
378                     
379                 
380             }
381             if(!$se){
382                 
383                 $this->jerr('no data found', false, 'text/plain');
384             }
385             $se->send($fn .'.xls');
386             exit;
387             
388         } 
389         
390         
391         foreach($data as $x) {
392             //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
393             $line = array();
394             if ($titles== '*') {
395                 $titles= array_keys($x);
396             }
397             if ($cols== '*') {
398                 $cols= array_keys($x);
399             }
400             if ($titles !== false) {
401                 foreach($cols as $i=>$col) {
402                     $se_config['cols'][] = array(
403                         'header'=> isset($titles[$i]) ? $titles[$i] : $col,
404                         'dataIndex'=> $col,
405                         'width'=>  100,
406                        //     'renderer' => array($this, 'getThumb'),
407                          //   'color' => 'yellow', // set color for the cell which is a header element
408                           // 'fillBlank' => 'gray', // set 
409                     );
410                     $se = new Pman_Core_SimpleExcel(array(),$se_config);
411    
412                     
413                 }
414                 
415                 
416                 //fputcsv($fh, $titles);
417                 $titles = false;
418             }
419             
420             
421             
422             $se->addLine($se_config['workbook'], $x);
423         }
424         if(!$se){
425             $this->jerr('no data found');
426         }
427         $se->send($fn .'.xls');
428         exit;
429         
430     }
431     
432     function meta($x, $data)
433     {
434         $lost = 0;
435         $cols  = array_keys($data[0]);
436      
437         $options = &PEAR::getStaticProperty('DB_DataObject','options');
438         $reader = $options["ini_{$x->databaseNickname()}"] .'.reader';
439         if (!file_exists( $reader )) {
440             return;
441         }
442         
443         $rdata = unserialize(file_get_contents($reader));
444         
445         $keys = $x->keys();
446         $key = empty($keys) ? 'id' : $keys[0];
447         
448         
449         $meta = array();
450         foreach($cols as $c ) {
451             if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
452                 $meta[] = $c;
453                 continue;    
454             }
455             $add = $rdata[$this->cols[$c]];
456             $add['name'] = $c;
457             $meta[] = $add;
458         }
459         return array(
460             'totalProperty' =>  'total',
461             'successProperty' => 'success',
462             'root' => 'data',
463             'id' => $key, // was 'id'...
464             'fields' => $meta
465         );
466          
467         
468     }
469     
470     function multiSort($x)
471     {
472         $ms = json_decode($_REQUEST['_multisort']);
473         if (!isset($ms->order) || !is_array($ms->order)) {
474             return;
475         }
476         $sort_str = array();
477         
478         $cols = $x->table();
479         
480         foreach($ms->order  as $col) {
481             if (!isset($ms->sort->{$col})) {
482                 continue; // no direction..
483             }
484             $ms->sort->{$col} = $ms->sort->{$col}  == 'ASC' ? 'ASC' : 'DESC';
485             
486             if (strlen($col) && isset($cols[$col]) ) {
487                 $sort_str[] =  $x->tableName() .'.'.$col . ' ' .  $ms->sort->{$col};
488                 continue;
489             }
490             
491             if (in_array($col, array_keys($this->cols))) {
492                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
493                 continue;
494             }
495             if (isset($x->_extra_cols) && in_array($col, $x->_extra_cols)) {
496                 $sort_str[] = $col. ' ' . $ms->sort->{$col};
497             }
498         }
499          
500         if ($sort_str) {
501             $x->orderBy(implode(', ', $sort_str ));
502         }
503     }
504 }