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
50 var $ready = false; // this var is false after change in sql before first
51 // and before first query.
52 var $inactive_ctrl = false;
53 var $main_tbl; // table and key field name for inactive ctrl and edit/delete links
54 var $key; // key field name
56 // db_pager constructor
57 // accepts $sql like 'SELECT ...[FROM ...][WHERE ...][GROUP ...][ORDER ...]'
58 // $name is base name for pager controls
59 function db_pager($sql, $name, $table = null, $page_len=0)
62 if ($page_len == 0) $page_len = user_query_size();
64 $this->page_len = $page_len;
68 // Parse base sql select query.
70 function set_sql($sql)
72 if ($sql != $this->sql) {
78 // Set additional constraint on record set
80 function set_where($where = null)
83 if (!is_array($where))
84 $where = array($where);
86 if (count($where) == count($this->extra_where) &&
87 !count(array_diff($this->extra_where, $where)))
90 $this->extra_where = $where;
94 // Set query result page
96 function change_page($page=null)
98 $this->set_page($page);
103 // Change sort column direction
104 // in order asc->desc->none->asc
106 function sort_table($col)
108 $ord = $this->columns[$col]['ord'];
109 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
110 $this->columns[$col]['ord'] = $ord;
111 $n = array_search($col, $this->order);
113 unset($this->order[$n]);
115 array_unshift($this->order, $col); // store column number as first
128 $Ajax->activate("_{$this->name}_span");
129 $this->data = array();
133 if ($this->rec_count == 0) return true;
135 $sql = $this->_sql_gen(false);
137 $result = db_query($sql, 'Error browsing database: '.$sql );
140 // setting field names for subsequent queries
142 // add result field names to column defs for
143 // col value retrieve and sort purposes
144 $cnt = min(db_num_fields($result), count($this->columns));
145 for ($c = $i = 0; $c < $cnt; $c++) {
146 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
147 // if (!@($this->columns[$c]['type']=='skip'))
148 $this->columns[$c]['name']= db_field_name($result, $i);
149 if (!@($this->columns[$c]['type']=='insert'))
153 while ($row = db_fetch_assoc($result)) {
154 $this->data[] = $row;
161 // Calculates page numbers for html controls.
163 function set_page($to)
167 $page = $this->curr_page+1; break;
169 $page = $this->curr_page-1; break;
171 $page = $this->last_page; break;
173 if (is_numeric($to)) {
181 $max = $this->max_page;
184 $this->curr_page = $page;
185 $this->next_page = ($page < $max) ? $page+1 : null;
186 $this->prev_page = ($page > 1) ? ($page-1) : null;
187 $this->last_page = ($page < $max) ? $max : null;
188 $this->first_page = ($page != 1) ? 1: null;
191 // Set column definitions
192 // $flds: array( fldname1, fldname2=>type,...)
193 function set_columns($flds)
195 $this->columns = $this->order = array();
196 if (!is_array($flds)) {
197 $flds = array($flds);
199 foreach ($flds as $colnum=>$coldef) {
200 if (is_string($colnum)) { // 'colname'=>params
203 } else { // n=>params
204 if (is_array($coldef)) {
212 if (is_string($c)) // params is simple column type
213 $c = array('type'=>$c);
215 if (!isset($c['type']))
220 $this->inactive_ctrl = true;
223 $c['head'] = $h; break;
224 case 'skip': // skip the column (no header)
225 unset($c['head']); break;
228 array_push($this->order, count($this->columns));
229 $this->columns[] = $c;
233 // Generate db query from base sql
234 // $count==false - for current page data retrieval
235 // $count==true - for total records count
237 function _sql_gen($count=false)
240 if (count($this->extra_where)) {
241 $where = ' WHERE ('.implode(' AND ', $this->extra_where).')';
246 return "SELECT COUNT(*) FROM ($this->sql) $where AS _dummyname";
251 $sql = "SELECT * FROM ($this->sql) $where AS _dummyname";
253 foreach ($this->order as $n) {
254 $col = $this->columns[$n];
255 if (isset($col['ord'])) {
256 if ( $col['ord'] != '' && isset($col['name'])) {
257 $ord[] = $col['name'] .' '. $col['ord'];
262 $sql .= " ORDER BY " . implode($ord, ',');
265 $page_len = $this->page_len;
266 $offset = ($this->curr_page - 1) * $page_len;
269 $sql .= " LIMIT $offset, $page_len";
275 // Initialization after changing record set
281 if ($this->ready == false ) {
282 $sql = $this->_sql_gen(true);
283 $result = db_query($sql, 'Error reading record set');
284 if ($result == false)
286 $row = db_fetch_row($result);
287 $this->rec_count = $row[0];
288 $this->max_page = $this->page_len ?
289 ceil($this->rec_count/$this->page_len) : 0;
291 if ($go_debug) { // FIX - need column name parsing, but for now:
292 // check if field names are set explicite in col def
293 // for all initially ordered columns
294 foreach ($this->columns as $col) {
295 if (isset($col['ord']) && $col['ord'] != ''
296 && !isset($col['name'])) {
297 display_warning("Result field names must be set
298 for all initially ordered db_pager columns.");
308 // Set current page in response to user control.
310 function select_records()
314 $page = find_submit($this->name.'_page_', false);
315 $sort = find_submit($this->name.'_sort_', true);
317 $this->change_page($page);
318 if ($page == 'next' && !$this->next_page ||
319 $page == 'last' && !$this->last_page)
320 set_focus($this->name.'_page_prev');
321 if ($page == 'prev' && !$this->prev_page ||
322 $page == 'first' && !$this->first_page)
323 set_focus($this->name.'_page_next');
324 } elseif ($sort != -1) {
325 $this->sort_table($sort);
330 // Set check function to mark some rows.
332 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
334 $this->marker = $func;
335 $this->marker_txt = $notice;
336 $this->marker_class = $markercl;
337 $this->notice_class = $msgclass;
340 // Set handler to display additional row between titles and pager body.
341 // Return array of column contents.
343 function set_header($func, $headercl='inquirybg')
345 $this->header_fun = $func;
346 $this->header_class = $headercl;
349 // Set handler to display additional row between pager body and navibar.
350 // Return array of column contents.
352 function set_footer($func, $footercl='inquirybg')
354 $this->footer_fun = $func;
355 $this->footer_class = $footercl;
358 // Setter for table editors with inactive cell control.
360 function set_inactive_ctrl($table, $key) {
361 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
364 // Helper for display inactive control cells
366 function inactive_control_cell(&$row)
368 if ($this->inactive_ctrl) {
369 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
370 // $row['inactive'], $this->inactive_ctrl['table'],
371 // $this->inactive_ctrl['key']);
376 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
378 $table = $this->main_tbl;
379 $name = "Inactive". $id;
380 $value = $row['inactive'] ? 1:0;
382 if (check_value('show_inactive')) {
383 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
384 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
385 update_record_status($id, !$value, $table, $key);
388 echo '<td align="center">'. checkbox(null, $name, $value, true, '', "align='center'")
389 . hidden("LInact[$id]", $value, false) . '</td>';
396 //-----------------------------------------------------------------------------
397 // Creates new db_pager $_SESSION object on first page call.
398 // Retrieves from $_SESSION var on subsequent $_POST calls
400 // $name - base name for pager controls and $_SESSION object name
401 // $sql - base sql for data inquiry. Order of fields implies
402 // pager columns order.
403 // $coldef - array of column definitions. Example definitions
404 // Column with title 'User name' and default text format:
406 // Skipped field from sql query. Data for the field is not displayed:
408 // Column without title, data retrieved form row data with function func():
409 // array('fun'=>'func')
410 // Inserted column with title 'Some', formated with function rowfun().
412 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
413 // Column with name 'Another', formatted as date,
414 // sortable with ascending start order (available orders: asc,desc, '').
415 // 'Another' => array('type'=>'date', 'ord'=>'asc')
417 // All available column format types you will find in db_pager_view.inc file.
418 // If query result has more fields than count($coldef), rest of data is ignored
419 // during display, but can be used in format handlers for 'spec' and 'insert'
422 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
424 if (isset($_SESSION[$name]) &&
425 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
426 unset($_SESSION[$name]); // kill pager if sql has changed
428 if (!isset($_SESSION[$name])) {
429 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
430 $_SESSION[$name]->main_tbl = $table;
431 $_SESSION[$name]->key = $key;
432 $_SESSION[$name]->set_sql($sql);
433 $_SESSION[$name]->set_columns($coldef);
436 return $_SESSION[$name];
440 // Force pager initialization.
442 function refresh_pager($name)
444 if (isset($_SESSION[$name]))
445 $_SESSION[$name]->ready = false;