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.
72 // or use an associative array.
73 // Usefull is the query can't be split correctly (using subquery for example).
74 // The associative array shouldn't contain the keyword itself.
76 // array('select' => 'SUM(quantity)', 'from' => TB_PREF."stock_moves", 'group' => 'location')
77 function set_sql($sql)
79 if ($sql != $this->sql) {
84 foreach(explode(' ', 'select from where group order') as $section) {
85 $this->$section = @$sql[$section];
87 $this->select = "SELECT ".$this->select;
91 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
92 if(count($parts) == 2) {
94 $this->order = $parts[1];
96 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
97 if(count($parts) == 2) {
99 $this->group = $parts[1];
101 $parts = preg_split('/\sWHERE\s/si', $sql, 2);
102 if(count($parts) == 2) {
104 $this->where = $parts[1];
106 $parts = preg_split('/\sFROM\s/si', $sql, 2);
107 if(count($parts) == 2) {
109 $this->from = $parts[1];
111 $this->select = $sql;
116 // Set additional constraint on record set
118 function set_where($where = null)
121 if (!is_array($where))
122 $where = array($where);
124 if (count($where) == count($this->extra_where) &&
125 !count(array_diff($this->extra_where, $where)))
128 $this->extra_where = $where;
129 $this->ready = false;
132 // Set query result page
134 function change_page($page=null)
136 $this->set_page($page);
141 // Change sort column direction
142 // in order asc->desc->none->asc
144 function sort_table($col)
146 $ord = $this->columns[$col]['ord'];
147 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
148 $this->columns[$col]['ord'] = $ord;
160 $Ajax->activate("_{$this->name}_span");
161 $this->data = array();
165 if ($this->rec_count == 0) return true;
167 $sql = $this->_sql_gen(false);
169 $result = db_query($sql, 'Error browsing database: '.$sql );
172 // setting field names for subsequent queries
174 // add result field names to column defs for
175 // col value retrieve and sort purposes
176 $cnt = min(db_num_fields($result), count($this->columns));
177 for ($c = $i = 0; $c < $cnt; $c++) {
178 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
179 // if (!@($this->columns[$c]['type']=='skip'))
180 $this->columns[$c]['name']= db_field_name($result, $i);
181 if (!@($this->columns[$c]['type']=='insert'))
185 while ($row = db_fetch_assoc($result)) {
186 $this->data[] = $row;
193 // Calculates page numbers for html controls.
195 function set_page($to)
199 $page = $this->curr_page+1; break;
201 $page = $this->curr_page-1; break;
203 $page = $this->last_page; break;
205 if (is_numeric($to)) {
213 $max = $this->max_page;
216 $this->curr_page = $page;
217 $this->next_page = ($page < $max) ? $page+1 : null;
218 $this->prev_page = ($page > 1) ? ($page-1) : null;
219 $this->last_page = ($page < $max) ? $max : null;
220 $this->first_page = ($page != 1) ? 1: null;
223 // Set column definitions
224 // $flds: array( fldname1, fldname2=>type,...)
225 function set_columns($flds)
227 $this->columns = array();
228 if (!is_array($flds)) {
229 $flds = array($flds);
231 foreach ($flds as $colnum=>$coldef) {
232 if (is_string($colnum)) { // 'colname'=>params
235 } else { // n=>params
236 if (is_array($coldef)) {
244 if (is_string($c)) // params is simple column type
245 $c = array('type'=>$c);
247 if (!isset($c['type']))
252 $this->inactive_ctrl = true;
255 $c['head'] = $h; break;
256 case 'skip': // skip the column (no header)
257 unset($c['head']); break;
259 $this->columns[] = $c;
263 // Generate db query from base sql
264 // $count==false - for current page data retrieval
265 // $count==true - for total records count
267 function _sql_gen($count=false)
269 $select = $this->select;
271 $where = $this->where;
272 $group = $this->group;
273 $order = $this->order;
275 if(count($this->extra_where)) {
276 $where .= ($where=='' ? '' : ' AND ')
277 .implode(' AND ', $this->extra_where);
279 if ($where) $where = " WHERE ($where)";
282 $group = $group == '' ? "*" : "DISTINCT $group";
284 return "SELECT COUNT($group) FROM $from $where";
287 $sql = "$select FROM $from $where";
288 if ($group) $sql.= " GROUP BY $group";
291 foreach ($this->columns as $col) {
292 if (isset($col['ord'])) {
293 if ( $col['ord'] != '' && isset($col['name'])) {
294 $ord[] = $col['name'] .' '. $col['ord'];
300 $ord = array_map(function_exists('mysql_real_escape_string') ?
301 'mysql_real_escape_string': 'mysql_escape_string', $ord);
302 $sql .= " ORDER BY " . implode(',', $ord);
305 $sql .= " ORDER BY $order"; // original base query order
308 $page_len = $this->page_len;
309 $offset = ($this->curr_page - 1) * $page_len;
311 $sql .= " LIMIT $offset, $page_len";
317 // Initialization after changing record set
323 if ($this->ready == false ) {
324 $sql = $this->_sql_gen(true);
325 $result = db_query($sql, 'Error reading record set');
326 if ($result == false)
328 $row = db_fetch_row($result);
329 $this->rec_count = $row[0];
330 $this->max_page = $this->page_len ?
331 ceil($this->rec_count/$this->page_len) : 0;
333 if ($go_debug) { // FIX - need column name parsing, but for now:
334 // check if field names are set explicite in col def
335 // for all initially ordered columns
336 foreach ($this->columns as $col) {
337 if (isset($col['ord']) && $col['ord'] != ''
338 && !isset($col['name'])) {
339 display_warning("Result field names must be set
340 for all intially ordered db_pager columns.");
350 // Set current page in response to user control.
352 function select_records()
356 $page = find_submit($this->name.'_page_', false);
357 $sort = find_submit($this->name.'_sort_', true);
359 $this->change_page($page);
360 if ($page == 'next' && !$this->next_page ||
361 $page == 'last' && !$this->last_page)
362 set_focus($this->name.'_page_prev');
363 if ($page == 'prev' && !$this->prev_page ||
364 $page == 'first' && !$this->first_page)
365 set_focus($this->name.'_page_next');
366 } elseif ($sort != -1) {
367 $this->sort_table($sort);
372 // Set check function to mark some rows.
374 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
376 $this->marker = $func;
377 $this->marker_txt = $notice;
378 $this->marker_class = $markercl;
379 $this->notice_class = $msgclass;
382 // Set handler to display additional row between titles and pager body.
383 // Return array of column contents.
385 function set_header($func, $headercl='inquirybg')
387 $this->header_fun = $func;
388 $this->header_class = $headercl;
391 // Set handler to display additional row between pager body and navibar.
392 // Return array of column contents.
394 function set_footer($func, $footercl='inquirybg')
396 $this->footer_fun = $func;
397 $this->footer_class = $footercl;
400 // Setter for table editors with inactive cell control.
402 function set_inactive_ctrl($table, $key) {
403 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
406 // Helper for display inactive control cells
408 function inactive_control_cell(&$row)
410 if ($this->inactive_ctrl) {
411 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
412 // $row['inactive'], $this->inactive_ctrl['table'],
413 // $this->inactive_ctrl['key']);
418 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
420 $table = $this->main_tbl;
421 $name = "Inactive". $id;
422 $value = $row['inactive'] ? 1:0;
424 if (check_value('show_inactive')) {
425 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
426 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
427 update_record_status($id, !$value, $table, $key);
430 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
431 . hidden("LInact[$id]", $value, false) . '</td>';
438 //-----------------------------------------------------------------------------
439 // Creates new db_pager $_SESSION object on first page call.
440 // Retrieves from $_SESSION var on subsequent $_POST calls
442 // $name - base name for pager controls and $_SESSION object name
443 // $sql - base sql for data inquiry. Order of fields implies
444 // pager columns order.
445 // $coldef - array of column definitions. Example definitions
446 // Column with title 'User name' and default text format:
448 // Skipped field from sql query. Data for the field is not displayed:
450 // Column without title, data retrieved form row data with function func():
451 // array('fun'=>'func')
452 // Inserted column with title 'Some', formated with function rowfun().
454 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
455 // Column with name 'Another', formatted as date,
456 // sortable with ascending start order (available orders: asc,desc, '').
457 // 'Another' => array('type'=>'date', 'ord'=>'asc')
459 // All available column format types you will find in db_pager_view.inc file.
460 // If query result has more fields than count($coldef), rest of data is ignored
461 // during display, but can be used in format handlers for 'spec' and 'insert'
464 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
466 if (isset($_SESSION[$name]) &&
467 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
468 unset($_SESSION[$name]); // kill pager if sql has changed
470 if (!isset($_SESSION[$name])) {
471 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
472 $_SESSION[$name]->main_tbl = $table;
473 $_SESSION[$name]->key = $key;
474 $_SESSION[$name]->set_sql($sql);
475 $_SESSION[$name]->set_columns($coldef);
478 return $_SESSION[$name];
482 // Force pager initialization.
484 function refresh_pager($name)
486 if (isset($_SESSION[$name]))
487 $_SESSION[$name]->ready = false;