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