New files from unstable branch
[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 set_db_connection($id = -1)
157         {
158                 return set_global_connection($id);
159         }
160
161         function update_prefs($prefs)
162         {
163                 global $allow_demo_mode;
164                 
165                 if(!$allow_demo_mode) {
166                         update_user_prefs($this->user, $prefs);
167                 }
168
169                 $this->prefs = new user_prefs(get_user($this->user));
170         }
171 }
172
173 //--------------------------------------------------------------------------
174
175 function round2($number, $decimals=0)
176 {
177         $delta = ($number < 0 ? -.0000000001 : .0000000001);
178         return round($number+$delta, $decimals);
179 }
180
181 /*
182         Returns number formatted according to user setup and using $decimals digits after dot 
183         (defualt is 0). When $decimals is set to 'max' maximum available precision is used 
184         (decimals depend on value) and trailing zeros are trimmed.
185 */
186 function number_format2($number, $decimals=0)
187 {
188         global $thoseps, $decseps;
189         $tsep = $thoseps[$_SESSION["wa_current_user"]->prefs->tho_sep()];
190         $dsep = $decseps[$_SESSION["wa_current_user"]->prefs->dec_sep()];
191         //return number_format($number, $decimals, $dsep,       $tsep);
192         if($decimals==='max')
193                 $dec = 15 - floor(log10(abs($number)));
194         else {
195                 $delta = ($number < 0 ? -.0000000001 : .0000000001);
196                 $number += $delta;
197                 $dec = $decimals;
198         }
199
200         $num = number_format($number, $dec, $dsep, $tsep);
201
202         return $decimals==='max' ? rtrim($num, '0') : $num;
203
204 }
205 //
206 //      Current ui mode.
207 //
208 function fallback_mode() {
209     return $_SESSION["wa_current_user"]->ui_mode==0;
210 }
211
212 function price_format($number) {
213     return number_format2($number,
214         $_SESSION["wa_current_user"]->prefs->price_dec());
215 }
216
217 function price_decimal_format($number, &$dec)
218 {
219         $dec = user_price_dec();
220         $str = strval($number);
221         $pos = strpos($str, '.');
222         if ($pos !== false)
223         {
224                 $len = strlen(substr($str, $pos + 1));
225                 if ($len > $dec)
226                         $dec = $len;
227         }
228         return number_format2($number, $dec);
229 }
230 // function money_format doesn't exist in OS Win.
231 if (!function_exists('money_format'))
232 {
233         function money_format($format, $number) 
234         {
235                 return price_format($number);
236         } 
237 }       
238
239 // 2008-06-15. Added extra parameter $stock_id and reference for $dec
240 //--------------------------------------------------------------------
241 function qty_format($number, $stock_id=null, &$dec) {
242         $dec = get_qty_dec($stock_id);
243     return number_format2($number, $dec);
244 }
245
246 // and get_qty_dec
247 function get_qty_dec($stock_id=null)
248 {
249         global $path_to_root;
250         include_once($path_to_root."/inventory/includes/db/items_units_db.inc");
251         if ($stock_id != null)
252                 $dec = get_unit_dec($stock_id);
253         if ($stock_id == null || $dec == -1 || $dec == null)
254                 $dec = $_SESSION["wa_current_user"]->prefs->qty_dec();
255         return $dec;
256 }
257 //-------------------------------------------------------------------
258 //
259 //      Maximum precision format. Strips trailing unsignificant digits.
260 //
261 function maxprec_format($number) {
262     return number_format2($number, 'max');
263 }
264
265 function exrate_format($number) {
266     return number_format2($number,
267         $_SESSION["wa_current_user"]->prefs->exrate_dec());
268 }
269
270 function percent_format($number) {
271     return number_format2($number,
272         $_SESSION["wa_current_user"]->prefs->percent_dec());
273 }
274
275 function user_numeric($input) {
276     global $decseps, $thoseps;
277
278     $num = trim($input);
279     $sep = $thoseps[user_tho_sep()];
280     if ($sep!='')
281         $num = str_replace( $sep, '', $num);
282
283     $sep = $decseps[user_dec_sep()];
284     if ($sep!='.')
285         $num = str_replace( $sep, '.', $num);
286
287     if (!is_numeric($num))
288           return false;
289     $num = (float)$num;
290     if ($num == (int)$num)
291           return (int)$num;
292     else
293           return $num;
294 }
295
296 function user_company()
297 {
298         global $def_coy;
299         
300         return isset($_SESSION["wa_current_user"]) ? $_SESSION["wa_current_user"]->company : $def_coy;
301 }
302
303 function user_pos()
304 {
305         return $_SESSION["wa_current_user"]->pos;
306 }
307
308 function user_language()
309 {
310         return $_SESSION["wa_current_user"]->prefs->language();
311 }
312
313 function user_qty_dec()
314 {
315         return $_SESSION["wa_current_user"]->prefs->qty_dec();
316 }
317
318 function user_price_dec()
319 {
320         return $_SESSION["wa_current_user"]->prefs->price_dec();
321 }
322
323 function user_exrate_dec()
324 {
325         return $_SESSION["wa_current_user"]->prefs->exrate_dec();
326 }
327
328 function user_percent_dec()
329 {
330         return $_SESSION["wa_current_user"]->prefs->percent_dec();
331 }
332
333 function user_show_gl_info()
334 {
335         return $_SESSION["wa_current_user"]->prefs->show_gl_info();
336 }
337
338 function user_show_codes()
339 {
340         return $_SESSION["wa_current_user"]->prefs->show_codes();
341 }
342
343 function user_date_format()
344 {
345         return $_SESSION["wa_current_user"]->prefs->date_format();
346 }
347
348 function user_date_display()
349 {
350         return $_SESSION["wa_current_user"]->prefs->date_display();
351 }
352
353 function user_date_sep()
354 {
355         return $_SESSION["wa_current_user"]->prefs->date_sep();
356 }
357
358 function user_tho_sep()
359 {
360         return $_SESSION["wa_current_user"]->prefs->tho_sep();
361 }
362
363 function user_dec_sep()
364 {
365         return $_SESSION["wa_current_user"]->prefs->dec_sep();
366 }
367
368 function user_theme()
369 {
370         return isset($_SESSION["wa_current_user"]) ?
371                 $_SESSION["wa_current_user"]->prefs->get_theme() : 'default';
372 }
373
374 function user_pagesize()
375 {
376         return $_SESSION["wa_current_user"]->prefs->get_pagesize();
377 }
378
379 function user_hints()
380 {
381         return $_SESSION["wa_current_user"]->prefs->show_hints();
382 }
383
384 function user_print_profile()
385 {
386         return $_SESSION["wa_current_user"]->prefs->print_profile();
387 }
388
389 function user_rep_popup()
390 {
391         return $_SESSION["wa_current_user"]->prefs->rep_popup();
392 }
393
394 function user_query_size()
395 {
396         return $_SESSION["wa_current_user"]->prefs->query_size();
397 }
398
399 function user_graphic_links()
400 {
401         return $_SESSION["wa_current_user"]->prefs->graphic_links();
402 }
403
404 function sticky_doc_date()
405 {
406         return $_SESSION["wa_current_user"]->prefs->sticky_date();
407 }
408
409 function user_startup_tab()
410 {
411         return $_SESSION["wa_current_user"]->prefs->start_up_tab();
412 }
413
414 function set_user_prefs($prefs)
415 {
416         $_SESSION["wa_current_user"]->update_prefs($prefs);
417 }
418
419 function add_user_js_data() {
420         global $path_to_root, $thoseps, $decseps, $date_system, $dateseps;
421
422         $ts = $thoseps[user_tho_sep()];
423         $ds = $decseps[user_dec_sep()];
424
425     $js = "\n"
426           . "var user = {\n"
427           . "theme: '". $path_to_root . '/themes/'. user_theme().'/'."',\n"
428           . "loadtxt: '"._('Requesting data...')."',\n"
429           . "date: '".Today()."',\n"    // server date
430           . "datesys: ".$date_system.",\n"
431           . "datefmt: ".user_date_format().",\n"
432           . "datesep: '".$dateseps[user_date_sep()]."',\n"
433           . "ts: '$ts',\n"
434           . "ds: '$ds',\n"
435           . "pdec : " . user_price_dec() . "}\n";
436
437   add_js_source($js);
438 }
439
440 //--------------------------------------------------------------------------
441
442 function session_timeout()
443 {
444         $tout = @get_company_pref('login_tout'); // mask warning for db ver. 2.2
445         return $tout ? $tout : ini_get('session.gc_maxlifetime');
446 }
447
448 //-----------------------------------------------------------------------------
449 //      Inserts $elements into $array at position $index.
450 //      $elements is list of any objects
451 //
452 function array_insert(&$array, $index, $elements)
453 {
454         if (!is_array($elements)) $elements = array($elements);
455
456         $head  = array_splice($array, 0, $index);
457         $array = array_merge($head, $elements, $array);
458 }
459
460 function array_remove(&$array, $index, $len=1)
461 {
462         array_splice($array, $index, $len);
463 }
464
465 function array_substitute(&$array, $index, $len, $elements)
466 {
467         array_splice($array, $index, $len);
468         array_insert($array, $index, $elements);
469 }
470
471 function array_append(&$array, $elements)
472 {
473         foreach($elements as $key => $el) {
474                 if(is_int($key))
475                         $array[] = $el;
476                 else
477                         $array[$key] = $el;
478         }
479 }
480 //
481 //      Search $needle in $haystack or in $haystack[][$valuekey]
482 //      returns $needle found or null.
483 //
484 function array_search_value($needle, $haystack, $valuekey=null)
485 {
486         foreach($haystack as $key => $value) {
487                 $val = isset($valuekey) ? @$value[$valuekey] : $value;
488                 if ($needle == $val){
489                         return $value;
490                 }
491         }
492         return null;
493 }
494 //
495 //      Search $needle in $haystack or in $haystack[][$valuekey]
496 //      returns array of keys of $haystack elements found
497 //
498 function array_search_keys($needle, $haystack, $valuekey=null)
499 {
500         $keys = array();
501         if($haystack)
502                 foreach($haystack as $key => $value) {
503                         $val = isset($valuekey) ? @$value[$valuekey] : $value;
504                         if ($needle == $val){
505                                 $keys[] = $key;
506                         }
507                 }
508         return $keys;
509 }
510 //
511 //      Find first (single) $needle in $haystack or in $haystack[][$valuekey]
512 //      returns $haystack element found or null
513 //
514 function array_search_key($needle, $haystack, $valuekey=null)
515 {
516         $keys = array_search_keys($needle, $haystack, $valuekey);
517         return @$keys[0];
518 }
519
520 function flush_dir($path, $wipe = false) 
521 {
522         $dir = opendir($path);
523         while(false !== ($fname = readdir($dir))) {
524                 if($fname=='.' || $fname=='..' || $fname=='CVS' || (!$wipe && $fname=='index.php')) continue;
525                 if(is_dir($path.'/'.$fname)) {
526                     flush_dir($path.'/'.$fname, $wipe);
527                     if ($wipe) @rmdir($path.'/'.$fname);
528                 } else
529                     @unlink($path.'/'.$fname);
530         }
531 }
532 /*
533         Returns current path to company private folder.
534         (Current path can change after chdir).
535 */
536 function company_path($comp=null)
537 {
538         global $path_to_root, $comp_path;
539
540         if (!isset($comp))
541                 $comp = user_company();
542
543         // if path is relative, set current path_to_root
544         return ($comp_path[0]=='.' ? $path_to_root.'/'.basename($comp_path) : $comp_path)
545                         . '/'.$comp;
546 }
547
548 ?>