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