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 define('VARLIB_PATH', $path_to_root.'/tmp');
13 define('VARLOG_PATH', $path_to_root.'/tmp');
17 function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
19 // Set the cookie name
23 $https = isset($secure) ? $secure : (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
25 // Set session cookie options
26 if (version_compare(PHP_VERSION, '5.2', '<')) // avoid failure on older php versions
27 session_set_cookie_params($limit, $path, $domain, $https);
29 session_set_cookie_params($limit, $path, $domain, $https, true);
33 // Make sure the session hasn't expired, and destroy it if it has
34 if ($this->validateSession())
36 // Check to see if the session is new or a hijacking attempt
37 if(!$this->preventHijacking())
39 // Reset session data and regenerate id
41 $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
42 $_SESSION['userAgent'] = @$_SERVER['HTTP_USER_AGENT'];
43 $this->regenerateSession();
45 // Give a 5% chance of the session id changing on any request
47 elseif (rand(1, 100) <= 5)
49 $this->regenerateSession();
60 function preventHijacking()
62 if (!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
65 if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
68 if ( $_SESSION['userAgent'] != @$_SERVER['HTTP_USER_AGENT'])
74 function regenerateSession()
76 // If this session is obsolete it means there already is a new id
77 if (isset($_SESSION['OBSOLETE']) && ($_SESSION['OBSOLETE'] == true))
80 // Set current session to expire in 10 seconds
81 $_SESSION['OBSOLETE'] = true;
82 $_SESSION['EXPIRES'] = time() + 10;
84 // Create new session without destroying the old one
85 session_regenerate_id();
86 // Grab current session ID and close both sessions to allow other scripts to use them
87 $newSession = session_id();
88 session_write_close();
89 // Set session ID to the new one, and start it back up again
91 session_id($newSession);
94 // Now we unset the obsolete and expiration values for the session we want to keep
95 unset($_SESSION['OBSOLETE']);
96 unset($_SESSION['EXPIRES']);
99 function validateSession()
101 if (isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
104 if (isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
111 function output_html($text)
113 global $before_box, $Ajax, $messages;
114 // Fatal errors are not send to error_handler,
115 // so we must check the output
116 if ($text && preg_match('/\bFatal error(<.*?>)?:(.*)/i', $text, $m)) {
117 $Ajax->aCommands = array(); // Don't update page via ajax on errors
118 $text = preg_replace('/\bFatal error(<.*?>)?:(.*)/i','', $text);
119 $messages[] = array(E_ERROR, $m[2], null, null);
122 return in_ajax() ? fmt_errors() : ($before_box.fmt_errors().$text);
124 //----------------------------------------------------------------------------------------
126 function kill_login()
131 //----------------------------------------------------------------------------------------
133 function login_fail()
135 global $path_to_root;
137 header("HTTP/1.1 401 Authorization Required");
138 echo "<center><br><br><font size='5' color='red'><b>" . _("Incorrect Password") . "<b></font><br><br>";
139 echo "<b>" . _("The user and password combination is not valid for the system.") . "<b><br><br>";
141 echo _("If you are not an authorized user, please contact your system administrator to obtain an account to enable you to use the system.");
142 echo "<br><a href='$path_to_root/index.php'>" . _("Try again") . "</a>";
149 function password_reset_fail()
151 global $path_to_root;
153 echo "<center><br><br><font size='5' color='red'><b>" . _("Incorrect Email") . "<b></font><br><br>";
154 echo "<b>" . _("The email address does not exist in the system, or is used by more than one user.") . "<b><br><br>";
156 echo _("Plase try again or contact your system administrator to obtain new password.");
157 echo "<br><a href='$path_to_root/index.php?reset=1'>" . _("Try again") . "</a>";
164 function password_reset_success()
166 global $path_to_root;
168 echo "<center><br><br><font size='5' color='green'><b>" . _("New password sent") . "<b></font><br><br>";
169 echo "<b>" . _("A new password has been sent to your mailbox.") . "<b><br><br>";
171 echo "<br><a href='$path_to_root/index.php'>" . _("Login here") . "</a>";
178 function check_faillog()
180 global $SysPrefs, $login_faillog;
182 $user = $_SESSION["wa_current_user"]->user;
184 if (@$SysPrefs->login_delay && (@$login_faillog[$user][$_SERVER['REMOTE_ADDR']] >= @$SysPrefs->login_max_attempts) && (time() < $login_faillog[$user]['last'] + $SysPrefs->login_delay))
191 Ensure file is re-read on next request if php caching is active
193 function cache_invalidate($filename)
195 if (function_exists('opcache_invalidate')) // OpCode extension
196 opcache_invalidate($filename);
200 Simple brute force attack detection is performed before connection to company database is open. Therefore access counters have to be stored in file.
201 Login attempts counter is created for every new user IP, which partialy prevent DOS attacks.
203 function write_login_filelog($login, $result)
205 global $login_faillog, $SysPrefs, $path_to_root;
207 $user = $_SESSION["wa_current_user"]->user;
209 $ip = $_SERVER['REMOTE_ADDR'];
211 if (!isset($login_faillog[$user][$ip]) || $result) // init or reset on successfull login
212 $login_faillog[$user] = array($ip => 0, 'last' => '');
216 if ($login_faillog[$user][$ip] < @$SysPrefs->login_max_attempts) {
218 $login_faillog[$user][$ip]++;
220 $login_faillog[$user][$ip] = 0; // comment out to restart counter only after successfull login.
221 error_log(sprintf(_("Brute force attack on account '%s' detected. Access for non-logged users temporarily blocked." ), $login));
223 $login_faillog[$user]['last'] = time();
228 $msg .= "Login attempts info.\n";
230 $msg .= "\$login_faillog = " .var_export($login_faillog, true). ";\n";
232 $filename = VARLIB_PATH."/faillog.php";
234 if ((!file_exists($filename) && is_writable(VARLIB_PATH)) || is_writable($filename))
236 file_put_contents($filename, $msg);
237 cache_invalidate($filename);
241 //----------------------------------------------------------------------------------------
243 function check_page_security($page_security)
249 if (!$_SESSION["wa_current_user"]->check_user_access())
251 // notification after upgrade from pre-2.2 version
252 $msg = $_SESSION["wa_current_user"]->old_db ?
253 _("Security settings have not been defined for your user account.")
254 . "<br>" . _("Please contact your system administrator.")
255 : _("Please remove \$security_groups and \$security_headings arrays from config.php file!");
256 } elseif (!$SysPrefs->db_ok && !$_SESSION["wa_current_user"]->can_access('SA_SOFTWAREUPGRADE'))
258 $msg = _('Access to application has been blocked until database upgrade is completed by system administrator.');
263 end_page(@$_REQUEST['popup']);
268 if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
271 echo "<center><br><br><br><b>";
272 echo _("The security settings on your account do not permit you to access this function");
274 echo "<br><br><br><br></center>";
275 end_page(@$_REQUEST['popup']);
278 if (!$SysPrefs->db_ok
279 && !in_array($page_security, array('SA_SOFTWAREUPGRADE', 'SA_OPEN', 'SA_BACKUP')))
281 display_error(_('System is blocked after source upgrade until database is updated on System/Software Upgrade page'));
288 Helper function for setting page security level depeding on
289 GET start variable and/or some value stored in session variable.
290 Before the call $page_security should be set to default page_security value.
292 function set_page_security($value=null, $trans = array(), $gtrans = array())
294 global $page_security;
296 // first check is this is not start page call
297 foreach($gtrans as $key => $area)
298 if (isset($_GET[$key])) {
299 $page_security = $area;
303 // then check session value
304 if (isset($trans[$value])) {
305 $page_security = $trans[$value];
310 //-----------------------------------------------------------------------------
311 // Removing magic quotes from nested arrays/variables
313 function strip_quotes($data)
315 if(get_magic_quotes_gpc()) {
316 if(is_array($data)) {
317 foreach($data as $k => $v) {
318 $data[$k] = strip_quotes($data[$k]);
321 return stripslashes($data);
327 htmlspecialchars does not support certain encodings.
328 ISO-8859-2 fortunately has the same special characters positions as
329 ISO-8859-1, so fix is easy. If any other unsupported encoding is used,
332 function html_specials_encode($str)
334 return htmlspecialchars($str, ENT_QUOTES, $_SESSION['language']->encoding=='iso-8859-2' ?
335 'ISO-8859-1' : $_SESSION['language']->encoding);
338 function html_cleanup(&$parms)
340 foreach($parms as $name => $value) {
341 if (is_array($value))
342 html_cleanup($parms[$name]);
344 $parms[$name] = html_specials_encode($value);
346 reset($parms); // needed for direct key() usage later throughout the sources
349 //============================================================================
352 function login_timeout()
354 // skip timeout on logout page
355 if ($_SESSION["wa_current_user"]->logged) {
356 $tout = $_SESSION["wa_current_user"]->timeout;
357 if ($tout && (time() > $_SESSION["wa_current_user"]->last_act + $tout))
359 $_SESSION["wa_current_user"]->logged = false;
361 $_SESSION["wa_current_user"]->last_act = time();
364 //============================================================================
365 if (!isset($path_to_root))
370 // Prevent register_globals vulnerability
371 if (isset($_GET['path_to_root']) || isset($_POST['path_to_root']))
372 die("Restricted access");
374 include_once($path_to_root . "/includes/errors.inc");
375 // colect all error msgs
376 set_error_handler('error_handler' /*, errtypes */);
377 set_exception_handler('exception_handler');
379 include_once($path_to_root . "/includes/current_user.inc");
380 include_once($path_to_root . "/frontaccounting.php");
381 include_once($path_to_root . "/admin/db/security_db.inc");
382 include_once($path_to_root . "/includes/lang/language.inc");
383 include_once($path_to_root . "/config_db.php");
384 include_once($path_to_root . "/includes/ajax.inc");
385 include_once($path_to_root . "/includes/ui/ui_msgs.inc");
386 include_once($path_to_root . "/includes/prefs/sysprefs.inc");
388 include_once($path_to_root . "/includes/hooks.inc");
390 // include all extensions hook files.
392 foreach ($installed_extensions as $ext)
394 if (file_exists($path_to_root.'/'.$ext['path'].'/hooks.php'))
395 include_once($path_to_root.'/'.$ext['path'].'/hooks.php');
398 ini_set('session.gc_maxlifetime', 36000); // moved from below.
400 $Session_manager = new SessionManager();
401 $Session_manager->sessionStart('FA'.md5(dirname(__FILE__)));
403 $_SESSION['SysPrefs'] = new sys_prefs();
405 $SysPrefs = &$_SESSION['SysPrefs'];
407 //----------------------------------------------------------------------------------------
408 // set to reasonable values if not set in config file (pre-2.3.12 installations)
410 if ((!isset($SysPrefs->login_delay)) || ($SysPrefs->login_delay < 0))
411 $SysPrefs->login_delay = 10;
413 if ((!isset($SysPrefs->login_max_attempts)) || ($SysPrefs->login_max_attempts < 0))
414 $SysPrefs->login_max_attempts = 3;
416 if ($SysPrefs->go_debug > 0)
419 error_reporting(E_USER_WARNING|E_USER_ERROR|E_USER_NOTICE);
420 ini_set("display_errors", "On");
422 if ($SysPrefs->error_logfile != '') {
423 ini_set("error_log", $SysPrefs->error_logfile);
424 ini_set("ignore_repeated_errors", "On");
425 ini_set("log_errors", "On");
429 Uncomment the setting below when using FA on shared hosting
430 to avoid unexpeced session timeouts.
431 Make sure this directory exists and is writable!
433 // ini_set('session.save_path', VARLIB_PATH.'/');
435 // ini_set('session.gc_maxlifetime', 36000); // 10hrs - moved to before session_manager
437 hook_session_start(@$_POST["company_login_name"]);
439 // this is to fix the "back-do-you-want-to-refresh" issue - thanx PHPFreaks
440 header("Cache-control: private");
444 if ($SysPrefs->login_delay > 0 && file_exists(VARLIB_PATH."/faillog.php"))
445 include_once(VARLIB_PATH."/faillog.php");
447 // Page Initialisation
448 if (!isset($_SESSION['wa_current_user']) || !$_SESSION['wa_current_user']->logged_in()
449 || !isset($_SESSION['language']) || !method_exists($_SESSION['language'], 'set_language'))
451 $l = array_search_value($dflt_lang, $installed_languages, 'code');
452 $_SESSION['language'] = new language($l['name'], $l['code'], $l['encoding'],
453 (isset($l['rtl']) && $l['rtl'] === true) ? 'rtl' : 'ltr');
456 $_SESSION['language']->set_language($_SESSION['language']->code);
459 include_once($path_to_root . "/includes/access_levels.inc");
460 include_once($path_to_root . "/version.php");
461 include_once($path_to_root . "/includes/main.inc");
462 include_once($path_to_root . "/includes/app_entries.inc");
464 // Ajax communication object
467 // js/php validation rules container
469 // bindings for editors
471 // page help. Currently help for function keys.
474 $Refs = new references();
476 // intercept all output to destroy it in case of ajax call
477 register_shutdown_function('end_flush');
478 ob_start('output_html',0);
480 if (!isset($_SESSION["wa_current_user"]))
481 $_SESSION["wa_current_user"] = new current_user();
484 html_cleanup($_POST);
485 html_cleanup($_REQUEST);
486 html_cleanup($_SERVER);
488 // logout.php is the only page we should have always
489 // accessable regardless of access level and current login status.
490 if (!defined('FA_LOGOUT_PHP_FILE')){
494 if (!$_SESSION["wa_current_user"]->old_db && file_exists($path_to_root . '/company/'.user_company().'/installed_extensions.php'))
495 include($path_to_root . '/company/'.user_company().'/installed_extensions.php');
499 if (!$_SESSION["wa_current_user"]->logged_in())
501 if (@$SysPrefs->allow_password_reset && !$SysPrefs->allow_demo_mode
502 && (isset($_GET['reset']) || isset($_POST['email_entry_field']))) {
503 if (!isset($_POST["email_entry_field"])) {
504 include($path_to_root . "/access/password_reset.php");
508 if (isset($_POST["company_login_nickname"]) && !isset($_POST["company_login_name"])) {
509 for ($i = 0; $i < count($db_connections); $i++) {
510 if ($db_connections[$i]["name"] == $_POST["company_login_nickname"]) {
511 $_POST["company_login_name"] = $i;
512 unset($_POST["company_login_nickname"]);
513 break 1; // cannot pass variables to break from PHP v5.4 onwards
517 $_succeed = isset($db_connections[$_POST["company_login_name"]]) &&
518 $_SESSION["wa_current_user"]->reset_password($_POST["company_login_name"],
519 $_POST["email_entry_field"]);
522 password_reset_success();
525 password_reset_fail();
529 if (!isset($_POST["user_name_entry_field"]) or $_POST["user_name_entry_field"] == "")
531 // strip ajax marker from uri, to force synchronous page reload
532 $_SESSION['timeout'] = array( 'uri'=>preg_replace('/JsHttpRequest=(?:(\d+)-)?([^&]+)/s',
533 '', html_specials_encode($_SERVER['REQUEST_URI'])),
536 include($path_to_root . "/access/login.php");
538 $Ajax->activate('_page_body');
541 if (isset($_POST["company_login_nickname"]) && !isset($_POST["company_login_name"])) {
542 for ($i = 0; $i < count($db_connections); $i++) {
543 if ($db_connections[$i]["name"] == $_POST["company_login_nickname"]) {
544 $_POST["company_login_name"] = $i;
545 unset($_POST["company_login_nickname"]);
546 break 1; // cannot pass variables to break from PHP v5.4 onwards
550 $succeed = isset($db_connections[$_POST["company_login_name"]]) &&
551 $_SESSION["wa_current_user"]->login($_POST["company_login_name"],
552 $_POST["user_name_entry_field"], $_POST["password"]);
553 // select full vs fallback ui mode on login
554 $_SESSION["wa_current_user"]->ui_mode = $_POST['ui_mode'];
557 // Incorrect password
560 elseif(isset($_SESSION['timeout']) && !$_SESSION['timeout']['post'])
562 // in case of GET request redirect to avoid confirmation dialog
563 // after return from menu option
564 header("HTTP/1.1 303 See Other");
565 header("Location: ".$_SESSION['timeout']['uri']);
568 $lang = &$_SESSION['language'];
569 $lang->set_language($_SESSION['language']->code);
573 set_global_connection();
576 db_set_encoding($_SESSION['language']->encoding);
578 $SysPrefs->refresh();
580 if (!isset($_SESSION["App"])) {
581 $_SESSION["App"] = new front_accounting();
582 $_SESSION["App"]->init();
586 // POST vars cleanup needed for direct reuse.
587 // We quote all values later with db_escape() before db update.
588 $_POST = strip_quotes($_POST);