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)
82 if ($sql != $this->sql) {
87 foreach(explode(' ', 'select from where group order') as $section) {
88 $this->$section = @$sql[$section];
90 $this->select = "SELECT ".$this->select;
94 $parts = preg_split('/\sFROM\s/si', $sql, 2);
95 if (count($parts) == 2) {
96 $this->select = $parts[0];
99 if ($SysPrefs->go_debug)
100 display_error("Invalid sql input for db_pager");
103 $parts = preg_split('/\sWHERE(?!.*WHERE.*)\s/si', $sql, 2); // last occurence
104 if(count($parts) == 2) {
105 $this->from = $parts[0];
108 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
109 if(count($parts) == 2) {
111 $this->order = $parts[1];
113 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
114 if(count($parts) == 2) {
116 $this->group = $parts[1];
124 // Set additional constraint on record set
126 function set_where($where = null)
129 if (!is_array($where))
130 $where = array($where);
132 if (count($where) == count($this->extra_where) &&
133 !count(array_diff($this->extra_where, $where)))
136 $this->extra_where = $where;
137 $this->ready = false;
140 // Set query result page
142 function change_page($page=null)
144 $this->set_page($page);
149 // Change sort column direction
150 // in order asc->desc->none->asc
152 function sort_table($col)
156 foreach($this->columns as $id => $_col) {
157 if(!isset($_col['ord_priority'])) continue;
158 $max_priority = max($max_priority, $_col['ord_priority']);
162 $ord = $this->columns[$col]['ord'];
163 $this->columns[$col]['ord_priority'] = $max_priority+1; // set priority , higher than anything else
164 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
165 $this->columns[$col]['ord'] = $ord;
177 $Ajax->activate("_{$this->name}_span");
178 $this->data = array();
182 if ($this->rec_count == 0) return true;
184 $sql = $this->_sql_gen(false);
186 $result = db_query($sql, 'Error browsing database: '.$sql );
189 // setting field names for subsequent queries
191 // add result field names to column defs for
192 // col value retrieve and sort purposes
193 $cnt = min(db_num_fields($result), count($this->columns));
194 for ($c = $i = 0; $c < $cnt; $c++) {
195 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
196 // if (!@($this->columns[$c]['type']=='skip'))
197 $this->columns[$c]['name']= db_field_name($result, $i);
198 if (!@($this->columns[$c]['type']=='insert'))
202 while ($row = db_fetch_assoc($result)) {
203 $this->data[] = $row;
210 // Calculates page numbers for html controls.
212 function set_page($to)
216 $page = $this->curr_page+1; break;
218 $page = $this->curr_page-1; break;
220 $page = $this->last_page; break;
222 if (is_numeric($to)) {
230 $max = $this->max_page;
233 $this->curr_page = $page;
234 $this->next_page = ($page < $max) ? $page+1 : null;
235 $this->prev_page = ($page > 1) ? ($page-1) : null;
236 $this->last_page = ($page < $max) ? $max : null;
237 $this->first_page = ($page != 1) ? 1: null;
240 // Set column definitions
241 // $flds: array( fldname1, fldname2=>type,...)
242 function set_columns($flds)
244 $this->columns = array();
245 if (!is_array($flds)) {
246 $flds = array($flds);
248 foreach ($flds as $colnum=>$coldef) {
249 if (is_string($colnum)) { // 'colname'=>params
252 } else { // n=>params
253 if (is_array($coldef)) {
261 if (is_string($c)) // params is simple column type
262 $c = array('type'=>$c);
264 if (!isset($c['type']))
269 $this->inactive_ctrl = true;
272 $c['head'] = $h; break;
273 case 'skip': // skip the column (no header)
274 unset($c['head']); break;
276 $this->columns[] = $c;
280 // Generate db query from base sql
281 // $count==false - for current page data retrieval
282 // $count==true - for total records count
284 function _sql_gen($count=false)
286 $select = $this->select;
288 $where = $this->where;
289 $group = $this->group;
290 $order = $this->order;
292 if(count($this->extra_where)) {
293 $where .= ($where=='' ? '' : ' AND ')
294 .implode(' AND ', $this->extra_where);
296 if ($where) $where = " WHERE ($where)";
299 return "SELECT COUNT(*) FROM ($this->sql) tmp_count";
301 $sql = "$select FROM $from $where";
302 if ($group) $sql.= " GROUP BY $group";
305 // sort order column by priority instead of table order.
307 foreach ($this->columns as $col) {
308 if(isset($col['ord_priority'])) {
309 $columns[$col['ord_priority']] = $col;
314 foreach ($columns as $col) {
315 if (isset($col['ord'])) {
316 if ( $col['ord'] != '' && isset($col['name'])) {
317 $ord[] = $col['name'] .' '. $col['ord'];
323 $ord = array_map('db_escape_function', $ord);
324 $sql .= " ORDER BY " . implode(',', $ord);
327 $sql .= " ORDER BY $order"; // original base query order
330 $page_len = $this->page_len;
331 $offset = ($this->curr_page - 1) * $page_len;
333 $sql .= " LIMIT $offset, $page_len";
339 // Initialization after changing record set
345 if ($this->ready == false ) {
346 $sql = $this->_sql_gen(true);
347 $result = db_query($sql, 'Error reading record set');
348 if ($result == false)
350 $row = db_fetch_row($result);
351 $this->rec_count = $row[0];
352 $this->max_page = $this->page_len ?
353 ceil($this->rec_count/$this->page_len) : 0;
355 if ($SysPrefs->go_debug) { // FIX - need column name parsing, but for now:
356 // check if field names are set explicite in col def
357 // for all initially ordered columns
358 foreach ($this->columns as $col) {
359 if (isset($col['ord']) && $col['ord'] != ''
360 && !isset($col['name'])) {
361 display_warning("Result field names must be set
362 for all initially ordered db_pager columns.");
372 // Set current page in response to user control.
374 function select_records()
378 $page = find_submit($this->name.'_page_', false);
379 $sort = find_submit($this->name.'_sort_', true);
381 $this->change_page($page);
382 if ($page == 'next' && !$this->next_page ||
383 $page == 'last' && !$this->last_page)
384 set_focus($this->name.'_page_prev');
385 if ($page == 'prev' && !$this->prev_page ||
386 $page == 'first' && !$this->first_page)
387 set_focus($this->name.'_page_next');
388 } elseif ($sort != -1) {
389 $this->sort_table($sort);
394 // Set check function to mark some rows.
396 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
398 $this->marker = $func;
399 $this->marker_txt = $notice;
400 $this->marker_class = $markercl;
401 $this->notice_class = $msgclass;
404 // Set handler to display additional row between titles and pager body.
405 // Return array of column contents.
407 function set_header($func, $headercl='inquirybg')
409 $this->header_fun = $func;
410 $this->header_class = $headercl;
413 // Set handler to display additional row between pager body and navibar.
414 // Return array of column contents.
416 function set_footer($func, $footercl='inquirybg')
418 $this->footer_fun = $func;
419 $this->footer_class = $footercl;
422 // Setter for table editors with inactive cell control.
424 function set_inactive_ctrl($table, $key) {
425 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
428 // Helper for display inactive control cells
430 function inactive_control_cell(&$row)
432 if ($this->inactive_ctrl) {
437 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
439 $table = $this->main_tbl;
440 $name = "Inactive". $id;
441 $value = $row['inactive'] ? 1:0;
443 if (check_value('show_inactive')) {
444 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
445 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
446 update_record_status($id, !$value, $table, $key);
449 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
450 . hidden("LInact[$id]", $value, false) . '</td>';
457 //-----------------------------------------------------------------------------
458 // Creates new db_pager $_SESSION object on first page call.
459 // Retrieves from $_SESSION var on subsequent $_POST calls
461 // $name - base name for pager controls and $_SESSION object name
462 // $sql - base sql for data inquiry. Order of fields implies
463 // pager columns order.
464 // $coldef - array of column definitions. Example definitions
465 // Column with title 'User name' and default text format:
467 // Skipped field from sql query. Data for the field is not displayed:
469 // Column without title, data retrieved form row data with function func():
470 // array('fun'=>'func')
471 // Inserted column with title 'Some', formated with function rowfun().
473 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
474 // Column with name 'Another', formatted as date,
475 // sortable with ascending start order (available orders: asc,desc, '').
476 // 'Another' => array('type'=>'date', 'ord'=>'asc')
478 // All available column format types you will find in db_pager_view.inc file.
479 // If query result has more fields than count($coldef), rest of data is ignored
480 // during display, but can be used in format handlers for 'spec' and 'insert'
483 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
485 if (isset($_SESSION[$name]) &&
486 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
487 unset($_SESSION[$name]); // kill pager if sql has changed
489 if (!isset($_SESSION[$name])) {
490 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
491 $_SESSION[$name]->main_tbl = $table;
492 $_SESSION[$name]->key = $key;
493 $_SESSION[$name]->set_sql($sql);
494 $_SESSION[$name]->set_columns($coldef);
497 return $_SESSION[$name];
501 // Force pager initialization.
503 function refresh_pager($name)
505 if (isset($_SESSION[$name]))
506 $_SESSION[$name]->ready = false;