Fixed problem with too early SysPrefs reference.
[fa-stable.git] / includes / session.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 class SessionManager
14 {
15         function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
16         {
17                 // Set the cookie name
18                 session_name($name);
19
20                 // Set SSL level
21                 $https = isset($secure) ? $secure : (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
22
23                 // Set session cookie options
24                 if (version_compare(PHP_VERSION, '5.2', '<')) // avoid failure on older php versions
25                         session_set_cookie_params($limit, $path, $domain, $https);
26                 else
27                         session_set_cookie_params($limit, $path, $domain, $https, true);
28
29                 session_start();
30
31                 // Make sure the session hasn't expired, and destroy it if it has
32                 if ($this->validateSession())
33                 {
34                         // Check to see if the session is new or a hijacking attempt
35                         if(!$this->preventHijacking())
36                         {
37                                 // Reset session data and regenerate id
38                                 $_SESSION = array();
39                                 $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
40                                 $_SESSION['userAgent'] = @$_SERVER['HTTP_USER_AGENT'];
41                                 $this->regenerateSession();
42
43                         // Give a 5% chance of the session id changing on any request
44                         }
45                         elseif (rand(1, 100) <= 5)
46                         {
47                                 $this->regenerateSession();
48                         }
49                 }
50                 else
51                 {
52                         $_SESSION = array();
53                         session_destroy();
54                         session_start();
55                 }
56         }
57
58         function preventHijacking()
59         {
60                 if (!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
61                         return false;
62
63                 if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
64                         return false;
65
66                 if ( $_SESSION['userAgent'] != @$_SERVER['HTTP_USER_AGENT'])
67                         return false;
68
69                 return true;
70         }
71
72         function regenerateSession()
73         {
74                 // If this session is obsolete it means there already is a new id
75                 if (isset($_SESSION['OBSOLETE']) && ($_SESSION['OBSOLETE'] == true))
76                         return;
77
78                 // Set current session to expire in 10 seconds
79                 $_SESSION['OBSOLETE'] = true;
80                 $_SESSION['EXPIRES'] = time() + 10;
81
82                 // Create new session without destroying the old one
83                 session_regenerate_id();
84                 // Grab current session ID and close both sessions to allow other scripts to use them
85                 $newSession = session_id();
86                 session_write_close();
87                 // Set session ID to the new one, and start it back up again
88
89                 session_id($newSession);
90                 session_start();
91                 
92                 // Now we unset the obsolete and expiration values for the session we want to keep
93                 unset($_SESSION['OBSOLETE']);
94                 unset($_SESSION['EXPIRES']);
95         }
96
97         function validateSession()
98         {
99                 if (isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
100                         return false;
101
102                 if (isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
103                         return false;
104
105                 return true;
106         }
107 }
108
109 function output_html($text)
110 {
111         global $before_box, $Ajax, $messages;
112         // Fatal errors are not send to error_handler,
113         // so we must check the output
114         if ($text && preg_match('/\bFatal error(<.*?>)?:(.*)/i', $text, $m)) {
115                 $Ajax->aCommands = array();  // Don't update page via ajax on errors
116                 $text = preg_replace('/\bFatal error(<.*?>)?:(.*)/i','', $text);
117                 $messages[] = array(E_ERROR, $m[2], null, null);
118         }
119         $Ajax->run();
120         return  in_ajax() ? fmt_errors() : ($before_box.fmt_errors().$text);
121 }
122 //----------------------------------------------------------------------------------------
123
124 function kill_login()
125 {
126         session_unset();
127         session_destroy();
128 }
129 //----------------------------------------------------------------------------------------
130
131 function login_fail()
132 {
133         global $path_to_root;
134         
135         header("HTTP/1.1 401 Authorization Required");
136         echo "<center><br><br><font size='5' color='red'><b>" . _("Incorrect Password") . "<b></font><br><br>";
137         echo "<b>" . _("The user and password combination is not valid for the system.") . "<b><br><br>";
138
139         echo _("If you are not an authorized user, please contact your system administrator to obtain an account to enable you to use the system.");
140         echo "<br><a href='$path_to_root/index.php'>" . _("Try again") . "</a>";
141         echo "</center>";
142
143         kill_login();
144         die();
145 }
146
147 function password_reset_fail()
148 {
149         global $path_to_root;
150         
151   echo "<center><br><br><font size='5' color='red'><b>" . _("Incorrect Email") . "<b></font><br><br>";
152   echo "<b>" . _("The email address does not exist in the system.") . "<b><br><br>";
153
154   echo _("If you are not an authorized user, please contact your system administrator to obtain an account to enable you to use the system.");
155   echo "<br><a href='$path_to_root/index.php?reset=1'>" . _("Try again") . "</a>";
156   echo "</center>";
157
158         kill_login();
159         die();
160 }
161
162 function password_reset_success()
163 {
164         global $path_to_root;
165
166   echo "<center><br><br><font size='5' color='green'><b>" . _("New password sent") . "<b></font><br><br>";
167   echo "<b>" . _("A new password has been sent to your mailbox.") . "<b><br><br>";
168
169   echo "<br><a href='$path_to_root/index.php'>" . _("Login here") . "</a>";
170   echo "</center>";
171         
172         kill_login();
173         die();
174 }
175
176 function check_faillog()
177 {
178         global $SysPrefs, $login_faillog;
179
180         $user = $_SESSION["wa_current_user"]->user;
181
182         if (@$SysPrefs->login_delay && (@$login_faillog[$user][$_SERVER['REMOTE_ADDR']] >= @$SysPrefs->login_max_attempts) && (time() < $login_faillog[$user]['last'] + $SysPrefs->login_delay))
183                 return true;
184
185         return false;
186 }
187 /*
188         Simple brute force attack detection is performed before connection to company database is open. Therefore access counters have to be stored in file.
189         Login attempts counter is created for every new user IP, which partialy prevent DOS attacks.
190 */
191 function write_login_filelog($login, $result)
192 {
193         global $login_faillog, $SysPrefs, $path_to_root;
194
195         $user = $_SESSION["wa_current_user"]->user;
196
197         $ip = $_SERVER['REMOTE_ADDR'];
198
199         if (!isset($login_faillog[$user][$ip]) || $result) // init or reset on successfull login
200                 $login_faillog[$user] = array($ip => 0, 'last' => '');
201
202         if (!$result)
203         {
204                 if ($login_faillog[$user][$ip] < @$SysPrefs->login_max_attempts) {
205
206                         $login_faillog[$user][$ip]++;
207                 } else {
208                         $login_faillog[$user][$ip] = 0; // comment out to restart counter only after successfull login.
209                         error_log(sprintf(_("Brute force attack on account '%s' detected. Access for non-logged users temporarily blocked."     ), $login));
210                 }
211                 $login_faillog[$user]['last'] = time();
212         }
213
214         $msg = "<?php\n";
215         $msg .= "/*\n";
216         $msg .= "Login attempts info.\n";
217         $msg .= "*/\n";
218         $msg .= "\$login_faillog = " .var_export($login_faillog, true). ";\n";
219
220         $filename = $path_to_root."/tmp/faillog.php";
221
222         if ((!file_exists($filename) && is_writable($path_to_root.'/tmp')) || is_writable($filename))
223         {
224                 file_put_contents($filename, $msg);
225         }
226 }
227
228 //----------------------------------------------------------------------------------------
229
230 function check_page_security($page_security)
231 {
232         global $SysPrefs;
233         
234         $msg = '';
235         
236         if (!$_SESSION["wa_current_user"]->check_user_access())
237         {
238                 // notification after upgrade from pre-2.2 version
239                 $msg = $_SESSION["wa_current_user"]->old_db ?
240                          _("Security settings have not been defined for your user account.")
241                                 . "<br>" . _("Please contact your system administrator.")       
242                         : _("Please remove \$security_groups and \$security_headings arrays from config.php file!");
243         } elseif (!$_SESSION['SysPrefs']->db_ok && !$_SESSION["wa_current_user"]->can_access('SA_SOFTWAREUPGRADE')) {
244                 $msg = _('Access to application has been blocked until database upgrade is completed by system administrator.');
245         }
246         
247         if ($msg){
248                 display_error($msg);
249                 end_page(@$_REQUEST['popup']);
250                 kill_login();
251                 exit;
252         }
253
254         if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
255         {
256
257                 echo "<center><br><br><br><b>";
258                 echo _("The security settings on your account do not permit you to access this function");
259                 echo "</b>";
260                 echo "<br><br><br><br></center>";
261                 end_page(@$_REQUEST['popup']);
262                 exit;
263         }
264         if (!$_SESSION['SysPrefs']->db_ok 
265                 && !in_array($page_security, array('SA_SOFTWAREUPGRADE', 'SA_OPEN', 'SA_BACKUP')))
266         {
267                 display_error(_('System is blocked after source upgrade until database is updated on System/Software Upgrade page'));
268                 end_page();
269                 exit;
270         }
271
272 }
273 /*
274         Helper function for setting page security level depeding on 
275         GET start variable and/or some value stored in session variable.
276         Before the call $page_security should be set to default page_security value.
277 */
278 function set_page_security($value=null, $trans = array(), $gtrans = array())
279 {
280         global $page_security;
281
282         // first check is this is not start page call
283         foreach($gtrans as $key => $area)
284                 if (isset($_GET[$key])) {
285                         $page_security = $area;
286                         return;
287                 }
288
289         // then check session value
290         if (isset($trans[$value])) {
291                 $page_security = $trans[$value];
292                 return;
293         }
294 }
295
296 //-----------------------------------------------------------------------------
297 //      Removing magic quotes from nested arrays/variables
298 //
299 function strip_quotes($data)
300 {
301         if(get_magic_quotes_gpc()) {
302                 if(is_array($data)) {
303                         foreach($data as $k => $v) {
304                                 $data[$k] = strip_quotes($data[$k]);
305                         }
306                 } else
307                         return stripslashes($data);
308         }
309         return $data;
310 }
311
312 function html_cleanup(&$parms)
313 {
314         foreach($parms as $name => $value) {
315 //              $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
316                 if (is_array($value))
317                         html_cleanup($parms[$name]);
318                 else
319                         $parms[$name] = @htmlspecialchars($value, ENT_QUOTES, $_SESSION['language']->encoding=='iso-8859-2' ? 'ISO-8859-1' : $_SESSION['language']->encoding);
320         }
321         reset($parms); // needed for direct key() usage later throughout the sources
322 }
323
324 //============================================================================
325 //
326 //
327 function login_timeout()
328 {
329         // skip timeout on logout page
330         if ($_SESSION["wa_current_user"]->logged) {
331                 $tout = $_SESSION["wa_current_user"]->timeout;
332                 if ($tout && (time() > $_SESSION["wa_current_user"]->last_act + $tout))
333                 {
334                         $_SESSION["wa_current_user"]->logged = false;
335                 }
336                 $_SESSION["wa_current_user"]->last_act = time();
337         }
338 }
339 //============================================================================
340 if (!isset($path_to_root))
341 {
342         $path_to_root = ".";
343 }
344
345 // Prevent register_globals vulnerability
346 if (isset($_GET['path_to_root']) || isset($_POST['path_to_root']))
347         die("Restricted access");
348
349 include_once($path_to_root . "/includes/errors.inc");
350 // colect all error msgs
351 set_error_handler('error_handler' /*, errtypes */);
352
353 include_once($path_to_root . "/includes/current_user.inc");
354 include_once($path_to_root . "/frontaccounting.php");
355 include_once($path_to_root . "/admin/db/security_db.inc");
356 include_once($path_to_root . "/includes/lang/language.inc");
357 include_once($path_to_root . "/config_db.php");
358 include_once($path_to_root . "/includes/ajax.inc");
359 include_once($path_to_root . "/includes/ui/ui_msgs.inc");
360 include_once($path_to_root . "/includes/prefs/sysprefs.inc");
361
362 include_once($path_to_root . "/includes/hooks.inc");
363 //
364 // include all extensions hook files.
365 //
366 foreach ($installed_extensions as $ext)
367 {
368         if (file_exists($path_to_root.'/'.$ext['path'].'/hooks.php'))
369                 include_once($path_to_root.'/'.$ext['path'].'/hooks.php');
370 }
371
372 $_SESSION['SysPrefs'] = new sys_prefs();
373
374 $SysPrefs = &$_SESSION['SysPrefs'];
375
376 //----------------------------------------------------------------------------------------
377 // set to reasonable values if not set in config file (pre-2.3.12 installations)
378
379 if ((!isset($SysPrefs->login_delay)) || ($SysPrefs->login_delay < 0))
380     $SysPrefs->login_delay = 10;
381
382 if ((!isset($SysPrefs->login_max_attempts)) || ($SysPrefs->login_max_attempts < 0))
383     $SysPrefs->login_max_attempts = 3; 
384
385 if ($SysPrefs->go_debug > 0)
386         error_reporting(-1);
387 else
388         error_reporting(E_USER_WARNING|E_USER_ERROR|E_USER_NOTICE);
389 ini_set("display_errors", "On");
390
391 if ($SysPrefs->error_logfile != '') {
392         ini_set("error_log", $SysPrefs->error_logfile);
393         ini_set("ignore_repeated_errors", "On");
394         ini_set("log_errors", "On");
395 }
396
397
398 /*
399         Uncomment the setting below when using FA on shared hosting
400         to avoid unexpeced session timeouts.
401         Make sure this directory exists and is writable!
402 */
403 // ini_set('session.save_path', dirname(__FILE__).'/../tmp/');
404
405 ini_set('session.gc_maxlifetime', 36000); // 10hrs
406
407 hook_session_start(@$_POST["company_login_name"]);
408
409 $Session_manager = new SessionManager();
410 $Session_manager->sessionStart('FA'.md5(dirname(__FILE__)));
411
412 // this is to fix the "back-do-you-want-to-refresh" issue - thanx PHPFreaks
413 header("Cache-control: private");
414
415 get_text_init();
416
417 if ($SysPrefs->login_delay > 0)
418         @include_once($path_to_root . "/tmp/faillog.php");
419
420 // Page Initialisation
421 if (!isset($_SESSION['wa_current_user']) || !$_SESSION['wa_current_user']->logged_in()
422         || !isset($_SESSION['language']) || !method_exists($_SESSION['language'], 'set_language'))
423 {
424         $l = array_search_value($dflt_lang, $installed_languages,  'code');
425         $_SESSION['language'] = new language($l['name'], $l['code'], $l['encoding'],
426          (isset($l['rtl']) && $l['rtl'] === true) ? 'rtl' : 'ltr');
427 }
428
429 $_SESSION['language']->set_language($_SESSION['language']->code);
430
431
432 include_once($path_to_root . "/includes/access_levels.inc");
433 include_once($path_to_root . "/version.php");
434 include_once($path_to_root . "/includes/main.inc");
435 include_once($path_to_root . "/includes/app_entries.inc");
436
437 // Ajax communication object
438 $Ajax = new Ajax();
439
440 // js/php validation rules container
441 $Validate = array();
442 // bindings for editors
443 $Editors = array();
444 // page help. Currently help for function keys.
445 $Pagehelp = array();
446
447 $Refs = new references();
448
449 // intercept all output to destroy it in case of ajax call
450 register_shutdown_function('end_flush');
451 ob_start('output_html',0);
452
453 if (!isset($_SESSION["wa_current_user"]))
454         $_SESSION["wa_current_user"] = new current_user();
455
456 html_cleanup($_GET);
457 html_cleanup($_POST);
458 html_cleanup($_REQUEST);
459 html_cleanup($_SERVER);
460
461 // logout.php is the only page we should have always 
462 // accessable regardless of access level and current login status.
463 if (!defined('FA_LOGOUT_PHP_FILE')){
464
465         login_timeout();
466
467         if (!$_SESSION["wa_current_user"]->old_db)
468                 include_once($path_to_root . '/company/'.user_company().'/installed_extensions.php');
469
470         install_hooks();
471
472         if (!$_SESSION["wa_current_user"]->logged_in())
473         {
474       if (@$SysPrefs->allow_password_reset && !$SysPrefs->allow_demo_mode
475         && (isset($_GET['reset']) || isset($_POST['email_entry_field']))) {
476                   if (!isset($_POST["email_entry_field"])) {
477         include($path_to_root . "/access/password_reset.php");
478         exit();
479       }
480       else {
481         if (isset($_POST["company_login_nickname"]) && !isset($_POST["company_login_name"])) {
482           for ($i = 0; $i < count($db_connections); $i++) {
483             if ($db_connections[$i]["name"] == $_POST["company_login_nickname"]) {
484               $_POST["company_login_name"] = $i;
485               unset($_POST["company_login_nickname"]);
486               break 1; // cannot pass variables to break from PHP v5.4 onwards
487             }
488           }
489         }
490         $_succeed = isset($db_connections[$_POST["company_login_name"]]) &&
491           $_SESSION["wa_current_user"]->reset_password($_POST["company_login_name"],
492           $_POST["email_entry_field"]);
493         if ($_succeed)
494         {
495           password_reset_success();
496         }
497
498         password_reset_fail();
499       }
500     }
501                 // Show login screen
502                 if (!isset($_POST["user_name_entry_field"]) or $_POST["user_name_entry_field"] == "")
503                 {
504                         // strip ajax marker from uri, to force synchronous page reload
505                         $_SESSION['timeout'] = array( 'uri'=>preg_replace('/JsHttpRequest=(?:(\d+)-)?([^&]+)/s',
506                                         '', @htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, $_SESSION['language']->encoding=='iso-8859-2'
507                                                  ? 'ISO-8859-1' : $_SESSION['language']->encoding)), 
508                                 'post' => $_POST);
509
510                         include($path_to_root . "/access/login.php");
511                         if (in_ajax())
512                                 $Ajax->activate('_page_body');
513                         exit;
514                 } else {
515                         if (isset($_POST["company_login_nickname"]) && !isset($_POST["company_login_name"])) {
516                                 for ($i = 0; $i < count($db_connections); $i++) {
517                                         if ($db_connections[$i]["name"] == $_POST["company_login_nickname"]) {
518                                                 $_POST["company_login_name"] = $i;
519                                                 unset($_POST["company_login_nickname"]);
520                                                 break 1; // cannot pass variables to break from PHP v5.4 onwards
521                                         }
522                                 }
523                         }
524                         $succeed = isset($db_connections[$_POST["company_login_name"]]) &&
525                                 $_SESSION["wa_current_user"]->login($_POST["company_login_name"],
526                                 $_POST["user_name_entry_field"], $_POST["password"]);
527                         // select full vs fallback ui mode on login
528                         $_SESSION["wa_current_user"]->ui_mode = $_POST['ui_mode'];
529                         if (!$succeed)
530                         {
531                         // Incorrect password
532                                 login_fail();
533                         }
534                         elseif(isset($_SESSION['timeout']) && !$_SESSION['timeout']['post'])
535                         {
536                                 // in case of GET request redirect to avoid confirmation dialog 
537                                 // after return from menu option
538                                 header("HTTP/1.1 303 See Other");
539                                 header("Location: ".$_SESSION['timeout']['uri']);
540                                 exit();
541                         }
542                         $lang = &$_SESSION['language'];
543                         $lang->set_language($_SESSION['language']->code);
544                 }
545         } else
546         {       set_global_connection();
547                         if (db_fixed())
548                                 db_set_encoding($_SESSION['language']->encoding);
549         }
550
551         if (!isset($_SESSION["App"])) {
552                 $_SESSION["App"] = new front_accounting();
553                 $_SESSION["App"]->init();
554         }
555 }
556
557
558 // POST vars cleanup needed for direct reuse.
559 // We quote all values later with db_escape() before db update.
560 $_POST = strip_quotes($_POST);