Fixed hidden fields output. Fields are displayed after following table end (if any).
[fa-stable.git] / includes / ui / ui_controls.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         Retrieve value of POST variable(s).
14         For $name passed as array $dflt is not used, 
15         default values can be passed as values with non-numeric keys instead.
16         If some field have user formatted numeric value, pass float default value to
17         convert automatically to POSIX.
18 */
19 function get_post($name, $dflt='')
20 {
21         if (is_array($name)) {
22                 $ret = array();
23                 foreach($name as $key => $dflt)
24                         if (!is_numeric($key)) {
25                                 $ret[$key] = is_float($dflt) ? input_num($key, $dflt) : get_post($key, $dflt);
26                         } else {
27                                 $ret[$dflt] = get_post($dflt, null);
28                         }
29                 return $ret;
30         } else
31                 return is_float($dflt) ? input_num($name, $dflt) :
32                                 ((!isset($_POST[$name]) /*|| $_POST[$name] === ''*/) ? $dflt : $_POST[$name]);
33 }
34 //---------------------------------------------------------------------------------
35 $form_nested = -1;
36
37 function start_form($multi=false, $dummy=false, $action="", $name="")
38 {
39         // $dummy - leaved for compatibility with 2.0 API
40         global $form_nested;
41
42         if (++$form_nested) return;
43
44         if ($name != "")
45                 $name = "name='$name'";
46         if ($action == "")
47                 $action = $_SERVER['PHP_SELF'];
48
49         if ($multi)
50                 echo "<form enctype='multipart/form-data' method='post' action='$action' $name>\n";
51         else
52                 echo "<form method='post' action='$action' $name>\n";
53
54 }
55
56 /*
57         Flush hidden fields buffer.
58 */
59 function output_hidden()
60 {
61         global $hidden_fields;
62
63         echo implode('', $hidden_fields);
64         $hidden_fields = array();
65 }
66 //---------------------------------------------------------------------------------
67
68 function end_form($breaks=0)
69 {
70         global $Ajax, $form_nested, $hidden_fields;
71
72         if ($form_nested-- > 0) return;
73
74         $_SESSION['csrf_token'] = hash('sha256', uniqid(mt_rand(), true));
75         if ($breaks)
76                 br($breaks);
77         hidden('_focus');
78         hidden('_modified', get_post('_modified', 0));
79         hidden('_confirmed'); // helper for final form confirmation
80         hidden('_token', $_SESSION['csrf_token']);
81
82         output_hidden();
83         echo "</form>\n";
84         $Ajax->activate('_token');
85         $Ajax->activate('_confirmed');
86 }
87
88 function check_csrf_token()
89 {
90         if ($_SESSION['csrf_token'] != @$_POST['_token'])
91         {
92                 display_error(_("Request from outside of this page is forbidden."));
93                 error_log(_("CSRF attack detected from: ").@$_SERVER['HTTP_HOST'].' ('.@$_SERVER['HTTP_REFERER'].')');
94                 return false;
95         }
96         return true;
97 }
98
99 function start_table($class=false, $extra="", $padding='2', $spacing='0')
100 {
101         echo "<center><table";
102         if ($class == TABLESTYLE_NOBORDER)
103                 echo " class='tablestyle_noborder'";
104         elseif ($class == TABLESTYLE2)
105                 echo " class='tablestyle2'";
106         elseif ($class == TABLESTYLE)
107                 echo " class='tablestyle'";
108         if ($extra != "")
109                 echo " $extra";
110         echo " cellpadding='$padding' cellspacing='$spacing'>\n";
111 }
112
113 function end_table($breaks=0)
114 {
115         echo "</table></center>\n";
116         output_hidden();
117         if ($breaks)
118                 br($breaks);
119 }
120
121 function start_outer_table($class=false, $extra="", $padding='2', $spacing='0', $br=false)
122 {
123         if ($br)
124                 br();
125         start_table($class, $extra, $padding, $spacing);
126         echo "<tr valign=top><td>\n"; // outer table
127 }
128
129 function table_section($number=1, $width=false)
130 {
131         if ($number > 1)
132         {
133                 echo "</table>\n";
134                 $width = ($width ? "width='$width'" : "");
135                 //echo "</td><td class='tableseparator' $width>\n"; // outer table
136                 echo "</td><td style='border-left:1px solid #cccccc;' $width>\n"; // outer table
137         }
138         echo "<table class='tablestyle_inner'>\n";
139 }       
140
141 function end_outer_table($breaks=0, $close_table=true)
142 {
143         if ($close_table)
144                 echo "</table>\n";
145         echo "</td></tr>\n";
146         end_table($breaks);
147 }
148 //
149 //  outer table spacer
150 //
151 function vertical_space($params='')
152 {
153         echo "</td></tr><tr><td valign=center $params>";
154 }
155
156 function meta_forward($forward_to, $params="", $timeout=0)
157 {
158     global $Ajax;
159         echo "<meta http-equiv='Refresh' content='".$timeout."; url=$forward_to?$params'>\n";
160         echo "<center><br>" . _("You should automatically be forwarded.");
161         echo " " . _("If this does not happen") . " " . "<a href='$forward_to?$params'>" . _("click here") . "</a> " . _("to continue") . ".<br><br></center>\n";
162         if ($params !='') $params = '?'.$params;
163         $Ajax->redirect($forward_to.$params);
164         exit;
165 }
166
167 //-----------------------------------------------------------------------------------
168 // Find and replace hotkey marker.
169 // if $clean == true marker is removed and clean label is returned 
170 // (for use in wiki help system), otherwise result is array of label 
171 // with underlined hotkey letter and access property string.
172 //
173 function access_string($label, $clean=false)
174 {
175         $access = '';
176         $slices = array();
177
178         if (preg_match('/(.*)&([a-zA-Z0-9])(.*)/', $label, $slices))    
179         {
180                 $label = $clean ? $slices[1].$slices[2].$slices[3] :
181                         $slices[1].'<u>'.$slices[2].'</u>'.$slices[3];
182                 $access = " accesskey='".strtoupper($slices[2])."'";
183         }
184         
185         $label = str_replace( '&&', '&', $label);
186
187         return $clean ? $label : array($label, $access);
188 }
189
190 function hyperlink_back($center=true, $no_menu=true, $type_no=0, $trans_no=0, $final=false)
191 {
192         global $path_to_root;
193
194         if ($center)
195                 echo "<center>";
196         $id = 0;        
197         if ($no_menu && $trans_no != 0)
198         {
199                 include_once($path_to_root."/admin/db/attachments_db.inc");
200                 $id = has_attachment($type_no, $trans_no);
201                 $attach = get_attachment_string($type_no, $trans_no);
202         echo $attach;
203         }
204         $width = ($id != 0 ? "30%" : "20%");    
205         start_table(false, "width='$width'");
206         start_row();
207         if ($no_menu)
208         {
209                 echo "<td align=center><a href='javascript:window.print();'>"._("Print")."</a></td>\n";
210         }       
211         echo "<td align=center><a href='javascript:goBack(".($final ? '-2' : '').");'>".($no_menu ? _("Close") : _("Back"))."</a></td>\n";
212         end_row();
213         end_table();
214         if ($center)
215                 echo "</center>";
216         echo "<br>";
217 }
218
219 function hyperlink_no_params($target, $label, $center=true)
220 {
221         $id = default_focus();
222         $pars = access_string($label);
223         if ($target == '')
224                 $target = $_SERVER['PHP_SELF'];
225         if ($center)
226                 echo "<br><center>";
227         echo "<a href='$target' id='$id' $pars[1]>$pars[0]</a>\n";
228         if ($center)
229                 echo "</center>";
230 }
231
232 function hyperlink_no_params_td($target, $label)
233 {
234         echo "<td>";
235         hyperlink_no_params($target, $label);
236         echo "</td>\n";
237 }
238
239 function viewer_link($label, $url='', $class='', $id='',  $icon=null)
240 {
241         global $path_to_root;
242         
243         if ($class != '')
244                 $class = " class='$class'";
245
246         if ($id != '')
247                 $class = " id='$id'";
248
249         if ($url != "")
250         {
251                 $pars = access_string($label);
252                 if (user_graphic_links() && $icon)
253                         $pars[0] = set_icon($icon, $pars[0]);
254 -               $preview_str = "<a target='_blank' $class $id href='$path_to_root/$url' onclick=\"javascript:openWindow(this.href,this.target); return false;\"$pars[1]>$pars[0]</a>";
255         }
256         else
257                 $preview_str = $label;
258  return $preview_str;
259 }
260
261 function menu_link($url, $label, $id=null)
262 {
263         $id = default_focus($id);
264         $pars = access_string($label);
265         return "<a href='$url' class='menu_option' id='$id' $pars[1]>$pars[0]</a>";
266 }
267
268 function submenu_option($title, $url, $id=null)
269 {
270         display_note( menu_link($url, $title, $id), 0, 1);
271 }
272
273 function submenu_view($title, $type, $number, $id=null)
274 {
275         display_note(get_trans_view_str($type, $number, $title, false, 'viewlink', $id), 0, 1);
276 }
277
278 function submenu_print($title, $type, $number, $id=null, $email=0, $extra=0)
279 {
280         display_note(print_document_link($number, $title, true, $type, false, 'printlink', $id, $email, $extra), 0, 1);
281 }
282 //-----------------------------------------------------------------------------------
283
284 function hyperlink_params($target, $label, $params, $center=true)
285 {
286         $id = default_focus();
287         
288         $pars = access_string($label);
289         if ($target == '')
290                 $target = $_SERVER['PHP_SELF'];
291         if ($center)
292                 echo "<br><center>";
293         echo "<a id='$id' href='$target?$params'$pars[1]>$pars[0]</a>\n";
294         if ($center)
295                 echo "</center>";
296 }
297
298 function hyperlink_params_td($target, $label, $params)
299 {
300         echo "<td>";
301         hyperlink_params($target, $label, $params, false);
302         echo "</td>\n";
303 }
304
305 //-----------------------------------------------------------------------------------
306
307 function hyperlink_params_separate($target, $label, $params, $center=false)
308 {
309         $id = default_focus();
310
311         $pars = access_string($label);
312         if ($center)
313                 echo "<br><center>";
314         echo "<a target='_blank' id='$id' href='$target?$params' $pars[1]>$pars[0]</a>\n";
315         if ($center)
316                 echo "</center>";
317 }
318
319 function hyperlink_params_separate_td($target, $label, $params)
320 {
321         echo "<td>";
322         hyperlink_params_separate($target, $label, $params);
323         echo "</td>\n";
324 }
325
326 //--------------------------------------------------------------------------------------------------
327
328 function alt_table_row_color(&$k, $extra_class=null)
329 {
330         $classes = $extra_class ? array($extra_class) : array();
331         if ($k == 1)
332         {
333                 array_push($classes, 'oddrow');
334                 $k = 0;
335         }
336         else
337         {
338                 array_push($classes, 'evenrow');
339                 $k++;
340         }
341         echo "<tr class='".implode(' ', $classes)."'>\n";
342 }
343
344 function table_section_title($msg, $colspan=2)
345 {
346         echo "<tr><td colspan=$colspan class='tableheader'>$msg</td></tr>\n";
347 }
348
349 function table_header($labels, $params='')
350 {
351         start_row();
352         foreach ($labels as $label)
353                 labelheader_cell($label, $params);
354         end_row();
355 }
356 //-----------------------------------------------------------------------------------
357
358 function start_row($param="")
359 {
360         if ($param != "")
361                 echo "<tr $param>\n";
362         else
363                 echo "<tr>\n";
364 }
365
366 function end_row()
367 {
368         echo "</tr>\n";
369 }
370
371 function br($num=1)
372 {
373         for ($i = 0; $i < $num; $i++)
374                 echo "<br>";
375 }
376
377 $ajax_divs = array();
378
379 function div_start($id='', $trigger=null, $non_ajax=false)
380 {
381     global $ajax_divs;
382
383         if ($non_ajax) { // div for non-ajax elements
384                 array_push($ajax_divs, array($id, null));
385                 echo "<div style='display:none' class='js_only' ".($id !='' ? "id='$id'" : '').">";
386         } else { // ajax ready div
387                 array_push($ajax_divs, array($id, $trigger===null ? $id : $trigger));
388                 echo "<div ". ($id !='' ? "id='$id'" : '').">";
389                 ob_start();
390         }
391 }
392
393 function div_end()
394 {
395     global $ajax_divs, $Ajax;
396
397     if (count($ajax_divs))
398     {
399                 $div = array_pop($ajax_divs);
400                 if ($div[1] !== null)
401                         $Ajax->addUpdate($div[1], $div[0], ob_get_flush());
402                 echo "</div>";
403     }
404 }
405
406 //-----------------------------------------------------------------------------
407 //      Tabbed area:
408 //      $name - prefix for widget internal elements:
409 //              Nth tab submit name:  {$name}_N
410 //              div id: _{$name}_div
411 //              sel (hidden) name: _{$name}_sel
412 // $tabs - array of tabs; string: tab title or array(tab_title, enabled_status)
413
414 function tabbed_content_start($name, $tabs, $dft='') {
415     global $Ajax;
416
417     $selname = '_'.$name.'_sel';
418         $div = '_'.$name.'_div';
419
420         $sel = find_submit($name.'_', false);
421         if($sel==null)
422                 $sel = get_post($selname, (string)($dft==='' ? key($tabs) : $dft));
423
424         if ($sel!==@$_POST[$selname])
425                 $Ajax->activate($name);
426
427         $_POST[$selname] = $sel;
428
429         div_start($name);
430         $str = "<ul class='ajaxtabs' rel='$div'>\n";
431         foreach($tabs as $tab_no => $tab) {
432                 
433                 $acc = access_string(is_array($tab) ? $tab[0] : $tab);
434                 $disabled = (is_array($tab) && !$tab[1])  ? 'disabled ' : '';
435                 $str .= ( "<li>"
436                         ."<button type='submit' name='{$name}_".$tab_no
437                         ."' class='".((string)$tab_no===$sel ? 'current':'ajaxbutton')."' $acc[1] $disabled>"
438                         ."<span>$acc[0]</span>"
439                         ."</button>\n"
440                         ."</li>\n" );
441         }
442
443         $str .= "</ul>\n";
444         $str .= "<div class='spaceBox'></div>\n";
445         $str .= "<input type='hidden' name='$selname' value='$sel'>\n";
446         $str .= "<div class='contentBox' id='$div'>\n";
447         echo $str;
448 }
449
450 function tabbed_content_end() {
451         echo "</div>"; // content box (don't change to div_end() unless div_start() is used above)
452         div_end(); // tabs widget
453 }
454
455 function tab_changed($name)
456 {
457         $to = find_submit("{$name}_", false);
458         if (!$to) return null;
459
460         return array('from' => $from = get_post("_{$name}_sel"),
461                 'to' => $to);
462 }
463 /*
464         Check whether tab has been just switched on
465 */
466 function tab_opened($name, $tab)
467 {
468         return (get_post('_'.$name.'_sel') != $tab) && (find_submit($name.'_', false) == $tab);
469 }
470 /*
471         Check whether tab has been just switched off
472 */
473 function tab_closed($name, $tab)
474 {
475         return (get_post('_'.$name.'_sel') == $tab) && (find_submit($name.'_', false) != $tab);
476 }
477 /*
478         Check whether tab is visible on current page
479 */
480 function tab_visible($name, $tab)
481 {
482         $new = find_submit($name.'_', false);
483         return (get_post('_'.$name.'_sel') == $tab && !$new) || $new==$tab;
484 }
485
486 /* Table editor interfaces. Key is editor type
487         0 => url of editor page
488         1 => hotkey code
489         2 => context help
490 */
491 $popup_editors = array(
492         'customer' => array('/sales/manage/customers.php?debtor_no=', 
493                 113,    _("Customers"), 900, 500),
494         'branch' => array('/sales/manage/customer_branches.php?SelectedBranch=', 
495                 114, _("Branches"), 900, 700),
496         'supplier' => array('/purchasing/manage/suppliers.php?supplier_id=', 
497                 113, _("Suppliers"), 900, 700),
498         'item' => array('/inventory/manage/items.php?stock_id=', 
499                 115, _("Items"), 800, 600)
500 );
501 /*
502         Bind editors for various selectors.
503         $type - type of editor
504         $input - name of related input field
505         $caller - optional function key code (available values F1-F12: 112-123,
506                 true: default)
507 */
508 function set_editor($type, $input, $caller=true)
509 {
510         global $path_to_root, $Editors, $popup_editors, $Pagehelp;
511
512         $key = $caller===true ? $popup_editors[$type][1] : $caller;
513
514         $Editors[$key] = array( $path_to_root . $popup_editors[$type][0], $input, 
515                 $popup_editors[$type][3], $popup_editors[$type][4]);
516         
517         $help = 'F' . ($key - 111) . ' - ';
518         $help .= $popup_editors[$type][2];
519         $Pagehelp[] = $help;
520 }
521 //------------------------------------------------------------------------------
522 // Procedures below are now obsolete. Preserved for eventual future use.
523
524 /*
525         External page call with saving current context.
526         $call - url of external page
527         $ctx - optional. name of SESSION context object or array of names of POST 
528                 variables saved on call
529 */
530 function context_call($call, $ctx='')
531 {
532         if (is_array($ctx)) 
533         {
534                 foreach($ctx as $postname)
535                 {
536                         $context[$postname] = get_post($postname);
537                 }
538         } else 
539                 $context = isset($_SESSION[$ctx]) ? $_SESSION[$ctx] : null;
540
541         array_unshift($_SESSION['Context'], array('name' => $ctx, 
542                 'ctx' => $context,
543                 'caller' => $_SERVER['PHP_SELF'],
544                 'ret' => array()));
545         meta_forward($call);
546 }
547 /*
548         Restores context after external page call and
549         returns array of data passed by external page.
550 */
551 function context_restore()
552 {
553         if ( count($_SESSION['Context'])) {
554                 if ($_SERVER['PHP_SELF'] == $_SESSION['Context'][0]['caller']) {
555                         $ctx = array_shift($_SESSION['Context']);
556                         if ($ctx) {
557                                 if (is_array($ctx['ctx'])) {
558                                         foreach($ctx['ctx'] as $name => $val) 
559                                         {
560                                                 $_POST[$name] = $val;
561                                         }
562                                 } else
563                                         if ($ctx['name']!='')
564                                                 $_SESSION[$ctx['name']] = $ctx['ctx'];
565                                 return $ctx['ret'];
566                         }
567                 }
568         }
569         return false;
570 }
571
572 /*
573         Return to caller page if the page was called from external context.
574 */
575 function context_return($ret)
576 {
577         if ( count($_SESSION['Context'])) {
578                 $ctx = &$_SESSION['Context'][0];
579                 $ctx['ret'] = $ret;
580                 meta_forward( $ctx['caller'] );
581         }
582 }
583 /*
584         Clearing context stack after page cancel.
585 */
586 function context_reset()
587 {
588         $_SESSION['Context'] = array();
589 }
590 /*
591         Context stack initialization
592 */
593 if (!isset($_SESSION['Context'])) {
594                 context_reset();
595 }
596 /*
597         Redirector for selector F4 calls.
598         $sel_editors is array of selname=>editor_page
599 */
600 function editor_redirect($sel_editors, $save_fun='') {
601         foreach ($sel_editors as $selname=>$editor)
602                 if (isset($_POST['_'.$selname.'_editor'])) {
603                         if (function_exists($save_fun))
604                                 $save_fun();
605                         unset($_POST['_'.$selname.'_editor']);
606                         context_call($editor, array_keys($_POST));
607                 }
608 }
609 /*
610         Return procedure for selector F4 calls
611 */
612 function editor_return($vars, $restore_fun='') {
613         if (function_exists($restore_fun))
614                 $restore_fun();
615
616         if ($ret = context_restore()) {
617                 foreach ($vars as $postname=>$retname)
618                         if (isset($ret[$retname])) {
619                                 $_POST[$postname] = $ret[$retname];
620                                 set_focus($postname);
621                         }
622         }
623 }
624
625 function confirm_dialog($submit, $msg) {
626         if (find_post($submit)) {
627                 display_warning($msg);
628                 br();
629                 submit_center_first('DialogConfirm', _("Proceed"), '', true);
630                 submit_center_last('DialogCancel', _("Cancel"), '', 'cancel');
631                 return 0;
632         } else
633                 return get_post('DialogConfirm', 0);
634 }
635 /*
636         Confirm dialog to be used optionally in final form checking routine.
637         Displays warning conditionally unless it was displayed
638 */
639 function display_confirmation($msg)
640 {
641         global $Ajax;
642
643         if (!get_post('_confirmed'))
644         {
645                 $_POST['_confirmed'] = 1;
646                 display_warning($msg);
647                 return false;
648         } else
649                 return true;
650 }
651 /*
652         Block menu/shortcut links during transaction procesing.
653 */
654 function page_processing($msg = false)
655 {
656         global $Ajax;
657
658         if ($msg === true)
659                 $msg = _('Entered data has not been saved yet.\nDo you want to abandon changes?');
660
661         $js = "_validate._processing=" . (
662                 $msg ? '\''.strtr($msg, array("\n"=>'\\n')) . '\';' : 'null;');
663         if (in_ajax()) {
664                 $Ajax->addScript(true, $js);
665         } else
666                 add_js_source($js);
667 }
668
669 function page_modified($status = true)
670 {
671         global $Ajax;
672
673         $js = "_validate._modified=" . ($status ? 1:0).';';
674         if (in_ajax()) {
675                 $Ajax->addScript(true, $js);
676         } else
677                 add_js_source($js);
678 }