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