Improved db_pager::set_sql to use array as well as query string.
[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             $ord = $this->columns[$col]['ord'];
147             $ord = ($ord == '') ? 'asc' : (($ord == 'asc') ? 'desc' : '');
148             $this->columns[$col]['ord'] = $ord;
149             $this->set_page(1);
150             $this->query();
151             return true;
152         }
153         //
154         // Query database
155         //
156         function query() 
157         {
158                 global $Ajax;
159
160                 $Ajax->activate("_{$this->name}_span");
161             $this->data = array();
162             if (!$this->_init()) 
163                   return false;
164
165             if ($this->rec_count == 0) return true;
166
167             $sql = $this->_sql_gen(false);
168
169             $result = db_query($sql, 'Error browsing database: '.$sql );
170
171             if ($result) {
172                 // setting field names for subsequent queries
173                         $c = 0;
174                   // add result field names to column defs for 
175                   // col value retrieve and sort purposes 
176                    $cnt = min(db_num_fields($result), count($this->columns));
177                         for ($c = $i = 0; $c < $cnt; $c++) {
178                                 if (!(isset($this->columns[$c]['insert']) && $this->columns[$c]['insert'])) {
179 //                                      if (!@($this->columns[$c]['type']=='skip'))
180                                                 $this->columns[$c]['name']= db_field_name($result, $i);
181                                         if (!@($this->columns[$c]['type']=='insert'))
182                                         $i++;
183                                         }
184                         }
185                         while ($row = db_fetch_assoc($result)) {
186                                 $this->data[] = $row;
187                         }
188                 } else 
189                   return false;
190                 return true;
191         }           
192         //
193         //      Calculates page numbers for html controls.
194         //
195         function set_page($to) 
196         {
197             switch($to) {
198                 case 'next':
199                     $page = $this->curr_page+1; break;
200                 case 'prev':
201                     $page = $this->curr_page-1; break;
202                 case 'last':
203                     $page = $this->last_page; break;
204                 default:
205                     if (is_numeric($to)) {
206                          $page = $to; break;
207                     }
208                 case 'first':
209                     $page = 1; break;
210             }
211           if ($page < 1) 
212             $page = 1;
213           $max = $this->max_page;
214           if ($page > $max) 
215             $page = $max;
216           $this->curr_page = $page;
217           $this->next_page = ($page < $max) ? $page+1 : null;
218           $this->prev_page = ($page > 1) ? ($page-1) : null;
219           $this->last_page = ($page < $max) ? $max : null;
220           $this->first_page = ($page != 1) ? 1: null;
221         }
222         //
223         //      Set column definitions
224         //  $flds: array( fldname1, fldname2=>type,...)
225         function set_columns($flds)
226         {
227                 $this->columns = array();
228                 if (!is_array($flds)) {
229                         $flds = array($flds);
230                 }
231                 foreach ($flds as $colnum=>$coldef) {
232                         if (is_string($colnum)) {       // 'colname'=>params
233                           $h = $colnum;
234                           $c = $coldef;
235                         } else {                        //  n=>params
236                                 if (is_array($coldef)) {
237                                         $h = '';
238                                         $c = $coldef;
239                                 } else {
240                                         $h = $coldef;
241                                         $c = 'text';
242                                 }
243                         }
244                         if (is_string($c))                      // params is simple column type
245                           $c = array('type'=>$c);
246
247                         if (!isset($c['type']))
248                           $c['type'] = 'text';
249
250                         switch($c['type']) {
251                                 case 'inactive': 
252                                         $this->inactive_ctrl = true;
253                                 case 'insert':
254                                 default:
255                                         $c['head'] = $h; break;
256                                 case 'skip':            // skip the column (no header)
257                                         unset($c['head']); break;
258                         }
259                         $this->columns[] = $c;  
260                 }
261         }
262         //
263         // Generate db query from base sql
264         // $count==false - for current page data retrieval 
265         // $count==true  - for total records count
266         //
267         function _sql_gen($count=false) 
268         {
269                 $select = $this->select;
270                 $from = $this->from;
271                 $where = $this->where;
272                 $group = $this->group;
273                 $order = $this->order;
274
275                 if(count($this->extra_where)) {
276                     $where .= ($where=='' ? '' : ' AND ')
277                                 .implode(' AND ', $this->extra_where);
278                 }
279                 if ($where) $where = " WHERE ($where)";
280
281                 if ($count) {
282                         $group = $group == '' ? "*" : "DISTINCT $group";
283
284                         return "SELECT COUNT($group) FROM $from $where";
285                 }
286
287                 $sql = "$select FROM $from $where";
288                 if ($group) $sql.= " GROUP BY $group";
289             $ord = array();
290
291             foreach ($this->columns as $col) {
292                 if (isset($col['ord'])) {
293                         if ( $col['ord'] != '' && isset($col['name'])) {
294                             $ord[] = $col['name'] .' '. $col['ord'];
295                             }
296                         }
297             }
298                                 
299             if (count($ord)) {
300                         $ord = array_map(function_exists('mysql_real_escape_string') ? 
301                                 'mysql_real_escape_string': 'mysql_escape_string', $ord);
302                         $sql .= " ORDER BY " . implode(',', $ord);
303                 } else {
304                         if($order)
305                                 $sql .= " ORDER BY $order"; // original base query order
306                 }
307
308             $page_len = $this->page_len;
309             $offset = ($this->curr_page - 1) * $page_len;
310
311             $sql .= " LIMIT $offset, $page_len";
312
313                 return $sql;
314                 
315         }
316         //
317         //      Initialization after changing record set
318         //
319         function _init() 
320         {
321                 global $go_debug;
322                 
323             if ($this->ready == false ) {
324                         $sql = $this->_sql_gen(true);
325                         $result = db_query($sql, 'Error reading record set');
326                         if ($result == false) 
327                                 return false;
328                         $row = db_fetch_row($result);
329                         $this->rec_count = $row[0];
330                         $this->max_page = $this->page_len ?
331                                 ceil($this->rec_count/$this->page_len) : 0;
332                 
333                         if ($go_debug) { // FIX - need column name parsing, but for now:
334                                 // check if field names are set explicite in col def
335                                 // for all initially ordered columns
336                             foreach ($this->columns as $col) {
337                                 if (isset($col['ord']) && $col['ord'] != '' 
338                                                 &&  !isset($col['name'])) {
339                                                         display_warning("Result field names must be set
340                                                                 for all intially ordered db_pager columns.");
341                                 }
342                                 }
343                 }
344                         $this->set_page(1);
345                         $this->ready = true;
346             }
347         return true;
348         }
349         //
350         //      Set current page in response to user control.
351         //
352         function select_records() 
353         {
354                 global $Ajax;
355                 
356                 $page = find_submit($this->name.'_page_', false);
357                 $sort = find_submit($this->name.'_sort_', true);
358                 if ($page) {
359                         $this->change_page($page);
360                         if ($page == 'next' && !$this->next_page ||
361                                 $page == 'last' && !$this->last_page)
362                                         set_focus($this->name.'_page_prev');
363                         if ($page == 'prev' && !$this->prev_page ||
364                                 $page == 'first' && !$this->first_page)
365                                         set_focus($this->name.'_page_next');
366                 } elseif ($sort != -1) {
367                         $this->sort_table($sort);
368                 } else
369                         $this->query();
370         }
371         //
372         //      Set check function to mark some rows.
373         //      
374         function set_marker($func, $notice='', $markercl='overduebg', $msgclass='overduefg' )
375         {
376                 $this->marker = $func;
377                 $this->marker_txt = $notice;
378                 $this->marker_class = $markercl;
379                 $this->notice_class = $msgclass;
380         }
381         //
382         //      Set handler to display additional row between titles and pager body.
383         //      Return array of column contents.
384         //
385         function set_header($func, $headercl='inquirybg')
386         {
387                 $this->header_fun = $func;
388                 $this->header_class = $headercl;
389         }
390         //
391         //      Set handler to display additional row between pager body and navibar.
392         //      Return array of column contents.
393         //
394         function set_footer($func, $footercl='inquirybg')
395         {
396                 $this->footer_fun = $func;
397                 $this->footer_class = $footercl;
398         }
399         //
400         //      Setter for table editors with inactive cell control.
401         //
402         function set_inactive_ctrl($table, $key) {
403                 $this->inactive_ctrl = array('table'=>$table, 'key'=>$key);
404         }
405         //
406         //      Helper for display inactive control cells
407         //
408         function inactive_control_cell(&$row)
409         {
410                 if ($this->inactive_ctrl) {
411 //                      return inactive_control_cell($row[$this->inactive_ctrl['key']],
412 //                               $row['inactive'], $this->inactive_ctrl['table'], 
413 //                               $this->inactive_ctrl['key']);
414                                  
415                         global  $Ajax;
416
417                         $key = $this->key ?
418                                 $this->key : $this->columns[0]['name'];         // TODO - support for complex keys
419                         $id = $row[$key];
420                         $table = $this->main_tbl;
421                         $name = "Inactive". $id;
422                         $value = $row['inactive'] ? 1:0;
423
424                         if (check_value('show_inactive')) {
425                                 if (isset($_POST['LInact'][$id]) && (get_post('_Inactive'.$id.'_update') || 
426                                         get_post('Update')) && (check_value('Inactive'.$id) != $value)) {
427                                         update_record_status($id, !$value, $table, $key);
428                                         $value = !$value;
429                                 }
430                                 echo '<td align="center">'. checkbox(null, $name, $value, true, '')
431                                 . hidden("LInact[$id]", $value, false) . '</td>';       
432                         }
433                 } else
434                         return '';
435         }
436
437 };
438 //-----------------------------------------------------------------------------
439 //      Creates new db_pager $_SESSION object on first page call.
440 //  Retrieves from $_SESSION var on subsequent $_POST calls
441 //
442 //  $name - base name for pager controls and $_SESSION object name
443 //  $sql  - base sql for data inquiry. Order of fields implies
444 //              pager columns order.
445 //      $coldef - array of column definitions. Example definitions
446 //              Column with title 'User name' and default text format:
447 //                              'User name'
448 //              Skipped field from sql query. Data for the field is not displayed:
449 //                              'dummy' => 'skip'
450 //              Column without title, data retrieved form row data with function func():
451 //                              array('fun'=>'func')
452 //              Inserted column with title 'Some', formated with function rowfun().
453 //      formated as date:
454 //                              'Some' => array('type'=>'date, 'insert'=>true, 'fun'=>'rowfun')
455 //              Column with name 'Another', formatted as date, 
456 // sortable with ascending start order (available orders: asc,desc, '').
457 //                              'Another' => array('type'=>'date', 'ord'=>'asc')
458 //
459 //      All available column format types you will find in db_pager_view.inc file.
460 //              If query result has more fields than count($coldef), rest of data is ignored
461 //  during display, but can be used in format handlers for 'spec' and 'insert' 
462 //      type columns.
463
464 function &new_db_pager($name, $sql, $coldef, $table = null, $key = null, $page_len = 0)  {
465
466     if (isset($_SESSION[$name]) &&
467                  ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SESSION[$name]->sql != $sql)) {
468                 unset($_SESSION[$name]); // kill pager if sql has changed
469         }
470         if (!isset($_SESSION[$name])) {
471             $_SESSION[$name] = new db_pager($sql, $name, $table, $page_len);
472                 $_SESSION[$name]->main_tbl = $table;
473                 $_SESSION[$name]->key = $key;
474                 $_SESSION[$name]->set_sql($sql);
475                 $_SESSION[$name]->set_columns($coldef);
476         }
477         
478         return  $_SESSION[$name];
479
480 }
481 //
482 //      Force pager initialization.
483 //
484 function refresh_pager($name)
485 {
486         if (isset($_SESSION[$name]))
487                 $_SESSION[$name]->ready = false;
488 }
489 ?>