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>";
140 echo _("If you are not an authorized user, please contact your system administrator to obtain an account to enable you to use the system.");
141 echo "<br><a href='$path_to_root/index.php'>" . _("Try again") . "</a>";
147 function password_reset_fail()
149 global $path_to_root;
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, or is used by more than one user.") . "<b><br><br>";
154 echo _("Plase try again or contact your system administrator to obtain new password.");
155 echo "<br><a href='$path_to_root/index.php?reset=1'>" . _("Try again") . "</a>";
162 function password_reset_success()
164 global $path_to_root;
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>";
169 echo "<br><a href='$path_to_root/index.php'>" . _("Login here") . "</a>";
176 function check_faillog()
178 global $SysPrefs, $login_faillog;
180 $user = $_SESSION["wa_current_user"]->user;
182 if (@$SysPrefs->login_delay && (@$login_faillog[$user][$_SERVER['REMOTE_ADDR']] >= @$SysPrefs->login_max_attempts) && (time() < $login_faillog[$user]['last'] + $SysPrefs->login_delay))
189 Ensure file is re-read on next request if php caching is active
191 function cache_invalidate($filename)
193 if (function_exists('opcache_invalidate')) // OpCode extension
194 opcache_invalidate($filename);
198 Simple brute force attack detection is performed before connection to company database is open. Therefore access counters have to be stored in file.
199 Login attempts counter is created for every new user IP, which partialy prevent DOS attacks.
201 function write_login_filelog($login, $result)
203 global $login_faillog, $SysPrefs, $path_to_root;
205 $user = $_SESSION["wa_current_user"]->user;
207 $ip = $_SERVER['REMOTE_ADDR'];
209 if (!isset($login_faillog[$user][$ip]) || $result) // init or reset on successfull login
210 $login_faillog[$user] = array($ip => 0, 'last' => '');
214 if ($login_faillog[$user][$ip] < @$SysPrefs->login_max_attempts) {
216 $login_faillog[$user][$ip]++;
218 $login_faillog[$user][$ip] = 0; // comment out to restart counter only after successfull login.
219 error_log(sprintf(_("Brute force attack on account '%s' detected. Access for non-logged users temporarily blocked." ), $login));
221 $login_faillog[$user]['last'] = time();
226 $msg .= "Login attempts info.\n";
228 $msg .= "\$login_faillog = " .var_export($login_faillog, true). ";\n";
230 $filename = VARLIB_PATH."/faillog.php";
232 if ((!file_exists($filename) && is_writable(VARLIB_PATH)) || is_writable($filename))
234 file_put_contents($filename, $msg);
235 cache_invalidate($filename);
239 //----------------------------------------------------------------------------------------
241 function check_page_security($page_security)
247 if (!$_SESSION["wa_current_user"]->check_user_access())
249 // notification after upgrade from pre-2.2 version
250 $msg = $_SESSION["wa_current_user"]->old_db ?
251 _("Security settings have not been defined for your user account.")
252 . "<br>" . _("Please contact your system administrator.")
253 : _("Please remove \$security_groups and \$security_headings arrays from config.php file!");
254 } elseif (!$SysPrefs->db_ok && !$_SESSION["wa_current_user"]->can_access('SA_SOFTWAREUPGRADE'))
256 $msg = _('Access to application has been blocked until database upgrade is completed by system administrator.');
261 end_page(@$_REQUEST['popup']);
266 if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
269 echo "<center><br><br><br><b>";
270 echo _("The security settings on your account do not permit you to access this function");
272 echo "<br><br><br><br></center>";
273 end_page(@$_REQUEST['popup']);
276 if (!$SysPrefs->db_ok
277 && !in_array($page_security, array('SA_SOFTWAREUPGRADE', 'SA_OPEN', 'SA_BACKUP')))
279 display_error(_('System is blocked after source upgrade until database is updated on System/Software Upgrade page'));
286 Helper function for setting page security level depeding on
287 GET start variable and/or some value stored in session variable.
288 Before the call $page_security should be set to default page_security value.
290 function set_page_security($value=null, $trans = array(), $gtrans = array())
292 global $page_security;
294 // first check is this is not start page call
295 foreach($gtrans as $key => $area)
296 if (isset($_GET[$key])) {
297 $page_security = $area;
301 // then check session value
302 if (isset($trans[$value])) {
303 $page_security = $trans[$value];
308 //-----------------------------------------------------------------------------
309 // Removing magic quotes from nested arrays/variables
311 function strip_quotes($data)
313 if(version_compare(phpversion(), '5.4', '<') && get_magic_quotes_gpc()) {
314 if(is_array($data)) {
315 foreach($data as $k => $v) {
316 $data[$k] = strip_quotes($data[$k]);
319 return stripslashes($data);
325 htmlspecialchars does not support certain encodings.
326 ISO-8859-2 fortunately has the same special characters positions as
327 ISO-8859-1, so fix is easy. If any other unsupported encoding is used,
330 function html_specials_encode($str)
332 return htmlspecialchars($str, ENT_QUOTES, $_SESSION['language']->encoding=='iso-8859-2' ?
333 'ISO-8859-1' : $_SESSION['language']->encoding);
336 function html_cleanup(&$parms)
338 foreach($parms as $name => $value) {
339 if (is_array($value))
340 html_cleanup($parms[$name]);
342 $parms[$name] = html_specials_encode($value);
344 reset($parms); // needed for direct key() usage later throughout the sources
347 //============================================================================
350 function login_timeout()
352 // skip timeout on logout page
353 if ($_SESSION["wa_current_user"]->logged) {
354 $tout = $_SESSION["wa_current_user"]->timeout;
355 if ($tout && (time() > $_SESSION["wa_current_user"]->last_act + $tout))
357 $_SESSION["wa_current_user"]->logged = false;
359 $_SESSION["wa_current_user"]->last_act = time();
362 //============================================================================
363 if (!isset($path_to_root))
368 // Prevent register_globals vulnerability
369 if (isset($_GET['path_to_root']) || isset($_POST['path_to_root']))
370 die("Restricted access");
372 include_once($path_to_root . "/includes/errors.inc");
373 // colect all error msgs
374 set_error_handler('error_handler' /*, errtypes */);
375 set_exception_handler('exception_handler');
377 include_once($path_to_root . "/includes/current_user.inc");
378 include_once($path_to_root . "/frontaccounting.php");
379 include_once($path_to_root . "/admin/db/security_db.inc");
380 include_once($path_to_root . "/includes/lang/language.inc");
381 include_once($path_to_root . "/config_db.php");
382 include_once($path_to_root . "/includes/ajax.inc");
383 include_once($path_to_root . "/includes/ui/ui_msgs.inc");
384 include_once($path_to_root . "/includes/prefs/sysprefs.inc");
386 include_once($path_to_root . "/includes/hooks.inc");
388 // include all extensions hook files.
390 foreach ($installed_extensions as $ext)
392 if (file_exists($path_to_root.'/'.$ext['path'].'/hooks.php'))
393 include_once($path_to_root.'/'.$ext['path'].'/hooks.php');
396 ini_set('session.gc_maxlifetime', 36000); // moved from below.
398 $Session_manager = new SessionManager();
399 $Session_manager->sessionStart('FA'.md5(dirname(__FILE__)));
401 $_SESSION['SysPrefs'] = new sys_prefs();
403 $SysPrefs = &$_SESSION['SysPrefs'];
405 //----------------------------------------------------------------------------------------
406 // set to reasonable values if not set in config file (pre-2.3.12 installations)
408 if ((!isset($SysPrefs->login_delay)) || ($SysPrefs->login_delay < 0))
409 $SysPrefs->login_delay = 10;
411 if ((!isset($SysPrefs->login_max_attempts)) || ($SysPrefs->login_max_attempts < 0))
412 $SysPrefs->login_max_attempts = 3;
414 if ($SysPrefs->go_debug > 0)
417 error_reporting(E_USER_WARNING|E_USER_ERROR|E_USER_NOTICE);
418 ini_set("display_errors", "On");
420 if ($SysPrefs->error_logfile != '') {
421 ini_set("error_log", $SysPrefs->error_logfile);
422 ini_set("ignore_repeated_errors", "On");
423 ini_set("log_errors", "On");
427 Uncomment the setting below when using FA on shared hosting
428 to avoid unexpeced session timeouts.
429 Make sure this directory exists and is writable!
431 // ini_set('session.save_path', VARLIB_PATH.'/');
433 // ini_set('session.gc_maxlifetime', 36000); // 10hrs - moved to before session_manager
435 hook_session_start(@$_POST["company_login_name"]);
437 // this is to fix the "back-do-you-want-to-refresh" issue - thanx PHPFreaks
438 header("Cache-control: private");
442 if ($SysPrefs->login_delay > 0 && file_exists(VARLIB_PATH."/faillog.php"))
443 include_once(VARLIB_PATH."/faillog.php");
445 // Page Initialisation
446 if (!isset($_SESSION['wa_current_user']) || !$_SESSION['wa_current_user']->logged_in()
447 || !isset($_SESSION['language']) || !method_exists($_SESSION['language'], 'set_language'))
449 $l = array_search_value($dflt_lang, $installed_languages, 'code');
450 $_SESSION['language'] = new language($l['name'], $l['code'], $l['encoding'],
451 (isset($l['rtl']) && $l['rtl'] === true) ? 'rtl' : 'ltr');
454 $_SESSION['language']->set_language($_SESSION['language']->code);
457 include_once($path_to_root . "/includes/access_levels.inc");
458 include_once($path_to_root . "/version.php");
459 include_once($path_to_root . "/includes/main.inc");
460 include_once($path_to_root . "/includes/app_entries.inc");
462 // Ajax communication object
465 // js/php validation rules container
467 // bindings for editors
469 // page help. Currently help for function keys.
472 $Refs = new references();
474 // intercept all output to destroy it in case of ajax call
475 register_shutdown_function('end_flush');
476 ob_start('output_html',0);
478 if (!isset($_SESSION["wa_current_user"]))
479 $_SESSION["wa_current_user"] = new current_user();
482 html_cleanup($_POST);
483 html_cleanup($_REQUEST);
484 html_cleanup($_SERVER);
486 // logout.php is the only page we should have always
487 // accessable regardless of access level and current login status.
488 if (!defined('FA_LOGOUT_PHP_FILE')){
492 if (!$_SESSION["wa_current_user"]->old_db && file_exists($path_to_root . '/company/'.user_company().'/installed_extensions.php'))
493 include($path_to_root . '/company/'.user_company().'/installed_extensions.php');
497 if (!$_SESSION["wa_current_user"]->logged_in())
499 if (@$SysPrefs->allow_password_reset && !$SysPrefs->allow_demo_mode
500 && (isset($_GET['reset']) || isset($_POST['email_entry_field']))) {
501 if (!isset($_POST["email_entry_field"])) {
502 include($path_to_root . "/access/password_reset.php");
506 if (isset($_POST["company_login_nickname"]) && !isset($_POST["company_login_name"])) {
507 for ($i = 0; $i < count($db_connections); $i++) {
508 if ($db_connections[$i]["name"] == $_POST["company_login_nickname"]) {
509 $_POST["company_login_name"] = $i;
510 unset($_POST["company_login_nickname"]);
511 break 1; // cannot pass variables to break from PHP v5.4 onwards
515 $_succeed = isset($db_connections[$_POST["company_login_name"]]) &&
516 $_SESSION["wa_current_user"]->reset_password($_POST["company_login_name"],
517 $_POST["email_entry_field"]);
520 password_reset_success();
523 password_reset_fail();
527 if (!isset($_POST["user_name_entry_field"]) or $_POST["user_name_entry_field"] == "")
529 // strip ajax marker from uri, to force synchronous page reload
530 $_SESSION['timeout'] = array( 'uri'=>preg_replace('/JsHttpRequest=(?:(\d+)-)?([^&]+)/s',
531 '', html_specials_encode($_SERVER['REQUEST_URI'])),
535 $Ajax->popup($path_to_root ."/access/timeout.php");
537 include($path_to_root . "/access/login.php");
540 if (isset($_POST["company_login_nickname"]) && !isset($_POST["company_login_name"])) {
541 for ($i = 0; $i < count($db_connections); $i++) {
542 if ($db_connections[$i]["name"] == $_POST["company_login_nickname"]) {
543 $_POST["company_login_name"] = $i;
544 unset($_POST["company_login_nickname"]);
545 break 1; // cannot pass variables to break from PHP v5.4 onwards
549 $succeed = isset($db_connections[$_POST["company_login_name"]]) &&
550 $_SESSION["wa_current_user"]->login($_POST["company_login_name"],
551 $_POST["user_name_entry_field"], $_POST["password"]);
552 // select full vs fallback ui mode on login
553 $_SESSION["wa_current_user"]->ui_mode = $_POST['ui_mode'];
556 // Incorrect password
557 if (isset($_SESSION['timeout'])) {
558 include($path_to_root . "/access/login.php");
563 elseif(isset($_SESSION['timeout']) && !$_SESSION['timeout']['post'])
565 // in case of GET request redirect to avoid confirmation dialog
566 // after return from menu option
567 header("HTTP/1.1 307 Temporary Redirect");
568 header("Location: ".$_SESSION['timeout']['uri']);
571 $lang = &$_SESSION['language'];
572 $lang->set_language($_SESSION['language']->code);
576 set_global_connection();
579 db_set_encoding($_SESSION['language']->encoding);
581 $SysPrefs->refresh();
583 if (!isset($_SESSION["App"])) {
584 $_SESSION["App"] = new front_accounting();
585 $_SESSION["App"]->init();
589 // POST vars cleanup needed for direct reuse.
590 // We quote all values later with db_escape() before db update.
591 $_POST = strip_quotes($_POST);