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