2 /**********************************************************************
3 Copyright (C) FrontAccounting, LLC.
4 Released under the terms of the GNU General Public License, GPL,
5 as published by the Free Software Foundation, either version 3
6 of the License, or (at your option) any later version.
7 This program is distributed in the hope that it will be useful,
8 but WITHOUT ANY WARRANTY; without even the implied warranty of
9 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
11 ***********************************************************************/
13 // Controler part of database table pager with column sort.
14 // To display actual html object call display_db_pager($name) inside
17 // View definition you will find in the following file:
18 include_once($path_to_root."/includes/ui/db_pager_view.inc");
23 var $columns; // column definitions (head, type, order)
25 var $marker; // marker check function
29 var $width; // table width (default '95%')
30 var $header_fun; // additional row between title and body
53 var $ready = false; // this var is false after change in sql before first
54 // and before first query.
55 var $inactive_ctrl = false;
56 var $main_tbl; // table and key field name for inactive ctrl and edit/delete links
57 var $key; // key field name
59 // db_pager constructor
60 // accepts $sql query either as:
61 // a. string in form 'SELECT field_list FROM table_joins [WHERE conditions [GROUP group_list [ORDER order_list]]]'
62 // - if WHERE keyword is used in table_joins, WHERE conditions is obligatory
63 // b. associative array using select, where, group and order keys ex :
64 // array('select' => 'SUM(quantity)', 'from' => TB_PREF."stock_moves", 'group' => 'location')
66 // $name is base name for pager controls
67 function db_pager($sql, $name, $table = null, $page_len=0)
70 if ($page_len == 0) $page_len = user_query_size();
72 $this->page_len = $page_len;
76 // Parse base sql select query or use an associative array.
78 function set_sql($sql)
80 if ($sql != $this->sql) {
85 foreach(explode(' ', 'select from where group order') as $section) {
86 $this->$section = @$sql[$section];
88 $this->select = "SELECT ".$this->select;
92 $parts = preg_split('/\sFROM\s/si', $sql, 2);
93 if (count($parts) == 2) {
94 $this->select = $parts[0];
98 display_error("Invalid sql input for db_pager");
101 $parts = preg_split('/\sWHERE(?!.*WHERE.*)\s/si', $sql, 2); // last occurence
102 if(count($parts) == 2) {
103 $this->from = $parts[0];
106 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
107 if(count($parts) == 2) {
109 $this->order = $parts[1];
111 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
112 if(count($parts) == 2) {
114 $this->group = $parts[1];
120 //_vd($this->select);
127 // Set additional constraint on record set
129 function set_where($where = null)
132 if (!is_array($where))
133 $where = array($where);
135 if (count($where) == count($this->extra_where) &&
136 !count(array_diff($this->extra_where, $where)))
139 $this->extra_where = $where;
140 $this->ready = false;
143 // Set query result page
145 function change_page($page=null)
147 $this->set_page($page);
152 // Change sort column direction
153 // in order asc->desc->none->asc
155 function sort_table($col)
159 foreach($this->columns as $id => $_col) {
160 if(!isset($_col['ord_priority'])) continue;
161 $max_priority = max($max_priority, $_col['ord_priority']);
165 $ord = $this->columns[$col]['ord'];
166 $this->columns[$col]['ord_priority'] = $max_priority+1; // set priority , higher than anything else
167 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
168 $this->columns[$col]['ord'] = $ord;
180 $Ajax->activate("_{$this->name}_span");
181 $this->data = array();
185 if ($this->rec_count == 0) return true;
187 $sql = $this->_sql_gen(false);
189 $result = db_query($sql, 'Error browsing database: '.$sql );
192 // setting field names for subsequent queries
194 // add result field names to column defs for
195 // col value retrieve and sort purposes
196 $cnt = min(db_num_fields($result), count($this->columns));
197 for ($c = $i = 0; $c < $cnt; $c++) {
198 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
199 // if (!@($this->columns[$c]['type']=='skip'))
200 $this->columns[$c]['name']= db_field_name($result, $i);
201 if (!@($this->columns[$c]['type']=='insert'))
205 while ($row = db_fetch_assoc($result)) {
206 $this->data[] = $row;
213 // Calculates page numbers for html controls.
215 function set_page($to)
219 $page = $this->curr_page+1; break;
221 $page = $this->curr_page-1; break;
223 $page = $this->last_page; break;
225 if (is_numeric($to)) {
233 $max = $this->max_page;
236 $this->curr_page = $page;
237 $this->next_page = ($page < $max) ? $page+1 : null;
238 $this->prev_page = ($page > 1) ? ($page-1) : null;
239 $this->last_page = ($page < $max) ? $max : null;
240 $this->first_page = ($page != 1) ? 1: null;
243 // Set column definitions
244 // $flds: array( fldname1, fldname2=>type,...)
245 function set_columns($flds)
247 $this->columns = array();
248 if (!is_array($flds)) {
249 $flds = array($flds);
251 foreach ($flds as $colnum=>$coldef) {
252 if (is_string($colnum)) { // 'colname'=>params
255 } else { // n=>params
256 if (is_array($coldef)) {
264 if (is_string($c)) // params is simple column type
265 $c = array('type'=>$c);
267 if (!isset($c['type']))
272 $this->inactive_ctrl = true;
275 $c['head'] = $h; break;
276 case 'skip': // skip the column (no header)
277 unset($c['head']); break;
279 $this->columns[] = $c;
283 // Generate db query from base sql
284 // $count==false - for current page data retrieval
285 // $count==true - for total records count
287 function _sql_gen($count=false)
289 $select = $this->select;
291 $where = $this->where;
292 $group = $this->group;
293 $order = $this->order;
295 if(count($this->extra_where)) {
296 $where .= ($where=='' ? '' : ' AND ')
297 .implode(' AND ', $this->extra_where);
299 if ($where) $where = " WHERE ($where)";
302 $group = $group == '' ? "*" : "DISTINCT $group";
304 return "SELECT COUNT($group) FROM $from $where";
307 $sql = "$select FROM $from $where";
308 if ($group) $sql.= " GROUP BY $group";
311 // sort order column by priority instead of table order.
313 foreach ($this->columns as $col) {
314 if(isset($col['ord_priority'])) {
315 $columns[$col['ord_priority']] = $col;
320 foreach ($columns as $col) {
321 if (isset($col['ord'])) {
322 if ( $col['ord'] != '' && isset($col['name'])) {
323 $ord[] = $col['name'] .' '. $col['ord'];
329 $ord = array_map('db_escape_function', $ord);
330 $sql .= " ORDER BY " . implode(',', $ord);
333 $sql .= " ORDER BY $order"; // original base query order
336 $page_len = $this->page_len;
337 $offset = ($this->curr_page - 1) * $page_len;
339 $sql .= " LIMIT $offset, $page_len";
345 // Initialization after changing record set
351 if ($this->ready == false ) {
352 $sql = $this->_sql_gen(true);
353 $result = db_query($sql, 'Error reading record set');
354 if ($result == false)
356 $row = db_fetch_row($result);
357 $this->rec_count = $row[0];
358 $this->max_page = $this->page_len ?
359 ceil($this->rec_count/$this->page_len) : 0;
361 if ($go_debug) { // FIX - need column name parsing, but for now:
362 // check if field names are set explicite in col def
363 // for all initially ordered columns
364 foreach ($this->columns as $col) {
365 if (isset($col['ord']) && $col['ord'] != ''
366 && !isset($col['name'])) {
367 display_warning("Result field names must be set
368 for all initially ordered db_pager columns.");
378 // Set current page in response to user control.
380 function select_records()
384 $page = find_submit($this->name.'_page_', false);
385 $sort = find_submit($this->name.'_sort_', true);
387 $this->change_page($page);
388 if ($page == 'next' && !$this->next_page ||
389 $page == 'last' && !$this->last_page)
390 set_focus($this->name.'_page_prev');
391 if ($page == 'prev' && !$this->prev_page ||
392 $page == 'first' && !$this->first_page)
393 set_focus($this->name.'_page_next');
394 } elseif ($sort != -1) {
395 $this->sort_table($sort);
400 // Set check function to mark some rows.
402 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
404 $this->marker = $func;
405 $this->marker_txt = $notice;
406 $this->marker_class = $markercl;
407 $this->notice_class = $msgclass;
410 // Set handler to display additional row between titles and pager body.
411 // Return array of column contents.
413 function set_header($func, $headercl='inquirybg')
415 $this->header_fun = $func;
416 $this->header_class = $headercl;
419 // Set handler to display additional row between pager body and navibar.
420 // Return array of column contents.
422 function set_footer($func, $footercl='inquirybg')
424 $this->footer_fun = $func;
425 $this->footer_class = $footercl;
428 // Setter for table editors with inactive cell control.
430 function set_inactive_ctrl($table, $key) {
431 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
434 // Helper for display inactive control cells
436 function inactive_control_cell(&$row)
438 if ($this->inactive_ctrl) {
439 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
440 // $row['inactive'], $this->inactive_ctrl['table'],
441 // $this->inactive_ctrl['key']);
446 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
448 $table = $this->main_tbl;
449 $name = "Inactive". $id;
450 $value = $row['inactive'] ? 1:0;
452 if (check_value('show_inactive')) {
453 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
454 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
455 update_record_status($id, !$value, $table, $key);
458 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
459 . hidden("LInact[$id]", $value, false) . '</td>';
466 //-----------------------------------------------------------------------------
467 // Creates new db_pager $_SESSION object on first page call.
468 // Retrieves from $_SESSION var on subsequent $_POST calls
470 // $name - base name for pager controls and $_SESSION object name
471 // $sql - base sql for data inquiry. Order of fields implies
472 // pager columns order.
473 // $coldef - array of column definitions. Example definitions
474 // Column with title 'User name' and default text format:
476 // Skipped field from sql query. Data for the field is not displayed:
478 // Column without title, data retrieved form row data with function func():
479 // array('fun'=>'func')
480 // Inserted column with title 'Some', formated with function rowfun().
482 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
483 // Column with name 'Another', formatted as date,
484 // sortable with ascending start order (available orders: asc,desc, '').
485 // 'Another' => array('type'=>'date', 'ord'=>'asc')
487 // All available column format types you will find in db_pager_view.inc file.
488 // If query result has more fields than count($coldef), rest of data is ignored
489 // during display, but can be used in format handlers for 'spec' and 'insert'
492 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
494 if (isset($_SESSION[$name]) &&
495 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
496 unset($_SESSION[$name]); // kill pager if sql has changed
498 if (!isset($_SESSION[$name])) {
499 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
500 $_SESSION[$name]->main_tbl = $table;
501 $_SESSION[$name]->key = $key;
502 $_SESSION[$name]->set_sql($sql);
503 $_SESSION[$name]->set_columns($coldef);
506 return $_SESSION[$name];
510 // Force pager initialization.
512 function refresh_pager($name)
514 if (isset($_SESSION[$name]))
515 $_SESSION[$name]->ready = false;