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 ***********************************************************************/
15 function sessionStart($name, $limit = 0, $path = '/', $domain = null, $secure = null)
17 // Set the cookie name
21 $https = isset($secure) ? $secure : isset($_SERVER['HTTPS']);
23 // Set session cookie options
24 session_set_cookie_params($limit, $path, $domain, $https, true);
27 // Make sure the session hasn't expired, and destroy it if it has
28 if ($this->validateSession())
30 // Check to see if the session is new or a hijacking attempt
31 if(!$this->preventHijacking())
33 // Reset session data and regenerate id
35 $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
36 $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
37 $this->regenerateSession();
39 // Give a 5% chance of the session id changing on any request
41 elseif (rand(1, 100) <= 5)
43 $this->regenerateSession();
54 function preventHijacking()
56 if (!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
59 if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
62 if ( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
68 function regenerateSession()
70 // If this session is obsolete it means there already is a new id
71 if (isset($_SESSION['OBSOLETE']) && ($_SESSION['OBSOLETE'] == true))
74 // Set current session to expire in 10 seconds
75 $_SESSION['OBSOLETE'] = true;
76 $_SESSION['EXPIRES'] = time() + 10;
78 // Create new session without destroying the old one
79 session_regenerate_id();
81 // Grab current session ID and close both sessions to allow other scripts to use them
82 $newSession = session_id();
83 session_write_close();
84 // Set session ID to the new one, and start it back up again
86 session_id($newSession);
89 // Now we unset the obsolete and expiration values for the session we want to keep
90 unset($_SESSION['OBSOLETE']);
91 unset($_SESSION['EXPIRES']);
94 function validateSession()
96 if (isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
99 if (isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
105 function output_html($text)
107 global $before_box, $Ajax, $messages;
108 // Fatal errors are not send to error_handler,
109 // so we must check the output
110 if ($text && preg_match('/\bFatal error(<.*?>)?:(.*)/i', $text, $m)) {
111 $Ajax->aCommands = array(); // Don't update page via ajax on errors
112 $text = preg_replace('/\bFatal error(<.*?>)?:(.*)/i','', $text);
113 $messages[] = array(E_ERROR, $m[2], null, null);
116 return in_ajax() ? fmt_errors() : ($before_box.fmt_errors().$text);
118 //----------------------------------------------------------------------------------------
120 function kill_login()
125 //----------------------------------------------------------------------------------------
127 function login_fail()
129 global $path_to_root;
131 header("HTTP/1.1 401 Authorization Required");
132 echo "<center><br><br><font size='5' color='red'><b>" . _("Incorrect Password") . "<b></font><br><br>";
133 echo "<b>" . _("The user and password combination is not valid for the system.") . "<b><br><br>";
135 echo _("If you are not an authorized user, please contact your system administrator to obtain an account to enable you to use the system.");
136 echo "<br><a href='$path_to_root/index.php'>" . _("Try again") . "</a>";
143 //----------------------------------------------------------------------------------------
145 function check_page_security($page_security)
151 if (!$_SESSION["wa_current_user"]->check_user_access())
153 // notification after upgrade from pre-2.2 version
154 $msg = $_SESSION["wa_current_user"]->old_db ?
155 _("Security settings have not been defined for your user account.")
156 . "<br>" . _("Please contact your system administrator.")
157 : _("Please remove \$security_groups and \$security_headings arrays from config.php file!");
158 } elseif (!$_SESSION['SysPrefs']->db_ok && !$_SESSION["wa_current_user"]->can_access('SA_SOFTWAREUPGRADE')) {
159 $msg = _('Access to application has been blocked until database upgrade is completed by system administrator.');
164 end_page(@$_REQUEST['popup']);
169 if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
172 echo "<center><br><br><br><b>";
173 echo _("The security settings on your account do not permit you to access this function");
175 echo "<br><br><br><br></center>";
176 end_page(@$_REQUEST['popup']);
179 if (!$_SESSION['SysPrefs']->db_ok
180 && !in_array($page_security, array('SA_SOFTWAREUPGRADE', 'SA_OPEN', 'SA_BACKUP')))
182 display_error(_('System is blocked after source upgrade until database is updated on System/Software Upgrade page'));
189 Helper function for setting page security level depeding on
190 GET start variable and/or some value stored in session variable.
191 Before the call $page_security should be set to default page_security value.
193 function set_page_security($value=null, $trans = array(), $gtrans = array())
195 global $page_security;
197 // first check is this is not start page call
198 foreach($gtrans as $key => $area)
199 if (isset($_GET[$key])) {
200 $page_security = $area;
204 // then check session value
205 if (isset($trans[$value])) {
206 $page_security = $trans[$value];
211 //-----------------------------------------------------------------------------
212 // Removing magic quotes from nested arrays/variables
214 function strip_quotes($data)
216 if(get_magic_quotes_gpc()) {
217 if(is_array($data)) {
218 foreach($data as $k => $v) {
219 $data[$k] = strip_quotes($data[$k]);
222 return stripslashes($data);
227 function html_cleanup(&$parms)
229 foreach($parms as $name => $value) {
230 // $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
231 if (is_array($value))
232 html_cleanup($parms[$name]);
234 $parms[$name] = @htmlspecialchars($value, ENT_QUOTES, $_SESSION['language']->encoding);
236 reset($parms); // needed for direct key() usage later throughout the sources
239 //============================================================================
242 function login_timeout()
244 // skip timeout on logout page
245 if ($_SESSION["wa_current_user"]->logged) {
246 $tout = $_SESSION["wa_current_user"]->timeout;
247 if ($tout && (time() > $_SESSION["wa_current_user"]->last_act + $tout))
249 $_SESSION["wa_current_user"]->logged = false;
251 $_SESSION["wa_current_user"]->last_act = time();
254 //============================================================================
255 if (!isset($path_to_root))
260 // Prevent register_globals vulnerability
261 if (isset($_GET['path_to_root']) || isset($_POST['path_to_root']))
262 die("Restricted access");
264 include_once($path_to_root . "/includes/errors.inc");
265 // colect all error msgs
266 set_error_handler('error_handler' /*, errtypes */);
268 include_once($path_to_root . "/includes/current_user.inc");
269 include_once($path_to_root . "/frontaccounting.php");
270 include_once($path_to_root . "/admin/db/security_db.inc");
271 include_once($path_to_root . "/includes/lang/language.php");
272 include_once($path_to_root . "/config_db.php");
273 include_once($path_to_root . "/includes/ajax.inc");
274 include_once($path_to_root . "/includes/ui/ui_msgs.inc");
275 include_once($path_to_root . "/includes/prefs/sysprefs.inc");
277 include_once($path_to_root . "/includes/hooks.inc");
279 // include all extensions hook files.
281 foreach ($installed_extensions as $ext)
283 if (file_exists($path_to_root.'/'.$ext['path'].'/hooks.php'))
284 include_once($path_to_root.'/'.$ext['path'].'/hooks.php');
288 Uncomment the setting below when using FA on shared hosting
289 to avoid unexpeced session timeouts.
290 Make sure this directory exists and is writable!
292 // ini_set('session.save_path', dirname(__FILE__).'/../tmp/');
294 ini_set('session.gc_maxlifetime', 36000); // 10hrs
296 hook_session_start(@$_POST["company_login_name"]);
298 $Session_manager = new SessionManager();
299 $Session_manager->sessionStart('FA'.md5(dirname(__FILE__)));
301 // this is to fix the "back-do-you-want-to-refresh" issue - thanx PHPFreaks
302 header("Cache-control: private");
304 include_once($path_to_root . "/config.php");
307 // Page Initialisation
308 if (!isset($_SESSION['language']) || !method_exists($_SESSION['language'], 'set_language'))
310 $l = array_search_value($dflt_lang, $installed_languages, 'code');
311 $_SESSION['language'] = new language($l['name'], $l['code'], $l['encoding'],
312 (isset($l['rtl']) && $l['rtl'] === true) ? 'rtl' : 'ltr');
315 $_SESSION['language']->set_language($_SESSION['language']->code);
318 include_once($path_to_root . "/includes/access_levels.inc");
319 include_once($path_to_root . "/version.php");
320 include_once($path_to_root . "/includes/main.inc");
321 include_once($path_to_root . "/includes/app_entries.inc");
323 // Ajax communication object
326 // js/php validation rules container
328 // bindings for editors
330 // page help. Currently help for function keys.
333 $Refs = new references();
335 // intercept all output to destroy it in case of ajax call
336 register_shutdown_function('end_flush');
337 ob_start('output_html',0);
339 if (!isset($_SESSION["wa_current_user"]))
340 $_SESSION["wa_current_user"] = new current_user();
343 html_cleanup($_POST);
344 html_cleanup($_REQUEST);
345 html_cleanup($_SERVER);
347 // logout.php is the only page we should have always
348 // accessable regardless of access level and current login status.
349 if (strstr($_SERVER['PHP_SELF'], 'logout.php') == false){
353 if (!$_SESSION["wa_current_user"]->old_db)
354 include_once($path_to_root . '/company/'.user_company().'/installed_extensions.php');
358 if (!$_SESSION["wa_current_user"]->logged_in())
361 if (!isset($_POST["user_name_entry_field"]) or $_POST["user_name_entry_field"] == "")
363 // strip ajax marker from uri, to force synchronous page reload
364 $_SESSION['timeout'] = array( 'uri'=>preg_replace('/JsHttpRequest=(?:(\d+)-)?([^&]+)/s',
365 '', @htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, $_SESSION['language']->encoding)),
368 include($path_to_root . "/access/login.php");
370 $Ajax->activate('_page_body');
374 $succeed = isset($db_connections[$_POST["company_login_name"]]) &&
375 $_SESSION["wa_current_user"]->login($_POST["company_login_name"],
376 $_POST["user_name_entry_field"], $_POST["password"]);
377 // select full vs fallback ui mode on login
378 $_SESSION["wa_current_user"]->ui_mode = $_POST['ui_mode'];
381 // Incorrect password
384 $lang = &$_SESSION['language'];
385 $lang->set_language($_SESSION['language']->code);
388 set_global_connection();
390 if (!isset($_SESSION["App"])) {
391 $_SESSION["App"] = new front_accounting();
392 $_SESSION["App"]->init();
396 $SysPrefs = &$_SESSION['SysPrefs'];
398 // POST vars cleanup needed for direct reuse.
399 // We quote all values later with db_escape() before db update.
400 $_POST = strip_quotes($_POST);