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