Added graphic edit/add icons in lists with $editkey.
[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 without destroying the old one
79                 session_regenerate_id(false);
80
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
85                 // Set session ID to the new one, and start it back up again
86                 session_id($newSession);
87                 session_start();
88
89                 // Now we unset the obsolete and expiration values for the session we want to keep
90                 unset($_SESSION['OBSOLETE']);
91                 unset($_SESSION['EXPIRES']);
92         }
93
94         function validateSession()
95         {
96                 if (isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES']) )
97                         return false;
98
99                 if (isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time())
100                         return false;
101
102                 return true;
103         }
104 }
105
106 function output_html($text)
107 {
108         global $before_box, $Ajax, $messages;
109         // Fatal errors are not send to error_handler,
110         // so we must check the output
111         if ($text && preg_match('/\bFatal error(<.*?>)?:(.*)/i', $text, $m)) {
112                 $Ajax->aCommands = array();  // Don't update page via ajax on errors
113                 $text = preg_replace('/\bFatal error(<.*?>)?:(.*)/i','', $text);
114                 $messages[] = array(E_ERROR, $m[2], null, null);
115         }
116         $Ajax->run();
117         return  in_ajax() ? fmt_errors() : ($before_box.fmt_errors().$text);
118 }
119 //----------------------------------------------------------------------------------------
120
121 function kill_login()
122 {
123         session_unset();
124         session_destroy();
125 }
126 //----------------------------------------------------------------------------------------
127
128 function login_fail()
129 {
130         global $path_to_root;
131         
132         header("HTTP/1.1 401 Authorization Required");
133         echo "<center><br><br><font size='5' color='red'><b>" . _("Incorrect Password") . "<b></font><br><br>";
134         echo "<b>" . _("The user and password combination is not valid for the system.") . "<b><br><br>";
135
136         echo _("If you are not an authorized user, please contact your system administrator to obtain an account to enable you to use the system.");
137         echo "<br><a href='$path_to_root/index.php'>" . _("Try again") . "</a>";
138         echo "</center>";
139
140         kill_login();
141         die();
142 }
143
144 //----------------------------------------------------------------------------------------
145
146 function check_page_security($page_security)
147 {
148         global $SysPrefs;
149         
150         $msg = '';
151         
152         if (!$_SESSION["wa_current_user"]->check_user_access())
153         {
154                 // notification after upgrade from pre-2.2 version
155                 $msg = $_SESSION["wa_current_user"]->old_db ?
156                          _("Security settings have not been defined for your user account.")
157                                 . "<br>" . _("Please contact your system administrator.")       
158                         : _("Please remove \$security_groups and \$security_headings arrays from config.php file!");
159         } elseif (!$_SESSION['SysPrefs']->db_ok && !$_SESSION["wa_current_user"]->can_access('SA_SOFTWAREUPGRADE')) {
160                 $msg = _('Access to application has been blocked until database upgrade is completed by system administrator.');
161         }
162         
163         if ($msg){
164                 display_error($msg);
165                 end_page(@$_REQUEST['popup']);
166                 kill_login();
167                 exit;
168         }
169
170         if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
171         {
172
173                 echo "<center><br><br><br><b>";
174                 echo _("The security settings on your account do not permit you to access this function");
175                 echo "</b>";
176                 echo "<br><br><br><br></center>";
177                 end_page(@$_REQUEST['popup']);
178                 exit;
179         }
180         if (!$_SESSION['SysPrefs']->db_ok 
181                 && !in_array($page_security, array('SA_SOFTWAREUPGRADE', 'SA_OPEN', 'SA_BACKUP')))
182         {
183                 display_error(_('System is blocked after source upgrade until database is updated on System/Software Upgrade page'));
184                 end_page();
185                 exit;
186         }
187
188 }
189 /*
190         Helper function for setting page security level depeding on 
191         GET start variable and/or some value stored in session variable.
192         Before the call $page_security should be set to default page_security value.
193 */
194 function set_page_security($value=null, $trans = array(), $gtrans = array())
195 {
196         global $page_security;
197
198         // first check is this is not start page call
199         foreach($gtrans as $key => $area)
200                 if (isset($_GET[$key])) {
201                         $page_security = $area;
202                         return;
203                 }
204
205         // then check session value
206         if (isset($trans[$value])) {
207                 $page_security = $trans[$value];
208                 return;
209         }
210 }
211
212 //-----------------------------------------------------------------------------
213 //      Removing magic quotes from nested arrays/variables
214 //
215 function strip_quotes($data)
216 {
217         if(get_magic_quotes_gpc()) {
218                 if(is_array($data)) {
219                         foreach($data as $k => $v) {
220                                 $data[$k] = strip_quotes($data[$k]);
221                         }
222                 } else
223                         return stripslashes($data);
224         }
225         return $data;
226 }
227
228 function html_cleanup(&$parms)
229 {
230         foreach($parms as $name => $value) {
231 //              $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
232                 if (is_array($value))
233                         html_cleanup($parms[$name]);
234                 else
235                         $parms[$name] = @htmlspecialchars($value, ENT_QUOTES, $_SESSION['language']->encoding);
236         }
237         reset($parms); // needed for direct key() usage later throughout the sources
238 }
239
240 //============================================================================
241 //
242 //
243 function login_timeout()
244 {
245         // skip timeout on logout page
246         if ($_SESSION["wa_current_user"]->logged) {
247                 $tout = $_SESSION["wa_current_user"]->timeout;
248                 if ($tout && (time() > $_SESSION["wa_current_user"]->last_act + $tout))
249                 {
250                         $_SESSION["wa_current_user"]->logged = false;
251                 }
252                 $_SESSION["wa_current_user"]->last_act = time();
253         }
254 }
255 //============================================================================
256 if (!isset($path_to_root))
257 {
258         $path_to_root = ".";
259 }
260
261 // Prevent register_globals vulnerability
262 if (isset($_GET['path_to_root']) || isset($_POST['path_to_root']))
263         die("Restricted access");
264
265 include_once($path_to_root . "/includes/errors.inc");
266 // colect all error msgs
267 set_error_handler('error_handler' /*, errtypes */);
268
269 include_once($path_to_root . "/includes/current_user.inc");
270 include_once($path_to_root . "/frontaccounting.php");
271 include_once($path_to_root . "/admin/db/security_db.inc");
272 include_once($path_to_root . "/includes/lang/language.php");
273 include_once($path_to_root . "/config_db.php");
274 include_once($path_to_root . "/includes/ajax.inc");
275 include_once($path_to_root . "/includes/ui/ui_msgs.inc");
276 include_once($path_to_root . "/includes/prefs/sysprefs.inc");
277
278 include_once($path_to_root . "/includes/hooks.inc");
279 //
280 // include all extensions hook files.
281 //
282 foreach ($installed_extensions as $ext)
283 {
284         if (file_exists($path_to_root.'/'.$ext['path'].'/hooks.php'))
285                 include_once($path_to_root.'/'.$ext['path'].'/hooks.php');
286 }
287
288 /*
289         Uncomment the setting below when using FA on shared hosting
290         to avoid unexpeced session timeouts.
291         Make sure this directory exists and is writable!
292 */
293 // ini_set('session.save_path', dirname(__FILE__).'/../tmp/');
294
295 ini_set('session.gc_maxlifetime', 36000); // 10hrs
296
297 $Session_manager = new SessionManager();
298 $Session_manager->sessionStart('FA'.md5(dirname(__FILE__)));
299
300 // this is to fix the "back-do-you-want-to-refresh" issue - thanx PHPFreaks
301 header("Cache-control: private");
302
303 include_once($path_to_root . "/config.php");
304 get_text_init();
305
306 // Page Initialisation
307 if (!isset($_SESSION['language']) || !method_exists($_SESSION['language'], 'set_language')) 
308 {
309         $l = array_search_value($dflt_lang, $installed_languages,  'code');
310         $_SESSION['language'] = new language($l['name'], $l['code'], $l['encoding'],
311          (isset($l['rtl']) && $l['rtl'] === true) ? 'rtl' : 'ltr');
312 }
313
314 $_SESSION['language']->set_language($_SESSION['language']->code);
315
316
317 include_once($path_to_root . "/includes/access_levels.inc");
318 include_once($path_to_root . "/version.php");
319 include_once($path_to_root . "/includes/main.inc");
320
321 // Ajax communication object
322 $Ajax = new Ajax();
323
324 // js/php validation rules container
325 $Validate = array();
326 // bindings for editors
327 $Editors = array();
328 // page help. Currently help for function keys.
329 $Pagehelp = array();
330
331 $Refs = new references();
332
333 // intercept all output to destroy it in case of ajax call
334 register_shutdown_function('end_flush');
335 ob_start('output_html',0);
336
337 if (!isset($_SESSION["wa_current_user"]))
338         $_SESSION["wa_current_user"] = new current_user();
339
340 html_cleanup($_GET);
341 html_cleanup($_POST);
342 html_cleanup($_REQUEST);
343 html_cleanup($_SERVER);
344
345 // logout.php is the only page we should have always 
346 // accessable regardless of access level and current login status.
347 if (strstr($_SERVER['PHP_SELF'], 'logout.php') == false){
348
349         login_timeout();
350
351         if (!$_SESSION["wa_current_user"]->old_db)
352                 include_once($path_to_root . '/company/'.user_company().'/installed_extensions.php');
353
354         install_hooks();
355
356         if (!$_SESSION["wa_current_user"]->logged_in())
357         {
358                 // Show login screen
359                 if (!isset($_POST["user_name_entry_field"]) or $_POST["user_name_entry_field"] == "")
360                 {
361                         // strip ajax marker from uri, to force synchronous page reload
362                         $_SESSION['timeout'] = array( 'uri'=>preg_replace('/JsHttpRequest=(?:(\d+)-)?([^&]+)/s',
363                                         '', @htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, $_SESSION['language']->encoding)), 
364                                 'post' => $_POST);
365
366                         include($path_to_root . "/access/login.php");
367                         if (in_ajax())
368                                 $Ajax->activate('_page_body');
369                         exit;
370                 } else {
371
372                         $succeed = isset($db_connections[$_POST["company_login_name"]]) &&
373                                 $_SESSION["wa_current_user"]->login($_POST["company_login_name"],
374                                 $_POST["user_name_entry_field"], $_POST["password"]);
375                         // select full vs fallback ui mode on login
376                         $_SESSION["wa_current_user"]->ui_mode = $_POST['ui_mode'];
377                         if (!$succeed)
378                         {
379                         // Incorrect password
380                                 login_fail();
381                         }
382                         $lang = &$_SESSION['language'];
383                         $lang->set_language($_SESSION['language']->code);
384                 }
385         } else
386                 set_global_connection();
387
388         if (!isset($_SESSION["App"])) {
389                 $_SESSION["App"] = new front_accounting();
390                 $_SESSION["App"]->init();
391         }
392 }
393
394 $SysPrefs = &$_SESSION['SysPrefs'];
395
396 // POST vars cleanup needed for direct reuse.
397 // We quote all values later with db_escape() before db update.
398 $_POST = strip_quotes($_POST);
399
400 ?>