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.
56 // db_pager constructor
57 // accepts $sql like 'SELECT ...[FROM ...][WHERE ...][GROUP ...][ORDER ...]'
58 // $name is base name for pager controls
59 function db_pager($sql, $name, $page_len=0)
63 if ($page_len == 0) $page_len = user_query_size();
65 $this->page_len = $page_len;
69 // Parse base sql select query.
71 function set_sql($sql)
73 if ($sql != $this->sql) {
76 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
77 if(count($parts) == 2) {
79 $this->order = $parts[1];
81 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
82 if(count($parts) == 2) {
84 $this->group = $parts[1];
86 $parts = preg_split('/\sWHERE\s/si', $sql, 2);
87 if(count($parts) == 2) {
89 $this->where = $parts[1];
91 $parts = preg_split('/\sFROM\s/si', $sql, 2);
92 if(count($parts) == 2) {
94 $this->from = $parts[1];
100 // Set additional constraint on record set
102 function set_where($where = null)
105 if (!is_array($where))
106 $where = array($where);
108 if (count($where) == count($this->extra_where) &&
109 !count(array_diff($this->extra_where, $where)))
112 $this->extra_where = $where;
113 $this->ready = false;
116 // Set query result page
118 function change_page($page=null)
120 $this->set_page($page);
125 // Change sort column direction
126 // in order asc->desc->none->asc
128 function sort_table($col)
130 $ord = $this->columns[$col]['ord'];
131 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
132 $this->columns[$col]['ord'] = $ord;
144 $Ajax->activate("_{$this->name}_span");
145 $this->data = array();
149 if ($this->rec_count == 0) return true;
151 $sql = $this->_sql_gen(false);
153 $result = db_query($sql, 'Error browsing database: '.$sql );
156 // setting field names for subsequent queries
158 // add result field names to column defs for
159 // col value retrieve and sort purposes
160 for ($c = $i = 0; $c < count($this->columns); $c++) {
161 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert']))
162 $this->columns[$c]['name']= mysql_field_name($result, $i++);
165 while ($row = db_fetch_assoc($result))
166 $this->data[] = $row;
173 // Calculates page numbers for html controls.
175 function set_page($to)
179 $page = $this->curr_page+1; break;
181 $page = $this->curr_page-1; break;
183 $page = $this->last_page; break;
185 if (is_numeric($to)) {
193 $max = $this->max_page;
196 $this->curr_page = $page;
197 $this->next_page = ($page < $max) ? $page+1 : null;
198 $this->prev_page = ($page > 1) ? ($page-1) : null;
199 $this->last_page = ($page < $max) ? $max : null;
200 $this->first_page = ($page != 1) ? 1: null;
203 // Set column definitions
204 // $flds: array( fldname1, fldname2=>type,...)
205 function set_columns($flds)
207 $this->columns = array();
208 if (!is_array($flds)) {
209 $flds = array($flds);
211 foreach ($flds as $colnum=>$coldef) {
212 if (is_string($colnum)) { // 'colname'=>params
215 } else { // n=>params
216 if (is_array($coldef)) {
224 if (is_string($c)) // params is simple column type
225 $c = array('type'=>$c);
227 if (!isset($c['type']))
233 $c['head'] = $h; break;
234 case 'skip': // skip the column (no header)
235 unset($c['head']); // paranoid code
237 $this->columns[] = $c;
241 // Generate db query from base sql
242 // $count==false - for current page data retrieval
243 // $count==true - for total records count
245 function _sql_gen($count=false)
247 $select = $this->select;
249 $where = $this->where;
250 $group = $this->group;
251 $order = $this->order;
253 if(count($this->extra_where)) {
254 $where .= ($where=='' ? '' : ' AND ')
255 .implode( $this->extra_where, ' AND ');
257 if ($where) $where = " WHERE ($where)";
260 $group = $group == '' ? "*" : "DISTINCT $group";
262 return "SELECT COUNT($group) FROM $from $where";
265 $sql = "$select FROM $from $where";
266 if ($group) $sql.= " GROUP BY $group";
269 foreach ($this->columns as $col) {
270 if (isset($col['ord'])) {
271 if ( $col['ord'] != '' && isset($col['name'])) {
272 $ord[] = $col['name'] .' '. $col['ord'];
278 $sql .= " ORDER BY " . implode($ord, ',');
281 $sql .= " ORDER BY $order"; // original base query order
284 $page_len = $this->page_len;
285 $offset = ($this->curr_page - 1) * $page_len;
287 $sql .= " LIMIT $offset, $page_len";
293 // Initialization after changing record set
299 if ($this->ready == false ) {
300 $sql = $this->_sql_gen(true);
301 $result = db_query($sql, 'Error reading record set');
302 if ($result == false)
304 $row = db_fetch_row($result);
305 $this->rec_count = $row[0];
306 $this->max_page = ceil($this->rec_count/$this->page_len);
308 if ($go_debug) { // FIX - need column name parsing, but for now:
309 // check if field names are set explicite in col def
310 // for all initially ordered columns
311 foreach ($this->columns as $col) {
312 if (isset($col['ord']) && $col['ord'] != ''
313 && !isset($col['name'])) {
314 display_warning("Result field names must be set
315 for all intially ordered db_pager columns.");
325 // Set current page in response to user control.
327 function select_records()
331 $page = find_submit($this->name.'_page_', false);
332 $sort = find_submit($this->name.'_sort_', true);
334 $this->change_page($page);
335 if ($page == 'next' && !$this->next_page ||
336 $page == 'last' && !$this->last_page)
337 set_focus($this->name.'_page_prev');
338 if ($page == 'prev' && !$this->prev_page ||
339 $page == 'first' && !$this->first_page)
340 set_focus($this->name.'_page_next');
341 } elseif ($sort != -1) {
342 $this->sort_table($sort);
347 // Set check function to mark some rows.
349 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
351 $this->marker = $func;
352 $this->marker_txt = $notice;
353 $this->marker_class = $markercl;
354 $this->notice_class = $msgclass;
357 // Set handler to display additional row between titles and pager body.
358 // Return array of column contents.
360 function set_header($func, $headercl='inquirybg')
362 $this->header_fun = $func;
363 $this->header_class = $headercl;
366 // Set handler to display additional row between pager body and navibar.
367 // Return array of column contents.
369 function set_footer($func, $footercl='inquirybg')
371 $this->footer_fun = $func;
372 $this->footer_class = $footercl;
375 //-----------------------------------------------------------------------------
376 // Creates new db_pager $_SESSION object on first page call.
377 // Retrieves from $_SESSION var on subsequent $_POST calls
379 // $name - base name for pager controls and $_SESSION object name
380 // $sql - base sql for data inquiry. Order of fields implies
381 // pager columns order.
382 // $coldef - array of column definitions. Example definitions
383 // Column with title 'User name' and default text format:
385 // Skipped field from sql query. Data for the field is not displayed:
387 // Column without title, data retrieved form row data with function func():
388 // array('fun'=>'func')
389 // Inserted column with title 'Some', formated with function rowfun().
391 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
392 // Column with name 'Another', formatted as date,
393 // sortable with ascending start order (available orders: asc,desc, '').
394 // 'Another' => array('type'=>'date', 'ord'=>'asc')
396 // All available column format types you will find in db_pager_view.inc file.
397 // If query result has more fields than count($coldef), rest of data is ignored
398 // during display, but can be used in format handlers for 'spec' and 'insert'
401 function &new_db_pager($name, $sql, $coldef, $page_len = 0) {
403 if ($_SERVER['REQUEST_METHOD'] == 'GET')
404 unset($_SESSION[$name]); // kill old pager if any exists on first page call
406 if (!isset($_SESSION[$name])) {
407 $_SESSION[$name] =& new db_pager($sql, $name, $page_len);
408 $_SESSION[$name]->set_sql($sql);
409 $_SESSION[$name]->set_columns($coldef);
412 $ret = &$_SESSION[$name];
417 // Force pager initialization.
419 function refresh_pager($name)
421 if (isset($_SESSION[$name]))
422 $_SESSION[$name]->ready = false;