c2ae04b6ecbd15b474981232b1fee77c8dfdfc39
[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                         $group = $group == '' ? "*" : "DISTINCT $group";
292
293                         return "SELECT COUNT(*) FROM (SELECT $group FROM $from $where) tmp_count";
294                 }
295
296                 $sql = "$select FROM $from $where";
297                 if ($group) $sql.= " GROUP BY $group";
298             $ord = array();
299
300                         // sort order column by priority instead of table order.
301                         $columns = array();
302             foreach ($this->columns as $col) {
303                                         if(isset($col['ord_priority'])) {
304                                                 $columns[$col['ord_priority']] = $col;
305                                         }
306                         }
307                         krsort($columns);
308
309             foreach ($columns as $col) {
310                 if (isset($col['ord'])) {
311                         if ( $col['ord'] != '' && isset($col['name'])) {
312                             $ord[] = $col['name'] .' '. $col['ord'];
313                             }
314                         }
315             }
316                                 
317             if (count($ord)) {
318                         $ord = array_map(function_exists('mysql_real_escape_string') ? 
319                                 'mysql_real_escape_string': 'mysql_escape_string', $ord);
320                         $sql .= " ORDER BY " . implode(',', $ord);
321                 } else {
322                         if($order)
323                                 $sql .= " ORDER BY $order"; // original base query order
324                 }
325
326             $page_len = $this->page_len;
327             $offset = ($this->curr_page - 1) * $page_len;
328
329             $sql .= " LIMIT $offset, $page_len";
330
331                 return $sql;
332                 
333         }
334         //
335         //      Initialization after changing record set
336         //
337         function _init() 
338         {
339                 global $go_debug;
340                 
341             if ($this->ready == false ) {
342                         $sql = $this->_sql_gen(true);
343                         $result = db_query($sql, 'Error reading record set');
344                         if ($result == false) 
345                                 return false;
346                         $row = db_fetch_row($result);
347                         $this->rec_count = $row[0];
348                         $this->max_page = $this->page_len ?
349                                 ceil($this->rec_count/$this->page_len) : 0;
350                 
351                         if ($go_debug) { // FIX - need column name parsing, but for now:
352                                 // check if field names are set explicite in col def
353                                 // for all initially ordered columns
354                             foreach ($this->columns as $col) {
355                                 if (isset($col['ord']) && $col['ord'] != '' 
356                                                 &&  !isset($col['name'])) {
357                                                         display_warning("Result field names must be set
358                                                                 for all intially ordered db_pager columns.");
359                                 }
360                                 }
361                 }
362                         $this->set_page(1);
363                         $this->ready = true;
364             }
365         return true;
366         }
367         //
368         //      Set current page in response to user control.
369         //
370         function select_records() 
371         {
372                 global $Ajax;
373                 
374                 $page = find_submit($this->name.'_page_', false);
375                 $sort = find_submit($this->name.'_sort_', true);
376                 if ($page) {
377                         $this->change_page($page);
378                         if ($page == 'next' && !$this->next_page ||
379                                 $page == 'last' && !$this->last_page)
380                                         set_focus($this->name.'_page_prev');
381                         if ($page == 'prev' && !$this->prev_page ||
382                                 $page == 'first' && !$this->first_page)
383                                         set_focus($this->name.'_page_next');
384                 } elseif ($sort != -1) {
385                         $this->sort_table($sort);
386                 } else
387                         $this->query();
388         }
389         //
390         //      Set check function to mark some rows.
391         //      
392         function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
393         {
394                 $this->marker = $func;
395                 $this->marker_txt = $notice;
396                 $this->marker_class = $markercl;
397                 $this->notice_class = $msgclass;
398         }
399         //
400         //      Set handler to display additional row between titles and pager body.
401         //      Return array of column contents.
402         //
403         function set_header($func, $headercl='inquirybg')
404         {
405                 $this->header_fun = $func;
406                 $this->header_class = $headercl;
407         }
408         //
409         //      Set handler to display additional row between pager body and navibar.
410         //      Return array of column contents.
411         //
412         function set_footer($func, $footercl='inquirybg')
413         {
414                 $this->footer_fun = $func;
415                 $this->footer_class = $footercl;
416         }
417         //
418         //      Setter for table editors with inactive cell control.
419         //
420         function set_inactive_ctrl($table, $key) {
421                 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
422         }
423         //
424         //      Helper for display inactive control cells
425         //
426         function inactive_control_cell(&$row)
427         {
428                 if ($this->inactive_ctrl) {
429 //                      return inactive_control_cell($row[$this->inactive_ctrl['key']],
430 //                               $row['inactive'], $this->inactive_ctrl['table'], 
431 //                               $this->inactive_ctrl['key']);
432                                  
433                         global  $Ajax;
434
435                         $key = $this->key ?
436                                 $this->key : $this->columns[0]['name'];         // TODO - support for complex keys
437                         $id = $row[$key];
438                         $table = $this->main_tbl;
439                         $name = "Inactive". $id;
440                         $value = $row['inactive'] ? 1:0;
441
442                         if (check_value('show_inactive')) {
443                                 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') || 
444                                         get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
445                                         update_record_status($id, !$value, $table, $key);
446                                         $value = !$value;
447                                 }
448                                 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
449                                 . hidden("LInact[$id]", $value, false) . '</td>';       
450                         }
451                 } else
452                         return '';
453         }
454
455 };
456 //-----------------------------------------------------------------------------
457 //      Creates new db_pager $_SESSION object on first page call.
458 //  Retrieves from $_SESSION var on subsequent $_POST calls
459 //
460 //  $name - base name for pager controls and $_SESSION object name
461 //  $sql  - base sql for data inquiry. Order of fields implies
462 //              pager columns order.
463 //      $coldef - array of column definitions. Example definitions
464 //              Column with title 'User name' and default text format:
465 //                              'User name'
466 //              Skipped field from sql query. Data for the field is not displayed:
467 //                              'dummy' => 'skip'
468 //              Column without title, data retrieved form row data with function func():
469 //                              array('fun'=>'func')
470 //              Inserted column with title 'Some', formated with function rowfun().
471 //      formated as date:
472 //                              'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
473 //              Column with name 'Another', formatted as date, 
474 // sortable with ascending start order (available orders: asc,desc, '').
475 //                              'Another' => array('type'=>'date', 'ord'=>'asc')
476 //
477 //      All available column format types you will find in db_pager_view.inc file.
478 //              If query result has more fields than count($coldef), rest of data is ignored
479 //  during display, but can be used in format handlers for 'spec' and 'insert' 
480 //      type columns.
481
482 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0)  {
483
484     if (isset($_SESSION[$name]) &&
485                  ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
486                 unset($_SESSION[$name]); // kill pager if sql has changed
487         }
488         if (!isset($_SESSION[$name])) {
489             $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
490                 $_SESSION[$name]->main_tbl = $table;
491                 $_SESSION[$name]->key = $key;
492                 $_SESSION[$name]->set_sql($sql);
493                 $_SESSION[$name]->set_columns($coldef);
494         }
495         
496         return  $_SESSION[$name];
497
498 }
499 //
500 //      Force pager initialization.
501 //
502 function refresh_pager($name)
503 {
504         if (isset($_SESSION[$name]))
505                 $_SESSION[$name]->ready = false;
506 }
507 ?>