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