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)
148 foreach($this->columns as $id => $_col) {
149 if(!isset($_col['ord_priority'])) continue;
150 $max_priority = max($max_priority, $_col['ord_priority']);
154 $ord = $this->columns[$col]['ord'];
155 $this->columns[$col]['ord_priority'] = $max_priority+1; // set priority , higher than anything else
156 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
157 $this->columns[$col]['ord'] = $ord;
169 $Ajax->activate("_{$this->name}_span");
170 $this->data = array();
174 if ($this->rec_count == 0) return true;
176 $sql = $this->_sql_gen(false);
178 $result = db_query($sql, 'Error browsing database: '.$sql );
181 // setting field names for subsequent queries
183 // add result field names to column defs for
184 // col value retrieve and sort purposes
185 $cnt = min(db_num_fields($result), count($this->columns));
186 for ($c = $i = 0; $c < $cnt; $c++) {
187 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
188 // if (!@($this->columns[$c]['type']=='skip'))
189 $this->columns[$c]['name']= db_field_name($result, $i);
190 if (!@($this->columns[$c]['type']=='insert'))
194 while ($row = db_fetch_assoc($result)) {
195 $this->data[] = $row;
202 // Calculates page numbers for html controls.
204 function set_page($to)
208 $page = $this->curr_page+1; break;
210 $page = $this->curr_page-1; break;
212 $page = $this->last_page; break;
214 if (is_numeric($to)) {
222 $max = $this->max_page;
225 $this->curr_page = $page;
226 $this->next_page = ($page < $max) ? $page+1 : null;
227 $this->prev_page = ($page > 1) ? ($page-1) : null;
228 $this->last_page = ($page < $max) ? $max : null;
229 $this->first_page = ($page != 1) ? 1: null;
232 // Set column definitions
233 // $flds: array( fldname1, fldname2=>type,...)
234 function set_columns($flds)
236 $this->columns = array();
237 if (!is_array($flds)) {
238 $flds = array($flds);
240 foreach ($flds as $colnum=>$coldef) {
241 if (is_string($colnum)) { // 'colname'=>params
244 } else { // n=>params
245 if (is_array($coldef)) {
253 if (is_string($c)) // params is simple column type
254 $c = array('type'=>$c);
256 if (!isset($c['type']))
261 $this->inactive_ctrl = true;
264 $c['head'] = $h; break;
265 case 'skip': // skip the column (no header)
266 unset($c['head']); break;
268 $this->columns[] = $c;
272 // Generate db query from base sql
273 // $count==false - for current page data retrieval
274 // $count==true - for total records count
276 function _sql_gen($count=false)
278 $select = $this->select;
280 $where = $this->where;
281 $group = $this->group;
282 $order = $this->order;
284 if(count($this->extra_where)) {
285 $where .= ($where=='' ? '' : ' AND ')
286 .implode(' AND ', $this->extra_where);
288 if ($where) $where = " WHERE ($where)";
291 $group = $group == '' ? "*" : "DISTINCT $group";
293 return "SELECT COUNT($group) FROM $from $where";
296 $sql = "$select FROM $from $where";
297 if ($group) $sql.= " GROUP BY $group";
300 // sort order column by priority instead of table order.
302 foreach ($this->columns as $col) {
303 if(isset($col['ord_priority'])) {
304 $columns[$col['ord_priority']] = $col;
309 foreach ($columns as $col) {
310 if (isset($col['ord'])) {
311 if ( $col['ord'] != '' && isset($col['name'])) {
312 $ord[] = $col['name'] .' '. $col['ord'];
318 $ord = array_map(function_exists('mysql_real_escape_string') ?
319 'mysql_real_escape_string': 'mysql_escape_string', $ord);
320 $sql .= " ORDER BY " . implode(',', $ord);
323 $sql .= " ORDER BY $order"; // original base query order
326 $page_len = $this->page_len;
327 $offset = ($this->curr_page - 1) * $page_len;
329 $sql .= " LIMIT $offset, $page_len";
335 // Initialization after changing record set
341 if ($this->ready == false ) {
342 $sql = $this->_sql_gen(true);
343 $result = db_query($sql, 'Error reading record set');
344 if ($result == false)
346 $row = db_fetch_row($result);
347 $this->rec_count = $row[0];
348 $this->max_page = $this->page_len ?
349 ceil($this->rec_count/$this->page_len) : 0;
351 if ($go_debug) { // FIX - need column name parsing, but for now:
352 // check if field names are set explicite in col def
353 // for all initially ordered columns
354 foreach ($this->columns as $col) {
355 if (isset($col['ord']) && $col['ord'] != ''
356 && !isset($col['name'])) {
357 display_warning("Result field names must be set
358 for all initially ordered db_pager columns.");
368 // Set current page in response to user control.
370 function select_records()
374 $page = find_submit($this->name.'_page_', false);
375 $sort = find_submit($this->name.'_sort_', true);
377 $this->change_page($page);
378 if ($page == 'next' && !$this->next_page ||
379 $page == 'last' && !$this->last_page)
380 set_focus($this->name.'_page_prev');
381 if ($page == 'prev' && !$this->prev_page ||
382 $page == 'first' && !$this->first_page)
383 set_focus($this->name.'_page_next');
384 } elseif ($sort != -1) {
385 $this->sort_table($sort);
390 // Set check function to mark some rows.
392 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
394 $this->marker = $func;
395 $this->marker_txt = $notice;
396 $this->marker_class = $markercl;
397 $this->notice_class = $msgclass;
400 // Set handler to display additional row between titles and pager body.
401 // Return array of column contents.
403 function set_header($func, $headercl='inquirybg')
405 $this->header_fun = $func;
406 $this->header_class = $headercl;
409 // Set handler to display additional row between pager body and navibar.
410 // Return array of column contents.
412 function set_footer($func, $footercl='inquirybg')
414 $this->footer_fun = $func;
415 $this->footer_class = $footercl;
418 // Setter for table editors with inactive cell control.
420 function set_inactive_ctrl($table, $key) {
421 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
424 // Helper for display inactive control cells
426 function inactive_control_cell(&$row)
428 if ($this->inactive_ctrl) {
429 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
430 // $row['inactive'], $this->inactive_ctrl['table'],
431 // $this->inactive_ctrl['key']);
436 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
438 $table = $this->main_tbl;
439 $name = "Inactive". $id;
440 $value = $row['inactive'] ? 1:0;
442 if (check_value('show_inactive')) {
443 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
444 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
445 update_record_status($id, !$value, $table, $key);
448 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
449 . hidden("LInact[$id]", $value, false) . '</td>';
456 //-----------------------------------------------------------------------------
457 // Creates new db_pager $_SESSION object on first page call.
458 // Retrieves from $_SESSION var on subsequent $_POST calls
460 // $name - base name for pager controls and $_SESSION object name
461 // $sql - base sql for data inquiry. Order of fields implies
462 // pager columns order.
463 // $coldef - array of column definitions. Example definitions
464 // Column with title 'User name' and default text format:
466 // Skipped field from sql query. Data for the field is not displayed:
468 // Column without title, data retrieved form row data with function func():
469 // array('fun'=>'func')
470 // Inserted column with title 'Some', formated with function rowfun().
472 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
473 // Column with name 'Another', formatted as date,
474 // sortable with ascending start order (available orders: asc,desc, '').
475 // 'Another' => array('type'=>'date', 'ord'=>'asc')
477 // All available column format types you will find in db_pager_view.inc file.
478 // If query result has more fields than count($coldef), rest of data is ignored
479 // during display, but can be used in format handlers for 'spec' and 'insert'
482 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
484 if (isset($_SESSION[$name]) &&
485 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
486 unset($_SESSION[$name]); // kill pager if sql has changed
488 if (!isset($_SESSION[$name])) {
489 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
490 $_SESSION[$name]->main_tbl = $table;
491 $_SESSION[$name]->key = $key;
492 $_SESSION[$name]->set_sql($sql);
493 $_SESSION[$name]->set_columns($coldef);
496 return $_SESSION[$name];
500 // Force pager initialization.
502 function refresh_pager($name)
504 if (isset($_SESSION[$name]))
505 $_SESSION[$name]->ready = false;