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