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];
122 //_vd($this->select);
129 // Set additional constraint on record set
131 function set_where($where = null)
134 if (!is_array($where))
135 $where = array($where);
137 if (count($where) == count($this->extra_where) &&
138 !count(array_diff($this->extra_where, $where)))
141 $this->extra_where = $where;
142 $this->ready = false;
145 // Set query result page
147 function change_page($page=null)
149 $this->set_page($page);
154 // Change sort column direction
155 // in order asc->desc->none->asc
157 function sort_table($col)
161 foreach($this->columns as $id => $_col) {
162 if(!isset($_col['ord_priority'])) continue;
163 $max_priority = max($max_priority, $_col['ord_priority']);
167 $ord = $this->columns[$col]['ord'];
168 $this->columns[$col]['ord_priority'] = $max_priority+1; // set priority , higher than anything else
169 $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
170 $this->columns[$col]['ord'] = $ord;
182 $Ajax->activate("_{$this->name}_span");
183 $this->data = array();
187 if ($this->rec_count == 0) return true;
189 $sql = $this->_sql_gen(false);
191 $result = db_query($sql, 'Error browsing database: '.$sql );
194 // setting field names for subsequent queries
196 // add result field names to column defs for
197 // col value retrieve and sort purposes
198 $cnt = min(db_num_fields($result), count($this->columns));
199 for ($c = $i = 0; $c < $cnt; $c++) {
200 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
201 // if (!@($this->columns[$c]['type']=='skip'))
202 $this->columns[$c]['name']= db_field_name($result, $i);
203 if (!@($this->columns[$c]['type']=='insert'))
207 while ($row = db_fetch_assoc($result)) {
208 $this->data[] = $row;
215 // Calculates page numbers for html controls.
217 function set_page($to)
221 $page = $this->curr_page+1; break;
223 $page = $this->curr_page-1; break;
225 $page = $this->last_page; break;
227 if (is_numeric($to)) {
235 $max = $this->max_page;
238 $this->curr_page = $page;
239 $this->next_page = ($page < $max) ? $page+1 : null;
240 $this->prev_page = ($page > 1) ? ($page-1) : null;
241 $this->last_page = ($page < $max) ? $max : null;
242 $this->first_page = ($page != 1) ? 1: null;
245 // Set column definitions
246 // $flds: array( fldname1, fldname2=>type,...)
247 function set_columns($flds)
249 $this->columns = array();
250 if (!is_array($flds)) {
251 $flds = array($flds);
253 foreach ($flds as $colnum=>$coldef) {
254 if (is_string($colnum)) { // 'colname'=>params
257 } else { // n=>params
258 if (is_array($coldef)) {
266 if (is_string($c)) // params is simple column type
267 $c = array('type'=>$c);
269 if (!isset($c['type']))
274 $this->inactive_ctrl = true;
277 $c['head'] = $h; break;
278 case 'skip': // skip the column (no header)
279 unset($c['head']); break;
281 $this->columns[] = $c;
285 // Generate db query from base sql
286 // $count==false - for current page data retrieval
287 // $count==true - for total records count
289 function _sql_gen($count=false)
291 $select = $this->select;
293 $where = $this->where;
294 $group = $this->group;
295 $order = $this->order;
297 if(count($this->extra_where)) {
298 $where .= ($where=='' ? '' : ' AND ')
299 .implode(' AND ', $this->extra_where);
301 if ($where) $where = " WHERE ($where)";
304 return "SELECT COUNT(*) FROM ($this->sql) tmp_count";
306 $sql = "$select FROM $from $where";
307 if ($group) $sql.= " GROUP BY $group";
310 // sort order column by priority instead of table order.
312 foreach ($this->columns as $col) {
313 if(isset($col['ord_priority'])) {
314 $columns[$col['ord_priority']] = $col;
319 foreach ($columns as $col) {
320 if (isset($col['ord'])) {
321 if ( $col['ord'] != '' && isset($col['name'])) {
322 $ord[] = $col['name'] .' '. $col['ord'];
328 $ord = array_map('db_escape_function', $ord);
329 $sql .= " ORDER BY " . implode(',', $ord);
332 $sql .= " ORDER BY $order"; // original base query order
335 $page_len = $this->page_len;
336 $offset = ($this->curr_page - 1) * $page_len;
338 $sql .= " LIMIT $offset, $page_len";
344 // Initialization after changing record set
350 if ($this->ready == false ) {
351 $sql = $this->_sql_gen(true);
352 $result = db_query($sql, 'Error reading record set');
353 if ($result == false)
355 $row = db_fetch_row($result);
356 $this->rec_count = $row[0];
357 $this->max_page = $this->page_len ?
358 ceil($this->rec_count/$this->page_len) : 0;
360 if ($SysPrefs->go_debug) { // FIX - need column name parsing, but for now:
361 // check if field names are set explicite in col def
362 // for all initially ordered columns
363 foreach ($this->columns as $col) {
364 if (isset($col['ord']) && $col['ord'] != ''
365 && !isset($col['name'])) {
366 display_warning("Result field names must be set
367 for all initially ordered db_pager columns.");
377 // Set current page in response to user control.
379 function select_records()
383 $page = find_submit($this->name.'_page_', false);
384 $sort = find_submit($this->name.'_sort_', true);
386 $this->change_page($page);
387 if ($page == 'next' && !$this->next_page ||
388 $page == 'last' && !$this->last_page)
389 set_focus($this->name.'_page_prev');
390 if ($page == 'prev' && !$this->prev_page ||
391 $page == 'first' && !$this->first_page)
392 set_focus($this->name.'_page_next');
393 } elseif ($sort != -1) {
394 $this->sort_table($sort);
399 // Set check function to mark some rows.
401 function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
403 $this->marker = $func;
404 $this->marker_txt = $notice;
405 $this->marker_class = $markercl;
406 $this->notice_class = $msgclass;
409 // Set handler to display additional row between titles and pager body.
410 // Return array of column contents.
412 function set_header($func, $headercl='inquirybg')
414 $this->header_fun = $func;
415 $this->header_class = $headercl;
418 // Set handler to display additional row between pager body and navibar.
419 // Return array of column contents.
421 function set_footer($func, $footercl='inquirybg')
423 $this->footer_fun = $func;
424 $this->footer_class = $footercl;
427 // Setter for table editors with inactive cell control.
429 function set_inactive_ctrl($table, $key) {
430 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
433 // Helper for display inactive control cells
435 function inactive_control_cell(&$row)
437 if ($this->inactive_ctrl) {
438 // return inactive_control_cell($row[$this->inactive_ctrl['key']],
439 // $row['inactive'], $this->inactive_ctrl['table'],
440 // $this->inactive_ctrl['key']);
445 $this->key : $this->columns[0]['name']; // TODO - support for complex keys
447 $table = $this->main_tbl;
448 $name = "Inactive". $id;
449 $value = $row['inactive'] ? 1:0;
451 if (check_value('show_inactive')) {
452 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') ||
453 get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
454 update_record_status($id, !$value, $table, $key);
457 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
458 . hidden("LInact[$id]", $value, false) . '</td>';
465 //-----------------------------------------------------------------------------
466 // Creates new db_pager $_SESSION object on first page call.
467 // Retrieves from $_SESSION var on subsequent $_POST calls
469 // $name - base name for pager controls and $_SESSION object name
470 // $sql - base sql for data inquiry. Order of fields implies
471 // pager columns order.
472 // $coldef - array of column definitions. Example definitions
473 // Column with title 'User name' and default text format:
475 // Skipped field from sql query. Data for the field is not displayed:
477 // Column without title, data retrieved form row data with function func():
478 // array('fun'=>'func')
479 // Inserted column with title 'Some', formated with function rowfun().
481 // 'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
482 // Column with name 'Another', formatted as date,
483 // sortable with ascending start order (available orders: asc,desc, '').
484 // 'Another' => array('type'=>'date', 'ord'=>'asc')
486 // All available column format types you will find in db_pager_view.inc file.
487 // If query result has more fields than count($coldef), rest of data is ignored
488 // during display, but can be used in format handlers for 'spec' and 'insert'
491 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0) {
493 if (isset($_SESSION[$name]) &&
494 ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
495 unset($_SESSION[$name]); // kill pager if sql has changed
497 if (!isset($_SESSION[$name])) {
498 $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
499 $_SESSION[$name]->main_tbl = $table;
500 $_SESSION[$name]->key = $key;
501 $_SESSION[$name]->set_sql($sql);
502 $_SESSION[$name]->set_columns($coldef);
505 return $_SESSION[$name];
509 // Force pager initialization.
511 function refresh_pager($name)
513 if (isset($_SESSION[$name]))
514 $_SESSION[$name]->ready = false;