tiki-setup_base.php 21 KB
Newer Older
1
<?php
2
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
changi67's avatar
changi67 committed
3
// 
4 5
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6
// $Id$
changi67's avatar
changi67 committed
7

8
//this script may only be included - so its better to die if called directly.
changi67's avatar
changi67 committed
9 10 11
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
12
}
13
require_once ('tiki-filter-base.php');
14 15 16 17
// ---------------------------------------------------------------------
// basic php conf adjustment
// xhtml compliance
ini_set('arg_separator.output', '&amp;');
changi67's avatar
changi67 committed
18
// URL session handling is not safe or pretty
19
// better avoid using trans_sid for security reasons
changi67's avatar
changi67 committed
20 21
ini_set('session.use_only_cookies', 1);
// true, but you cannot change the url_rewriter.tags in safe mode ...
22
// its usually safe to leave it as is.
changi67's avatar
changi67 committed
23
//ini_set('url_rewriter.tags', '');
24 25 26 27 28 29
// use shared memory for sessions (useful in shared space)
// ini_set('session.save_handler', 'mm');
// ... or if you use turck mmcache
// ini_set('session.save_handler', 'mmcache');
// ... or if you just cant to store sessions in file
// ini_set('session.save_handler', 'files');
30
// Smarty workaround - if this would be 'On' in php.ini Smarty fails to parse tags
changi67's avatar
changi67 committed
31 32 33
ini_set('magic_quotes_sybase', 'Off');
ini_set('magic_quotes_runtime', 0);
ini_set('allow_call_time_pass_reference', 'On');
34 35
// ---------------------------------------------------------------------
// inclusions of mandatory stuff and setup
36 37 38 39
require_once ('lib/setup/compat.php');
require_once ('lib/tikiticketlib.php');
require_once ('db/tiki-db.php');
require_once ('lib/tikilib.php');
40
$tikilib = new TikiLib;
41 42
// Get tiki-setup_base needed preferences in one query
$prefs = array();
43 44
$needed_prefs = array(
	'session_lifetime' => '0',
45
	'session_storage' => 'default',
46 47
	'session_silent' => 'n',
	'session_cookie_name' => session_name(),
48
	'session_protected' => 'n',
49
	'tiki_cdn' => '',
50
	'tiki_cdn_ssl' => '',
51
	'language' => 'en',
52
	'lang_use_db' => 'n',
53 54 55 56 57 58 59
	'lastUpdatePrefs' => - 1,
	'feature_fullscreen' => 'n',
	'error_reporting_level' => 0,
	'smarty_notice_reporting' => 'n',
	'memcache_enabled' => 'n',
	'memcache_expiration' => 3600,
	'memcache_prefix' => 'tiki_',
60
	'memcache_compress' => 'y',
61
	'memcache_servers' => false,
sept_7's avatar
sept_7 committed
62 63
	'min_pass_length' => 5,
	'pass_chr_special' => 'n'
64
);
65 66 67 68 69 70
// check that tiki_preferences is there
if (empty($tikilib->query("SHOW TABLES LIKE 'tiki_preferences'")->numrows)) {
	// smarty not initialised at this point to do a polite message, sadly
	header('location: tiki-install.php');
	exit;
}
71
$tikilib->get_preferences($needed_prefs, true, true);
72
if (!isset($prefs['lastUpdatePrefs']) || $prefs['lastUpdatePrefs'] == - 1) {
rlpowell's avatar
 
rlpowell committed
73
	$tikilib->query('delete from `tiki_preferences` where `name`=?', array('lastUpdatePrefs'));
74
	$tikilib->query('insert into `tiki_preferences`(`name`,`value`) values(?,?)', array('lastUpdatePrefs', 1));
75 76 77 78 79
}

