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->jerr("Not authenticated", array('authFailure' => true));
98        //echo '<PRE>';print_R($_GET);
99       //DB_DataObject::debuglevel(1);
100         
101         $this->init(); // from pman.
102         //DB_DataObject::debuglevel(1);
103         HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
104         
105    
106         
107         // debugging...
108         
109         
110         
111         if ( $this->checkDebugPost()) {
112                     
113             
114             
115             $_POST  = $_GET;
116             //DB_DAtaObject::debuglevel(1);
117             return $this->post($tab);
118         }
119         
120         $this->checkDebug();
121         
122         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
123    
124         $tab = array_shift(explode('/', $tab));
125         $x = $this->dataObject($tab);
126         
127         $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
128         
129         if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
130              $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
131              // actually exits.
132         }
133         
134         
135         // single fetch (use '0' to fetch an empty object..)
136         if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
137              
138              $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
139              // actually exits.
140         }
141         
142         // Depricated...
143
144        
145         if (isset($_REQUEST['_delete'])) {
146             $this->jerr("DELETE by GET has been removed - update the code to use POST");
147             /*
148             
149             $keys = $x->keys();
150             if (empty($keys) ) {
151                 $this->jerr('no key');
152             }
153             
154             $this->key = $keys[0];
155             
156             
157             // do we really delete stuff!?!?!?
158             return $this->delete($x,$_REQUEST);
159             */
160         } 
161         
162         
163         // Depricated...
164         
165         if (isset($_REQUEST['_toggleActive'])) {
166             // do we really delete stuff!?!?!?
167             if (!$this->hasPerm("Core.Staff", 'E'))  {
168                 $this->jerr("PERMISSION DENIED (ta)");
169             }
170             $clean = create_function('$v', 'return (int)$v;');
171             $bits = array_map($clean, explode(',', $_REQUEST['_toggleActive']));
172             if (in_array($this->authUser->id, $bits) && $this->authUser->active) {
173                 $this->jerr("you can not disable yourself");
174             }
175             $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
176             $this->addEvent("USERTOGGLE", false, implode(',', $bits));
177             $this->jok("Updated");
178             
179         }
180        //DB_DataObject::debugLevel(1);
181        
182         
183         // sets map and countWhat
184         $this->loadMap($x, array(
185                     'columns' => $_columns,
186                     'distinct' => empty($_REQUEST['_distinct']) ? false:  $_REQUEST['_distinct'],
187                     'exclude' => empty($_REQUEST['_exclude_columns']) ? false:  explode(',', $_REQUEST['_exclude_columns'])
188             ));
189         
190         
191         $this->setFilters($x,$_REQUEST);
192         
193         if (!$this->checkPerm($x,'S', $_REQUEST))  {
194             $this->jerr("PERMISSION DENIED (g)");
195         }
196         
197          //print_r($x);
198         // build join if req.
199           //DB_DataObject::debugLevel(1);
200        //   var_dump($this->countWhat);
201         $total = $x->count($this->countWhat);
202         // sorting..
203       //   
204         //var_dump($total);exit;
205         $this->applySort($x);
206         
207         $fake_limit = false;
208         
209         if (!empty($_REQUEST['_distinct']) && $total < 400) {
210             $fake_limit  = true;
211         }
212         
213         if (!$fake_limit) {
214  
215             $x->limit(
216                 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
217                 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
218             );
219         } 
220         $queryObj = clone($x);
221         //DB_DataObject::debuglevel(1);
222         
223         $this->sessionState(0);
224         $res = $x->find();
225         $this->sessionState(1);
226         
227         if (false === $res) {
228             $this->jerr($x->_lastError->toString());
229             
230         }
231         
232         
233         
234         $ret = array();
235         
236         // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
237         
238         
239         if (!empty($_REQUEST['query']['add_blank'])) {
240             $ret[] = array( 'id' => 0, 'name' => '----');
241             $total+=1;
242         }
243          
244         $rooar = method_exists($x, 'toRooArray');
245         $_columnsf = $_columns  ? array_flip($_columns) : false;
246         while ($x->fetch()) {
247             //print_R($x);exit;
248             $add = $rooar  ? $x->toRooArray($_REQUEST) : $x->toArray();
249             if ($add === false) {
250                 continue;
251             }
252             $ret[] =  !$_columns ? $add : array_intersect_key($add, $_columnsf);
253         }
254         
255         if ($fake_limit) {
256             $ret = array_slice($ret,
257                    empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
258                     min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
259             );
260             
261         }
262         
263         
264         $extra = false;
265         if (method_exists($queryObj ,'postListExtra')) {
266             $extra = $queryObj->postListExtra($_REQUEST, $this);
267         }
268         
269         
270         // filter results, and add any data that is needed...
271         if (method_exists($x,'postListFilter')) {
272             $ret = $x->postListFilter($ret, $this->authUser, $_REQUEST);
273         }
274         
275         
276         
277         if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
278             
279             
280             $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
281                         empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
282                          );
283             
284             
285         
286         }
287         //die("DONE?");
288       
289         //if ($x->tableName() == 'Documents_Tracking') {
290         //    $ret = $this->replaceSubject(&$ret, 'doc_id_subject');
291        // }
292         
293         
294         
295         if (!empty($_REQUEST['_requestMeta']) &&  count($ret)) {
296             $meta = $this->meta($x, $ret);
297             if ($meta) {
298                 $extra['metaData'] = $meta;
299             }
300         }
301         // this make take some time...
302         $this->sessionState(0);
303        // echo "<PRE>"; print_r($ret);
304         $this->jdata($ret, max(count($ret), $total), $extra );
305
306     
307     }
308 }