Avoid notices in some environments
[squirrelmail.git] / include / init.php
CommitLineData
202bcbcc 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 *
1977ab55 8 * @copyright 2006-2010 The SquirrelMail Project Team
202bcbcc 9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
10 * @version $Id$
11 * @package squirrelmail
12 */
13
202bcbcc 14/**
15 * This is a development version so in order to track programmer mistakes we
16 * set the error reporting to E_ALL
1888b1bf 17FIXME: disabling this for now, because we now have $sm_debug_mode, but the problem with that is that we don't know what it will be until we have loaded the config file, a good 175 lines below after several important files have been included, etc. For now, we'll trust that developers have turned on E_ALL in php.ini anyway, but this can be uncommented if not.
202bcbcc 18 */
1888b1bf 19//error_reporting(E_ALL);
20
202bcbcc 21
202bcbcc 22/**
c7ebdfcf 23 * Make sure we have a page name
24 *
25 */
26if ( !defined('PAGE_NAME') ) define('PAGE_NAME', NULL);
27
28
29/**
6a2a6e44 30 * If register_globals are on, unregister globals.
a3b99374 31 * Second test covers boolean set as string (php_value register_globals off).
6a2a6e44 32 */
55dd9abf 33if ((bool) ini_get('register_globals') &&
a3b99374 34 strtolower(ini_get('register_globals'))!='off') {
6a2a6e44 35 /**
55dd9abf 36 * Remove all globals that are not reserved by PHP
37 * 'value' and 'key' are used by foreach. Don't unset them inside foreach.
6a2a6e44 38 */
55dd9abf 39 foreach ($GLOBALS as $key => $value) {
40 switch($key) {
41 case 'HTTP_POST_VARS':
42 case '_POST':
43 case 'HTTP_GET_VARS':
44 case '_GET':
45 case 'HTTP_COOKIE_VARS':
46 case '_COOKIE':
47 case 'HTTP_SERVER_VARS':
48 case '_SERVER':
49 case 'HTTP_ENV_VARS':
50 case '_ENV':
51 case 'HTTP_POST_FILES':
52 case '_FILES':
53 case '_REQUEST':
54 case 'HTTP_SESSION_VARS':
55 case '_SESSION':
56 case 'GLOBALS':
57 case 'key':
58 case 'value':
59 break;
55dd9abf 60 default:
61 unset($GLOBALS[$key]);
62 }
6a2a6e44 63 }
55dd9abf 64 // Unset variables used in foreach
65 unset($GLOBALS['key']);
66 unset($GLOBALS['value']);
6a2a6e44 67}
68
71efd1ed 69/**
d849b570 70 * Used as a dummy value, e.g., for passing as an empty
e39d00e9 71 * hook argument (where the value is passed by reference,
72 * and therefore NULL itself is not acceptable).
d849b570 73 */
086ad092 74global $null;
d849b570 75$null = NULL;
76
77/**
dbbd586e 78 * The global $server_os variable will be "windows" if
79 * we are working in a Windows environment or "*nix"
80 * otherwise.
81 */
82global $server_os;
83if (DIRECTORY_SEPARATOR == '\\') $server_os = 'windows'; else $server_os = '*nix';
84
85/**
71efd1ed 86 * [#1518885] session.use_cookies = off breaks SquirrelMail
87 *
086ad092 88 * When session cookies are not used, all http redirects, meta refreshes,
89 * src/download.php and javascript URLs are broken. Setting must be set
71efd1ed 90 * before session is started.
91 */
92if (!(bool)ini_get('session.use_cookies') ||
93 ini_get('session.use_cookies') == 'off') {
94 ini_set('session.use_cookies','1');
95}
6a2a6e44 96
79dd8c72 97/**
98 * Initialize seed of random number generator.
99 * We use a number of things to randomize input: current time in ms,
100 * info about the remote client, info about the current process, the
101 * randomness of uniqid and stat of the current file.
102 *
103 * We seed this here only once per init, not only to save cycles
104 * but also to make the result of mt_rand more random (it now also
105 * depends on the number of times mt_rand was called before in this
106 * execution.
107 */
108$seed = microtime() . $_SERVER['REMOTE_PORT'] . $_SERVER['REMOTE_ADDR'] . getmypid();
109
110if (function_exists('getrusage')) {
111 /* Avoid warnings with Win32 */
112 $dat = @getrusage();
113 if (isset($dat) && is_array($dat)) { $seed .= implode('', $dat); }
114}
115
116if(!empty($_SERVER['UNIQUE_ID'])) {
117 $seed .= $_SERVER['UNIQUE_ID'];
118}
119
120$seed .= uniqid(mt_rand(),TRUE);
7428254a 121$seed .= implode('', stat( __FILE__));
79dd8c72 122
8313aa5e 123// mt_srand() uses an integer to seed, so we need to distill our
124// very large seed to something useful (without taking a sub-string,
125// the integer conversion of such a large number is always 0 on
126// many systems, but strangely, 9 hex numbers - even if larger
127// than a signed 32 bit integer - seem to be an acceptable "integer"
128// seed (perhaps it is used as unsigned?)...
129// we may want to revisit this and always force it to be less than
130// 2,147,483,647
131//
132$seed = hexdec(substr(md5($seed), 0, 9));
133
134// PHP 4.2 and up don't require seeding, but their used seed algorithm
135// is of questionable quality, so we keep doing it ourselves. */
136mt_srand($seed);
3f081dd0 137
6a2a6e44 138/**
202bcbcc 139 * calculate SM_PATH and calculate the base_uri
140 * assumptions made: init.php is only called from plugins or from the src dir.
141 * files in the plugin directory may not be part of a subdirectory called "src"
142 *
143 */
144if (isset($_SERVER['SCRIPT_NAME'])) {
3f081dd0 145 $a = explode('/', $_SERVER['SCRIPT_NAME']);
202bcbcc 146} elseif (isset($HTTP_SERVER_VARS['SCRIPT_NAME'])) {
3f081dd0 147 $a = explode('/', $HTTP_SERVER_VARS['SCRIPT_NAME']);
b0829edf 148} else {
3f081dd0 149 $error = 'Unable to detect script environment. Please test your PHP '
150 . 'settings and send your PHP core configuration, $_SERVER and '
151 . '$HTTP_SERVER_VARS contents to the SquirrelMail developers.';
b0829edf 152 die($error);
202bcbcc 153}
154$sSM_PATH = '';
3f081dd0 155for($i = count($a) -2; $i > -1; --$i) {
202bcbcc 156 $sSM_PATH .= '../';
157 if ($a[$i] === 'src' || $a[$i] === 'plugins') {
158 break;
159 }
160}
161
3f081dd0 162$base_uri = implode('/', array_slice($a, 0, $i)). '/';
202bcbcc 163
202bcbcc 164define('SM_PATH',$sSM_PATH);
6a2a6e44 165define('SM_BASE_URI', $base_uri);
3f081dd0 166
167
202bcbcc 168/**
169 * global var $bInit is used to check if initialisation took place.
170 * At this moment it's a workarounf for the include of addrbook_search_html
171 * inside compose.php. If we found a better way then remove this. Do only use
172 * this var if you know for sure a page can be called stand alone and be included
173 * in another file.
174 */
175$bInit = true;
176
8e1e2794 177/**
178 * This theme as a failsafe if no themes were found, or if we error
179 * out before anything could be initialised.
180 */
181$color = array();
182$color[0] = '#DCDCDC'; /* light gray TitleBar */
183$color[1] = '#800000'; /* red */
184$color[2] = '#CC0000'; /* light red Warning/Error Messages */
185$color[3] = '#A0B8C8'; /* green-blue Left Bar Background */
186$color[4] = '#FFFFFF'; /* white Normal Background */
187$color[5] = '#FFFFCC'; /* light yellow Table Headers */
188$color[6] = '#000000'; /* black Text on left bar */
189$color[7] = '#0000CC'; /* blue Links */
190$color[8] = '#000000'; /* black Normal text */
191$color[9] = '#ABABAB'; /* mid-gray Darker version of #0 */
192$color[10] = '#666666'; /* dark gray Darker version of #9 */
193$color[11] = '#770000'; /* dark red Special Folders color */
194$color[12] = '#EDEDED';
195$color[13] = '#800000'; /* (dark red) Color for quoted text -- > 1 quote */
196$color[14] = '#ff0000'; /* (red) Color for quoted text -- >> 2 or more */
197$color[15] = '#002266'; /* (dark blue) Unselectable folders */
198$color[16] = '#ff9933'; /* (orange) Highlight color */
199
1888b1bf 200require(SM_PATH . 'include/constants.php');
202bcbcc 201require(SM_PATH . 'functions/global.php');
4ffcf13a 202require(SM_PATH . 'functions/strings.php');
918fcc1d 203require(SM_PATH . 'functions/arrays.php');
67c826ce 204require(SM_PATH . 'functions/files.php');
5e68a08e 205
206/* load default configuration */
207require(SM_PATH . 'config/config_default.php');
208/* reset arrays in default configuration */
209$ldap_server = array();
210$plugins = array();
211$fontsets = array();
5e68a08e 212$aTemplateSet = array();
28294310 213$aTemplateSet[0]['ID'] = 'default';
214$aTemplateSet[0]['NAME'] = 'Default';
01fd1d1a 215
5e68a08e 216/* load site configuration */
202bcbcc 217require(SM_PATH . 'config/config.php');
5e68a08e 218/* load local configuration overrides */
219if (file_exists(SM_PATH . 'config/config_local.php')) {
220 require(SM_PATH . 'config/config_local.php');
221}
222
1888b1bf 223
224/**
225 * Set PHP error reporting level based on the SquirrelMail debug mode
226 */
227$error_level = 0;
228if ($sm_debug_mode & SM_DEBUG_MODE_SIMPLE)
229 $error_level |= E_ERROR;
230if ($sm_debug_mode & SM_DEBUG_MODE_MODERATE
231 || $sm_debug_mode & SM_DEBUG_MODE_ADVANCED)
232 $error_level |= E_ALL;
233if ($sm_debug_mode & SM_DEBUG_MODE_STRICT)
234 $error_level |= E_STRICT;
235error_reporting($error_level);
236
237
8f557b94 238/**
239 * Detect SSL connections
240 */
241$is_secure_connection = is_ssl_secured_connection();
242
243
202bcbcc 244require(SM_PATH . 'functions/plugin.php');
202bcbcc 245require(SM_PATH . 'include/languages.php');
42b5e8aa 246require(SM_PATH . 'class/template/Template.class.php');
5ab684a5 247require(SM_PATH . 'class/error.class.php');
202bcbcc 248
249/**
250 * If magic_quotes_runtime is on, SquirrelMail breaks in new and creative ways.
251 * Force magic_quotes_runtime off.
252 * tassium@squirrelmail.org - I put it here in the hopes that all SM code includes this.
253 * If there's a better place, please let me know.
254 */
255ini_set('magic_quotes_runtime','0');
256
257
258/* if running with magic_quotes_gpc then strip the slashes
259 from POST and GET global arrays */
430a19f3 260if (function_exists('get_magic_quotes_gpc') && @get_magic_quotes_gpc()) {
202bcbcc 261 sqstripslashes($_GET);
262 sqstripslashes($_POST);
263}
264
202bcbcc 265
960b7ec2 266/**
267 * Strip any tags added to the url from PHP_SELF.
268 * This fixes hand crafted url XXS expoits for any
269 * page that uses PHP_SELF as the FORM action
270 * Update: strip_tags() won't catch something like
271 * src/right_main.php?sort=0&startMessage=1&mailbox=INBOX&xxx="><script>window.open("http://example.com")</script>
272 * or
273 * contrib/decrypt_headers.php/%22%20onmouseover=%22alert(%27hello%20world%27)%22%3E
274 * because it doesn't bother with broken tags.
275 * htmlspecialchars() is the preferred method.
276 * QUERY_STRING also needs the same treatment since it is
277 * used in php_self().
278 */
49ec41bc 279if (isset($_SERVER['REQUEST_URI']))
280 $_SERVER['REQUEST_URI'] = htmlspecialchars($_SERVER['REQUEST_URI']);
281if (isset($_SERVER['PHP_SELF']))
282 $_SERVER['PHP_SELF'] = htmlspecialchars($_SERVER['PHP_SELF']);
283if (isset($_SERVER['QUERY_STRING']))
284 $_SERVER['QUERY_STRING'] = htmlspecialchars($_SERVER['QUERY_STRING']);
202bcbcc 285
286$PHP_SELF = php_self();
287
288/**
289 * Initialize the session
290 */
291
e8c4e350 292/** set the name of the session cookie */
293if (!isset($session_name) || !$session_name) {
294 $session_name = 'SQMSESSID';
295}
296
297/**
319ad3c0 298 * When session.auto_start is On we want to destroy/close the session
1d537493 299 */
300$sSessionAutostartName = session_name();
ccb5faf0 301$sSessionAutostartID = session_id();
302if (!empty($sSessionAutostartID) && $sSessionAutostartName !== $session_name) {
1d537493 303 $sCookiePath = ini_get('session.cookie_path');
304 $sCookieDomain = ini_get('session.cookie_domain');
e8c4e350 305 // reset the cookie
ccb5faf0 306 sqsetcookie($sSessionAutostartName,'',1,$sCookiePath,$sCookieDomain);
e8c4e350 307 @session_destroy();
308 session_write_close();
1d537493 309}
e8c4e350 310
202bcbcc 311/**
312 * includes from classes stored in the session
313 */
314require(SM_PATH . 'class/mime.class.php');
315
202bcbcc 316ini_set('session.name' , $session_name);
317session_set_cookie_params (0, $base_uri);
318sqsession_is_active();
319
202bcbcc 320/**
319ad3c0 321 * When on login page, have to reset the user session, making
322 * sure to save session restore data first
323 */
324if (PAGE_NAME == 'login') {
325 if (!sqGetGlobalVar('session_expired_post', $sep, SQ_SESSION))
326 $sep = '';
327 if (!sqGetGlobalVar('session_expired_location', $sel, SQ_SESSION))
328 $sel = '';
329 sqsession_destroy();
330 session_write_close();
331
332 /**
333 * in some rare instances, the session seems to stick
334 * around even after destroying it (!!), so if it does,
335 * we'll manually flatten the $_SESSION data
336 */
337 if (!empty($_SESSION))
338 $_SESSION = array();
339
bc3acc5a 340 /**
341 * Allow administrators to define custom session handlers
342 * for SquirrelMail without needing to change anything in
343 * php.ini (application-level).
344 *
345 * In config_local.php, admin needs to put:
346 *
347 * $custom_session_handlers = array(
348 * 'my_open_handler',
349 * 'my_close_handler',
350 * 'my_read_handler',
351 * 'my_write_handler',
352 * 'my_destroy_handler',
353 * 'my_gc_handler',
354 * );
355 * session_module_name('user');
356 * session_set_save_handler(
357 * $custom_session_handlers[0],
358 * $custom_session_handlers[1],
359 * $custom_session_handlers[2],
360 * $custom_session_handlers[3],
361 * $custom_session_handlers[4],
362 * $custom_session_handlers[5]
363 * );
364 *
365 * We need to replicate that code once here because PHP has
366 * long had a bug that resets the session handler mechanism
367 * when the session data is also destroyed. Because of this
368 * bug, even administrators who define custom session handlers
369 * via a PHP pre-load defined in php.ini (auto_prepend_file)
370 * will still need to define the $custom_session_handlers array
371 * in config_local.php.
372 */
373 global $custom_session_handlers;
374 if (!empty($custom_session_handlers)) {
375 $open = $custom_session_handlers[0];
376 $close = $custom_session_handlers[1];
377 $read = $custom_session_handlers[2];
378 $write = $custom_session_handlers[3];
379 $destroy = $custom_session_handlers[4];
380 $gc = $custom_session_handlers[5];
381 session_module_name('user');
382 session_set_save_handler($open, $close, $read, $write, $destroy, $gc);
383 }
384
319ad3c0 385 sqsession_is_active();
386 session_regenerate_id();
ef33def6 387
388 // put session restore data back into session if necessary
389 if (!empty($sel)) {
390 sqsession_register($sel, 'session_expired_location');
391 if (!empty($sep))
392 sqsession_register($sep, 'session_expired_post');
393 }
319ad3c0 394}
395
396/**
5aed95be 397 * SquirrelMail internal version number -- DO NOT CHANGE
398 * $sm_internal_version = array (release, major, minor)
399 */
a895042a 400$SQM_INTERNAL_VERSION = explode('.', SM_VERSION, 3);
b37e457f 401$SQM_INTERNAL_VERSION[2] = intval($SQM_INTERNAL_VERSION[2]);
5aed95be 402
93d67e0d 403
6d5775db 404/* load prefs system; even when user not logged in, should be OK to do this here */
405require(SM_PATH . 'functions/prefs.php');
406
6d5775db 407
086ad092 408/* if plugins are disabled only for one user and
93d67e0d 409 * the current user is NOT that user, turn them
410 * back on
411 */
0d56053e 412sqgetGlobalVar('username', $username, SQ_SESSION);
93d67e0d 413if ($disable_plugins && !empty($disable_plugins_user)
414 && $username != $disable_plugins_user) {
415 $disable_plugins = false;
416}
417
4a9f6063 418
93d67e0d 419/* remove all plugins if they are disabled */
420if ($disable_plugins) {
421 $plugins = array();
422}
423
424
5aed95be 425/**
426 * Include Compatibility plugin if available.
427 */
93d67e0d 428if (!$disable_plugins && file_exists(SM_PATH . 'plugins/compatibility/functions.php'))
5aed95be 429 include_once(SM_PATH . 'plugins/compatibility/functions.php');
430
4a9f6063 431
5aed95be 432/**
433 * MAIN PLUGIN LOADING CODE HERE
086ad092 434 * On init, we no longer need to load all plugin setup files.
5aed95be 435 * Now, we load the statically generated hook registrations here
436 * and let the hook calls include only the plugins needed.
437 */
438$squirrelmail_plugin_hooks = array();
93d67e0d 439if (!$disable_plugins && file_exists(SM_PATH . 'config/plugin_hooks.php')) {
4a9f6063 440//FIXME: if we keep the plugin hooks array static like this, it seems like we should also keep the template files list in a static file too (when a new user session is started or the template set is changed, the code will dynamically iterate through the directory heirarchy of the template directory and catalog all the template files therein (and store the "catalog" in PHP session) -- instead, we could do that once at config-time and keep that static so SM can just include the file just like the line below)
5aed95be 441 require(SM_PATH . 'config/plugin_hooks.php');
442}
443
4a9f6063 444
5aed95be 445/**
4a9f6063 446 * Plugin authors note that the "config_override" hook used to be
447 * executed here, but please adapt your plugin to use this "prefs_backend"
448 * hook instead, making sure that it does NOT return anything, since
449 * doing so will interfere with proper prefs system functionality.
450 * Of course, otherwise, this hook may be used to do any configuration
451 * overrides as needed, as well as set up a custom preferences backend.
5aed95be 452 */
4a9f6063 453$prefs_backend = do_hook('prefs_backend', $null);
454if (isset($prefs_backend) && !empty($prefs_backend) && file_exists(SM_PATH . $prefs_backend)) {
455 require(SM_PATH . $prefs_backend);
456} elseif (isset($prefs_dsn) && !empty($prefs_dsn)) {
457 require(SM_PATH . 'functions/db_prefs.php');
458} else {
459 require(SM_PATH . 'functions/file_prefs.php');
460}
461
462
5aed95be 463
464/**
3464e1f4 465 * DISABLED.
202bcbcc 466 * Remove globalized session data in rg=on setups
086ad092 467 *
3464e1f4 468 * Code can be utilized when session is started, but data is not loaded.
086ad092 469 * We have already loaded configuration and other important vars. Can't
aae60854 470 * clean session globals here, beside, the cleanout of globals at the
471 * top of this file will have removed anything this code would find anyway.
3464e1f4 472if ((bool) @ini_get('register_globals') &&
473 strtolower(ini_get('register_globals'))!='off') {
202bcbcc 474 foreach ($_SESSION as $key => $value) {
475 unset($GLOBALS[$key]);
476 }
477}
3464e1f4 478*/
6a2a6e44 479
826ddd72 480sqsession_register(SM_BASE_URI,'base_uri');
6a2a6e44 481
202bcbcc 482/**
483 * Retrieve the language cookie
484 */
485if (! sqgetGlobalVar('squirrelmail_language',$squirrelmail_language,SQ_COOKIE)) {
486 $squirrelmail_language = '';
487}
488
bf3abdc3 489
202bcbcc 490/**
775a1f52 491 * In some cases, buffering all output allows more complex functionality,
492 * especially for plugins that want to add headers on hooks that are beyond
493 * the point of output having been sent to the browser otherwise.
494 *
495 * Note that we don't turn this on any earlier since we want to allow plugins
496 * to turn it on themselves via a configuration override on the prefs_backend
497 * hook.
498 *
499 */
500if ($buffer_output) ob_start(!empty($buffered_output_handler) ? $buffered_output_handler : NULL);
501
502
503/**
f0d28f44 504 * Do something special for some pages. This is based on the PAGE_NAME constant
9e06a3ea 505 * set at the top of every page.
202bcbcc 506 */
0d56053e 507$set_up_langage_after_template_setup = FALSE;
9e06a3ea 508switch (PAGE_NAME) {
086ad092 509 case 'style':
c4e5f61f 510
2b26084f 511 // need to get the right template set up
28294310 512 //
513 sqGetGlobalVar('templateid', $templateid, SQ_GET);
c4e5f61f 514
2b26084f 515 // sanitize just in case...
28294310 516 //
517 $templateid = preg_replace('/(\.\.\/){1,}/', '', $templateid);
518
519 // make sure given template actually is available
520 //
28294310 521 $found_templateset = false;
522 for ($i = 0; $i < count($aTemplateSet); ++$i) {
523 if ($aTemplateSet[$i]['ID'] == $templateid) {
524 $found_templateset = true;
525 break;
526 }
527 }
c4e5f61f 528
be155e14 529// FIXME: do we need/want to check here for actual (physical) presence of template sets?
28294310 530 // selected template not available, fall back to default template
531 //
532 if (!$found_templateset) {
42b5e8aa 533 $sTemplateID = Template::get_default_template_set();
28294310 534 } else {
535 $sTemplateID = $templateid;
c4e5f61f 536 }
537
2b26084f 538 session_write_close();
c4e5f61f 539 break;
540
f0d28f44 541 case 'mailto':
542 // nothing to do
543 break;
544
202bcbcc 545 case 'redirect':
2e616fa4 546 require(SM_PATH . 'functions/auth.php');
202bcbcc 547 //nobreak;
bf3abdc3 548
202bcbcc 549 case 'login':
550 require(SM_PATH . 'functions/display_messages.php' );
551 require(SM_PATH . 'functions/page_header.php');
552 require(SM_PATH . 'functions/html.php');
42b5e8aa 553
554 // reset template file cache
555 //
556 $sTemplateID = Template::get_default_template_set();
d81572f7 557 Template::cache_template_file_hierarchy($sTemplateID, TRUE);
42b5e8aa 558
1d537493 559 /**
01fd1d1a 560 * Make sure icon variables are setup for the login page.
561 */
562 $icon_theme = $icon_themes[$icon_theme_def]['PATH'];
563 /*
564 * NOTE: The $icon_theme_path var should contain the path to the icon
565 * theme to use. If the admin has disabled icons, or the user has
566 * set the icon theme to "None," no icons will be used.
567 */
568 $icon_theme_path = (!$use_icons || $icon_theme=='none') ? NULL : ($icon_theme == 'template' ? SM_PATH . Template::calculate_template_images_directory($sTemplateID) : $icon_theme);
569
202bcbcc 570 break;
571 default:
572 require(SM_PATH . 'functions/display_messages.php' );
573 require(SM_PATH . 'functions/page_header.php');
574 require(SM_PATH . 'functions/html.php');
202bcbcc 575
576
577 /**
7428254a 578 * Check if we are logged in and does optional referrer check
202bcbcc 579 */
580 require(SM_PATH . 'functions/auth.php');
581
7428254a 582 global $check_referrer, $domain;
583 if (!sqgetGlobalVar('HTTP_REFERER', $referrer, SQ_SERVER)) $referrer = '';
584 if ($check_referrer == '###DOMAIN###') $check_referrer = $domain;
585 if (!empty($check_referrer)) {
586 $ssl_check_referrer = 'https://' . $check_referrer;
587 $check_referrer = 'http://' . $check_referrer;
588 }
589 if (!sqsession_is_registered('user_is_logged_in')
590 || ($check_referrer && !empty($referrer)
591 && strpos(strtolower($referrer), strtolower($check_referrer)) !== 0
592 && strpos(strtolower($referrer), strtolower($ssl_check_referrer)) !== 0)) {
f8eb968d 593
594 // use $message to indicate what logout text the user
595 // will see... if 0, typical "You must be logged in"
596 // if 1, information that the user session was saved
7428254a 597 // and will be resumed after (re)login, if 2, there
598 // seems to have been a XSS or phishing attack (bad
599 // referrer)
f8eb968d 600 //
601 $message = 0;
602
202bcbcc 603 // First we store some information in the new session to prevent
604 // information-loss.
605 //
606 $session_expired_post = $_POST;
f8e68605 607 $session_expired_location = PAGE_NAME;
202bcbcc 608 if (!sqsession_is_registered('session_expired_post')) {
609 sqsession_register($session_expired_post,'session_expired_post');
610 }
611 if (!sqsession_is_registered('session_expired_location')) {
612 sqsession_register($session_expired_location,'session_expired_location');
f8e68605 613 if ($session_expired_location == 'compose')
f8eb968d 614 $message = 1;
202bcbcc 615 }
7428254a 616
617 // was bad referrer the reason we were rejected?
618 //
619 if (sqsession_is_registered('user_is_logged_in')
620 && $check_referrer && !empty($referrer))
621 $message = 2;
622
202bcbcc 623 // signout page will deal with users who aren't logged
624 // in on its own; don't show error here
625 //
9e06a3ea 626 if ( PAGE_NAME == 'signout' ) {
a140422a 627 return;
202bcbcc 628 }
629
8efadc6b 630 /**
631 * Initialize the template object (logout_error uses it)
632 */
8efadc6b 633 /*
086ad092 634 * $sTemplateID is not initialized when a user is not logged in, so we
635 * will use the config file defaults here. If the neccesary variables
d81572f7 636 * are not set, force a default value.
8efadc6b 637 */
d81572f7 638 if (PAGE_NAME == 'squirrelmail_rpc') {
639 $sTemplateID = Template::get_rpc_template_set();
640 } else {
641 $sTemplateID = Template::get_default_template_set();
642 }
28294310 643 $oTemplate = Template::construct_template($sTemplateID);
8efadc6b 644
202bcbcc 645 set_up_language($squirrelmail_language, true);
f8eb968d 646 if (!$message)
647 logout_error( _("You must be logged in to access this page.") );
7428254a 648 else if ($message == 1)
f8eb968d 649 logout_error( _("Your session has expired, but will be resumed after logging in again.") );
7428254a 650 else if ($message == 2)
651 logout_error( _("The current page request appears to have originated from an unrecognized source.") );
202bcbcc 652 exit;
653 }
654
79524620 655 sqgetGlobalVar('authz',$authz,SQ_SESSION);
202bcbcc 656
657 /**
658 * Setting the prefs backend
659 */
660 sqgetGlobalVar('prefs_cache', $prefs_cache, SQ_SESSION );
661 sqgetGlobalVar('prefs_are_cached', $prefs_are_cached, SQ_SESSION );
662
663 if ( !sqsession_is_registered('prefs_are_cached') ||
664 !isset( $prefs_cache) ||
665 !is_array( $prefs_cache)) {
666 $prefs_are_cached = false;
667 $prefs_cache = false; //array();
668 }
669
202bcbcc 670 /**
671 * initializing user settings
672 */
673 require(SM_PATH . 'include/load_prefs.php');
674
202bcbcc 675 /**
676 * We'll need this to later have a noframes version
677 *
678 * Check if the user has a language preference, but no cookie.
679 * Send him a cookie with his language preference, if there is
680 * such discrepancy.
681 */
682 $my_language = getPref($data_dir, $username, 'language');
683 if ($my_language != $squirrelmail_language) {
684 sqsetcookie('squirrelmail_language', $my_language, time()+2592000, $base_uri);
685 }
202bcbcc 686
0d56053e 687 $set_up_langage_after_template_setup = TRUE;
202bcbcc 688
689 $timeZone = getPref($data_dir, $username, 'timezone');
690
691 /* Check to see if we are allowed to set the TZ environment variable.
692 * We are able to do this if ...
693 * safe_mode is disabled OR
694 * safe_mode_allowed_env_vars is empty (you are allowed to set any) OR
695 * safe_mode_allowed_env_vars contains TZ
696 */
697 $tzChangeAllowed = (!ini_get('safe_mode')) ||
698 !strcmp(ini_get('safe_mode_allowed_env_vars'),'') ||
699 preg_match('/^([\w_]+,)*TZ/', ini_get('safe_mode_allowed_env_vars'));
700
701 if ( $timeZone != SMPREF_NONE && ($timeZone != "")
702 && $tzChangeAllowed ) {
703
704 // get time zone key, if strict or custom strict timezones are used
705 if (isset($time_zone_type) &&
706 ($time_zone_type == 1 || $time_zone_type == 3)) {
707 /* load time zone functions */
708 require(SM_PATH . 'include/timezones.php');
709 $realTimeZone = sq_get_tz_key($timeZone);
710 } else {
711 $realTimeZone = $timeZone;
712 }
713
714 // set time zone
715 if ($realTimeZone) {
716 putenv("TZ=".$realTimeZone);
717 }
718 }
867fed37 719
720 /**
721 * php 5.1.0 added time zone functions. Set time zone with them in order
722 * to prevent E_STRICT notices and allow time zone modifications in safe_mode.
723 */
724 if (function_exists('date_default_timezone_set')) {
725 if ($timeZone != SMPREF_NONE && $timeZone != "") {
726 date_default_timezone_set($timeZone);
727 } else {
728 // interface runs on server's time zone. Remove php E_STRICT complains
729 $default_timezone = @date_default_timezone_get();
086ad092 730 date_default_timezone_set($default_timezone);
867fed37 731 }
732 }
202bcbcc 733 break;
734}
735
202bcbcc 736/*
086ad092 737 * $sTemplateID is not initialized when a user is not logged in, so we
738 * will use the config file defaults here. If the neccesary variables
28294310 739 * are not set, force a default value.
086ad092 740 *
741 * If the user is logged in, $sTemplateID will be set in load_prefs.php,
28294310 742 * so we shouldn't change it here.
202bcbcc 743 */
28294310 744if (!isset($sTemplateID)) {
d81572f7 745 if (PAGE_NAME == 'squirrelmail_rpc') {
746 $sTemplateID = Template::get_rpc_template_set();
747 } else {
748 $sTemplateID = Template::get_default_template_set();
749 }
28294310 750 $icon_theme_path = !$use_icons ? NULL : Template::calculate_template_images_directory($sTemplateID);
3aa46abc 751}
be155e14 752
753// template object may have already been constructed in load_prefs.php
754//
755if (empty($oTemplate)) {
756 $oTemplate = Template::construct_template($sTemplateID);
757}
202bcbcc 758
7aae649d 759// We want some variables to always be available to the template
551c7b53 760//
e39d00e9 761$oTemplate->assign('javascript_on',
762 (sqGetGlobalVar('user_is_logged_in', $user_is_logged_in, SQ_SESSION)
763 ? checkForJavascript() : 0));
fe8103c2 764$oTemplate->assign('base_uri', sqm_baseuri());
457e8593 765$always_include = array('sTemplateID', 'icon_theme_path');
7aae649d 766foreach ($always_include as $var) {
767 $oTemplate->assign($var, (isset($$var) ? $$var : NULL));
768}
769
551c7b53 770// A few output elements are used often, so just get them once here
771//
772$nbsp = $oTemplate->fetch('non_breaking_space.tpl');
773$br = $oTemplate->fetch('line_break.tpl');
774
0d56053e 775
776/**
777 * Set up the language.
778 *
779 * This code block corresponds to the *default* block of the switch
780 * statement above, but the language cannot be set up until after the
781 * template is instantiated, so we set $set_up_langage_after_template_setup
782 * above and do the linguistic stuff now.
783 */
784if ($set_up_langage_after_template_setup) {
785 $err=set_up_language(getPref($data_dir, $username, 'language'));
786
787 // Japanese translation used without mbstring support
788 if ($err==2) {
789 $sError = "<p>Your administrator needs to have PHP installed with the multibyte string extension enabled (using configure option --enable-mbstring).</p>\n"
790 . "<p>This system has assumed that you accidently switched to Japanese and has reverted your language preference to English.</p>\n"
791 . "<p>Please refresh this page in order to continue using your webmail.</p>\n";
792 error_box($sError);
793 }
794}
795
796
202bcbcc 797/**
798 * Initialize our custom error handler object
799 */
202bcbcc 800$oErrorHandler = new ErrorHandler($oTemplate,'error_message.tpl');
801
0d56053e 802
202bcbcc 803/**
804 * Activate custom error handling
805 */
806if (version_compare(PHP_VERSION, "4.3.0", ">=")) {
807 $oldErrorHandler = set_error_handler(array($oErrorHandler, 'SquirrelMailErrorhandler'));
808} else {
809 $oldErrorHandler = set_error_handler('SquirrelMailErrorhandler');
810}
811
f0d28f44 812
813// ============================================================================
814// ================= End of Live Code, Beginning of Functions =================
815// ============================================================================
816
817
202bcbcc 818/**
819 * Javascript support detection function
820 * @param boolean $reset recheck javascript support if set to true.
867fed37 821 * @return integer SMPREF_JS_ON or SMPREF_JS_OFF ({@see include/constants.php})
202bcbcc 822 * @since 1.5.1
823 */
202bcbcc 824function checkForJavascript($reset = FALSE) {
825 global $data_dir, $username, $javascript_on, $javascript_setting;
826
827 if ( !$reset && sqGetGlobalVar('javascript_on', $javascript_on, SQ_SESSION) )
828 return $javascript_on;
829
960b7ec2 830 //FIXME: this isn't used anywhere else in this function; can we remove it? why is it here?
e39d00e9 831 $user_is_logged_in = FALSE;
bf3abdc3 832 if ( $reset || !isset($javascript_setting) )
202bcbcc 833 $javascript_setting = getPref($data_dir, $username, 'javascript_setting', SMPREF_JS_AUTODETECT);
834
835 if ( !sqGetGlobalVar('new_js_autodetect_results', $js_autodetect_results) &&
836 !sqGetGlobalVar('js_autodetect_results', $js_autodetect_results) )
837 $js_autodetect_results = SMPREF_JS_OFF;
838
839 if ( $javascript_setting == SMPREF_JS_AUTODETECT )
840 $javascript_on = $js_autodetect_results;
841 else
842 $javascript_on = $javascript_setting;
843
844 sqsession_register($javascript_on, 'javascript_on');
845 return $javascript_on;
846}
847
848function sqm_baseuri() {
849 global $base_uri;
850 return $base_uri;
8e1e2794 851}