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