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