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