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