Merged changes form stable branch up to 2.3.13
[fa-stable.git] / includes / current_user.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 include_once($path_to_root . "/includes/prefs/userprefs.inc");
14 if (!defined('TB_PREF')) {
15         define('TB_PREF', '&TB_PREF&');
16 }
17 //--------------------------------------------------------------------------
18
19 class current_user
20 {
21         var $user = 0;
22         var $loginname;
23         var $username;
24         var $name;
25         var $company; // user's company
26         var $pos;
27         var $access;
28         var $timeout;
29         var $last_act;
30         var $role_set = false;
31         var $old_db;
32         var $logged;
33         var $ui_mode = 0;
34         
35         var $prefs;
36         var $cur_con; // current db connection (can be different from $company for superuser)
37
38         function current_user()
39         {
40                 global $def_coy;
41                 
42                 $this->loginname = $this->username = $this->name = "";
43                 $this->company = isset($def_coy)? $def_coy : 0;
44                 $this->logged = false;
45
46                 $this->prefs = new user_prefs();
47         }
48
49         function logged_in()
50         {
51                 return $this->logged;
52         }
53
54         function set_company($company)
55         {
56                 $this->company = $company;
57         }
58
59         function login($company, $loginname, $password)
60         {
61                 global $security_areas, $security_groups, $security_headings, $path_to_root, $dflt_lang, $login_delay;
62
63                 $this->set_company($company);
64             $this->logged = false;
65
66                 set_global_connection($company);
67                 $lang = &$_SESSION['language'];
68                 $lang->set_language($_SESSION['language']->code);
69                 db_set_encoding($_SESSION['language']->encoding);
70
71                 // Use external authentication source if any.
72                 // Keep in mind you need to have user data set for $loginname
73                 // in FA users table anyway to successfully log in.
74                 $Auth_Result = hook_authenticate($loginname, $password);
75
76                 if (!isset($Auth_Result))       // if not used: standard method
77                         $Auth_Result = get_user_auth($loginname, md5($password));
78
79                 if ($login_delay > 0)
80                         write_login_filelog($loginname, $Auth_Result);
81
82                 if ($Auth_Result)
83                 {
84                         $myrow = get_user_by_login($loginname);
85                         if ($myrow['language'] != $dflt_lang)
86                         {        // refresh language and user data
87                                 $lang->set_language($myrow['language']);
88                                 db_set_encoding($_SESSION['language']->encoding);
89                                 $myrow = get_user_by_login($loginname);
90                         }
91
92                         $this->old_db = isset($myrow["full_access"]);
93                         if (! @$myrow["inactive"]) {
94                                 if ($this->old_db) { 
95                                         // Transition code:
96                                         // db was not yet upgraded after source update to v.2.2
97                                         // give enough access for admin user to continue upgrade
98                                         if (!isset($security_groups) || !isset($security_headings)) {
99                                                 echo "<center><br><br><font size='5' color='red'><b>";
100                                                 echo _('Before software upgrade you have to include old $security_groups and $security_headings arrays from old config.php file to the new one.');
101                                                 echo '<br>'."<a href=$path_to_root/index.php>"._("Back")."</a>";
102                                                 echo "</b></font><br><br></center>";
103                                                 exit;
104                                         }
105                             $this->access = $myrow["full_access"];
106                             if (in_array(20, $security_groups[$this->access]))
107                                                 // temporary access for admin users
108                                                 $this->role_set[] = $security_areas['SA_SOFTWAREUPGRADE'][0];
109                                         else {
110                                                 echo "<center><br><br><font size='5' color='red'><b>";
111                                                 echo _('System is available for site admin only until full database upgrade');
112                                                 echo "</b></font><br><br></center>";
113                                                 exit;
114                                         }
115                         } else {
116                                         $this->role_set = array();
117                             $this->access = $myrow["role_id"];
118                                         // store area codes available for current user role
119                                         $role = get_security_role($this->access);
120                                         if (!$role) 
121                                                 return false;
122                                         foreach( $role['areas'] as $code )
123                                                 // filter only area codes for enabled security sections
124                                                 if (in_array($code&~0xff, $role['sections'])) 
125                                                         $this->role_set[] = $code;
126                         }
127                     $this->name = $myrow["real_name"];
128                     $this->pos = $myrow["pos"];
129                     $this->loginname = $loginname;
130                     $this->username = $this->loginname;
131                     $this->prefs = new user_prefs($myrow);
132                     $this->user = @$myrow["id"];
133                         update_user_visitdate($this->username);
134                         $this->logged = true;
135                                 $this->last_act = time();
136                                 $this->timeout = session_timeout();
137                         }
138                 }
139                 return $this->logged;
140         }
141
142         function check_user_access()
143         {
144                 global $security_groups;
145                 if ($this->old_db) {
146                         // notification after upgrade from pre-2.2 version
147                         return isset($security_groups) && is_array(@$security_groups[$this->access]);
148                 } else
149                         return !isset($security_groups) && is_array($this->role_set);
150         }
151
152         function can_access($sec_area)
153         {
154                 global $security_groups, $security_areas;
155                 if (isset($security_groups)) {
156                         return is_admin_company() &&
157                                 in_array(20, $security_groups[$this->access]);
158                 }
159
160                 if ($sec_area === 'SA_OPEN') 
161                         return true;
162                 if ($sec_area === 'SA_DENIED' || $sec_area === '') 
163                         return false;
164
165                 $code = $security_areas[$sec_area][0];
166
167                 // only first registered company has site admin privileges
168                 return $code && in_array($code, $this->role_set)
169                         && ($this->company == 0 || (($code&~0xff) != SS_SADMIN));
170         }
171
172         function can_access_page($page_level)
173         {
174                 return $this->can_access($page_level);
175         }
176
177         function check_application_access($waapp)
178         {
179                 if (!$this->hide_inaccessible_menu_items())
180                 {
181                         return true;
182                 }
183
184                 foreach ($waapp->modules as $module)
185                 {
186                         if ($this->check_module_access($module))
187                         {
188                                 return true;
189                         }
190                 }
191
192                 return false;
193
194         }
195
196         function check_module_access($module)
197         {
198
199                 if (!$this->hide_inaccessible_menu_items())
200                 {
201                         return true;
202                 }
203
204                 if (sizeof($module->lappfunctions) > 0)
205                 {
206                         foreach ($module->lappfunctions as $appfunction)
207                         {
208                                 if ($appfunction->label != "" && $this->can_access_page($appfunction->access))
209                                 {
210                                         return true;
211                                 }
212                         }
213                 }
214
215                 if (sizeof($module->rappfunctions) > 0)
216                 {
217                         foreach ($module->rappfunctions as $appfunction)
218                         {
219                                 if ($appfunction->label != "" && $this->can_access_page($appfunction->access))
220                                 {
221                                         return true;
222                                 }
223                         }
224                 }
225
226                 return false;
227
228         }
229
230         function hide_inaccessible_menu_items()
231         {
232                 global $hide_inaccessible_menu_items;
233
234                 if (!isset($hide_inaccessible_menu_items) || $hide_inaccessible_menu_items == 0)
235                 {
236                         return false;
237                 }
238
239                 else
240                 {
241                         return true;
242                 }
243         }
244
245         function set_db_connection($id = -1)
246         {
247                 return set_global_connection($id);
248         }
249
250         function update_prefs($prefs)
251         {
252                 global $allow_demo_mode;
253                 
254                 if(!$allow_demo_mode) {
255                         update_user_prefs($this->user, $prefs);
256                 }
257
258                 $this->prefs = new user_prefs(get_user($this->user));
259         }
260 }
261
262 //--------------------------------------------------------------------------
263
264 function round2($number, $decimals=0)
265 {
266         $delta = ($number < 0 ? -.0000000001 : .0000000001);
267         return round($number+$delta, $decimals);
268 }
269
270 /*
271         Returns number formatted according to user setup and using $decimals digits after dot 
272         (defualt is 0). When $decimals is set to 'max' maximum available precision is used 
273         (decimals depend on value) and trailing zeros are trimmed.
274 */
275 function number_format2($number, $decimals=0)
276 {
277         global $thoseps, $decseps;
278         $tsep = $thoseps[$_SESSION["wa_current_user"]->prefs->tho_sep()];
279         $dsep = $decseps[$_SESSION["wa_current_user"]->prefs->dec_sep()];
280         //return number_format($number, $decimals, $dsep,       $tsep);
281         if($decimals==='max')
282                 $dec = 15 - floor(log10(abs($number)));
283         else {
284                 $delta = ($number < 0 ? -.0000000001 : .0000000001);
285                 $number += $delta;
286                 $dec = $decimals;
287         }
288
289         $num = number_format($number, $dec, $dsep, $tsep);
290
291         return $decimals==='max' ? rtrim($num, '0') : $num;
292
293 }
294
295 /* price/float comparision helper to be used in any suspicious place for zero values? 
296 usage:
297 if (!floatcmp($value1, $value2)) 
298         compare value is 0
299 */
300
301 define('FLOAT_COMP_DELTA', 0.004);
302
303 function floatcmp($a, $b)
304 {
305     return $a - $b > FLOAT_COMP_DELTA ? 1 : ($b - $a > FLOAT_COMP_DELTA ? -1 : 0);
306 }
307
308 //
309 //      Current ui mode.
310 //
311 function fallback_mode() {
312     return $_SESSION["wa_current_user"]->ui_mode==0;
313 }
314
315 function price_format($number) {
316     return number_format2($number,
317         $_SESSION["wa_current_user"]->prefs->price_dec());
318 }
319
320 function price_decimal_format($number, &$dec)
321 {
322         $dec = user_price_dec();
323         $str = strval($number);
324         $pos = strpos($str, '.');
325         if ($pos !== false)
326         {
327                 $len = strlen(substr($str, $pos + 1));
328                 if ($len > $dec)
329                         $dec = $len;
330         }
331         return number_format2($number, $dec);
332 }
333 // function money_format doesn't exist in OS Win.
334 if (!function_exists('money_format'))
335 {
336         function money_format($format, $number) 
337         {
338                 return price_format($number);
339         } 
340 }       
341
342 // 2008-06-15. Added extra parameter $stock_id and reference for $dec
343 //--------------------------------------------------------------------
344 function qty_format($number, $stock_id=null, &$dec) {
345         $dec = get_qty_dec($stock_id);
346     return number_format2($number, $dec);
347 }
348
349 // and get_qty_dec
350 function get_qty_dec($stock_id=null)
351 {
352         global $path_to_root;
353         include_once($path_to_root."/inventory/includes/db/items_units_db.inc");
354         if ($stock_id != null)
355                 $dec = get_unit_dec($stock_id);
356         if ($stock_id == null || $dec == -1 || $dec == null)
357                 $dec = $_SESSION["wa_current_user"]->prefs->qty_dec();
358         return $dec;
359 }
360 //-------------------------------------------------------------------
361 //
362 //      Maximum precision format. Strips trailing unsignificant digits.
363 //
364 function maxprec_format($number) {
365     return number_format2($number, 'max');
366 }
367
368 function exrate_format($number) {
369     return number_format2($number,
370         $_SESSION["wa_current_user"]->prefs->exrate_dec());
371 }
372
373 function percent_format($number) {
374     return number_format2($number,
375         $_SESSION["wa_current_user"]->prefs->percent_dec());
376 }
377
378 function user_numeric($input) {
379     global $decseps, $thoseps;
380
381     $num = trim($input);
382     $sep = $thoseps[user_tho_sep()];
383     if ($sep!='')
384         $num = str_replace( $sep, '', $num);
385
386     $sep = $decseps[user_dec_sep()];
387     if ($sep!='.')
388         $num = str_replace( $sep, '.', $num);
389
390     if (!is_numeric($num))
391           return false;
392     $num = (float)$num;
393     if ($num == (int)$num)
394           return (int)$num;
395     else
396           return $num;
397 }
398
399 function user_company()
400 {
401         global $def_coy;
402         
403         return isset($_SESSION["wa_current_user"]) ? $_SESSION["wa_current_user"]->company : $def_coy;
404 }
405
406 function user_pos()
407 {
408         return $_SESSION["wa_current_user"]->pos;
409 }
410
411 function user_language()
412 {
413         return $_SESSION["wa_current_user"]->prefs->language();
414 }
415
416 function user_qty_dec()
417 {
418         return $_SESSION["wa_current_user"]->prefs->qty_dec();
419 }
420
421 function user_price_dec()
422 {
423         return $_SESSION["wa_current_user"]->prefs->price_dec();
424 }
425
426 function user_exrate_dec()
427 {
428         return $_SESSION["wa_current_user"]->prefs->exrate_dec();
429 }
430
431 function user_percent_dec()
432 {
433         return $_SESSION["wa_current_user"]->prefs->percent_dec();
434 }
435
436 function user_show_gl_info()
437 {
438         return $_SESSION["wa_current_user"]->prefs->show_gl_info();
439 }
440
441 function user_show_codes()
442 {
443         return $_SESSION["wa_current_user"]->prefs->show_codes();
444 }
445
446 function user_date_format()
447 {
448         return $_SESSION["wa_current_user"]->prefs->date_format();
449 }
450
451 function user_date_display()
452 {
453         return $_SESSION["wa_current_user"]->prefs->date_display();
454 }
455
456 function user_date_sep()
457 {
458         return $_SESSION["wa_current_user"]->prefs->date_sep();
459 }
460
461 function user_tho_sep()
462 {
463         return $_SESSION["wa_current_user"]->prefs->tho_sep();
464 }
465
466 function user_dec_sep()
467 {
468         return $_SESSION["wa_current_user"]->prefs->dec_sep();
469 }
470
471 function user_theme()
472 {
473         return isset($_SESSION["wa_current_user"]) ?
474                 $_SESSION["wa_current_user"]->prefs->get_theme() : 'default';
475 }
476
477 function user_pagesize()
478 {
479         return $_SESSION["wa_current_user"]->prefs->get_pagesize();
480 }
481
482 function user_hints()
483 {
484         return $_SESSION["wa_current_user"]->prefs->show_hints();
485 }
486
487 function user_print_profile()
488 {
489         return $_SESSION["wa_current_user"]->prefs->print_profile();
490 }
491
492 function user_rep_popup()
493 {
494         return $_SESSION["wa_current_user"]->prefs->rep_popup();
495 }
496
497 function user_query_size()
498 {
499         return $_SESSION["wa_current_user"]->prefs->query_size();
500 }
501
502 function user_graphic_links()
503 {
504         return $_SESSION["wa_current_user"]->prefs->graphic_links();
505 }
506
507 function sticky_doc_date()
508 {
509         return $_SESSION["wa_current_user"]->prefs->sticky_date();
510 }
511
512 function user_startup_tab()
513 {
514         return $_SESSION["wa_current_user"]->prefs->start_up_tab();
515 }
516
517 function user_transaction_days()
518 {
519     return $_SESSION["wa_current_user"]->prefs->transaction_days();
520 }
521
522
523 function user_check_access($sec_area)
524 {
525         return $_SESSION["wa_current_user"]->can_access($sec_area);
526 }
527
528 function set_user_prefs($prefs)
529 {
530         $_SESSION["wa_current_user"]->update_prefs($prefs);
531 }
532
533 function add_user_js_data() {
534         global $path_to_root, $thoseps, $decseps, $date_system, $dateseps;
535
536         $ts = $thoseps[user_tho_sep()];
537         $ds = $decseps[user_dec_sep()];
538
539     $js = "\n"
540           . "var user = {\n"
541           . "theme: '". $path_to_root . '/themes/'. user_theme().'/'."',\n"
542           . "loadtxt: '"._('Requesting data...')."',\n"
543           . "date: '".Today()."',\n"    // server date
544           . "datesys: ".$date_system.",\n"
545           . "datefmt: ".user_date_format().",\n"
546           . "datesep: '".$dateseps[user_date_sep()]."',\n"
547           . "ts: '$ts',\n"
548           . "ds: '$ds',\n"
549           . "pdec : " . user_price_dec() . "}\n";
550
551   add_js_source($js);
552 }
553
554 //--------------------------------------------------------------------------
555
556 function session_timeout()
557 {
558         $tout = @get_company_pref('login_tout'); // mask warning for db ver. 2.2
559         return $tout ? $tout : ini_get('session.gc_maxlifetime');
560 }
561
562 //-----------------------------------------------------------------------------
563 //      Inserts $elements into $array at position $index.
564 //      $elements is list of any objects
565 //
566 function array_insert(&$array, $index, $elements)
567 {
568         if (!is_array($elements)) $elements = array($elements);
569
570         $head  = array_splice($array, 0, $index);
571         $array = array_merge($head, $elements, $array);
572 }
573
574 function array_remove(&$array, $index, $len=1)
575 {
576         array_splice($array, $index, $len);
577 }
578
579 function array_substitute(&$array, $index, $len, $elements)
580 {
581         array_splice($array, $index, $len);
582         array_insert($array, $index, $elements);
583 }
584
585 function array_append(&$array, $elements)
586 {
587         foreach($elements as $key => $el) {
588                 if(is_int($key))
589                         $array[] = $el;
590                 else
591                         $array[$key] = $el;
592         }
593 }
594 //
595 //      Search $needle in $haystack or in $haystack[][$valuekey]
596 //      returns $needle found or null.
597 //
598 function array_search_value($needle, $haystack, $valuekey=null)
599 {
600         foreach($haystack as $key => $value) {
601                 $val = isset($valuekey) ? @$value[$valuekey] : $value;
602                 if ($needle == $val){
603                         return $value;
604                 }
605         }
606         return null;
607 }
608 //
609 //      Search $needle in $haystack or in $haystack[][$valuekey]
610 //      returns array of keys of $haystack elements found
611 //
612 function array_search_keys($needle, $haystack, $valuekey=null)
613 {
614         $keys = array();
615         if($haystack)
616                 foreach($haystack as $key => $value) {
617                         $val = isset($valuekey) ? @$value[$valuekey] : $value;
618                         if ($needle == $val){
619                                 $keys[] = $key;
620                         }
621                 }
622         return $keys;
623 }
624 //
625 //      Find first (single) $needle in $haystack or in $haystack[][$valuekey]
626 //      returns $haystack element found or null
627 //
628 function array_search_key($needle, $haystack, $valuekey=null)
629 {
630         $keys = array_search_keys($needle, $haystack, $valuekey);
631         return @$keys[0];
632 }
633
634 function flush_dir($path, $wipe = false) 
635 {
636         $dir = opendir($path);
637         if(!$dir)
638                 return;
639
640         while(false !== ($fname = readdir($dir))) {
641                 if($fname=='.' || $fname=='..' || $fname=='CVS' || (!$wipe && $fname=='index.php')) continue;
642                 if(is_dir($path.'/'.$fname)) {
643                     flush_dir($path.'/'.$fname, $wipe);
644                     if ($wipe) @rmdir($path.'/'.$fname);
645                 } else
646                     @unlink($path.'/'.$fname);
647         }
648 }
649 /*
650         Returns current path to company private folder.
651         (Current path can change after chdir).
652 */
653 function company_path($comp=null)
654 {
655         global $path_to_root, $comp_path;
656
657         if (!isset($comp))
658                 $comp = user_company();
659
660         // if path is relative, set current path_to_root
661         return ($comp_path[0]=='.' ? $path_to_root.'/'.basename($comp_path) : $comp_path)
662                         . '/'.$comp;
663 }
664
665 function is_admin_company()
666 {
667         return $this->company == 0;
668 }
669
670 ?>