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
32 var $row_fun; // Function for row preprocessing
52 var $extra_where = array();
54 var $ready = false; // this var is false after change in sql before first
55 // and before first query.
56 var $inactive_ctrl = false;
57 var $main_tbl; // table and key field name for inactive ctrl and edit/delete links
58 var $key; // key field name
60 // db_pager constructor
61 // accepts $sql query either as:
62 // a. string in form 'SELECT field_list FROM table_joins [WHERE conditions [GROUP group_list [ORDER order_list]]]'
63 // - if WHERE keyword is used in table_joins, WHERE conditions is obligatory
64 // b. associative array using select, where, group and order keys ex :
65 // array('select' => 'SUM(quantity)', 'from' => TB_PREF."stock_moves", 'group' => 'location')
67 // $name is base name for pager controls
68 function __construct($sql, $name, $table = null, $page_len=0)
71 if ($page_len == 0) $page_len = user_query_size();
73 $this->page_len = $page_len;
77 // Parse base sql select query or use an associative array.
79 function set_sql($sql)
83 if ($sql != $this->sql) {
88 foreach(explode(' ', 'select from where group order') as $section) {
89 $this->$section = @$sql[$section];
91 $this->select = "SELECT ".$this->select;
95 $parts = preg_split('/\sFROM\s/si', $sql, 2);
96 if (count($parts) == 2) {
97 $this->select = $parts[0];
100 if ($SysPrefs->go_debug)
101 display_error("Invalid sql input for db_pager");
104 $parts = preg_split('/\sWHERE(?!.*WHERE.*)\s/si', $sql, 2); // last occurence
105 if(count($parts) == 2) {
106 $this->from = $parts[0];
109 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
110 if(count($parts) == 2) {
112 $this->order = $parts[1];
114 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
115 if(count($parts) == 2) {
117 $this->group = $parts[1];
125 // Set additional constraint on record set
127 function set_where($where = null)
130 if (!is_array($where))
131 $where = array($where);
133 if (count($where) == count($this->extra_where) &&
134 !count(array_diff($this->extra_where, $where)))
137 $this->extra_where = $where;
138 $this->ready = false;
141 // Set query result page
143 function change_page($page=null)
145 $this->set_page($page);
150 // Change sort column direction
151 // in order asc->desc->none->asc
153 function sort_table($col)
157 foreach($this->columns as $id => $_col) {
158 if(!isset($_col['ord_priority'])) continue;
159 $max_priority = max($max_priority, $_col['ord_priority']);
163 $ord = $this->columns[$col]['ord'];
164 $this->columns[$col]['ord_priority'] = $max_priority+1; // set priority , higher than anything else
165 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
166 $this->columns[$col]['ord'] = $ord;
178 $Ajax->activate("_{$this->name}_span");
179 $this->data = array();
183 if ($this->rec_count == 0) return true;
185 $sql = $this->_sql_gen(false);
187 $result = db_query($sql, 'Error browsing database: '.$sql );
190 // setting field names for subsequent queries
192 // add result field names to column defs for
193 // col value retrieve and sort purposes
194 $cnt = min(db_num_fields($result), count($this->columns));
195 for ($c = $i = 0; $c < $cnt; $c++) {
196 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
197 // if (!@($this->columns[$c]['type']=='skip'))
198 $this->columns[$c]['name']= db_field_name($result, $i);
199 if (!@($this->columns[$c]['type']=='insert'))
203 while ($row = db_fetch_assoc($result)) {
204 $this->data[] = $row;
211 // Calculates page numbers for html controls.
213 function set_page($to)
217 $page = $this->curr_page+1; break;
219 $page = $this->curr_page-1; break;
221 $page = $this->last_page; break;
223 if (is_numeric($to)) {
231 $max = $this->max_page;
234 $this->curr_page = $page;
235 $this->next_page = ($page < $max) ? $page+1 : null;
236 $this->prev_page = ($page > 1) ? ($page-1) : null;
237 $this->last_page = ($page < $max) ? $max : null;
238 $this->first_page = ($page != 1) ? 1: null;
241 // Set column definitions
242 // $flds: array( fldname1, fldname2=>type,...)
243 function set_columns($flds)
245 $this->columns = array();
246 if (!is_array($flds)) {
247 $flds = array($flds);
249 foreach ($flds as $colnum=>$coldef) {
250 if (is_string($colnum)) { // 'colname'=>params
253 } else { // n=>params
254 if (is_array($coldef)) {
262 if (is_string($c)) // params is simple column type
263 $c = array('type'=>$c);
265 if (!isset($c['type']))
270 $this->inactive_ctrl = true;
273 $c['head'] = $h; break;
274 case 'skip': // skip the column (no header)
275 unset($c['head']); break;
277 $this->columns[] = $c;
281 // Generate db query from base sql
282 // $count==false - for current page data retrieval
283 // $count==true - for total records count
285 function _sql_gen($count=false)
287 $select = $this->select;
289 $where = $this->where;
290 $group = $this->group;
291 $order = $this->order;
293 if(count($this->extra_where)) {
294 $where .= ($where=='' ? '' : ' AND ')
295 .implode(' AND ', $this->extra_where);
297 if ($where) $where = " WHERE ($where)";
300 return "SELECT COUNT(*) FROM ($this->sql) tmp_count";
302 $sql = "$select FROM $from $where";
303 if ($group) $sql.= " GROUP BY $group";
306 // sort order column by priority instead of table order.
308 foreach ($this->columns as $col) {
309 if(isset($col['ord_priority'])) {
310 $columns[$col['ord_priority']] = $col;
315 foreach ($columns as $col) {
316 if (isset($col['ord'])) {
317 if ( $col['ord'] != '' && isset($col['name'])) {
318 $ord[] = $col['name'] .' '. $col['ord'];
324 $ord = array_map('db_escape_function', $ord);
325 $sql .= " ORDER BY " . implode(',', $ord);
328 $sql .= " ORDER BY $order"; // original base query order
331 $page_len = $this->page_len;
332 $offset = ($this->curr_page - 1) * $page_len;
334 $sql .= " LIMIT $offset, $page_len";
340 // Initialization after changing record set
346 if ($this->ready == false ) {
347 $sql = $this->_sql_gen(true);
348 $result = db_query($sql, 'Error reading record set');
349 if ($result == false)
351 $row = db_fetch_row($result);
352 $this->rec_count = is_array($row) ? $row[0] : 0;
354 $this->max_page = $this->page_len ?
355 ceil($this->rec_count/$this->page_len) : 0;
357 if ($SysPrefs->go_debug) { // FIX - need column name parsing, but for now:
358 // check if field names are set explicite in col def
359 // for all initially ordered columns
360 foreach ($this->columns as $col) {
361 if (isset($col['ord']) && $col['ord'] != ''
362 && !isset($col['name'])) {
363 display_warning("Result field names must be set
364 for all initially ordered db_pager columns.");
374 // Set current page in response to user control.
376 function select_records()
380 $page = find_submit($this->name.'_page_', false);
381 $sort = find_submit($this->name.'_sort_', true);
383 $this->change_page($page);
384 if ($page == 'next' && !$this->next_page ||
385 $page == 'last' && !$this->last_page)
386 set_focus($this->name.'_page_prev');
387 if ($page == 'prev' && !$this->prev_page ||
388 $page == 'first' && !$this->first_page)
389 set_focus($this->name.'_page_next');
390 } elseif ($sort != -1) {
391 $this->sort_table($sort);
396 // Set check function to mark some rows.
398 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
400 $this->marker = $func;
401 $this->marker_txt = $notice;
402 $this->marker_class = $markercl;
403 $this->notice_class = $msgclass;
406 // Set handler to display additional row between titles and pager body.
407 // Return array of column contents.
409 function set_header($func, $headercl='inquirybg')
411 $this->header_fun = $func;
412 $this->header_class = $headercl;
415 // Set handler to display additional row between pager body and navibar.
416 // Return array of column contents.
418 function set_footer($func, $footercl='inquirybg')
420 $this->footer_fun = $func;
421 $this->footer_class = $footercl;
424 // Setter for table editors with inactive cell control.
426 function set_inactive_ctrl($table, $key) {
427 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
430 // Helper for display inactive control cells
432 function inactive_control_cell(&$row)
434 if ($this->inactive_ctrl) {
439 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
441 $table = $this->main_tbl;
442 $name = "Inactive". $id;
443 $value = $row['inactive'] ? 1:0;
445 if (check_value('show_inactive')) {
446 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
447 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
448 update_record_status($id, !$value, $table, $key);
451 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
452 . hidden("LInact[$id]", $value, false) . '</td>';
459 //-----------------------------------------------------------------------------
460 // Creates new db_pager $_SESSION object on first page call.
461 // Retrieves from $_SESSION var on subsequent $_POST calls
463 // $name - base name for pager controls and $_SESSION object name
464 // $sql - base sql for data inquiry. Order of fields implies
465 // pager columns order.
466 // $coldef - array of column definitions. Example definitions
467 // Column with title 'User name' and default text format:
469 // Skipped field from sql query. Data for the field is not displayed:
471 // Column without title, data retrieved form row data with function func():
472 // array('fun'=>'func')
473 // Inserted column with title 'Some', formated with function rowfun().
475 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
476 // Column with name 'Another', formatted as date,
477 // sortable with ascending start order (available orders: asc,desc, '').
478 // 'Another' => array('type'=>'date', 'ord'=>'asc')
480 // All available column format types you will find in db_pager_view.inc file.
481 // If query result has more fields than count($coldef), rest of data is ignored
482 // during display, but can be used in format handlers for 'spec' and 'insert'
485 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
487 if (isset($_SESSION[$name]) &&
488 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
489 unset($_SESSION[$name]); // kill pager if sql has changed
491 if (!isset($_SESSION[$name])) {
492 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
493 $_SESSION[$name]->main_tbl = $table;
494 $_SESSION[$name]->key = $key;
495 $_SESSION[$name]->set_sql($sql);
496 $_SESSION[$name]->set_columns($coldef);
499 return $_SESSION[$name];
503 // Force pager initialization.
505 function refresh_pager($name)
507 if (isset($_SESSION[$name]))
508 $_SESSION[$name]->ready = false;