Added db_write/db_void hooks.
[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 function output_html($text)
13 {
14         global $before_box, $Ajax, $messages;
15         // Fatal errors are not send to error_handler,
16         // so we must check the output
17         if ($text && preg_match('/\bFatal error(<.*?>)?:(.*)/i', $text, $m)) {
18                 $Ajax->aCommands = array();  // Don't update page via ajax on errors
19                 $text = preg_replace('/\bFatal error(<.*?>)?:(.*)/i','', $text);
20                 $messages[] = array(E_ERROR, $m[2], null, null);
21         }
22         $Ajax->run();
23         return  in_ajax() ? fmt_errors() : ($before_box.fmt_errors().$text);
24 }
25 //----------------------------------------------------------------------------------------
26
27 function kill_login()
28 {
29         session_unset();
30         session_destroy();
31 }
32 //----------------------------------------------------------------------------------------
33
34 function login_fail()
35 {
36         global $path_to_root;
37         
38         header("HTTP/1.1 401 Authorization Required");
39         echo "<center><br><br><font size='5' color='red'><b>" . _("Incorrect Password") . "<b></font><br><br>";
40         echo "<b>" . _("The user and password combination is not valid for the system.") . "<b><br><br>";
41
42         echo _("If you are not an authorized user, please contact your system administrator to obtain an account to enable you to use the system.");
43         echo "<br><a href='$path_to_root/index.php'>" . _("Try again") . "</a>";
44         echo "</center>";
45
46         kill_login();
47         die();
48 }
49
50 //----------------------------------------------------------------------------------------
51
52 function check_page_security($page_security)
53 {
54         global $SysPrefs;
55         
56         $msg = '';
57         
58         if (!$_SESSION["wa_current_user"]->check_user_access())
59         {
60                 // notification after upgrade from pre-2.2 version
61                 $msg = $_SESSION["wa_current_user"]->old_db ?
62                          _("Security settings have not been defined for your user account.")
63                                 . "<br>" . _("Please contact your system administrator.")       
64                         : _("Please remove \$security_groups and \$security_headings arrays from config.php file!");
65         } elseif (!$_SESSION['SysPrefs']->db_ok && !$_SESSION["wa_current_user"]->can_access('SA_SOFTWAREUPGRADE')) {
66                 $msg = _('Access to application has been blocked until database upgrade is completed by system administrator.');
67         }
68         
69         if ($msg){
70                 display_error($msg);
71                 end_page();
72                 kill_login();
73                 exit;
74         }
75
76         if (!$_SESSION["wa_current_user"]->can_access_page($page_security))
77         {
78
79                 echo "<center><br><br><br><b>";
80                 echo _("The security settings on your account do not permit you to access this function");
81                 echo "</b>";
82                 echo "<br><br><br><br></center>";
83                 end_page();
84                 exit;
85         }
86         if (!$_SESSION['SysPrefs']->db_ok 
87                 && !in_array($page_security, array('SA_SOFTWAREUPGRADE', 'SA_OPEN', 'SA_BACKUP')))
88         {
89                 display_error(_('System is blocked after source upgrade until database is updated on System/Software Upgrade page'));
90                 end_page();
91                 exit;
92         }
93
94 }
95 /*
96         Helper function for setting page security level depeding on 
97         GET start variable and/or some value stored in session variable.
98         Before the call $page_security should be set to default page_security value.
99 */
100 function set_page_security($value=null, $trans = array(), $gtrans = array())
101 {
102         global $page_security;
103
104         // first check is this is not start page call
105         foreach($gtrans as $key => $area)
106                 if (isset($_GET[$key])) {
107                         $page_security = $area;
108                         return;
109                 }
110
111         // then check session value
112         if (isset($trans[$value])) {
113                 $page_security = $trans[$value];
114                 return;
115         }
116 }
117
118 //-----------------------------------------------------------------------------
119 //      Removing magic quotes from nested arrays/variables
120 //
121 function strip_quotes($data)
122 {
123         if(get_magic_quotes_gpc()) {
124                 if(is_array($data)) {
125                         foreach($data as $k => $v) {
126                                 $data[$k] = strip_quotes($data[$k]);
127                         }
128                 } else
129                         return stripslashes($data);
130         }
131         return $data;
132 }
133
134 function html_cleanup(&$parms)
135 {
136         foreach($parms as $name => $value) {
137 //              $value = @html_entity_decode($value, ENT_QUOTES, $_SESSION['language']->encoding);
138                 if (is_array($value))
139                         html_cleanup($parms[$name]);
140                 else
141                         $parms[$name] = @htmlspecialchars($value, ENT_QUOTES, $_SESSION['language']->encoding);
142         }
143         reset($parms); // needed for direct key() usage later throughout the sources
144 }
145
146 //============================================================================
147 //
148 //
149 function login_timeout()
150 {
151         // skip timeout on logout page
152         if ($_SESSION["wa_current_user"]->logged) {
153                 $tout = $_SESSION["wa_current_user"]->timeout;
154                 if ($tout && (time() > $_SESSION["wa_current_user"]->last_act + $tout))
155                 {
156                         $_SESSION["wa_current_user"]->logged = false;
157                 }
158                 $_SESSION["wa_current_user"]->last_act = time();
159         }
160 }
161 //============================================================================
162 if (!isset($path_to_root))
163 {
164         $path_to_root = ".";
165 }
166
167 // Prevent register_globals vulnerability
168 if (isset($_GET['path_to_root']) || isset($_POST['path_to_root']))
169         die("Restricted access");
170
171 include_once($path_to_root . "/includes/current_user.inc");
172 include_once($path_to_root . "/frontaccounting.php");
173 include_once($path_to_root . "/admin/db/security_db.inc");
174 include_once($path_to_root . "/includes/lang/language.php");
175 include_once($path_to_root . "/config_db.php");
176 include_once($path_to_root . "/includes/ajax.inc");
177 include_once($path_to_root . "/includes/ui/ui_msgs.inc");
178 include_once($path_to_root . "/includes/prefs/sysprefs.inc");
179
180 /*
181         Uncomment the setting below when using FA on shared hosting
182         to avoid unexpeced session timeouts.
183         Make sure this directory exists and is writable!
184 */
185 //ini_set('session.save_path', dirname(__FILE__).'/../tmp/');
186
187 ini_set('session.gc_maxlifetime', 36000); // 10hrs
188
189 session_name('FA'.md5(dirname(__FILE__)));
190 //include_once($path_to_root.'/modules/www_statistics/includes/db_sessions.inc');
191 session_start();
192
193 // this is to fix the "back-do-you-want-to-refresh" issue - thanx PHPFreaks
194 header("Cache-control: private");
195
196 include_once($path_to_root . "/config.php");
197 get_text_init();
198
199 // Page Initialisation
200 if (!isset($_SESSION['language']) || !method_exists($_SESSION['language'], 'set_language')) 
201 {
202         $l = array_search_value($dflt_lang, $installed_languages,  'code');
203         $_SESSION['language'] = new language($l['name'], $l['code'], $l['encoding'],
204          (isset($l['rtl']) && $l['rtl'] === true) ? 'rtl' : 'ltr');
205 }
206
207 $_SESSION['language']->set_language($_SESSION['language']->code);
208
209 include_once($path_to_root . "/includes/hooks.inc");
210
211 $Hooks = array();
212 // include current langauge related $Hooks object if locale file exists
213 if (file_exists($path_to_root . "/lang/".$_SESSION['language']->code."/locale.inc"))
214 {
215         include_once($path_to_root . "/lang/".$_SESSION['language']->code."/locale.inc");
216         $Hooks[] = new Hooks();
217 }
218
219 include_once($path_to_root . "/includes/access_levels.inc");
220 include_once($path_to_root . "/version.php");
221 include_once($path_to_root . "/includes/main.inc");
222
223 // Ajax communication object
224 $Ajax = new Ajax();
225
226 // js/php validation rules container
227 $Validate = array();
228 // bindings for editors
229 $Editors = array();
230 // page help. Currently help for function keys.
231 $Pagehelp = array();
232
233 $Refs = new references();
234
235 // intercept all output to destroy it in case of ajax call
236 register_shutdown_function('end_flush');
237 ob_start('output_html',0);
238
239 // colect all error msgs
240 set_error_handler('error_handler' /*, errtypes */);
241
242 if (!isset($_SESSION["wa_current_user"]))
243         $_SESSION["wa_current_user"] = new current_user();
244
245 html_cleanup($_GET);
246 html_cleanup($_POST);
247 html_cleanup($_REQUEST);
248
249 // logout.php is the only page we should have always 
250 // accessable regardless of access level and current login status.
251 if (strstr($_SERVER['PHP_SELF'], 'logout.php') == false){
252
253         login_timeout();
254
255         if (!$_SESSION["wa_current_user"]->logged_in())
256         {
257                 // Show login screen
258                 if (!isset($_POST["user_name_entry_field"]) or $_POST["user_name_entry_field"] == "")
259                 {
260                         // strip ajax marker from uri, to force synchronous page reload
261                         $_SESSION['timeout'] = array( 'uri'=>preg_replace('/JsHttpRequest=(?:(\d+)-)?([^&]+)/s',
262                                         '', @htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, $_SESSION['language']->encoding)), 
263                                 'post' => $_POST);
264
265                         include($path_to_root . "/access/login.php");
266                         if (in_ajax())
267                                 $Ajax->activate('_page_body');
268                         exit;
269                 } else {
270
271                         $succeed = isset($db_connections[$_POST["company_login_name"]]) &&
272                                 $_SESSION["wa_current_user"]->login($_POST["company_login_name"],
273                                 $_POST["user_name_entry_field"], md5($_POST["password"]));
274                         // select full vs fallback ui mode on login
275                         $_SESSION["wa_current_user"]->ui_mode = $_POST['ui_mode'];
276                         if (!$succeed)
277                         {
278                         // Incorrect password
279                                 login_fail();
280                         }
281                         $lang = &$_SESSION['language'];
282                         $lang->set_language($_SESSION['language']->code);
283                 }
284         } else
285                 set_global_connection();
286
287         if (!$_SESSION["wa_current_user"]->old_db)
288                 include_once($path_to_root . '/company/'.user_company().'/installed_extensions.php');
289
290         if (!isset($_SESSION["App"])) {
291                 $_SESSION["App"] = new front_accounting();
292                 $_SESSION["App"]->init();
293         }
294 }
295
296 $SysPrefs = &$_SESSION['SysPrefs'];
297
298 // POST vars cleanup needed for direct reuse.
299 // We quote all values later with db_escape() before db update.
300 $_POST = strip_quotes($_POST);
301
302 ?>