3 trait Pman_Core_RooGetTrait {
5 * GET method Roo/TABLENAME.php
7 * Generally for SELECT or 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()
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.
20 * - all tables are always autojoined.
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.
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..
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 ] }
42 * limit=25 limit number
46 * csvCols[0] csvCols[1].... = .... column titles for CSV output
47 * csvTitles[0], csvTitles[1] .... = columns to use for CSV output
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...)
55 * _post =1 = simulate a post with debuggin on.
56 * _debug_post << This is prefered, as _post may overlap with accouting posts..
58 * _debug = turn on DB_dataobject deubbing, must be admin at present..
61 * CALLS methods on dataobjects if they exist
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
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.
87 * - standard DataObject feature - causes all results to show all
91 * _extra_cols -- if set, then filtering by column etc. will use them.
99 HTML_FlexyFramework::get()->generateDataobjectsCache($this->isDev);
101 if ( $this->checkDebugPost()) {
103 return $this->post($tab);
108 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
110 $tab = array_shift(explode('/', $tab));
112 $x = $this->dataObject($tab);
114 $_columns = !empty($_REQUEST['_columns']) ? explode(',', $_REQUEST['_columns']) : false;
116 if (isset( $_REQUEST['lookup'] ) && is_array($_REQUEST['lookup'] )) { // single fetch based on key/value pairs
117 $this->selectSingle($x, $_REQUEST['lookup'],$_REQUEST);
122 // single fetch (use '0' to fetch an empty object..)
123 if (isset($_REQUEST['_id']) && is_numeric($_REQUEST['_id'])) {
125 $this->selectSingle($x, $_REQUEST['_id'],$_REQUEST);
132 if (isset($_REQUEST['_delete'])) {
133 $this->jerr("DELETE by GET has been removed - update the code to use POST");
139 if (isset($_REQUEST['_toggleActive'])) {
140 // do we really delete stuff!?!?!?
141 if (!$this->hasPerm("Core.Staff", 'E')) {
142 $this->jerr("PERMISSION DENIED (ta)");
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");
149 $x->query('UPDATE Person SET active = !active WHERE id IN (' .implode(',', $bits).')');
150 $this->addEvent("USERTOGGLE", false, implode(',', $bits));
151 $this->jok("Updated");
154 //DB_DataObject::debugLevel(1);
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'])
165 $this->setFilters($x,$_REQUEST);
167 if (!$this->checkPerm($x,'S', $_REQUEST)) {
168 $this->jerr("PERMISSION DENIED (g)");
171 $total = $x->count($this->countWhat);
174 //var_dump($total);exit;
175 $this->applySort($x);
179 if (!empty($_REQUEST['_distinct']) && $total < 400) {
186 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
187 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
190 $queryObj = clone($x);
191 //DB_DataObject::debuglevel(1);
193 $this->sessionState(0);
195 $this->sessionState(1);
197 if (false === $res) {
198 $this->jerr($x->_lastError->toString());
203 // ---------------- THESE ARE DEPRICATED.. they should be moved to the model...
206 if (!empty($_REQUEST['query']['add_blank'])) {
207 $ret[] = array( 'id' => 0, 'name' => '----');
211 $rooar = method_exists($x, 'toRooArray');
212 $_columnsf = $_columns ? array_flip($_columns) : false;
213 while ($x->fetch()) {
215 $add = $rooar ? $x->toRooArray($_REQUEST) : $x->toArray();
216 if ($add === false) {
219 $ret[] = !$_columns ? $add : array_intersect_key($add, $_columnsf);
223 $ret = array_slice($ret,
224 empty($_REQUEST['start']) ? 0 : (int)$_REQUEST['start'],
225 min(empty($_REQUEST['limit']) ? 25 : (int)$_REQUEST['limit'], 10000)
232 if (method_exists($queryObj ,'postListExtra')) {
233 $extra = $queryObj->postListExtra($_REQUEST, $this);
237 // filter results, and add any data that is needed...
238 if (method_exists($x,'postListFilter')) {
239 $ret = $x->postListFilter($ret, $this->getAuthUser(), $_REQUEST);
244 if (!empty($_REQUEST['csvCols']) && !empty($_REQUEST['csvTitles']) ) {
247 $this->toCsv($ret, $_REQUEST['csvCols'], $_REQUEST['csvTitles'],
248 empty($_REQUEST['csvFilename']) ? '' : $_REQUEST['csvFilename']
255 if (!empty($_REQUEST['_requestMeta']) && count($ret)) {
256 $meta = $this->meta($x, $ret);
258 $extra['metaData'] = $meta;
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 );
269 function checkDebugPost()
271 return (!empty($_GET['_post']) || !empty($_GET['_debug_post'])) &&
273 method_exists($this->authUser,'groups') &&
274 in_array('Administrators', $this->authUser->groups('name'));
278 function applySort($x, $sort = '', $dir ='')
280 $sort = empty($_REQUEST['sort']) ? $sort : $_REQUEST['sort'];
281 $dir = empty($_REQUEST['dir']) ? $dir : $_REQUEST['dir'];
282 $dir = $dir == 'ASC' ? 'ASC' : 'DESC';
284 $ms = empty($_REQUEST['_multisort']) ? false : $_REQUEST['_multisort'];
285 //var_Dump($ms);exit;
287 if (method_exists($x, 'applySort')) {
288 $sorted = $x->applySort(
289 $this->getAuthUser(),
292 array_keys($this->cols),
293 $ms ? json_decode($ms) : false
297 return $this->multiSort($x);
300 if ($sorted === false) {
303 $excols = array_keys($this->cols);
305 if (isset($x->_extra_cols)) {
306 $excols = array_merge($excols, $x->_extra_cols);
308 $sort_ar = explode(',', $sort);
311 foreach($sort_ar as $sort) {
313 if (strlen($sort) && isset($cols[$sort]) ) {
314 $sort_str[] = $x->tableName() .'.'.$sort . ' ' . $dir ;
316 } else if (in_array($sort, $excols)) {
317 $sort_str[] = $sort . ' ' . $dir ;
322 $x->orderBy(implode(', ', $sort_str ));
327 function toCsv($data, $cols, $titles, $filename, $addDate = true)
329 $this->sessionState(0); // turn off sessions - no locking..
331 require_once 'Pman/Core/SimpleExcel.php';
333 $fn = (empty($filename) ? 'list-export-' : urlencode($filename)) . (($addDate) ? date('Y-m-d') : '') ;
337 'workbook' => substr($fn, 0, 31),
344 if (is_object($data)) {
345 $rooar = method_exists($data, 'toRooArray');
346 while($data->fetch()) {
347 $x = $rooar ? $data->toRooArray($q) : $data->toArray();
350 if ($cols == '*') { /// did we get cols sent to us?
351 $cols = array_keys($x);
354 $titles= array_keys($x);
356 if ($titles !== false) {
358 foreach($cols as $i=>$col) {
359 $se_config['cols'][] = array(
360 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
364 $se = new Pman_Core_SimpleExcel(array(), $se_config);
370 //fputcsv($fh, $titles);
375 $se->addLine($se_config['workbook'], $x);
381 $this->jerr('no data found', false, 'text/plain');
383 $se->send($fn .'.xls');
389 foreach($data as $x) {
390 //echo "<PRE>"; print_r(array($_REQUEST['csvCols'], $x->toArray())); exit;
393 $titles= array_keys($x);
396 $cols= array_keys($x);
398 if ($titles !== false) {
399 foreach($cols as $i=>$col) {
400 $se_config['cols'][] = array(
401 'header'=> isset($titles[$i]) ? $titles[$i] : $col,
404 // 'renderer' => array($this, 'getThumb'),
405 // 'color' => 'yellow', // set color for the cell which is a header element
406 // 'fillBlank' => 'gray', // set
408 $se = new Pman_Core_SimpleExcel(array(),$se_config);
414 //fputcsv($fh, $titles);
420 $se->addLine($se_config['workbook'], $x);
423 $this->jerr('no data found');
425 $se->send($fn .'.xls');
430 function meta($x, $data)
433 $cols = array_keys($data[0]);
435 $options = &PEAR::getStaticProperty('DB_DataObject','options');
436 $reader = $options["ini_{$x->_database}"] .'.reader';
437 if (!file_exists( $reader )) {
441 $rdata = unserialize(file_get_contents($reader));
444 $key = empty($keys) ? 'id' : $keys[0];
448 foreach($cols as $c ) {
449 if (!isset($this->cols[$c]) || !isset($rdata[$this->cols[$c]]) || !is_array($rdata[$this->cols[$c]])) {
453 $add = $rdata[$this->cols[$c]];
458 'totalProperty' => 'total',
459 'successProperty' => 'success',
461 'id' => $key, // was 'id'...