tiki-setup_base.php 24.3 KB
Newer Older
1
<?php
changi67's avatar
changi67 committed
2 3 4
/**
 * @package tikiwiki
 */
5
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
6
//
7 8
// 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.
9
// $Id$
changi67's avatar
changi67 committed
10

11
//this script may only be included - so its better to die if called directly.
changi67's avatar
changi67 committed
12 13 14
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
	header("location: index.php");
	exit;
15
}
16
require_once ('tiki-filter-base.php');
17 18 19 20 21 22 23 24 25 26 27

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'])) {
	$_SERVER['SERVER_NAME'] = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']: '';
}

28 29 30 31
// ---------------------------------------------------------------------
// basic php conf adjustment
// xhtml compliance
ini_set('arg_separator.output', '&amp;');
changi67's avatar
changi67 committed
32
// URL session handling is not safe or pretty
33
// better avoid using trans_sid for security reasons
changi67's avatar
changi67 committed
34 35
ini_set('session.use_only_cookies', 1);
// true, but you cannot change the url_rewriter.tags in safe mode ...
36
// its usually safe to leave it as is.
changi67's avatar
changi67 committed
37
//ini_set('url_rewriter.tags', '');
38 39 40 41 42 43
// 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');
44
// Smarty workaround - if this would be 'On' in php.ini Smarty fails to parse tags
changi67's avatar
changi67 committed
45 46 47
ini_set('magic_quotes_sybase', 'Off');
ini_set('magic_quotes_runtime', 0);
ini_set('allow_call_time_pass_reference', 'On');
48

49
$memory_limiter = new Tiki_MemoryLimit('128M'); // Keep in variable to hold scope
50

51 52
// ---------------------------------------------------------------------
// inclusions of mandatory stuff and setup
53 54 55
require_once ('lib/tikiticketlib.php');
require_once ('db/tiki-db.php');
require_once ('lib/tikilib.php');
56
$tikilib = new TikiLib;
57 58
// Get tiki-setup_base needed preferences in one query
$prefs = array();
59 60
$needed_prefs = array(
	'session_lifetime' => '0',
61
	'session_storage' => 'default',
62 63
	'session_silent' => 'n',
	'session_cookie_name' => session_name(),
64
	'session_protected' => 'n',
65
	'tiki_cdn' => '',
66
	'tiki_cdn_ssl' => '',
67
	'language' => 'en',
68
	'lang_use_db' => 'n',
69 70 71 72 73
	'feature_fullscreen' => 'n',
	'error_reporting_level' => 0,
	'memcache_enabled' => 'n',
	'memcache_expiration' => 3600,
	'memcache_prefix' => 'tiki_',
74
	'memcache_compress' => 'y',
75
	'memcache_servers' => false,
sept_7's avatar
sept_7 committed
76
	'min_pass_length' => 5,
lphuberdeau's avatar
lphuberdeau committed
77
	'pass_chr_special' => 'n',
78
	'cookie_consent_feature' => 'n',
79
	'cookie_consent_disable' => 'n',
80 81
	'cookie_consent_name' => 'tiki_cookies_accepted',

82
);
83

84
// check that tiki_preferences is there
chealer's avatar
chealer committed
85
if ($tikilib->query("SHOW TABLES LIKE 'tiki_preferences'")->numRows() == 0) {
86 87 88 89
	// smarty not initialised at this point to do a polite message, sadly
	header('location: tiki-install.php');
	exit;
}
90
$tikilib->get_preferences($needed_prefs, true, true);
91
global $systemConfiguration;
92
$prefs = $systemConfiguration->preference->toArray() + $prefs;
93

94 95 96 97 98 99 100 101 102
// mose : simulate strong var type checking for http vars
$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
$patterns['hash'] = "/^[a-z0-9]*$/"; // for hash reqId in live support
103
$patterns['url'] = "/^(https?:\/\/)?[^<>\"]*$/";
104

