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)
66 if ($page_len == 0) $page_len = user_query_size();
68 $this->page_len = $page_len;
72 // Parse base sql select query.
74 function set_sql($sql)
76 if ($sql != $this->sql) {
79 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
80 if(count($parts) == 2) {
82 $this->order = $parts[1];
84 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
85 if(count($parts) == 2) {
87 $this->group = $parts[1];
89 $parts = preg_split('/\sWHERE\s/si', $sql, 2);
90 if(count($parts) == 2) {
92 $this->where = $parts[1];
94 $parts = preg_split('/\sFROM\s/si', $sql, 2);
95 if(count($parts) == 2) {
97 $this->from = $parts[1];
103 // Set additional constraint on record set
105 function set_where($where = null)
108 if (!is_array($where))
109 $where = array($where);
111 if (count($where) == count($this->extra_where) &&
112 !count(array_diff($this->extra_where, $where)))
115 $this->extra_where = $where;
116 $this->ready = false;
119 // Set query result page
121 function change_page($page=null)
123 $this->set_page($page);
128 // Change sort column direction
129 // in order asc->desc->none->asc
131 function sort_table($col)
133 $ord = $this->columns[$col]['ord'];
134 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
135 $this->columns[$col]['ord'] = $ord;
147 $Ajax->activate("_{$this->name}_span");
148 $this->data = array();
152 if ($this->rec_count == 0) return true;
154 $sql = $this->_sql_gen(false);
156 $result = db_query($sql, 'Error browsing database: '.$sql );
159 // setting field names for subsequent queries
161 // add result field names to column defs for
162 // col value retrieve and sort purposes
163 $cnt = min(mysql_num_fields($result), count($this->columns));
164 for ($c = $i = 0; $c < $cnt; $c++) {
165 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
166 // if (!@($this->columns[$c]['type']=='skip'))
167 $this->columns[$c]['name']= mysql_field_name($result, $i);
168 if (!@($this->columns[$c]['type']=='insert'))
172 while ($row = db_fetch_assoc($result)) {
173 $this->data[] = $row;
180 // Calculates page numbers for html controls.
182 function set_page($to)
186 $page = $this->curr_page+1; break;
188 $page = $this->curr_page-1; break;
190 $page = $this->last_page; break;
192 if (is_numeric($to)) {
200 $max = $this->max_page;
203 $this->curr_page = $page;
204 $this->next_page = ($page < $max) ? $page+1 : null;
205 $this->prev_page = ($page > 1) ? ($page-1) : null;
206 $this->last_page = ($page < $max) ? $max : null;
207 $this->first_page = ($page != 1) ? 1: null;
210 // Set column definitions
211 // $flds: array( fldname1, fldname2=>type,...)
212 function set_columns($flds)
214 $this->columns = array();
215 if (!is_array($flds)) {
216 $flds = array($flds);
218 foreach ($flds as $colnum=>$coldef) {
219 if (is_string($colnum)) { // 'colname'=>params
222 } else { // n=>params
223 if (is_array($coldef)) {
231 if (is_string($c)) // params is simple column type
232 $c = array('type'=>$c);
234 if (!isset($c['type']))
239 $this->inactive_ctrl = true;
242 $c['head'] = $h; break;
243 case 'skip': // skip the column (no header)
244 unset($c['head']); break;
246 $this->columns[] = $c;
250 // Generate db query from base sql
251 // $count==false - for current page data retrieval
252 // $count==true - for total records count
254 function _sql_gen($count=false)
256 $select = $this->select;
258 $where = $this->where;
259 $group = $this->group;
260 $order = $this->order;
262 if(count($this->extra_where)) {
263 $where .= ($where=='' ? '' : ' AND ')
264 .implode( $this->extra_where, ' AND ');
266 if ($where) $where = " WHERE ($where)";
269 $group = $group == '' ? "*" : "DISTINCT $group";
271 return "SELECT COUNT($group) FROM $from $where";
274 $sql = "$select FROM $from $where";
275 if ($group) $sql.= " GROUP BY $group";
278 foreach ($this->columns as $col) {
279 if (isset($col['ord'])) {
280 if ( $col['ord'] != '' && isset($col['name'])) {
281 $ord[] = $col['name'] .' '. $col['ord'];
287 $sql .= " ORDER BY " . implode($ord, ',');
290 $sql .= " ORDER BY $order"; // original base query order
293 $page_len = $this->page_len;
294 $offset = ($this->curr_page - 1) * $page_len;
296 $sql .= " LIMIT $offset, $page_len";
302 // Initialization after changing record set
308 if ($this->ready == false ) {
309 $sql = $this->_sql_gen(true);
310 $result = db_query($sql, 'Error reading record set');
311 if ($result == false)
313 $row = db_fetch_row($result);
314 $this->rec_count = $row[0];
315 $this->max_page = $this->page_len ?
316 ceil($this->rec_count/$this->page_len) : 0;
318 if ($go_debug) { // FIX - need column name parsing, but for now:
319 // check if field names are set explicite in col def
320 // for all initially ordered columns
321 foreach ($this->columns as $col) {
322 if (isset($col['ord']) && $col['ord'] != ''
323 && !isset($col['name'])) {
324 display_warning("Result field names must be set
325 for all intially ordered db_pager columns.");
335 // Set current page in response to user control.
337 function select_records()
341 $page = find_submit($this->name.'_page_', false);
342 $sort = find_submit($this->name.'_sort_', true);
344 $this->change_page($page);
345 if ($page == 'next' && !$this->next_page ||
346 $page == 'last' && !$this->last_page)
347 set_focus($this->name.'_page_prev');
348 if ($page == 'prev' && !$this->prev_page ||
349 $page == 'first' && !$this->first_page)
350 set_focus($this->name.'_page_next');
351 } elseif ($sort != -1) {
352 $this->sort_table($sort);
357 // Set check function to mark some rows.
359 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
361 $this->marker = $func;
362 $this->marker_txt = $notice;
363 $this->marker_class = $markercl;
364 $this->notice_class = $msgclass;
367 // Set handler to display additional row between titles and pager body.
368 // Return array of column contents.
370 function set_header($func, $headercl='inquirybg')
372 $this->header_fun = $func;
373 $this->header_class = $headercl;
376 // Set handler to display additional row between pager body and navibar.
377 // Return array of column contents.
379 function set_footer($func, $footercl='inquirybg')
381 $this->footer_fun = $func;
382 $this->footer_class = $footercl;
385 // Setter for table editors with inactive cell control.
387 function set_inactive_ctrl($table, $key) {
388 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
391 // Helper for display inactive control cells
393 function inactive_control_cell(&$row)
395 if ($this->inactive_ctrl) {
396 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
397 // $row['inactive'], $this->inactive_ctrl['table'],
398 // $this->inactive_ctrl['key']);
403 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
405 $table = $this->main_tbl;
406 $name = "Inactive". $id;
407 $value = $row['inactive'] ? 1:0;
409 if (check_value('show_inactive')) {
410 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
411 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
412 update_record_status($id, !$value, $table, $key);
415 echo '<td align="center">'. checkbox(null, $name, $value, true, '', "align='center'")
416 . hidden("LInact[$id]", $value, false) . '</td>';
423 //-----------------------------------------------------------------------------
424 // Creates new db_pager $_SESSION object on first page call.
425 // Retrieves from $_SESSION var on subsequent $_POST calls
427 // $name - base name for pager controls and $_SESSION object name
428 // $sql - base sql for data inquiry. Order of fields implies
429 // pager columns order.
430 // $coldef - array of column definitions. Example definitions
431 // Column with title 'User name' and default text format:
433 // Skipped field from sql query. Data for the field is not displayed:
435 // Column without title, data retrieved form row data with function func():
436 // array('fun'=>'func')
437 // Inserted column with title 'Some', formated with function rowfun().
439 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
440 // Column with name 'Another', formatted as date,
441 // sortable with ascending start order (available orders: asc,desc, '').
442 // 'Another' => array('type'=>'date', 'ord'=>'asc')
444 // All available column format types you will find in db_pager_view.inc file.
445 // If query result has more fields than count($coldef), rest of data is ignored
446 // during display, but can be used in format handlers for 'spec' and 'insert'
449 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
451 if (isset($_SESSION[$name]) &&
452 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
453 unset($_SESSION[$name]); // kill pager if sql has changed
455 if (!isset($_SESSION[$name])) {
456 $_SESSION[$name] =& new db_pager($sql, $name, $table, $page_len);
457 $_SESSION[$name]->main_tbl = $table;
458 $_SESSION[$name]->key = $key;
459 $_SESSION[$name]->set_sql($sql);
460 $_SESSION[$name]->set_columns($coldef);
463 return $_SESSION[$name];
467 // Force pager initialization.
469 function refresh_pager($name)
471 if (isset($_SESSION[$name]))
472 $_SESSION[$name]->ready = false;