Fixed a session_regenerate_id error leaving session files in /tmp folder.
[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 : isset($_SERVER['HTTPS']);
22
23                 // Set session cookie options
24                 session_set_cookie_params($limit, $path, $domain, $https, true);
25                 session_start();
26
27                 // Make sure the session hasn't expired, and destroy it if it has
28                 if ($this->validateSession())
29                 {
30                         // Check to see if the session is new or a hijacking attempt
31                         if(!$this->preventHijacking())
32                         {
33                                 // Reset session data and regenerate id
34                                 $_SESSION = array();
35                                 $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];
36                                 $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
37                                 $this->regenerateSession();
38
39                         // Give a 5% chance of the session id changing on any request
40                         }
41                         elseif (rand(1, 100) <= 5)
42                         {
43                                 $this->regenerateSession();
44                         }
45                 }
46                 else
47                 {
48                         $_SESSION = array();
49                         session_destroy();
50                         session_start();
51                 }
52         }
53
54         function preventHijacking()
55         {
56                 if (!isset($_SESSION['IPaddress']) || !isset($_SESSION['userAgent']))
57                         return false;
58
59                 if ($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
60                         return false;
61
62                 if ( $_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
63                         return false;
64
65                 return true;
66         }
67
68         function regenerateSession()
69         {
70                 // If this session is obsolete it means there already is a new id
71                 if (isset($_SESSION['OBSOLETE']) && ($_SESSION['OBSOLETE'] == true))
72                         return;
73
74                 // Set current session to expire in 10 seconds
75                 $_SESSION['OBSOLETE'] = true;
76                 $_SESSION['EXPIRES'] = time() + 10;
77
78                 // Create new session destroying the old one if posiible
79                 if (phpversion() >= "5.1.0")
80                         session_regenerate_id(true);
81                 else    
82                         session_regenerate_id();
83  
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 //----------------------------------------------------------------------------------------
148
149 function check_page_security($page_security)
150 {
151         global $SysPrefs;
152         
153         $msg = '';
154         
155         if (!$_SESSION["wa_current_user"]->check_user_access())
156         {
157                 // notification after upgrade from pre-2.2 version
158                 $msg = $_SESSION["wa_current_user"]->old_db ?
159                          _("Security settings have not been defined for your user account.")
160                                 . "<br>" . _("Please contact your system administrator.")       
161                         : _("Please remove \$security_groups and \$security_headings arrays from config.php file!");
162         } elseif (!$_SESSION['SysPrefs']->db_ok && !$_SESSION["wa_current_user"]->can_access('SA_SOFTWAREUPGRADE')) {
163                 $msg = _('Access to application has been blocked until database upgrade is completed by system administrator.');
164         }
165         
166         if ($msg){
167                 display_error($msg);
168                 end_page(@$_REQUEST['popup']);
169                 kill_login();
170                 exit;
171         }
172
173         if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
174         {
175
176                 echo "<center><br><br><br><b>";
177                 echo _("The security settings on your account do not permit you to access this function");
178                 echo "</b>";
179                 echo "<br><br><br><br></center>";
180                 end_page(@$_REQUEST['popup']);
181                 exit;
182         }
183         if (!$_SESSION['SysPrefs']->db_ok 
184                 && !in_array($page_security, array('SA_SOFTWAREUPGRADE', 'SA_OPEN', 'SA_BACKUP')))
185         {
186                 display_error(_('System is blocked after source upgrade until database is updated on System/Software Upgrade page'));
187                 end_page();
188                 exit;
189         }
190
191 }
192 /*
193         Helper function for setting page security level depeding on 
194         GET start variable and/or some value stored in session variable.
195         Before the call $page_security should be set to default page_security value.
196 */
197 function set_page_security($value=null, $trans = array(), $gtrans = array())
198 {
199         global $page_security;
200
201         // first check is this is not start page call
202         foreach($gtrans as $key => $area)
203                 if (isset($_GET[$key])) {
204                         $page_security = $area;
205                         return;
206                 }
207
208         // then check session value
209         if (isset($trans[$value])) {
210                 $page_security = $trans[$value];
211                 return;
212         }
213 }
214
215 //-----------------------------------------------------------------------------
216 //      Removing magic quotes from nested arrays/variables
217 //
218 function strip_quotes($data)
219 {
220         if(get_magic_quotes_gpc()) {
221                 if(is_array($data)) {
222                         foreach($data as $k => $v) {
223                                 $data[$k] = strip_quotes($data[$k]);
224                         }
225                 } else
226                         return stripslashes($data);
227         }
228         return $data;
229 }
230
231 function html_cleanup(&$parms)
232 {
233         foreach($parms as $name => $value) {
234 //              $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
235                 if (is_array($value))
236                         html_cleanup($parms[$name]);
237                 else
238                         $parms[$name] = @htmlspecialchars($value, ENT_QUOTES, $_SESSION['language']->encoding);
239         }
240         reset($parms); // needed for direct key() usage later throughout the sources
241 }
242
243 //============================================================================
244 //
245 //
246 function login_timeout()
247 {
248         // skip timeout on logout page
249         if ($_SESSION["wa_current_user"]->logged) {
250                 $tout = $_SESSION["wa_current_user"]->timeout;
251                 if ($tout && (time() > $_SESSION["wa_current_user"]->last_act + $tout))
252                 {
253                         $_SESSION["wa_current_user"]->logged = false;
254                 }
255                 $_SESSION["wa_current_user"]->last_act = time();
256         }
257 }
258 //============================================================================
259 if (!isset($path_to_root))
260 {
261         $path_to_root = ".";
262 }
263
264 // Prevent register_globals vulnerability
265 if (isset($_GET['path_to_root']) || isset($_POST['path_to_root']))
266         die("Restricted access");
267
268 include_once($path_to_root . "/includes/errors.inc");
269 // colect all error msgs
270 set_error_handler('error_handler' /*, errtypes */);
271
272 include_once($path_to_root . "/includes/current_user.inc");
273 include_once($path_to_root . "/frontaccounting.php");
274 include_once($path_to_root . "/admin/db/security_db.inc");
275 include_once($path_to_root . "/includes/lang/language.php");
276 include_once($path_to_root . "/config_db.php");
277 include_once($path_to_root . "/includes/ajax.inc");
278 include_once($path_to_root . "/includes/ui/ui_msgs.inc");
279 include_once($path_to_root . "/includes/prefs/sysprefs.inc");
280
281 include_once($path_to_root . "/includes/hooks.inc");
282 //
283 // include all extensions hook files.
284 //
285 foreach ($installed_extensions as $ext)
286 {
287         if (file_exists($path_to_root.'/'.$ext['path'].'/hooks.php'))
288                 include_once($path_to_root.'/'.$ext['path'].'/hooks.php');
289 }
290
291 /*
292         Uncomment the setting below when using FA on shared hosting
293         to avoid unexpeced session timeouts.
294         Make sure this directory exists and is writable!
295 */
296 // ini_set('session.save_path', dirname(__FILE__).'/../tmp/');
297
298 ini_set('session.gc_maxlifetime', 36000); // 10hrs
299
300 $Session_manager = new SessionManager();
301 $Session_manager->sessionStart('FA'.md5(dirname(__FILE__)));
302 //session_name('FA'.md5(dirname(__FILE__)));
303 //session_start();
304
305 // this is to fix the "back-do-you-want-to-refresh" issue - thanx PHPFreaks
306 header("Cache-control: private");
307
308 include_once($path_to_root . "/config.php");
309 get_text_init();
310
311 // Page Initialisation
312 if (!isset($_SESSION['language']) || !method_exists($_SESSION['language'], 'set_language')) 
313 {
314         $l = array_search_value($dflt_lang, $installed_languages,  'code');
315         $_SESSION['language'] = new language($l['name'], $l['code'], $l['encoding'],
316          (isset($l['rtl']) && $l['rtl'] === true) ? 'rtl' : 'ltr');
317 }
318
319 $_SESSION['language']->set_language($_SESSION['language']->code);
320
321
322 include_once($path_to_root . "/includes/access_levels.inc");
323 include_once($path_to_root . "/version.php");
324 include_once($path_to_root . "/includes/main.inc");
325
326 // Ajax communication object
327 $Ajax = new Ajax();
328
329 // js/php validation rules container
330 $Validate = array();
331 // bindings for editors
332 $Editors = array();
333 // page help. Currently help for function keys.
334 $Pagehelp = array();
335
336 $Refs = new references();
337
338 // intercept all output to destroy it in case of ajax call
339 register_shutdown_function('end_flush');
340 ob_start('output_html',0);
341
342 if (!isset($_SESSION["wa_current_user"]))
343         $_SESSION["wa_current_user"] = new current_user();
344
345 html_cleanup($_GET);
346 html_cleanup($_POST);
347 html_cleanup($_REQUEST);
348 html_cleanup($_SERVER);
349
350 // logout.php is the only page we should have always 
351 // accessable regardless of access level and current login status.
352 if (strstr($_SERVER['PHP_SELF'], 'logout.php') == false){
353
354         login_timeout();
355
356         if (!$_SESSION["wa_current_user"]->old_db)
357                 include_once($path_to_root . '/company/'.user_company().'/installed_extensions.php');
358
359         install_hooks();
360
361         if (!$_SESSION["wa_current_user"]->logged_in())
362         {
363                 // Show login screen
364                 if (!isset($_POST["user_name_entry_field"]) or $_POST["user_name_entry_field"] == "")
365                 {
366                         // strip ajax marker from uri, to force synchronous page reload
367                         $_SESSION['timeout'] = array( 'uri'=>preg_replace('/JsHttpRequest=(?:(\d+)-)?([^&]+)/s',
368                                         '', @htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, $_SESSION['language']->encoding)), 
369                                 'post' => $_POST);
370
371                         include($path_to_root . "/access/login.php");
372                         if (in_ajax())
373                                 $Ajax->activate('_page_body');
374                         exit;
375                 } else {
376
377                         $succeed = isset($db_connections[$_POST["company_login_name"]]) &&
378                                 $_SESSION["wa_current_user"]->login($_POST["company_login_name"],
379                                 $_POST["user_name_entry_field"], $_POST["password"]);
380                         // select full vs fallback ui mode on login
381                         $_SESSION["wa_current_user"]->ui_mode = $_POST['ui_mode'];
382                         if (!$succeed)
383                         {
384                         // Incorrect password
385                                 login_fail();
386                         }
387                         $lang = &$_SESSION['language'];
388                         $lang->set_language($_SESSION['language']->code);
389                 }
390         } else
391                 set_global_connection();
392
393         if (!isset($_SESSION["App"])) {
394                 $_SESSION["App"] = new front_accounting();
395                 $_SESSION["App"]->init();
396         }
397 }
398
399 $SysPrefs = &$_SESSION['SysPrefs'];
400
401 // POST vars cleanup needed for direct reuse.
402 // We quote all values later with db_escape() before db update.
403 $_POST = strip_quotes($_POST);
404
405 ?>