if ($prefs['session_protected'] == 'y' && ! isset($_SERVER['HTTPS'])) {
	header("Location: https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
	exit;
80
}
81

82 83 84 85 86 87
global $cachelib;
require_once ('lib/cache/cachelib.php');
global $logslib;
require_once ('lib/logs/logslib.php');
include_once ('lib/init/tra.php');

88 89 90 91 92 93 94 95
if( $prefs['memcache_enabled'] == 'y' ) {
	require_once('lib/cache/memcachelib.php');
	if( is_array( $prefs['memcache_servers'] ) ) {
		$servers = $prefs['memcache_servers'];
	} else {
		$servers = unserialize( $prefs['memcache_servers'] );
	}

96
	global $memcachelib;
97
	$memcachelib = new MemcacheLib( $servers, array(
98 99 100
		'enabled' => true,
		'expiration' => (int) $prefs['memcache_expiration'],
		'key_prefix' => $prefs['memcache_prefix'],
101
		'compress' => $prefs['memcache_compress'],
102 103 104
	) );
}

changi67's avatar
changi67 committed
105
require_once ('lib/tikidate.php');
106
$tikidate = new TikiDate();
107
// set session lifetime
108
if ($prefs['session_lifetime'] > 0) {
changi67's avatar
changi67 committed
109
	ini_set('session.gc_maxlifetime', $prefs['session_lifetime'] * 60);
110 111
}
// is session data  stored in DB or in filesystem?
112
if ($prefs['session_storage'] == 'db') {
113
	if ($api_tiki == 'adodb') {
changi67's avatar
changi67 committed
114
		require_once ('lib/tikisession-adodb.php');
115
	} elseif ($api_tiki == 'pdo') {
changi67's avatar
changi67 committed
116
		require_once ('lib/tikisession-pdo.php');
117
	}
lphuberdeau's avatar
lphuberdeau committed
118 119
} elseif( $prefs['session_storage'] == 'memcache' && isset( $memcachelib ) && $memcachelib->isEnabled() ) {
	require_once ('lib/tikisession-memcache.php');
120
}
lphuberdeau's avatar
lphuberdeau committed
121

122 123 124 125 126 127
if( ! isset( $prefs['session_cookie_name'] ) || empty( $prefs['session_cookie_name'] ) ) {
	$prefs['session_cookie_name'] = session_name();
}

session_name( $prefs['session_cookie_name'] );

128 129
// Only accept PHP's session ID in URL when the request comes from the tiki server itself
// This is used by features that need to query the server to retrieve tiki's generated html and images (e.g. pdf export)
130
if (isset($_GET[session_name()]) && $tikilib->get_ip_address() == '127.0.0.1') {
131 132
	$_COOKIE[session_name()] = $_GET[session_name()];
	session_id($_GET[session_name()]);
133
}
134

135 136 137 138
$start_session = true;
if ( $prefs['session_silent'] == 'y' && empty($_COOKIE[session_name()]) ) {
	$start_session = false;
}
139

140
// If called from the CDN, refuse to execute anything
141 142 143
$cdn_pref = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? $prefs['tiki_cdn_ssl'] : $prefs['tiki_cdn'];
if( $cdn_pref ) {
	$host = parse_url( $cdn_pref, PHP_URL_HOST );
144
	if( $host == $_SERVER['HTTP_HOST'] ) {
145 146 147
		header("HTTP/1.0 404 Not Found");
		echo "File not found.";
		exit;
148 149
	}
}
sylvieg's avatar
sylvieg committed
150 151 152
$cookie_path = '';
if (isset($_SERVER["REQUEST_URI"])) {
	$cookie_path = str_replace("\\", "/", dirname($_SERVER["REQUEST_URI"]));
153 154 155
	if ($cookie_path != '/') {
		$cookie_path .= '/';
	}
156
	ini_set('session.cookie_path', str_replace("\\", "/", $cookie_path));
157 158 159 160 161 162 163 164 165 166 167 168
	if ( $start_session ) {
		// enabing silent sessions mean a session is only started when a cookie is presented
		$session_params = session_get_cookie_params();
		session_set_cookie_params($session_params['lifetime'], $cookie_path);
		unset($session_params);
	
		try {
			require_once "Zend/Session.php";
			Zend_Session::start();
		} catch( Zend_Session_Exception $e ) {
			// Ignore
		}
169
	}
170
}
171

172
// Moved here from tiki-setup.php because smarty use a copy of session
173 174 175
if ($prefs['feature_fullscreen'] == 'y') {
	require_once ('lib/setup/fullscreen.php');
}
176
// Retrieve all preferences
changi67's avatar
changi67 committed
177
require_once ('lib/setup/prefs.php');
178
// Smarty needs session since 2.6.25
179
require_once ('lib/init/smarty.php');
180
require_once ('lib/userslib.php'); global $userlib;
181
$userlib = new UsersLib;
182
require_once ('lib/tikiaccesslib.php');
183
$access = new TikiAccessLib;
184
require_once ('lib/breadcrumblib.php');
185 186
// ------------------------------------------------------
// DEAL WITH XSS-TYPE ATTACKS AND OTHER REQUEST ISSUES
187
function remove_gpc(&$var) {
changi67's avatar
changi67 committed
188 189
	if (is_array($var)) {
		foreach($var as $key => $val) {
190
			remove_gpc($var[$key]);
191 192
		}
	} else {
193
		$var = stripslashes($var);
194 195 196
	}
}
// mose : simulate strong var type checking for http vars
changi67's avatar
changi67 committed
197 198 199 200 201 202 203
$patterns['int'] = "/^[0-9]*$/"; // *Id
$patterns['intSign'] = "/^[-+]?[0-9]*$/"; // *offset,
$patterns['char'] = "/^(pref:)?[-,_a-zA-Z0-9]*$/"; // sort_mode
$patterns['string'] = "/^<\/?(b|strong|small|br *\/?|ul|li|i)>|[^<>\";#]*$/"; // find, and such extended chars
$patterns['stringlist'] = "/^[^<>\"#]*$/"; // to, cc, bcc (for string lists like: user1;user2;user3)
$patterns['vars'] = "/^[-_a-zA-Z0-9]*$/"; // for variable keys
$patterns['dotvars'] = "/^[-_a-zA-Z0-9\.]*$/"; // same pattern as a variable key, but that may contain a dot
204
$patterns['hash'] = "/^[a-z0-9]*$/"; // for hash reqId in live support
205
// needed for the htmlpage inclusion in tiki-editpage
206
$patterns['url'] = "/^(https?:\/\/)?[^<>\"']*$/"; // needed for the htmlpage inclusion in tiki-editpage
207 208 209
// parameter type definitions. prepend a + if variable may not be empty, e.g. '+int'
$vartype['id'] = '+int';
$vartype['forumId'] = '+int';
210
$vartype['offset'] = 'intSign';
sylvieg's avatar
sylvieg committed
211 212
$vartype['prev_offset'] = 'intSign';
$vartype['next_offset'] = 'intSign';
213
$vartype['thresold'] = 'int';
214
$vartype['sort_mode'] = '+char';
215 216
$vartype['file_sort_mode'] = 'char';
$vartype['file_offset'] = 'int';
sylvieg's avatar
sylvieg committed
217 218 219
$vartype['file_find'] = 'string';
$vartype['file_prev_offset'] = 'intSign';
$vartype['file_next_offset'] = 'intSign';
220 221
$vartype['comments_offset'] = 'int';
$vartype['comments_thresold'] = 'int';
222
$vartype['comments_parentId'] = '+int';
223 224
$vartype['thread_sort_mode'] = '+char';
$vartype['thread_style'] = '+char';
225
$vartype['comments_per_page'] = '+int';
226
$vartype['topics_offset'] = 'int';
227
$vartype['topics_sort_mode'] = '+char';
228 229 230 231
$vartype['priority'] = 'int';
$vartype['theme'] = 'string';
$vartype['flag'] = 'char';
$vartype['lang'] = 'char';
232
$vartype['language'] = 'char';
233 234
$vartype['page'] = 'string';
$vartype['edit_mode'] = 'char';
235
$vartype['find'] = 'string';
236
$vartype['topic_find'] = 'string';
237
$vartype['initial'] = 'char';
238
$vartype['username'] = '+string';
239 240
$vartype['realName'] = 'string';
$vartype['homePage'] = 'string';
241 242 243
$vartype['to'] = 'stringlist';
$vartype['cc'] = 'stringlist';
$vartype['bcc'] = 'stringlist';
244 245
$vartype['subject'] = 'string';
$vartype['name'] = 'string';
246 247 248
$vartype['reqId'] = '+hash';
$vartype['days'] = '+int';
$vartype['max'] = '+int';
249
$vartype['maxRecords'] = '+int';
250 251 252 253 254
$vartype['numrows'] = '+int';
$vartype['rows'] = '+int';
$vartype['cols'] = '+int';
$vartype['topicname'] = '+string';
$vartype['error'] = 'string';
255
$vartype['editmode'] = 'char'; // from calendar
256 257
$vartype['actpass'] = '+string'; // remind password page
$vartype['user'] = '+string'; // remind password page
258
$vartype['remind'] = 'string'; // remind password page
259
$vartype['url'] = 'url';
lphuberdeau's avatar
lphuberdeau committed
260

261
$vartype['aid'] = '+int';
262 263
$vartype['description'] = 'string';
$vartype['filter_active'] = 'char';
264
$vartype['filter_name'] = 'string';
265 266 267 268
$vartype['newmajor'] = '+int';
$vartype['newminor'] = '+int';
$vartype['pid'] = '+int';
$vartype['remove_role'] = '+int';
269
$vartype['rolename'] = 'char';
270
$vartype['type'] = 'string';
271
$vartype['userole'] = 'int';
272
$vartype['focus'] = 'string';
273
$vartype['filegals_manager'] = 'vars';
274
$vartype['ver'] = 'dotvars'; // filename hash for drawlib + rss type for rsslib
sylvieg's avatar
sylvieg committed
275 276 277 278 279 280 281 282 283 284 285 286 287
$vartype['trackerId'] = 'int';
$vartype['articleId'] = 'int';
$vartype['galleryId'] = 'int';
$vartype['blogId'] = 'int';
$vartype['postId'] = 'int';
$vartype['calendarId'] = 'int';
$vartype['faqId'] = 'int';
$vartype['quizId'] = 'int';
$vartype['sheetId'] = 'int';
$vartype['surveyId'] = 'int';
$vartype['nlId'] = 'int';
$vartype['chartId'] = 'int';
$vartype['categoryId'] = 'int';
288
$vartype['parentId'] = 'int';
sylvieg's avatar
sylvieg committed
289 290 291
$vartype['bannerId'] = 'int';
$vartype['rssId'] = 'int';
$vartype['page_ref_id'] = 'int';
292 293 294
function varcheck(&$array, $category) {
	global $patterns, $vartype, $prefs;
	$return = array();
changi67's avatar
changi67 committed
295 296
	if (is_array($array)) {
		foreach($array as $rq => $rv) {
297
			// check if the variable name is allowed
changi67's avatar
changi67 committed
298
			if (!preg_match($patterns['vars'], $rq)) {
299
				//die(tra("Invalid variable name : "). htmlspecialchars($rq));
changi67's avatar
changi67 committed
300 301
				
			} elseif (isset($vartype["$rq"])) {
302 303
				$has_sign = false;
				// Variable allowed to be empty?
changi67's avatar
changi67 committed
304 305 306
				if ('+' == substr($vartype[$rq], 0, 1)) {
					if ($rv == "") {
						$return[] = tra("Notice: this variable may not be empty:") . ' <font color="red">$' . $category . '["' . $rq . '"]</font>';
307 308 309 310
						continue;
					}
					$has_sign = true;
				}
changi67's avatar
changi67 committed
311
				if (is_array($rv)) {
sept_7's avatar
sept_7 committed
312
					$tmp = varcheck($array[$rq], $category);
changi67's avatar
changi67 committed
313
					if ($tmp != "") {
sept_7's avatar
sept_7 committed
314 315
						$return[] = $tmp;
					}
316 317 318
				} else {
					// Check single parameters
					$pattern_key = $has_sign ? substr($vartype[$rq], 1) : $vartype[$rq];
changi67's avatar
changi67 committed
319 320
					if (!preg_match($patterns[$pattern_key], $rv)) {
						$return[] = tra("Notice: invalid variable value:") . ' $' . $category . '["' . $rq . '"] = <font color="red">' . htmlspecialchars($rv) . '</font>';
321
						$array[$rq] = ''; // Clear content
changi67's avatar
changi67 committed
322
						
323 324 325 326 327 328 329
					}
				}
			}
		}
	}
	return implode('<br />', $return);
}
330
unset($_COOKIE['offset']);
331 332
if (!empty($_REQUEST['highlight'])) {
	if (is_array($_REQUEST['highlight'])) $_REQUEST['highlight'] = '';
sylvieg's avatar
sylvieg committed
333
	$_REQUEST['highlight'] = htmlspecialchars($_REQUEST['highlight']);
334 335
	// Convert back sanitization tags into real tags to avoid them to be displayed
	$_REQUEST['highlight'] = str_replace('&lt;x&gt;', '<x>', $_REQUEST['highlight']);
336
}
337
// ---------------------------------------------------------------------
338 339 340 341 342 343 344
if (!isset($_SERVER['QUERY_STRING'])) {
	$_SERVER['QUERY_STRING'] = '';
}
if (empty($_SERVER['REQUEST_URI'])) {
	$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
}
if (empty($_SERVER['SERVER_NAME'])) {
345
	$_SERVER['SERVER_NAME'] = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']: '';
346
}
347 348 349 350 351 352 353 354 355 356

/*
 * Clean variables past in _GET & _POST & _COOKIE
 */
$magic_quotes_gpc = get_magic_quotes_gpc();
if ($magic_quotes_gpc) {
	remove_gpc($_GET);
	remove_gpc($_POST);
	remove_gpc($_COOKIE);
}
357 358 359

require_once ('lib/setup/absolute_urls.php');

360
// in the case of tikis on same domain we have to distinguish the realm
changi67's avatar
changi67 committed
361
// changed cookie and session variable name by a name made with browsertitle
362
$cookie_site = preg_replace("/[^a-zA-Z0-9]/", "", $prefs['cookie_name']);
changi67's avatar
changi67 committed
363
$user_cookie_site = 'tiki-user-' . $cookie_site;
364 365
// if remember me is enabled, check for cookie where auth hash is stored
// user gets logged in as the first user in the db with a matching hash
changi67's avatar
changi67 committed
366
if (($prefs['rememberme'] != 'disabled') and (isset($_COOKIE["$user_cookie_site"])) and (!isset($user) and !isset($_SESSION["$user_cookie_site"]))) {
367 368 369 370
	if ($prefs['feature_intertiki'] == 'y' and !empty($prefs['feature_intertiki_mymaster']) and $prefs['feature_intertiki_sharedcookie'] == 'y') {
		$rpcauth = $userlib->get_remote_user_by_cookie($_COOKIE["$user_cookie_site"]);
		if (is_object($rpcauth)) {
			$response_value = $rpcauth->value();
371 372
			if (is_object($response_value)) {
				$user = $response_value->scalarval();
373 374 375
			}
		}
	} else {
376 377 378 379
		if ($userId = $userlib->get_user_by_cookie($_COOKIE["$user_cookie_site"])) {
			$userInfo = $userlib->get_userid_info($userId);
			$user = $userInfo['login'];
		}
380
	}
381
	if (isset($user) && $user) {
382 383
		$_SESSION["$user_cookie_site"] = $user;
	}
384 385
}
// if the auth method is 'web site', look for the username in $_SERVER
386
if (($prefs['auth_method'] == 'ws') and (isset($_SERVER['REMOTE_USER']))) {
387
	if ($userlib->user_exists($_SERVER['REMOTE_USER'])) {
388 389
		$user = $_SERVER['REMOTE_USER'];
		$_SESSION["$user_cookie_site"] = $user;
changi67's avatar
changi67 committed
390
	} elseif ($userlib->user_exists(str_replace("\\\\", "\\", $_SERVER['REMOTE_USER']))) {
391
		// Check for the domain\username with just one backslash
392 393
		$user = str_replace("\\\\", "\\", $_SERVER['REMOTE_USER']);
		$_SESSION["$user_cookie_site"] = $user;
changi67's avatar
changi67 committed
394
	} elseif ($userlib->user_exists(substr($_SERVER['REMOTE_USER'], strpos($_SERVER['REMOTE_USER'], "\\") + 2))) {
395
		// Check for the username without the domain name
396 397 398 399 400 401 402 403 404 405 406
		$user = substr($_SERVER['REMOTE_USER'], strpos($_SERVER['REMOTE_USER'], "\\") + 2);
		$_SESSION["$user_cookie_site"] = $user;
	} elseif ($prefs['auth_ws_create_tiki'] == 'y') {
		$user = $_SERVER['REMOTE_USER'];
		if ($userlib->add_user($_SERVER['REMOTE_USER'],'', '')) {
			$user = $_SERVER['REMOTE_USER'];
			$_SESSION["$user_cookie_site"] = $user;
		}
	}
	if (!empty($_SESSION["$user_cookie_site"])) {
		$userlib->update_lastlogin($user);
407
	}
408
}
philwhipps's avatar
philwhipps committed
409
// Check for Shibboleth Login
changi67's avatar
changi67 committed
410
if ($prefs['auth_method'] == 'shib' and isset($_SERVER['REMOTE_USER'])) {
philwhipps's avatar
philwhipps committed
411
	// Validate the user (if not created create it)
changi67's avatar
changi67 committed
412
	if ($userlib->validate_user($_SERVER['REMOTE_USER'], "", "", "")) {
philwhipps's avatar
philwhipps committed
413 414 415
		$_SESSION["$user_cookie_site"] = $_SERVER['REMOTE_USER'];
	}
}
416

417
$userlib->check_cas_authentication($user_cookie_site);
418

419 420 421
// if the username is already saved in the session, pull it from there
if (isset($_SESSION["$user_cookie_site"])) {
	$user = $_SESSION["$user_cookie_site"];
nyloth's avatar
nyloth committed
422 423 424 425
	// There could be a case where the session contains a user that doesn't exists in this tiki
	// or that has never used the login step in this tiki.
	// Example : If using the same PHP SESSION cookies for more than one tiki.
	$user_details = $userlib->get_user_details($user);
changi67's avatar
changi67 committed
426 427
	if (!is_array($user_details) || !is_array($user_details['info']) || (int)$user_details['info']['lastLogin'] <= 0) {
		global $cachelib;
428
		require_once ('lib/cache/cachelib.php');
changi67's avatar
changi67 committed
429
		$cachelib->invalidate('user_details_' . $user);
430
		$user_details = $userlib->get_user_details($user);
changi67's avatar
changi67 committed
431
		if (!is_array($user_details) || !is_array($user_details['info'])) {
432 433 434
			$user = NULL;
		}
	}
nyloth's avatar
nyloth committed
435
	unset($user_details);
436 437 438 439 440
	
	// Generate anti-CSRF ticket
	if ($prefs['feature_ticketlib2'] == 'y' && !isset($_SESSION['ticket'])) {
		$_SESSION['ticket'] = md5(uniqid(rand()));
	}
441 442
} else {
	$user = NULL;
443 444 445 446 447 448

	if ($prefs['login_http_basic'] === 'always' ||
		($prefs['login_http_basic'] === 'ssl' && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')) {

		// Authenticate if the credentials are present, do nothing otherwise
		if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
lphuberdeau's avatar
lphuberdeau committed
449 450 451 452
			$validate = $userlib->validate_user($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);

			if ($validate[0]) {
				$user = $validate[1];
453
				$userlib->confirm_user($user);
lphuberdeau's avatar
lphuberdeau committed
454 455 456 457
			} else {
				header('WWW-Authenticate: Basic realm="'.$tikidomain.'"');
				header('HTTP/1.0 401 Unauthorized');
				exit;
458 459 460
			}
		}
	}
461
}
462 463 464 465

if (is_object($smarty)) {
	$smarty->assign( 'CSRFTicket', isset( $_SESSION['ticket'] ) ? $_SESSION['ticket'] : null);
}
466
require_once ('lib/setup/perms.php');
467
// --------------------------------------------------------------
468
// deal with register_globals
changi67's avatar
changi67 committed
469 470 471 472
if (ini_get('register_globals')) {
	foreach(array($_ENV, $_GET, $_POST, $_COOKIE, $_SERVER) as $superglob) {
		foreach($superglob as $key => $val) {
			if (isset($GLOBALS[$key]) && $GLOBALS[$key] == $val) { // if global has been set some other way
473 474
				// that is OK (prevents munging of $_SERVER with ?_SERVER=rubbish etc.)
				unset($GLOBALS[$key]);
475 476 477
			}
		}
	}
478
}
479
$serverFilter = new DeclFilter;
480
if ( $tiki_p_trust_input != 'y' ) {
481
	$serverFilter->addStaticKeyFilters(array('QUERY_STRING' => 'url', 'REQUEST_URI' => 'url', 'PHP_SELF' => 'url',));
482
}
changi67's avatar
changi67 committed
483 484
$jitServer = new JitFilter($_SERVER);
$_SERVER = $serverFilter->filter($_SERVER);
485 486
// Rebuild request after gpc fix
// _REQUEST should only contain GET and POST in the app
487 488 489 490 491

$prepareInput = new TikiFilter_PrepareInput('~');
$_GET = $prepareInput->prepare($_GET);
$_POST = $prepareInput->prepare($_POST);

492
$_REQUEST = array_merge($_GET, $_POST);
493
// Preserve unfiltered values accessible through JIT filtering
changi67's avatar
changi67 committed
494 495 496 497 498 499 500 501
$jitPost = new JitFilter($_POST);
$jitGet = new JitFilter($_GET);
$jitRequest = new JitFilter($_REQUEST);
$jitCookie = new JitFilter($_COOKIE);
$jitPost->setDefaultFilter('xss');
$jitGet->setDefaultFilter('xss');
$jitRequest->setDefaultFilter('xss');
$jitCookie->setDefaultFilter('xss');
502
// Apply configured filters to all other input
changi67's avatar
changi67 committed
503
if (!isset($inputConfiguration)) $inputConfiguration = array();
504

lphuberdeau's avatar
lphuberdeau committed
505
array_unshift( $inputConfiguration, array(
506 507
	'staticKeyFilters' => array(
		'menu' => 'striptags',
lphuberdeau's avatar
lphuberdeau committed
508 509 510 511
		'cat_categorize' => 'alpha',
		'cat_clearall' => 'alpha',
		'tab' => 'digits',
		'javascript_enabled' => 'alpha',
lphuberdeau's avatar
lphuberdeau committed
512
		'XDEBUG_PROFILE' => 'int',
513
	),
lphuberdeau's avatar
lphuberdeau committed
514 515 516 517 518
	'staticKeyFiltersForArrays' => array(
		'cat_managed' => 'digits',
		'cat_categories' => 'digits',
	),
) );
519

changi67's avatar
changi67 committed
520
$inputFilter = DeclFilter::fromConfiguration($inputConfiguration, array('catchAllFilter'));
521
if ( $tiki_p_trust_input != 'y' ) {
522 523
	$inputFilter->addCatchAllFilter('xss');
}
524 525 526
$cookieFilter = DeclFilter::fromConfiguration($inputConfiguration, array('catchAllFilter'));
$cookieFilter->addCatchAllFilter('striptags');

changi67's avatar
changi67 committed
527 528
$_GET = $inputFilter->filter($_GET);
$_POST = $inputFilter->filter($_POST);
529
$_COOKIE = $cookieFilter->filter($_COOKIE);
530 531
// Rebuild request with filtered values
$_REQUEST = array_merge($_GET, $_POST);
changi67's avatar
changi67 committed
532
if ($tiki_p_trust_input != 'y') {
533 534
	$varcheck_vars = array('_COOKIE', '_GET', '_POST', '_ENV', '_SERVER');
	$varcheck_errors = '';
changi67's avatar
changi67 committed
535 536 537 538 539
	foreach($varcheck_vars as $var) {
		if (!isset($$var)) continue;
		if (($tmp = varcheck($$var, $var)) != '') {
			if ($varcheck_errors != '') $varcheck_errors.= '<br />';
			$varcheck_errors.= $tmp;
540 541 542 543
		}
	}
	unset($tmp);
}
544 545 546 547 548 549 550

if ($prefs['tiki_check_file_content'] == 'y' && count($_FILES)) {
	if ($finfo = new finfo(FILEINFO_MIME)) {

		foreach ($_FILES as $key => & $upload_file_info) {
			if (is_array($upload_file_info['tmp_name'])) {
				foreach ($upload_file_info['tmp_name'] as $k => $tmp_name) {
lphuberdeau's avatar
lphuberdeau committed
551 552 553
					if ($tmp_name) {
						$upload_file_info['type'][$k] = $finfo->file($tmp_name);
					}
554
				}
lphuberdeau's avatar
lphuberdeau committed
555
			} elseif ($upload_file_info['tmp_name']) {
556 557 558 559 560 561 562 563
				$upload_file_info['type'] = $finfo->file($upload_file_info['tmp_name']);
			}
		}
	}

	unset($finfo);
}

564
// deal with old request globals (e.g. used by Smarty)
changi67's avatar
changi67 committed
565 566 567
$GLOBALS['HTTP_GET_VARS'] = & $_GET;
$GLOBALS['HTTP_POST_VARS'] = & $_POST;
$GLOBALS['HTTP_COOKIE_VARS'] = & $_COOKIE;
568 569 570 571 572
unset($GLOBALS['HTTP_ENV_VARS']);
unset($GLOBALS['HTTP_SERVER_VARS']);
unset($GLOBALS['HTTP_SESSION_VARS']);
unset($GLOBALS['HTTP_POST_FILES']);
// --------------------------------------------------------------
changi67's avatar
changi67 committed
573 574
if (isset($_REQUEST['highlight']) || (isset($prefs['feature_referer_highlight']) && $prefs['feature_referer_highlight'] == 'y')) {
	$smarty->load_filter('output', 'highlight');
575
}
576 577 578
if (function_exists('mb_internal_encoding')) {
	mb_internal_encoding("UTF-8");
}
579
// --------------------------------------------------------------
lrargerich's avatar
Fixes  
lrargerich committed
580
// Fix IIS servers not setting what they should set (ay ay IIS, ay ay)
changi67's avatar
changi67 committed
581
if (!isset($_SERVER['QUERY_STRING'])) $_SERVER['QUERY_STRING'] = '';
582
if (!isset($_SERVER['REQUEST_URI']) || empty($_SERVER['REQUEST_URI'])) {
changi67's avatar
changi67 committed
583
	$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'];
584
}
585 586 587
if (is_object($smarty)) {
	$smarty->assign("tikidomain", $tikidomain);
}