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