Fixed regression in db_pager.
[fa-stable.git] / includes / db_pager.inc
1 <?php
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 ***********************************************************************/
12 //
13 //      Controler part of database table pager with column sort.
14 //      To display actual html object call display_db_pager($name) inside
15 //  any form.
16 //
17 //      View definition you will find in the following file:
18 include_once($path_to_root."/includes/ui/db_pager_view.inc");
19
20 class db_pager {
21         var $sql;
22         var $name;
23         var $columns;           // column definitions (head, type, order)
24
25         var $marker;            // marker check function
26         var $marker_txt;        
27         var $marker_class;
28         var $notice_class;
29         var $width;                     // table width (default '95%')
30         var $header_fun;        // additional row between title and body
31         var $header_class;
32         var $footer_fun;
33         var $footer_class;
34         var $data = array();
35
36         var $curr_page,
37                 $max_page,
38             $last_page, 
39             $prev_page, 
40             $next_page,
41             $first_page;
42             
43         var $page_len,
44             $rec_count;
45         
46         var $select,
47                 $where,
48             $from,
49                 $group,
50                 $order;
51         var     $extra_where;
52         
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
58         
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) 
63         {
64                 $this->width = "95%";
65                 if ($page_len == 0) $page_len = user_query_size();
66                 $this->name = $name;
67                 $this->page_len = $page_len;
68                 $this->set_sql($sql);
69         }
70         //
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.
75         //  ex :
76         //  array('select' => 'SUM(quantity)', 'from' => TB_PREF."stock_moves", 'group' => 'location')
77         function set_sql($sql)
78         {
79                 if ($sql != $this->sql) {
80                     $this->sql = $sql;
81                     $this->ready = false;
82
83                                 if(is_array($sql)) {
84                                         foreach(explode(' ', 'select from where group order') as $section) {
85                                                 $this->$section = @$sql[$section];
86                                         }
87                                         $this->select = "SELECT ".$this->select;
88                                 }
89                                 else {
90                                         // parse the query
91                                                 $parts = preg_split('/\sORDER\s*BY\s/si', $sql, 2);
92                                         if(count($parts) == 2) {
93                                                 $sql = $parts[0];
94                                                 $this->order = $parts[1];
95                                         }
96                                                 $parts = preg_split('/\sGROUP\s*BY\s/si', $sql, 2);
97                                         if(count($parts) == 2) {
98                                                 $sql = $parts[0];
99                                                 $this->group = $parts[1];
100                                         }
101                                                 $parts = preg_split('/\sWHERE\s/si', $sql, 2);
102                                         if(count($parts) == 2) {
103                                                 $sql = $parts[0];
104                                                 $this->where = $parts[1];
105                                         }
106                                                 $parts = preg_split('/\sFROM\s/si', $sql, 2);
107                                         if(count($parts) == 2) {
108                                                 $sql = $parts[0];
109                                                 $this->from = $parts[1];
110                                         }
111                                         $this->select = $sql;
112                         }
113                 }
114         }
115         //
116         //      Set additional constraint on record set
117         //
118         function set_where($where = null)
119         {
120                 if ($where) {
121                 if (!is_array($where))
122                           $where = array($where);
123
124                     if (count($where) == count($this->extra_where) &&
125                                 !count(array_diff($this->extra_where, $where)))
126                                  return;
127                 }
128                 $this->extra_where = $where;
129                 $this->ready = false;
130         }
131         //
132         //      Set query result page
133         //
134         function change_page($page=null) 
135         {
136             $this->set_page($page);
137             $this->query();
138             return true;
139         }
140         //
141         //      Change sort column direction 
142         //      in order asc->desc->none->asc
143         //
144         function sort_table($col) 
145         {
146
147                         $max_priority = 0;
148                         foreach($this->columns as $id => $_col) {
149                         if(!isset($_col['ord_priority'])) continue;
150                                 $max_priority = max($max_priority, $_col['ord_priority']);
151                         };
152
153
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;
158             $this->set_page(1);
159             $this->query();
160             return true;
161         }
162         //
163         // Query database
164         //
165         function query() 
166         {
167                 global $Ajax;
168
169                 $Ajax->activate("_{$this->name}_span");
170             $this->data = array();
171             if (!$this->_init()) 
172                   return false;
173
174             if ($this->rec_count == 0) return true;
175
176             $sql = $this->_sql_gen(false);
177
178             $result = db_query($sql, 'Error browsing database: '.$sql );
179
180             if ($result) {
181                 // setting field names for subsequent queries
182                         $c = 0;
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'))
191                                         $i++;
192                                         }
193                         }
194                         while ($row = db_fetch_assoc($result)) {
195                                 $this->data[] = $row;
196                         }
197                 } else 
198                   return false;
199                 return true;
200         }           
201         //
202         //      Calculates page numbers for html controls.
203         //
204         function set_page($to) 
205         {
206             switch($to) {
207                 case 'next':
208                     $page = $this->curr_page+1; break;
209                 case 'prev':
210                     $page = $this->curr_page-1; break;
211                 case 'last':
212                     $page = $this->last_page; break;
213                 default:
214                     if (is_numeric($to)) {
215                          $page = $to; break;
216                     }
217                 case 'first':
218                     $page = 1; break;
219             }
220           if ($page < 1) 
221             $page = 1;
222           $max = $this->max_page;
223           if ($page > $max) 
224             $page = $max;
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;
230         }
231         //
232         //      Set column definitions
233         //  $flds: array( fldname1, fldname2=>type,...)
234         function set_columns($flds)
235         {
236                 $this->columns = array();
237                 if (!is_array($flds)) {
238                         $flds = array($flds);
239                 }
240                 foreach ($flds as $colnum=>$coldef) {
241                         if (is_string($colnum)) {       // 'colname'=>params
242                           $h = $colnum;
243                           $c = $coldef;
244                         } else {                        //  n=>params
245                                 if (is_array($coldef)) {
246                                         $h = '';
247                                         $c = $coldef;
248                                 } else {
249                                         $h = $coldef;
250                                         $c = 'text';
251                                 }
252                         }
253                         if (is_string($c))                      // params is simple column type
254                           $c = array('type'=>$c);
255
256                         if (!isset($c['type']))
257                           $c['type'] = 'text';
258
259                         switch($c['type']) {
260                                 case 'inactive': 
261                                         $this->inactive_ctrl = true;
262                                 case 'insert':
263                                 default:
264                                         $c['head'] = $h; break;
265                                 case 'skip':            // skip the column (no header)
266                                         unset($c['head']); break;
267                         }
268                         $this->columns[] = $c;  
269                 }
270         }
271         //
272         // Generate db query from base sql
273         // $count==false - for current page data retrieval 
274         // $count==true  - for total records count
275         //
276         function _sql_gen($count=false) 
277         {
278                 $select = $this->select;
279                 $from = $this->from;
280                 $where = $this->where;
281                 $group = $this->group;
282                 $order = $this->order;
283
284                 if(count($this->extra_where)) {
285                     $where .= ($where=='' ? '' : ' AND ')
286                                 .implode(' AND ', $this->extra_where);
287                 }
288                 if ($where) $where = " WHERE ($where)";
289
290                 if ($count)
291                         return "SELECT COUNT(*) FROM ($this->sql) tmp_count";
292
293                 $sql = "$select FROM $from $where";
294                 if ($group) $sql.= " GROUP BY $group";
295             $ord = array();
296
297                         // sort order column by priority instead of table order.
298                         $columns = array();
299             foreach ($this->columns as $col) {
300                                         if(isset($col['ord_priority'])) {
301                                                 $columns[$col['ord_priority']] = $col;
302                                         }
303                 }
304                 krsort($columns);
305
306             foreach ($columns as $col) {
307                 if (isset($col['ord'])) {
308                         if ( $col['ord'] != '' && isset($col['name'])) {
309                             $ord[] = $col['name'] .' '. $col['ord'];
310                             }
311                         }
312             }
313
314             if (count($ord)) {
315                         $ord = array_map(function_exists('mysql_real_escape_string') ? 
316                                 'mysql_real_escape_string': 'mysql_escape_string', $ord);
317                         $sql .= " ORDER BY " . implode(',', $ord);
318                 } else {
319                         if($order)
320                                 $sql .= " ORDER BY $order"; // original base query order
321                 }
322
323             $page_len = $this->page_len;
324             $offset = ($this->curr_page - 1) * $page_len;
325
326             $sql .= " LIMIT $offset, $page_len";
327
328                 return $sql;
329                 
330         }
331         //
332         //      Initialization after changing record set
333         //
334         function _init() 
335         {
336                 global $go_debug;
337                 
338             if ($this->ready == false ) {
339                         $sql = $this->_sql_gen(true);
340                         $result = db_query($sql, 'Error reading record set');
341                         if ($result == false) 
342                                 return false;
343                         $row = db_fetch_row($result);
344                         $this->rec_count = $row[0];
345                         $this->max_page = $this->page_len ?
346                                 ceil($this->rec_count/$this->page_len) : 0;
347                 
348                         if ($go_debug) { // FIX - need column name parsing, but for now:
349                                 // check if field names are set explicite in col def
350                                 // for all initially ordered columns
351                             foreach ($this->columns as $col) {
352                                 if (isset($col['ord']) && $col['ord'] != '' 
353                                                 &&  !isset($col['name'])) {
354                                                         display_warning("Result field names must be set
355                                                                 for all intially ordered db_pager columns.");
356                                 }
357                                 }
358                 }
359                         $this->set_page(1);
360                         $this->ready = true;
361             }
362         return true;
363         }
364         //
365         //      Set current page in response to user control.
366         //
367         function select_records() 
368         {
369                 global $Ajax;
370                 
371                 $page = find_submit($this->name.'_page_', false);
372                 $sort = find_submit($this->name.'_sort_', true);
373                 if ($page) {
374                         $this->change_page($page);
375                         if ($page == 'next' && !$this->next_page ||
376                                 $page == 'last' && !$this->last_page)
377                                         set_focus($this->name.'_page_prev');
378                         if ($page == 'prev' && !$this->prev_page ||
379                                 $page == 'first' && !$this->first_page)
380                                         set_focus($this->name.'_page_next');
381                 } elseif ($sort != -1) {
382                         $this->sort_table($sort);
383                 } else
384                         $this->query();
385         }
386         //
387         //      Set check function to mark some rows.
388         //      
389         function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
390         {
391                 $this->marker = $func;
392                 $this->marker_txt = $notice;
393                 $this->marker_class = $markercl;
394                 $this->notice_class = $msgclass;
395         }
396         //
397         //      Set handler to display additional row between titles and pager body.
398         //      Return array of column contents.
399         //
400         function set_header($func, $headercl='inquirybg')
401         {
402                 $this->header_fun = $func;
403                 $this->header_class = $headercl;
404         }
405         //
406         //      Set handler to display additional row between pager body and navibar.
407         //      Return array of column contents.
408         //
409         function set_footer($func, $footercl='inquirybg')
410         {
411                 $this->footer_fun = $func;
412                 $this->footer_class = $footercl;
413         }
414         //
415         //      Setter for table editors with inactive cell control.
416         //
417         function set_inactive_ctrl($table, $key) {
418                 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
419         }
420         //
421         //      Helper for display inactive control cells
422         //
423         function inactive_control_cell(&$row)
424         {
425                 if ($this->inactive_ctrl) {
426 //                      return inactive_control_cell($row[$this->inactive_ctrl['key']],
427 //                               $row['inactive'], $this->inactive_ctrl['table'], 
428 //                               $this->inactive_ctrl['key']);
429                                  
430                         global  $Ajax;
431
432                         $key = $this->key ?
433                                 $this->key : $this->columns[0]['name'];         // TODO - support for complex keys
434                         $id = $row[$key];
435                         $table = $this->main_tbl;
436                         $name = "Inactive". $id;
437                         $value = $row['inactive'] ? 1:0;
438
439                         if (check_value('show_inactive')) {
440                                 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') || 
441                                         get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
442                                         update_record_status($id, !$value, $table, $key);
443                                         $value = !$value;
444                                 }
445                                 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
446                                 . hidden("LInact[$id]", $value, false) . '</td>';       
447                         }
448                 } else
449                         return '';
450         }
451
452 };
453 //-----------------------------------------------------------------------------
454 //      Creates new db_pager $_SESSION object on first page call.
455 //  Retrieves from $_SESSION var on subsequent $_POST calls
456 //
457 //  $name - base name for pager controls and $_SESSION object name
458 //  $sql  - base sql for data inquiry. Order of fields implies
459 //              pager columns order.
460 //      $coldef - array of column definitions. Example definitions
461 //              Column with title 'User name' and default text format:
462 //                              'User name'
463 //              Skipped field from sql query. Data for the field is not displayed:
464 //                              'dummy' => 'skip'
465 //              Column without title, data retrieved form row data with function func():
466 //                              array('fun'=>'func')
467 //              Inserted column with title 'Some', formated with function rowfun().
468 //      formated as date:
469 //                              'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
470 //              Column with name 'Another', formatted as date, 
471 // sortable with ascending start order (available orders: asc,desc, '').
472 //                              'Another' => array('type'=>'date', 'ord'=>'asc')
473 //
474 //      All available column format types you will find in db_pager_view.inc file.
475 //              If query result has more fields than count($coldef), rest of data is ignored
476 //  during display, but can be used in format handlers for 'spec' and 'insert' 
477 //      type columns.
478
479 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0)  {
480
481     if (isset($_SESSION[$name]) &&
482                  ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
483                 unset($_SESSION[$name]); // kill pager if sql has changed
484         }
485         if (!isset($_SESSION[$name])) {
486             $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
487                 $_SESSION[$name]->main_tbl = $table;
488                 $_SESSION[$name]->key = $key;
489                 $_SESSION[$name]->set_sql($sql);
490                 $_SESSION[$name]->set_columns($coldef);
491         }
492         
493         return  $_SESSION[$name];
494
495 }
496 //
497 //      Force pager initialization.
498 //
499 function refresh_pager($name)
500 {
501         if (isset($_SESSION[$name]))
502                 $_SESSION[$name]->ready = false;
503 }
504 ?>