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 like 'SELECT ...[FROM ...][WHERE ...][GROUP ...][ORDER ...]'
61 // $name is base name for pager controls
62 function db_pager($sql, $name, $table = null, $page_len=0)
65 if ($page_len == 0) $page_len = user_query_size();
67 $this->page_len = $page_len;
71 // Parse base sql select query.
73 function set_sql($sql)
75 if ($sql != $this->sql) {
78 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
79 if(count($parts) == 2) {
81 $this->order = $parts[1];
83 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
84 if(count($parts) == 2) {
86 $this->group = $parts[1];
88 $parts = preg_split('/\sWHERE\s/si', $sql, 2);
89 if(count($parts) == 2) {
91 $this->where = $parts[1];
93 $parts = preg_split('/\sFROM\s/si', $sql, 2);
94 if(count($parts) == 2) {
96 $this->from = $parts[1];
102 // Set additional constraint on record set
104 function set_where($where = null)
107 if (!is_array($where))
108 $where = array($where);
110 if (count($where) == count($this->extra_where) &&
111 !count(array_diff($this->extra_where, $where)))
114 $this->extra_where = $where;
115 $this->ready = false;
118 // Set query result page
120 function change_page($page=null)
122 $this->set_page($page);
127 // Change sort column direction
128 // in order asc->desc->none->asc
130 function sort_table($col)
132 $ord = $this->columns[$col]['ord'];
133 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
134 $this->columns[$col]['ord'] = $ord;
146 $Ajax->activate("_{$this->name}_span");
147 $this->data = array();
151 if ($this->rec_count == 0) return true;
153 $sql = $this->_sql_gen(false);
155 $result = db_query($sql, 'Error browsing database: '.$sql );
158 // setting field names for subsequent queries
160 // add result field names to column defs for
161 // col value retrieve and sort purposes
162 $cnt = min(mysql_num_fields($result), count($this->columns));
163 for ($c = $i = 0; $c < $cnt; $c++) {
164 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
165 // if (!@($this->columns[$c]['type']=='skip'))
166 $this->columns[$c]['name']= mysql_field_name($result, $i);
167 if (!@($this->columns[$c]['type']=='insert'))
171 while ($row = db_fetch_assoc($result)) {
172 $this->data[] = $row;
179 // Calculates page numbers for html controls.
181 function set_page($to)
185 $page = $this->curr_page+1; break;
187 $page = $this->curr_page-1; break;
189 $page = $this->last_page; break;
191 if (is_numeric($to)) {
199 $max = $this->max_page;
202 $this->curr_page = $page;
203 $this->next_page = ($page < $max) ? $page+1 : null;
204 $this->prev_page = ($page > 1) ? ($page-1) : null;
205 $this->last_page = ($page < $max) ? $max : null;
206 $this->first_page = ($page != 1) ? 1: null;
209 // Set column definitions
210 // $flds: array( fldname1, fldname2=>type,...)
211 function set_columns($flds)
213 $this->columns = array();
214 if (!is_array($flds)) {
215 $flds = array($flds);
217 foreach ($flds as $colnum=>$coldef) {
218 if (is_string($colnum)) { // 'colname'=>params
221 } else { // n=>params
222 if (is_array($coldef)) {
230 if (is_string($c)) // params is simple column type
231 $c = array('type'=>$c);
233 if (!isset($c['type']))
238 $this->inactive_ctrl = true;
241 $c['head'] = $h; break;
242 case 'skip': // skip the column (no header)
243 unset($c['head']); break;
245 $this->columns[] = $c;
249 // Generate db query from base sql
250 // $count==false - for current page data retrieval
251 // $count==true - for total records count
253 function _sql_gen($count=false)
255 $select = $this->select;
257 $where = $this->where;
258 $group = $this->group;
259 $order = $this->order;
261 if(count($this->extra_where)) {
262 $where .= ($where=='' ? '' : ' AND ')
263 .implode( $this->extra_where, ' AND ');
265 if ($where) $where = " WHERE ($where)";
268 $group = $group == '' ? "*" : "DISTINCT $group";
270 return "SELECT COUNT($group) FROM $from $where";
273 $sql = "$select FROM $from $where";
274 if ($group) $sql.= " GROUP BY $group";
277 foreach ($this->columns as $col) {
278 if (isset($col['ord'])) {
279 if ( $col['ord'] != '' && isset($col['name'])) {
280 $ord[] = $col['name'] .' '. $col['ord'];
286 $sql .= " ORDER BY " . implode($ord, ',');
289 $sql .= " ORDER BY $order"; // original base query order
292 $page_len = $this->page_len;
293 $offset = ($this->curr_page - 1) * $page_len;
295 $sql .= " LIMIT $offset, $page_len";
301 // Initialization after changing record set
307 if ($this->ready == false ) {
308 $sql = $this->_sql_gen(true);
309 $result = db_query($sql, 'Error reading record set');
310 if ($result == false)
312 $row = db_fetch_row($result);
313 $this->rec_count = $row[0];
314 $this->max_page = $this->page_len ?
315 ceil($this->rec_count/$this->page_len) : 0;
317 if ($go_debug) { // FIX - need column name parsing, but for now:
318 // check if field names are set explicite in col def
319 // for all initially ordered columns
320 foreach ($this->columns as $col) {
321 if (isset($col['ord']) && $col['ord'] != ''
322 && !isset($col['name'])) {
323 display_warning("Result field names must be set
324 for all intially ordered db_pager columns.");
334 // Set current page in response to user control.
336 function select_records()
340 $page = find_submit($this->name.'_page_', false);
341 $sort = find_submit($this->name.'_sort_', true);
343 $this->change_page($page);
344 if ($page == 'next' && !$this->next_page ||
345 $page == 'last' && !$this->last_page)
346 set_focus($this->name.'_page_prev');
347 if ($page == 'prev' && !$this->prev_page ||
348 $page == 'first' && !$this->first_page)
349 set_focus($this->name.'_page_next');
350 } elseif ($sort != -1) {
351 $this->sort_table($sort);
356 // Set check function to mark some rows.
358 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
360 $this->marker = $func;
361 $this->marker_txt = $notice;
362 $this->marker_class = $markercl;
363 $this->notice_class = $msgclass;
366 // Set handler to display additional row between titles and pager body.
367 // Return array of column contents.
369 function set_header($func, $headercl='inquirybg')
371 $this->header_fun = $func;
372 $this->header_class = $headercl;
375 // Set handler to display additional row between pager body and navibar.
376 // Return array of column contents.
378 function set_footer($func, $footercl='inquirybg')
380 $this->footer_fun = $func;
381 $this->footer_class = $footercl;
384 // Setter for table editors with inactive cell control.
386 function set_inactive_ctrl($table, $key) {
387 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
390 // Helper for display inactive control cells
392 function inactive_control_cell(&$row)
394 if ($this->inactive_ctrl) {
395 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
396 // $row['inactive'], $this->inactive_ctrl['table'],
397 // $this->inactive_ctrl['key']);
402 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
404 $table = $this->main_tbl;
405 $name = "Inactive". $id;
406 $value = $row['inactive'] ? 1:0;
408 if (check_value('show_inactive')) {
409 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
410 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
411 update_record_status($id, !$value, $table, $key);
414 echo '<td align="center">'. checkbox(null, $name, $value, true, '', "align='center'")
415 . hidden("LInact[$id]", $value, false) . '</td>';
422 //-----------------------------------------------------------------------------
423 // Creates new db_pager $_SESSION object on first page call.
424 // Retrieves from $_SESSION var on subsequent $_POST calls
426 // $name - base name for pager controls and $_SESSION object name
427 // $sql - base sql for data inquiry. Order of fields implies
428 // pager columns order.
429 // $coldef - array of column definitions. Example definitions
430 // Column with title 'User name' and default text format:
432 // Skipped field from sql query. Data for the field is not displayed:
434 // Column without title, data retrieved form row data with function func():
435 // array('fun'=>'func')
436 // Inserted column with title 'Some', formated with function rowfun().
438 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
439 // Column with name 'Another', formatted as date,
440 // sortable with ascending start order (available orders: asc,desc, '').
441 // 'Another' => array('type'=>'date', 'ord'=>'asc')
443 // All available column format types you will find in db_pager_view.inc file.
444 // If query result has more fields than count($coldef), rest of data is ignored
445 // during display, but can be used in format handlers for 'spec' and 'insert'
448 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
450 if (isset($_SESSION[$name]) &&
451 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
452 unset($_SESSION[$name]); // kill pager if sql has changed
454 if (!isset($_SESSION[$name])) {
455 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
456 $_SESSION[$name]->main_tbl = $table;
457 $_SESSION[$name]->key = $key;
458 $_SESSION[$name]->set_sql($sql);
459 $_SESSION[$name]->set_columns($coldef);
462 return $_SESSION[$name];
466 // Force pager initialization.
468 function refresh_pager($name)
470 if (isset($_SESSION[$name]))
471 $_SESSION[$name]->ready = false;