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