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