Finally fix up session restore functionality. Move session handling from login.php...
[squirrelmail.git] / include / init.php
1 <?php
2
3 /**
4 * init.php -- initialisation file
5 *
6 * File should be loaded in every file in src/ or plugins that occupate an entire frame
7 *
8 * @copyright &copy; 2006 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 * @version $Id$
11 * @package squirrelmail
12 */
13
14 /**
15 * This is a development version so in order to track programmer mistakes we
16 * set the error reporting to E_ALL
17 */
18 error_reporting(E_ALL);
19
20
21 /**
22 * Make sure we have a page name
23 *
24 */
25 if ( !defined('PAGE_NAME') ) define('PAGE_NAME', NULL);
26
27
28 /**
29 * If register_globals are on, unregister globals.
30 * Second test covers boolean set as string (php_value register_globals off).
31 */
32 if ((bool) ini_get('register_globals') &&
33 strtolower(ini_get('register_globals'))!='off') {
34 /**
35 * Remove all globals that are not reserved by PHP
36 * 'value' and 'key' are used by foreach. Don't unset them inside foreach.
37 */
38 foreach ($GLOBALS as $key => $value) {
39 switch($key) {
40 case 'HTTP_POST_VARS':
41 case '_POST':
42 case 'HTTP_GET_VARS':
43 case '_GET':
44 case 'HTTP_COOKIE_VARS':
45 case '_COOKIE':
46 case 'HTTP_SERVER_VARS':
47 case '_SERVER':
48 case 'HTTP_ENV_VARS':
49 case '_ENV':
50 case 'HTTP_POST_FILES':
51 case '_FILES':
52 case '_REQUEST':
53 case 'HTTP_SESSION_VARS':
54 case '_SESSION':
55 case 'GLOBALS':
56 case 'key':
57 case 'value':
58 break;
59 default:
60 unset($GLOBALS[$key]);
61 }
62 }
63 // Unset variables used in foreach
64 unset($GLOBALS['key']);
65 unset($GLOBALS['value']);
66 }
67
68 /**
69 * Used as a dummy value, e.g., for passing as an empty
70 * hook argument (where the value is passed by reference,
71 * and therefore NULL itself is not acceptable).
72 */
73 global $null;
74 $null = NULL;
75
76 /**
77 * [#1518885] session.use_cookies = off breaks SquirrelMail
78 *
79 * When session cookies are not used, all http redirects, meta refreshes,
80 * src/download.php and javascript URLs are broken. Setting must be set
81 * before session is started.
82 */
83 if (!(bool)ini_get('session.use_cookies') ||
84 ini_get('session.use_cookies') == 'off') {
85 ini_set('session.use_cookies','1');
86 }
87
88 /**
89 * calculate SM_PATH and calculate the base_uri
90 * assumptions made: init.php is only called from plugins or from the src dir.
91 * files in the plugin directory may not be part of a subdirectory called "src"
92 *
93 */
94 if (isset($_SERVER['SCRIPT_NAME'])) {
95 $a = explode('/',$_SERVER['SCRIPT_NAME']);
96 } elseif (isset($HTTP_SERVER_VARS['SCRIPT_NAME'])) {
97 $a = explode('/',$HTTP_SERVER_VARS['SCRIPT_NAME']);
98 } else {
99 $error = 'Unable to detect script environment. '
100 .'Please test your PHP settings and send PHP core config, $_SERVER '
101 .'and $HTTP_SERVER_VARS to SquirrelMail developers.';
102 die($error);
103 }
104 $sSM_PATH = '';
105 for($i = count($a) -2;$i > -1; --$i) {
106 $sSM_PATH .= '../';
107 if ($a[$i] === 'src' || $a[$i] === 'plugins') {
108 break;
109 }
110 }
111
112 $base_uri = implode('/',array_slice($a,0,$i)). '/';
113
114 define('SM_PATH',$sSM_PATH);
115 define('SM_BASE_URI', $base_uri);
116 /**
117 * global var $bInit is used to check if initialisation took place.
118 * At this moment it's a workarounf for the include of addrbook_search_html
119 * inside compose.php. If we found a better way then remove this. Do only use
120 * this var if you know for sure a page can be called stand alone and be included
121 * in another file.
122 */
123 $bInit = true;
124
125 /**
126 * This theme as a failsafe if no themes were found, or if we error
127 * out before anything could be initialised.
128 */
129 $color = array();
130 $color[0] = '#DCDCDC'; /* light gray TitleBar */
131 $color[1] = '#800000'; /* red */
132 $color[2] = '#CC0000'; /* light red Warning/Error Messages */
133 $color[3] = '#A0B8C8'; /* green-blue Left Bar Background */
134 $color[4] = '#FFFFFF'; /* white Normal Background */
135 $color[5] = '#FFFFCC'; /* light yellow Table Headers */
136 $color[6] = '#000000'; /* black Text on left bar */
137 $color[7] = '#0000CC'; /* blue Links */
138 $color[8] = '#000000'; /* black Normal text */
139 $color[9] = '#ABABAB'; /* mid-gray Darker version of #0 */
140 $color[10] = '#666666'; /* dark gray Darker version of #9 */
141 $color[11] = '#770000'; /* dark red Special Folders color */
142 $color[12] = '#EDEDED';
143 $color[13] = '#800000'; /* (dark red) Color for quoted text -- > 1 quote */
144 $color[14] = '#ff0000'; /* (red) Color for quoted text -- >> 2 or more */
145 $color[15] = '#002266'; /* (dark blue) Unselectable folders */
146 $color[16] = '#ff9933'; /* (orange) Highlight color */
147
148 require(SM_PATH . 'functions/global.php');
149 require(SM_PATH . 'functions/strings.php');
150 require(SM_PATH . 'functions/arrays.php');
151
152 /* load default configuration */
153 require(SM_PATH . 'config/config_default.php');
154 /* reset arrays in default configuration */
155 $ldap_server = array();
156 $plugins = array();
157 $fontsets = array();
158 $aTemplateSet = array();
159 $aTemplateSet[0]['ID'] = 'default';
160 $aTemplateSet[0]['NAME'] = 'Default';
161
162 /* load site configuration */
163 require(SM_PATH . 'config/config.php');
164 /* load local configuration overrides */
165 if (file_exists(SM_PATH . 'config/config_local.php')) {
166 require(SM_PATH . 'config/config_local.php');
167 }
168
169 require(SM_PATH . 'functions/plugin.php');
170 require(SM_PATH . 'include/constants.php');
171 require(SM_PATH . 'include/languages.php');
172 require(SM_PATH . 'class/template/Template.class.php');
173 require(SM_PATH . 'class/error.class.php');
174
175 /**
176 * If magic_quotes_runtime is on, SquirrelMail breaks in new and creative ways.
177 * Force magic_quotes_runtime off.
178 * tassium@squirrelmail.org - I put it here in the hopes that all SM code includes this.
179 * If there's a better place, please let me know.
180 */
181 ini_set('magic_quotes_runtime','0');
182
183
184 /* if running with magic_quotes_gpc then strip the slashes
185 from POST and GET global arrays */
186 if (get_magic_quotes_gpc()) {
187 sqstripslashes($_GET);
188 sqstripslashes($_POST);
189 }
190
191
192 /* strip any tags added to the url from PHP_SELF.
193 This fixes hand crafted url XXS expoits for any
194 page that uses PHP_SELF as the FORM action */
195 $_SERVER['PHP_SELF'] = strip_tags($_SERVER['PHP_SELF']);
196
197 $PHP_SELF = php_self();
198
199 /**
200 * Initialize the session
201 */
202
203 /** set the name of the session cookie */
204 if (!isset($session_name) || !$session_name) {
205 $session_name = 'SQMSESSID';
206 }
207
208 /**
209 * When on login page or if session.auto_start is On
210 * we want to destroy/close the session (save off
211 * possible session restoration values first)
212 */
213 if (!sqGetGlobalVar('session_expired_post', $sep, SQ_SESSION))
214 $sep = '';
215 if (!sqGetGlobalVar('session_expired_location', $sel, SQ_SESSION))
216 $sel = '';
217 $sSessionAutostartName = session_name();
218 $sCookiePath = null;
219 if (PAGE_NAME == 'login'
220 || (isset($sSessionAutostartName) && $sSessionAutostartName !== $session_name)) {
221 $sCookiePath = ini_get('session.cookie_path');
222 $sCookieDomain = ini_get('session.cookie_domain');
223 // reset the cookie
224 setcookie($sSessionAutostartName,'',time() - 604800,$sCookiePath,$sCookieDomain);
225 @session_destroy();
226 session_write_close();
227
228 /**
229 * in some rare instances, the session seems to stick
230 * around even after destroying it (!!), so if it does,
231 * we'll manually flatten the $_SESSION data
232 */
233 if (!empty($_SESSION))
234 $_SESSION = array();
235 }
236
237 /**
238 * includes from classes stored in the session
239 */
240 require(SM_PATH . 'class/mime.class.php');
241
242 ini_set('session.name' , $session_name);
243 session_set_cookie_params (0, $base_uri);
244 sqsession_is_active();
245
246 /**
247 * SquirrelMail internal version number -- DO NOT CHANGE
248 * $sm_internal_version = array (release, major, minor)
249 */
250 $SQM_INTERNAL_VERSION = explode('.', SM_VERSION, 3);
251 $SQM_INTERNAL_VERSION[2] = intval($SQM_INTERNAL_VERSION[2]);
252
253
254 /* load prefs system; even when user not logged in, should be OK to do this here */
255 require(SM_PATH . 'functions/prefs.php');
256
257 $prefs_backend = do_hook('prefs_backend', $null);
258 if (isset($prefs_backend) && !empty($prefs_backend) && file_exists(SM_PATH . $prefs_backend)) {
259 require(SM_PATH . $prefs_backend);
260 } elseif (isset($prefs_dsn) && !empty($prefs_dsn)) {
261 require(SM_PATH . 'functions/db_prefs.php');
262 } else {
263 require(SM_PATH . 'functions/file_prefs.php');
264 }
265
266
267 /* if plugins are disabled only for one user and
268 * the current user is NOT that user, turn them
269 * back on
270 */
271 sqgetGlobalVar('username',$username,SQ_SESSION);
272 if ($disable_plugins && !empty($disable_plugins_user)
273 && $username != $disable_plugins_user) {
274 $disable_plugins = false;
275 }
276
277 /* remove all plugins if they are disabled */
278 if ($disable_plugins) {
279 $plugins = array();
280 }
281
282
283 /**
284 * Include Compatibility plugin if available.
285 */
286 if (!$disable_plugins && file_exists(SM_PATH . 'plugins/compatibility/functions.php'))
287 include_once(SM_PATH . 'plugins/compatibility/functions.php');
288
289 /**
290 * MAIN PLUGIN LOADING CODE HERE
291 * On init, we no longer need to load all plugin setup files.
292 * Now, we load the statically generated hook registrations here
293 * and let the hook calls include only the plugins needed.
294 */
295 $squirrelmail_plugin_hooks = array();
296 if (!$disable_plugins && file_exists(SM_PATH . 'config/plugin_hooks.php')) {
297 require(SM_PATH . 'config/plugin_hooks.php');
298 }
299
300 /**
301 * allow plugins to override main configuration; hook is placed
302 * here to allow plugins to use session information to do their work
303 */
304 do_hook('config_override', $null);
305
306 /**
307 * DISABLED.
308 * Remove globalized session data in rg=on setups
309 *
310 * Code can be utilized when session is started, but data is not loaded.
311 * We have already loaded configuration and other important vars. Can't
312 * clean session globals here.
313 if ((bool) @ini_get('register_globals') &&
314 strtolower(ini_get('register_globals'))!='off') {
315 foreach ($_SESSION as $key => $value) {
316 unset($GLOBALS[$key]);
317 }
318 }
319 */
320
321 sqsession_register(SM_BASE_URI,'base_uri');
322
323 /**
324 * Retrieve the language cookie
325 */
326 if (! sqgetGlobalVar('squirrelmail_language',$squirrelmail_language,SQ_COOKIE)) {
327 $squirrelmail_language = '';
328 }
329
330
331 /**
332 * Do something special for some pages. This is based on the PAGE_NAME constand
333 * set at the top of every page.
334 */
335 switch (PAGE_NAME) {
336 case 'style':
337
338 // need to get the right template set up
339 //
340 sqGetGlobalVar('templateid', $templateid, SQ_GET);
341
342 // sanitize just in case...
343 //
344 $templateid = preg_replace('/(\.\.\/){1,}/', '', $templateid);
345
346 // make sure given template actually is available
347 //
348 $found_templateset = false;
349 for ($i = 0; $i < count($aTemplateSet); ++$i) {
350 if ($aTemplateSet[$i]['ID'] == $templateid) {
351 $found_templateset = true;
352 break;
353 }
354 }
355
356 // FIXME: do we need/want to check here for actual (physical) presence of template sets?
357 // selected template not available, fall back to default template
358 //
359 if (!$found_templateset) {
360 $sTemplateID = Template::get_default_template_set();
361 } else {
362 $sTemplateID = $templateid;
363 }
364
365 session_write_close();
366 break;
367
368 case 'redirect':
369 require(SM_PATH . 'functions/auth.php');
370 //nobreak;
371
372 case 'login':
373 require(SM_PATH . 'functions/display_messages.php' );
374 require(SM_PATH . 'functions/page_header.php');
375 require(SM_PATH . 'functions/html.php');
376
377 // put session restore data back into session if necessary
378 if (!empty($sel)) {
379 sqsession_register($sel, 'session_expired_location');
380 if (!empty($sep))
381 sqsession_register($sep, 'session_expired_post');
382 }
383
384 // reset template file cache
385 //
386 $sTemplateID = Template::get_default_template_set();
387 Template::cache_template_file_hierarchy(TRUE);
388
389 /**
390 * Make sure icon variables are setup for the login page.
391 */
392 $icon_theme = $icon_themes[$icon_theme_def]['PATH'];
393 /*
394 * NOTE: The $icon_theme_path var should contain the path to the icon
395 * theme to use. If the admin has disabled icons, or the user has
396 * set the icon theme to "None," no icons will be used.
397 */
398 $icon_theme_path = (!$use_icons || $icon_theme=='none') ? NULL : ($icon_theme == 'template' ? SM_PATH . Template::calculate_template_images_directory($sTemplateID) : $icon_theme);
399
400 /**
401 * cleanup old cookies with a cookie path the same as the standard php.ini
402 * cookie path. All previous SquirrelMail version used the standard php.ini
403 * cookie path for storing the session name. That behaviour changed.
404 */
405 if ($sCookiePath !== SM_BASE_URI) {
406 /**
407 * do not delete the standard sessions with session.name is i.e. PHPSESSID
408 * because they probably belong to other php apps
409 */
410 if (ini_get('session.name') !== $sSessionAutostartName) {
411 // This does not work. Sometimes the cookie with SQSESSID=deleted and path /
412 // is picked up in webmail.php => login will fail
413 //sqsetcookie(ini_get('session.name'),'',0,$sCookiePath);
414 }
415 }
416 break;
417 default:
418 require(SM_PATH . 'functions/display_messages.php' );
419 require(SM_PATH . 'functions/page_header.php');
420 require(SM_PATH . 'functions/html.php');
421
422
423 /**
424 * Check if we are logged in
425 */
426 require(SM_PATH . 'functions/auth.php');
427
428 if ( !sqsession_is_registered('user_is_logged_in') ) {
429
430 // use $message to indicate what logout text the user
431 // will see... if 0, typical "You must be logged in"
432 // if 1, information that the user session was saved
433 // and will be resumed after (re)login
434 //
435 $message = 0;
436
437 // First we store some information in the new session to prevent
438 // information-loss.
439 //
440 $session_expired_post = $_POST;
441 $session_expired_location = PAGE_NAME;
442 if (!sqsession_is_registered('session_expired_post')) {
443 sqsession_register($session_expired_post,'session_expired_post');
444 }
445 if (!sqsession_is_registered('session_expired_location')) {
446 sqsession_register($session_expired_location,'session_expired_location');
447 if ($session_expired_location == 'compose')
448 $message = 1;
449 }
450 // signout page will deal with users who aren't logged
451 // in on its own; don't show error here
452 //
453 if ( PAGE_NAME == 'signout' ) {
454 return;
455 }
456
457 /**
458 * Initialize the template object (logout_error uses it)
459 */
460 /*
461 * $sTemplateID is not initialized when a user is not logged in, so we
462 * will use the config file defaults here. If the neccesary variables
463 * are net set, force a default value.
464 */
465 $sTemplateID = Template::get_default_template_set();
466 $oTemplate = Template::construct_template($sTemplateID);
467
468 set_up_language($squirrelmail_language, true);
469 if (!$message)
470 logout_error( _("You must be logged in to access this page.") );
471 else
472 logout_error( _("Your session has expired, but will be resumed after logging in again.") );
473 exit;
474 }
475
476 //FIXME: remove next line if the placement of the copy of this line above does not prove to be problematic
477 sqgetGlobalVar('username',$username,SQ_SESSION);
478 sqgetGlobalVar('authz',$authz,SQ_SESSION);
479
480 /**
481 * Setting the prefs backend
482 */
483 sqgetGlobalVar('prefs_cache', $prefs_cache, SQ_SESSION );
484 sqgetGlobalVar('prefs_are_cached', $prefs_are_cached, SQ_SESSION );
485
486 if ( !sqsession_is_registered('prefs_are_cached') ||
487 !isset( $prefs_cache) ||
488 !is_array( $prefs_cache)) {
489 $prefs_are_cached = false;
490 $prefs_cache = false; //array();
491 }
492
493 /**
494 * initializing user settings
495 */
496 require(SM_PATH . 'include/load_prefs.php');
497
498 // i do not understand the frames language cookie story
499 /**
500 * We'll need this to later have a noframes version
501 *
502 * Check if the user has a language preference, but no cookie.
503 * Send him a cookie with his language preference, if there is
504 * such discrepancy.
505 */
506 $my_language = getPref($data_dir, $username, 'language');
507 if ($my_language != $squirrelmail_language) {
508 sqsetcookie('squirrelmail_language', $my_language, time()+2592000, $base_uri);
509 }
510 // /dont understand
511
512 /**
513 * Set up the language.
514 */
515 $err=set_up_language(getPref($data_dir, $username, 'language'));
516
517 // Japanese translation used without mbstring support
518 if ($err==2) {
519 $sError =
520 "<p>You need to have PHP installed with the multibyte string function \n".
521 "enabled (using configure option --enable-mbstring).</p>\n".
522 "<p>System assumed that you accidently switched to Japanese translation \n".
523 "and reverted your language preference to English.</p>\n".
524 "<p>Please refresh this page in order to use webmail.</p>\n";
525 error_box($sError);
526 }
527
528 $timeZone = getPref($data_dir, $username, 'timezone');
529
530 /* Check to see if we are allowed to set the TZ environment variable.
531 * We are able to do this if ...
532 * safe_mode is disabled OR
533 * safe_mode_allowed_env_vars is empty (you are allowed to set any) OR
534 * safe_mode_allowed_env_vars contains TZ
535 */
536 $tzChangeAllowed = (!ini_get('safe_mode')) ||
537 !strcmp(ini_get('safe_mode_allowed_env_vars'),'') ||
538 preg_match('/^([\w_]+,)*TZ/', ini_get('safe_mode_allowed_env_vars'));
539
540 if ( $timeZone != SMPREF_NONE && ($timeZone != "")
541 && $tzChangeAllowed ) {
542
543 // get time zone key, if strict or custom strict timezones are used
544 if (isset($time_zone_type) &&
545 ($time_zone_type == 1 || $time_zone_type == 3)) {
546 /* load time zone functions */
547 require(SM_PATH . 'include/timezones.php');
548 $realTimeZone = sq_get_tz_key($timeZone);
549 } else {
550 $realTimeZone = $timeZone;
551 }
552
553 // set time zone
554 if ($realTimeZone) {
555 putenv("TZ=".$realTimeZone);
556 }
557 }
558
559 /**
560 * php 5.1.0 added time zone functions. Set time zone with them in order
561 * to prevent E_STRICT notices and allow time zone modifications in safe_mode.
562 */
563 if (function_exists('date_default_timezone_set')) {
564 if ($timeZone != SMPREF_NONE && $timeZone != "") {
565 date_default_timezone_set($timeZone);
566 } else {
567 // interface runs on server's time zone. Remove php E_STRICT complains
568 $default_timezone = @date_default_timezone_get();
569 date_default_timezone_set($default_timezone);
570 }
571 }
572 break;
573 }
574
575 /*
576 * $sTemplateID is not initialized when a user is not logged in, so we
577 * will use the config file defaults here. If the neccesary variables
578 * are not set, force a default value.
579 *
580 * If the user is logged in, $sTemplateID will be set in load_prefs.php,
581 * so we shouldn't change it here.
582 */
583 if (!isset($sTemplateID)) {
584 $sTemplateID = Template::get_default_template_set();
585 $icon_theme_path = !$use_icons ? NULL : Template::calculate_template_images_directory($sTemplateID);
586 }
587
588 // template object may have already been constructed in load_prefs.php
589 //
590 if (empty($oTemplate)) {
591 $oTemplate = Template::construct_template($sTemplateID);
592 }
593
594 // We want some variables to always be available to the template
595 $oTemplate->assign('javascript_on',
596 (sqGetGlobalVar('user_is_logged_in', $user_is_logged_in, SQ_SESSION)
597 ? checkForJavascript() : 0));
598 $oTemplate->assign('base_uri', sqm_baseuri());
599 $always_include = array('sTemplateID', 'icon_theme_path');
600 foreach ($always_include as $var) {
601 $oTemplate->assign($var, (isset($$var) ? $$var : NULL));
602 }
603
604 /**
605 * Initialize our custom error handler object
606 */
607 $oErrorHandler = new ErrorHandler($oTemplate,'error_message.tpl');
608
609 /**
610 * Activate custom error handling
611 */
612 if (version_compare(PHP_VERSION, "4.3.0", ">=")) {
613 $oldErrorHandler = set_error_handler(array($oErrorHandler, 'SquirrelMailErrorhandler'));
614 } else {
615 $oldErrorHandler = set_error_handler('SquirrelMailErrorhandler');
616 }
617
618 /**
619 * Javascript support detection function
620 * @param boolean $reset recheck javascript support if set to true.
621 * @return integer SMPREF_JS_ON or SMPREF_JS_OFF ({@see include/constants.php})
622 * @since 1.5.1
623 */
624 function checkForJavascript($reset = FALSE) {
625 global $data_dir, $username, $javascript_on, $javascript_setting;
626
627 if ( !$reset && sqGetGlobalVar('javascript_on', $javascript_on, SQ_SESSION) )
628 return $javascript_on;
629
630 $user_is_logged_in = FALSE;
631 if ( $reset || !isset($javascript_setting) )
632 $javascript_setting = getPref($data_dir, $username, 'javascript_setting', SMPREF_JS_AUTODETECT);
633
634 if ( !sqGetGlobalVar('new_js_autodetect_results', $js_autodetect_results) &&
635 !sqGetGlobalVar('js_autodetect_results', $js_autodetect_results) )
636 $js_autodetect_results = SMPREF_JS_OFF;
637
638 if ( $javascript_setting == SMPREF_JS_AUTODETECT )
639 $javascript_on = $js_autodetect_results;
640 else
641 $javascript_on = $javascript_setting;
642
643 sqsession_register($javascript_on, 'javascript_on');
644 return $javascript_on;
645 }
646
647 function sqm_baseuri() {
648 global $base_uri;
649 return $base_uri;
650 }