105 106 107
// IIS always sets the $_SERVER['HTTPS'] value (on|off)
$noSSLActive = !isset($_SERVER['HTTPS']) || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'off');
if (isset($prefs['session_protected']) && $prefs['session_protected'] == 'y' && $noSSLActive && php_sapi_name() != 'cli') {
108 109
	header("Location: https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
	exit;
110
}
111

lphuberdeau's avatar
lphuberdeau committed
112 113
$cachelib = TikiLib::lib('cache');
$logslib = TikiLib::lib('logs');
114
include_once ('lib/init/tra.php');
115
$tikidate = TikiLib::lib('tikidate');
116
// set session lifetime
117
if (isset($prefs['session_lifetime']) && $prefs['session_lifetime'] > 0) {
changi67's avatar
changi67 committed
118
	ini_set('session.gc_maxlifetime', $prefs['session_lifetime'] * 60);
119 120
}
// is session data  stored in DB or in filesystem?
121
if (isset($prefs['session_storage']) && $prefs['session_storage'] == 'db') {
122 123 124 125 126 127
	$db = TikiDb::get();
	if ($db instanceof TikiDb_MasterSlaveDispatch) {
		$db->getReal();
	}

	if ($db instanceof TikiDb_AdoDb) {
changi67's avatar
changi67 committed
128
		require_once ('lib/tikisession-adodb.php');
129
	} elseif ($db instanceof TikiDb_Pdo) {
changi67's avatar
changi67 committed
130
		require_once ('lib/tikisession-pdo.php');
131
	}
132
} elseif ( isset($prefs['session_storage']) && $prefs['session_storage'] == 'memcache' && TikiLib::lib("memcache")->isEnabled() ) {
lphuberdeau's avatar
lphuberdeau committed
133
	require_once ('lib/tikisession-memcache.php');
134
}
lphuberdeau's avatar
lphuberdeau committed
135

136
if ( ! isset( $prefs['session_cookie_name'] ) || empty( $prefs['session_cookie_name'] ) ) {
137 138 139
	$prefs['session_cookie_name'] = session_name();
}

changi67's avatar
changi67 committed
140
session_name($prefs['session_cookie_name']);
141

142 143
// 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)
144 145 146 147
// It could be , that the server initiates his request with its own ip, so we check also if server == remote
// Note: this is an incomplete implemenation - the session handling does not really work this way. Session data is lost and not regenerated.
// Maybe better to use tokens: see i.e. the example in lib/pdflib.php
if (isset($_GET[session_name()]) && (($tikilib->get_ip_address() == '127.0.0.1') || ($_SERVER["SERVER_ADDR"] == $_SERVER["REMOTE_ADDR"]))) {
148
	$_COOKIE[session_name()] = $_GET[session_name()];
149
	session_id($_GET[session_name()]);		
150
}
151

152 153 154 155 156 157 158
//Set tikiroot and tikidomain to blank string if not set.
if (empty($tikiroot)) {
	$tikiroot = "";
}
if (empty($tikidomain)) {
	$tikidomain = "";
}
159

160 161
if ($prefs['cookie_consent_feature'] === 'y' && empty($_COOKIE[$prefs['cookie_consent_name']]) && $prefs['cookie_consent_disable'] !== 'y' ) {
	// No consent yet
162 163
	$feature_no_cookie = true;
} else {
164
	// Cookie consent not implemented or consent given or consent forced with preference cookie_consent_disable
165 166 167
	$feature_no_cookie = false;
}

168
$start_session = true;
169
$extra_cookie_name = session_name() . 'CV';
170
if ( $prefs['session_silent'] == 'y' && empty($_COOKIE[session_name()]) && empty($_COOKIE[$extra_cookie_name]) ) {
171 172
	$start_session = false;
}
173

174
// If called from the CDN, refuse to execute anything
175
$cdn_pref = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? $prefs['tiki_cdn_ssl'] : isset($prefs['tiki_cdn']) ? $prefs['tiki_cdn'] : '' ;
176
if ( $cdn_pref ) {
changi67's avatar
changi67 committed
177
	$host = parse_url($cdn_pref, PHP_URL_HOST);
178
	if (isset($_SERVER['HTTP_HOST']) && $host == $_SERVER['HTTP_HOST'] ) {
179 180
		header("HTTP/1.0 410 Gone");
		echo "This is a Content Delivery Network (CDN) to speed up delivery of images, CSS, and javascript files. However, PHP code is not executed.";
181
		exit;
182 183
	}
}
sylvieg's avatar
sylvieg committed
184
if (isset($_SERVER["REQUEST_URI"])) {
185
	ini_set('session.cookie_path', str_replace("\\", "/", $tikiroot));
186 187 188
	if ( $start_session ) {
		// enabing silent sessions mean a session is only started when a cookie is presented
		$session_params = session_get_cookie_params();
189
		session_set_cookie_params($session_params['lifetime'], $tikiroot);
190
		unset($session_params);
191

192
		try {
193
						
194
			Zend\Session\Container::getDefaultManager()->start();
195 196 197 198 199 200 201 202 203 204 205 206 207

			/* This portion may seem strange, but it is an extra validation against session
			 * collisions. An extra cookie is set with an additional random value. When loading
			 * the session, it makes sure the extra cookie matches the one in the session. Otherwise
			 * it destroys the session and reloads the page for the user.
			 *
			 * Effectively, in the occurence of a collision, both users are kicked out.
			 * This is an extremely rare occurence that is hard to reproduce by nature.
			 */ 
			if (isset($_SESSION['extra_validation'])) {
				$cookie = isset($_COOKIE[$extra_cookie_name]) ? $_COOKIE[$extra_cookie_name] : null;

				if ($cookie !== $_SESSION['extra_validation']) {
208 209 210

					TikiLib::lib('logs')->add_log('system', 'session cookie validation failed');

211
					Zend\Session\Container::getDefaultManager()->destroy();
212 213 214 215 216 217 218 219 220
					header('Location: ' . $_SERVER['REQUEST_URI']);
					exit;
				}
			} else {
				$sequence = $tikilib->generate_unique_sequence(16);
				$_SESSION['extra_validation'] = $sequence;
				setcookie($extra_cookie_name, $sequence, time() + 365*24*3600, ini_get('session.cookie_path'));
				unset($sequence);
			}
221
		} catch( Zend\Session\Exception\ExceptionInterface $e ) {
222
			// Ignore
223 224
		} catch( Zend\Stdlib\Exception\InvalidArgumentException $e ) {
			// Ignore
225
		}
226
	}
227
}
228

229
// Moved here from tiki-setup.php because smarty use a copy of session
230
if (isset($prefs['feature_fullscreen']) && $prefs['feature_fullscreen'] == 'y') {
231 232
	require_once ('lib/setup/fullscreen.php');
}
233 234 235 236

// Retrieve Tiki addons
TikiAddons::refresh();

237
// Retrieve all preferences
changi67's avatar
changi67 committed
238
require_once ('lib/setup/prefs.php');
239

240
$access = TikiLib::lib('access');
241 242

require_once ('lib/setup/absolute_urls.php');
243
// Smarty needs session since 2.6.25
244 245
global $smarty;
$smarty = TikiLib::lib('smarty');
246 247 248 249 250

// Define the special maxRecords global variable
$maxRecords = $prefs['maxRecords'];
$smarty->assignByRef('maxRecords', $maxRecords);

251 252
global $userlib;
$userlib = TikiLib::lib('user');
253
require_once ('lib/breadcrumblib.php');
254 255
// ------------------------------------------------------
// DEAL WITH XSS-TYPE ATTACKS AND OTHER REQUEST ISSUES
256 257 258
/**
 * @param $var
 */
changi67's avatar
changi67 committed
259 260
function remove_gpc(&$var)
{
changi67's avatar
changi67 committed
261
	if (is_array($var)) {
262
		foreach ($var as $key => $val) {
263
			remove_gpc($var[$key]);
264 265
		}
	} else {
266
		$var = stripslashes($var);
267 268
	}
}
269 270 271
// parameter type definitions. prepend a + if variable may not be empty, e.g. '+int'
$vartype['id'] = '+int';
$vartype['forumId'] = '+int';
272
$vartype['offset'] = 'intSign';
sylvieg's avatar
sylvieg committed
273 274
$vartype['prev_offset'] = 'intSign';
$vartype['next_offset'] = 'intSign';
275
$vartype['threshold'] = 'int';
276
$vartype['sort_mode'] = '+char';
277 278
$vartype['file_sort_mode'] = 'char';
$vartype['file_offset'] = 'int';
sylvieg's avatar
sylvieg committed
279 280 281
$vartype['file_find'] = 'string';
$vartype['file_prev_offset'] = 'intSign';
$vartype['file_next_offset'] = 'intSign';
282
$vartype['comments_offset'] = 'int';
283
$vartype['comments_threshold'] = 'int';
284
$vartype['comments_parentId'] = '+int';
285 286
$vartype['thread_sort_mode'] = '+char';
$vartype['thread_style'] = '+char';
287
$vartype['comments_per_page'] = '+int';
288
$vartype['topics_offset'] = 'int';
289
$vartype['topics_sort_mode'] = '+char';
290 291 292
$vartype['theme'] = 'string';
$vartype['flag'] = 'char';
$vartype['lang'] = 'char';
293
$vartype['language'] = 'char';
294 295
$vartype['page'] = 'string';
$vartype['edit_mode'] = 'char';
296
$vartype['find'] = 'string';
297
$vartype['topic_find'] = 'string';
298
$vartype['initial'] = 'string';
299
$vartype['username'] = '+string';
300 301
$vartype['realName'] = 'string';
$vartype['homePage'] = 'string';
302 303 304
$vartype['to'] = 'stringlist';
$vartype['cc'] = 'stringlist';
$vartype['bcc'] = 'stringlist';
305 306
$vartype['subject'] = 'string';
$vartype['name'] = 'string';
307 308 309
$vartype['reqId'] = '+hash';
$vartype['days'] = '+int';
$vartype['max'] = '+int';
310
$vartype['maxRecords'] = '+int';
311 312 313 314 315
$vartype['numrows'] = '+int';
$vartype['rows'] = '+int';
$vartype['cols'] = '+int';
$vartype['topicname'] = '+string';
$vartype['error'] = 'string';
316
$vartype['editmode'] = 'char'; // from calendar
317 318
$vartype['actpass'] = '+string'; // remind password page
$vartype['user'] = '+string'; // remind password page
319
$vartype['remind'] = 'string'; // remind password page
320
$vartype['url'] = 'url';
lphuberdeau's avatar
lphuberdeau committed
321

322
$vartype['aid'] = '+int';
323 324
$vartype['description'] = 'string';
$vartype['filter_active'] = 'char';
325
$vartype['filter_name'] = 'string';
326 327 328 329
$vartype['newmajor'] = '+int';
$vartype['newminor'] = '+int';
$vartype['pid'] = '+int';
$vartype['remove_role'] = '+int';
330
$vartype['rolename'] = 'char';
331
$vartype['type'] = 'string';
332
$vartype['userole'] = 'int';
333
$vartype['focus'] = 'string';
334
$vartype['filegals_manager'] = 'vars';
335
$vartype['filesyntax'] = 'string';
336
$vartype['ver'] = 'dotvars'; // filename hash for drawlib + rss type for rsslib
sylvieg's avatar
sylvieg committed
337 338 339 340 341 342 343 344 345 346 347 348 349
$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';
350
$vartype['parentId'] = 'intSign';
sylvieg's avatar
sylvieg committed
351 352 353
$vartype['bannerId'] = 'int';
$vartype['rssId'] = 'int';
$vartype['page_ref_id'] = 'int';
354 355 356 357 358
/**
 * @param $array
 * @param $category
 * @return string
 */
changi67's avatar
changi67 committed
359 360
function varcheck(&$array, $category)
{
361 362
	global $patterns, $vartype, $prefs;
	$return = array();
changi67's avatar
changi67 committed
363
	if (is_array($array)) {
364
		foreach ($array as $rq => $rv) {
365
			// check if the variable name is allowed
changi67's avatar
changi67 committed
366
			if (!preg_match($patterns['vars'], $rq)) {
367
				//die(tra("Invalid variable name : "). htmlspecialchars($rq));
368

changi67's avatar
changi67 committed
369
			} elseif (isset($vartype["$rq"])) {
370 371
				$has_sign = false;
				// Variable allowed to be empty?
changi67's avatar
changi67 committed
372 373 374
				if ('+' == substr($vartype[$rq], 0, 1)) {
					if ($rv == "") {
						$return[] = tra("Notice: this variable may not be empty:") . ' <font color="red">$' . $category . '["' . $rq . '"]</font>';
375 376 377 378
						continue;
					}
					$has_sign = true;
				}
changi67's avatar
changi67 committed
379
				if (is_array($rv)) {
sept_7's avatar
sept_7 committed
380
					$tmp = varcheck($array[$rq], $category);
changi67's avatar
changi67 committed
381
					if ($tmp != "") {
sept_7's avatar
sept_7 committed
382 383
						$return[] = $tmp;
					}
384 385 386
				} else {
					// Check single parameters
					$pattern_key = $has_sign ? substr($vartype[$rq], 1) : $vartype[$rq];
changi67's avatar
changi67 committed
387 388
					if (!preg_match($patterns[$pattern_key], $rv)) {
						$return[] = tra("Notice: invalid variable value:") . ' $' . $category . '["' . $rq . '"] = <font color="red">' . htmlspecialchars($rv) . '</font>';
389
						$array[$rq] = ''; // Clear content
390

391 392 393 394 395 396 397
					}
				}
			}
		}
	}
	return implode('<br />', $return);
}
398
unset($_COOKIE['offset']);
399
if (!empty($_REQUEST['highlight'])) {
400 401 402
	if (is_array($_REQUEST['highlight'])) {
		$_REQUEST['highlight'] = '';
	}
sylvieg's avatar
sylvieg committed
403
	$_REQUEST['highlight'] = htmlspecialchars($_REQUEST['highlight']);
404 405
	// Convert back sanitization tags into real tags to avoid them to be displayed
	$_REQUEST['highlight'] = str_replace('&lt;x&gt;', '<x>', $_REQUEST['highlight']);
406
}
407
// ---------------------------------------------------------------------
408 409 410 411 412 413 414 415 416 417

/*
 * 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);
}
418

419 420 421 422
global $base_uri;
if (!empty($base_uri) && is_object($smarty)) {
	$smarty->assign('base_uri', $base_uri);
}
423

424
// in the case of tikis on same domain we have to distinguish the realm
changi67's avatar
changi67 committed
425
// changed cookie and session variable name by a name made with browsertitle
426
$cookie_site = preg_replace("/[^a-zA-Z0-9]/", "", $prefs['cookie_name']);
changi67's avatar
changi67 committed
427
$user_cookie_site = 'tiki-user-' . $cookie_site;
428 429
// 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
430
if (($prefs['rememberme'] != 'disabled') and (isset($_COOKIE["$user_cookie_site"])) and (!isset($user) and !isset($_SESSION["$user_cookie_site"]))) {
431 432 433 434
	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();
435 436
			if (is_object($response_value)) {
				$user = $response_value->scalarval();
437 438 439
			}
		}
	} else {
440 441 442 443
		if ($userId = $userlib->get_user_by_cookie($_COOKIE["$user_cookie_site"])) {
			$userInfo = $userlib->get_userid_info($userId);
			$user = $userInfo['login'];
		}
444
	}
445
	if (isset($user) && $user) {
446
		$_SESSION["$user_cookie_site"] = $user;
447 448 449 450 451 452 453 454
		if ($prefs['cookie_refresh_rememberme'] === 'y') {
			if (empty($userId)) {    // for intertiki
				$userId = $userlib->get_user_id($user);
			}
			$secret = $userlib->create_user_cookie($userId);
			setcookie($user_cookie_site, $secret . '.' . $userId, $tikilib->now + $prefs['remembertime'], $prefs['cookie_path'], $prefs['cookie_domain']);
			$logslib->add_log('login', 'refreshed a cookie for ' . $prefs['remembertime'] . ' seconds');
		}
455
	}
456 457
}
// if the auth method is 'web site', look for the username in $_SERVER
458
if (($prefs['auth_method'] == 'ws') and (isset($_SERVER['REMOTE_USER']))) {
459
	if ($userlib->user_exists($_SERVER['REMOTE_USER'])) {
460 461
		$user = $_SERVER['REMOTE_USER'];
		$_SESSION["$user_cookie_site"] = $user;
changi67's avatar
changi67 committed
462
	} elseif ($userlib->user_exists(str_replace("\\\\", "\\", $_SERVER['REMOTE_USER']))) {
463
		// Check for the domain\username with just one backslash
464 465
		$user = str_replace("\\\\", "\\", $_SERVER['REMOTE_USER']);
		$_SESSION["$user_cookie_site"] = $user;
changi67's avatar
changi67 committed
466
	} elseif ($userlib->user_exists(substr($_SERVER['REMOTE_USER'], strpos($_SERVER['REMOTE_USER'], "\\") + 2))) {
467
		// Check for the username without the domain name
468 469 470 471
		$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'];
changi67's avatar
changi67 committed
472
		if ($userlib->add_user($_SERVER['REMOTE_USER'], '', '')) {
473 474 475 476 477 478
			$user = $_SERVER['REMOTE_USER'];
			$_SESSION["$user_cookie_site"] = $user;
		}
	}
	if (!empty($_SESSION["$user_cookie_site"])) {
		$userlib->update_lastlogin($user);
479
	}
480
}
philwhipps's avatar
philwhipps committed
481
// Check for Shibboleth Login
changi67's avatar
changi67 committed
482
if ($prefs['auth_method'] == 'shib' and isset($_SERVER['REMOTE_USER'])) {
philwhipps's avatar
philwhipps committed
483
	// Validate the user (if not created create it)
484
	if ($userlib->validate_user($_SERVER['REMOTE_USER'], "")) {
philwhipps's avatar
philwhipps committed
485 486 487
		$_SESSION["$user_cookie_site"] = $_SERVER['REMOTE_USER'];
	}
}
488

489
$userlib->check_cas_authentication($user_cookie_site);
490

491 492 493
// 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
494 495 496 497
	// 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);
498
	if (!is_array($user_details) || !is_array($user_details['info']) || (int) $user_details['info']['lastLogin'] <= 0) {
lphuberdeau's avatar
lphuberdeau committed
499
		$cachelib = TikiLib::lib('cache');
changi67's avatar
changi67 committed
500
		$cachelib->invalidate('user_details_' . $user);
501
		$user_details = $userlib->get_user_details($user);
changi67's avatar
changi67 committed
502
		if (!is_array($user_details) || !is_array($user_details['info'])) {
503
			$user = null;
504 505
		}
	}
nyloth's avatar
nyloth committed
506
	unset($user_details);
507

508 509 510 511
	// Generate anti-CSRF ticket
	if ($prefs['feature_ticketlib2'] == 'y' && !isset($_SESSION['ticket'])) {
		$_SESSION['ticket'] = md5(uniqid(rand()));
	}
512
} else {
513
	$user = null;
514

515 516
	if ( isset($prefs['login_http_basic']) && $prefs['login_http_basic'] === 'always' ||
		(isset($prefs['login_http_basic']) && $prefs['login_http_basic'] === 'ssl' && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')) {
517
		// Authenticate if the credentials are present, do nothing otherwise
518
		if (! empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
519
			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
520
		}
521
		if (! empty($_SERVER['HTTP_AUTHORIZATION'])) {
522
			$ha = base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6));
523 524 525 526 527
			$ha = explode(':', $ha, 2);
			
			if (count($ha) == 2) {
				list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = $ha;
			}
528
		}
529
		if (isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
lphuberdeau's avatar
lphuberdeau committed
530 531 532
			$validate = $userlib->validate_user($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']);
			if ($validate[0]) {
				$user = $validate[1];
533
				$userlib->confirm_user($user);
lphuberdeau's avatar
lphuberdeau committed
534 535 536 537
			} else {
				header('WWW-Authenticate: Basic realm="'.$tikidomain.'"');
				header('HTTP/1.0 401 Unauthorized');
				exit;
538 539 540
			}
		}
	}
541
}
542

543 544
$smarty->assign('CSRFTicket', isset( $_SESSION['ticket'] ) ? $_SESSION['ticket'] : null);

545
require_once ('lib/setup/perms.php');
546
// --------------------------------------------------------------
547
// deal with register_globals
changi67's avatar
changi67 committed
548
if (ini_get('register_globals')) {
549 550
	foreach (array($_ENV, $_GET, $_POST, $_COOKIE, $_SERVER) as $superglob) {
		foreach ($superglob as $key => $val) {
551 552
			if (isset($GLOBALS[$key]) && $GLOBALS[$key] == $val) {
				// if global has been set some other way
553 554
				// that is OK (prevents munging of $_SERVER with ?_SERVER=rubbish etc.)
				unset($GLOBALS[$key]);
555 556 557
			}
		}
	}
558
}
559
$serverFilter = new DeclFilter;
sept_7's avatar
sept_7 committed
560
if ( ( isset($prefs['tiki_allow_trust_input']) && $prefs['tiki_allow_trust_input'] ) !== 'y' || $tiki_p_trust_input != 'y') {
561
	$serverFilter->addStaticKeyFilters(array('QUERY_STRING' => 'xss', 'REQUEST_URI' => 'url', 'PHP_SELF' => 'url',));
562
}
changi67's avatar
changi67 committed
563 564
$jitServer = new JitFilter($_SERVER);
$_SERVER = $serverFilter->filter($_SERVER);
565 566
// Rebuild request after gpc fix
// _REQUEST should only contain GET and POST in the app
567 568 569 570 571

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

572
$_REQUEST = array_merge($_GET, $_POST);
573
// Preserve unfiltered values accessible through JIT filtering
changi67's avatar
changi67 committed
574 575 576 577 578 579 580 581
$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');
582
// Apply configured filters to all other input
583 584 585
if (!isset($inputConfiguration)) {
	$inputConfiguration = array();
}
586

587
array_unshift(
588 589 590 591
	$inputConfiguration, array(
		'staticKeyFilters' => array(
			'menu' => 'striptags',
			'cat_categorize' => 'alpha',
592
			'tabs' => 'striptags',
593
			'javascript_enabled' => 'alpha',
594 595 596 597
			$prefs['cookie_consent_name'] => 'alpha',
			'mobile_mode' => 'alpha',
			'categ' => 'striptags',
			'local_tz' => 'text',
598
			'preview' => 'text',
599
			'rbox' => 'text',
600 601 602 603 604 605
		),
		'staticKeyFiltersForArrays' => array(
			'cat_managed' => 'digits',
			'cat_categories' => 'digits',
		),
	)
606
);
607

changi67's avatar
changi67 committed
608
$inputFilter = DeclFilter::fromConfiguration($inputConfiguration, array('catchAllFilter'));
sept_7's avatar
sept_7 committed
609
if ( ( isset($prefs['tiki_allow_trust_input']) && $prefs['tiki_allow_trust_input'] !== 'y' ) || $tiki_p_trust_input != 'y') {
610 611
	$inputFilter->addCatchAllFilter('xss');
}
612 613 614
$cookieFilter = DeclFilter::fromConfiguration($inputConfiguration, array('catchAllFilter'));
$cookieFilter->addCatchAllFilter('striptags');

changi67's avatar
changi67 committed
615 616
$_GET = $inputFilter->filter($_GET);
$_POST = $inputFilter->filter($_POST);
617
$_COOKIE = $cookieFilter->filter($_COOKIE);
618 619
// Rebuild request with filtered values
$_REQUEST = array_merge($_GET, $_POST);
sept_7's avatar
sept_7 committed
620
if ( ( isset($prefs['tiki_allow_trust_input']) && $prefs['tiki_allow_trust_input'] !== 'y' ) || $tiki_p_trust_input != 'y') {
621 622
	$varcheck_vars = array('_COOKIE', '_GET', '_POST', '_ENV', '_SERVER');
	$varcheck_errors = '';
623
	foreach ($varcheck_vars as $var) {
624 625 626
		if (!isset($$var)) {
			continue;
		}
changi67's avatar
changi67 committed
627
		if (($tmp = varcheck($$var, $var)) != '') {
628 629 630
			if ($varcheck_errors != '') {
				$varcheck_errors.= '<br />';
			}
changi67's avatar
changi67 committed
631
			$varcheck_errors.= $tmp;
632 633 634 635
		}
	}
	unset($tmp);
}
636

637 638 639 640 641 642 643 644 645
if (count($_FILES)) {
	$mimelib = TikiLib::lib('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) {
				if ($tmp_name) {
					$type = $mimelib->from_path($upload_file_info['name'][$k], $tmp_name);
					$upload_file_info['type'][$k] = $type;
646 647
				}
			}
648 649 650
		} elseif ($upload_file_info['tmp_name']) {
			$type = $mimelib->from_path($upload_file_info['name'], $upload_file_info['tmp_name']);
			$upload_file_info['type'] = $type;
651 652 653 654
		}
	}
}

655
// deal with old request globals (e.g. used by Smarty)
changi67's avatar
changi67 committed
656 657 658
$GLOBALS['HTTP_GET_VARS'] = & $_GET;
$GLOBALS['HTTP_POST_VARS'] = & $_POST;
$GLOBALS['HTTP_COOKIE_VARS'] = & $_COOKIE;
659 660 661 662 663
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
664
if (isset($_REQUEST['highlight']) || (isset($prefs['feature_referer_highlight']) && $prefs['feature_referer_highlight'] == 'y')) {
665
	$smarty->loadFilter('output', 'highlight');
666
}
667 668 669
if (function_exists('mb_internal_encoding')) {
	mb_internal_encoding("UTF-8");
}
670
// --------------------------------------------------------------
lrargerich's avatar
Fixes  
lrargerich committed
671
// Fix IIS servers not setting what they should set (ay ay IIS, ay ay)
672 673 674
if (!isset($_SERVER['QUERY_STRING'])) {
	$_SERVER['QUERY_STRING'] = '';
}
675

676 677


678
$smarty->assign("tikidomain", $tikidomain);