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 query either as:
61 // a. string in form 'SELECT field_list FROM table_joins [WHERE conditions [GROUP group_list [ORDER order_list]]]'
62 // - if WHERE keyword is used in table_joins, WHERE conditions is obligatory
63 // b. associative array using select, where, group and order keys ex :
64 // array('select' => 'SUM(quantity)', 'from' => TB_PREF."stock_moves", 'group' => 'location')
66 // $name is base name for pager controls
67 function db_pager($sql, $name, $table = null, $page_len=0)
70 if ($page_len == 0) $page_len = user_query_size();
72 $this->page_len = $page_len;
76 // Parse base sql select query or use an associative array.
78 function set_sql($sql)
80 if ($sql != $this->sql) {
85 foreach(explode(' ', 'select from where group order') as $section) {
86 $this->$section = @$sql[$section];
88 $this->select = "SELECT ".$this->select;
92 $parts = preg_split('/\sFROM\s/si', $sql, 2);
93 if (count($parts) == 2) {
94 $this->select = $parts[0];
98 display_error("Invalid sql input for db_pager");
101 $parts = preg_split('/\sWHERE(?!.*WHERE.*)\s/si', $sql, 2); // last occurence
102 if(count($parts) == 2) {
103 $this->from = $parts[0];
106 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
107 if(count($parts) == 2) {
109 $this->order = $parts[1];
111 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
112 if(count($parts) == 2) {
114 $this->group = $parts[1];
122 // Set additional constraint on record set
124 function set_where($where = null)
127 if (!is_array($where))
128 $where = array($where);
130 if (count($where) == count($this->extra_where) &&
131 !count(array_diff($this->extra_where, $where)))
134 $this->extra_where = $where;
135 $this->ready = false;
138 // Set query result page
140 function change_page($page=null)
142 $this->set_page($page);
147 // Change sort column direction
148 // in order asc->desc->none->asc
150 function sort_table($col)
154 foreach($this->columns as $id => $_col) {
155 if(!isset($_col['ord_priority'])) continue;
156 $max_priority = max($max_priority, $_col['ord_priority']);
160 $ord = $this->columns[$col]['ord'];
161 $this->columns[$col]['ord_priority'] = $max_priority+1; // set priority , higher than anything else
162 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
163 $this->columns[$col]['ord'] = $ord;
175 $Ajax->activate("_{$this->name}_span");
176 $this->data = array();
180 if ($this->rec_count == 0) return true;
182 $sql = $this->_sql_gen(false);
184 $result = db_query($sql, 'Error browsing database: '.$sql );
187 // setting field names for subsequent queries
189 // add result field names to column defs for
190 // col value retrieve and sort purposes
191 $cnt = min(db_num_fields($result), count($this->columns));
192 for ($c = $i = 0; $c < $cnt; $c++) {
193 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
194 // if (!@($this->columns[$c]['type']=='skip'))
195 $this->columns[$c]['name']= db_field_name($result, $i);
196 if (!@($this->columns[$c]['type']=='insert'))
200 while ($row = db_fetch_assoc($result)) {
201 $this->data[] = $row;
208 // Calculates page numbers for html controls.
210 function set_page($to)
214 $page = $this->curr_page+1; break;
216 $page = $this->curr_page-1; break;
218 $page = $this->last_page; break;
220 if (is_numeric($to)) {
228 $max = $this->max_page;
231 $this->curr_page = $page;
232 $this->next_page = ($page < $max) ? $page+1 : null;
233 $this->prev_page = ($page > 1) ? ($page-1) : null;
234 $this->last_page = ($page < $max) ? $max : null;
235 $this->first_page = ($page != 1) ? 1: null;
238 // Set column definitions
239 // $flds: array( fldname1, fldname2=>type,...)
240 function set_columns($flds)
242 $this->columns = array();
243 if (!is_array($flds)) {
244 $flds = array($flds);
246 foreach ($flds as $colnum=>$coldef) {
247 if (is_string($colnum)) { // 'colname'=>params
250 } else { // n=>params
251 if (is_array($coldef)) {
259 if (is_string($c)) // params is simple column type
260 $c = array('type'=>$c);
262 if (!isset($c['type']))
267 $this->inactive_ctrl = true;
270 $c['head'] = $h; break;
271 case 'skip': // skip the column (no header)
272 unset($c['head']); break;
274 $this->columns[] = $c;
278 // Generate db query from base sql
279 // $count==false - for current page data retrieval
280 // $count==true - for total records count
282 function _sql_gen($count=false)
284 $select = $this->select;
286 $where = $this->where;
287 $group = $this->group;
288 $order = $this->order;
290 if(count($this->extra_where)) {
291 $where .= ($where=='' ? '' : ' AND ')
292 .implode(' AND ', $this->extra_where);
294 if ($where) $where = " WHERE ($where)";
297 $group = $group == '' ? "*" : "DISTINCT $group";
299 return "SELECT COUNT($group) FROM $from $where";
302 $sql = "$select FROM $from $where";
303 if ($group) $sql.= " GROUP BY $group";
306 // sort order column by priority instead of table order.
308 foreach ($this->columns as $col) {
309 if(isset($col['ord_priority'])) {
310 $columns[$col['ord_priority']] = $col;
315 foreach ($columns as $col) {
316 if (isset($col['ord'])) {
317 if ( $col['ord'] != '' && isset($col['name'])) {
318 $ord[] = $col['name'] .' '. $col['ord'];
324 $ord = array_map(function_exists('mysql_real_escape_string') ?
325 'mysql_real_escape_string': 'mysql_escape_string', $ord);
326 $sql .= " ORDER BY " . implode(',', $ord);
329 $sql .= " ORDER BY $order"; // original base query order
332 $page_len = $this->page_len;
333 $offset = ($this->curr_page - 1) * $page_len;
335 $sql .= " LIMIT $offset, $page_len";
341 // Initialization after changing record set
347 if ($this->ready == false ) {
348 $sql = $this->_sql_gen(true);
349 $result = db_query($sql, 'Error reading record set');
350 if ($result == false)
352 $row = db_fetch_row($result);
353 $this->rec_count = $row[0];
354 $this->max_page = $this->page_len ?
355 ceil($this->rec_count/$this->page_len) : 0;
357 if ($go_debug) { // FIX - need column name parsing, but for now:
358 // check if field names are set explicite in col def
359 // for all initially ordered columns
360 foreach ($this->columns as $col) {
361 if (isset($col['ord']) && $col['ord'] != ''
362 && !isset($col['name'])) {
363 display_warning("Result field names must be set
364 for all initially ordered db_pager columns.");
374 // Set current page in response to user control.
376 function select_records()
380 $page = find_submit($this->name.'_page_', false);
381 $sort = find_submit($this->name.'_sort_', true);
383 $this->change_page($page);
384 if ($page == 'next' && !$this->next_page ||
385 $page == 'last' && !$this->last_page)
386 set_focus($this->name.'_page_prev');
387 if ($page == 'prev' && !$this->prev_page ||
388 $page == 'first' && !$this->first_page)
389 set_focus($this->name.'_page_next');
390 } elseif ($sort != -1) {
391 $this->sort_table($sort);
396 // Set check function to mark some rows.
398 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
400 $this->marker = $func;
401 $this->marker_txt = $notice;
402 $this->marker_class = $markercl;
403 $this->notice_class = $msgclass;
406 // Set handler to display additional row between titles and pager body.
407 // Return array of column contents.
409 function set_header($func, $headercl='inquirybg')
411 $this->header_fun = $func;
412 $this->header_class = $headercl;
415 // Set handler to display additional row between pager body and navibar.
416 // Return array of column contents.
418 function set_footer($func, $footercl='inquirybg')
420 $this->footer_fun = $func;
421 $this->footer_class = $footercl;
424 // Setter for table editors with inactive cell control.
426 function set_inactive_ctrl($table, $key) {
427 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
430 // Helper for display inactive control cells
432 function inactive_control_cell(&$row)
434 if ($this->inactive_ctrl) {
435 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
436 // $row['inactive'], $this->inactive_ctrl['table'],
437 // $this->inactive_ctrl['key']);
442 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
444 $table = $this->main_tbl;
445 $name = "Inactive". $id;
446 $value = $row['inactive'] ? 1:0;
448 if (check_value('show_inactive')) {
449 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
450 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
451 update_record_status($id, !$value, $table, $key);
454 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
455 . hidden("LInact[$id]", $value, false) . '</td>';
462 //-----------------------------------------------------------------------------
463 // Creates new db_pager $_SESSION object on first page call.
464 // Retrieves from $_SESSION var on subsequent $_POST calls
466 // $name - base name for pager controls and $_SESSION object name
467 // $sql - base sql for data inquiry. Order of fields implies
468 // pager columns order.
469 // $coldef - array of column definitions. Example definitions
470 // Column with title 'User name' and default text format:
472 // Skipped field from sql query. Data for the field is not displayed:
474 // Column without title, data retrieved form row data with function func():
475 // array('fun'=>'func')
476 // Inserted column with title 'Some', formated with function rowfun().
478 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
479 // Column with name 'Another', formatted as date,
480 // sortable with ascending start order (available orders: asc,desc, '').
481 // 'Another' => array('type'=>'date', 'ord'=>'asc')
483 // All available column format types you will find in db_pager_view.inc file.
484 // If query result has more fields than count($coldef), rest of data is ignored
485 // during display, but can be used in format handlers for 'spec' and 'insert'
488 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
490 if (isset($_SESSION[$name]) &&
491 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
492 unset($_SESSION[$name]); // kill pager if sql has changed
494 if (!isset($_SESSION[$name])) {
495 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
496 $_SESSION[$name]->main_tbl = $table;
497 $_SESSION[$name]->key = $key;
498 $_SESSION[$name]->set_sql($sql);
499 $_SESSION[$name]->set_columns($coldef);
502 return $_SESSION[$name];
506 // Force pager initialization.
508 function refresh_pager($name)
510 if (isset($_SESSION[$name]))
511 $_SESSION[$name]->ready = false;