PageRenderTime 162ms CodeModel.GetById 80ms app.highlight 4ms RepoModel.GetById 77ms app.codeStats 0ms

/users/tools.php

http://showslow.googlecode.com/
PHP | 71 lines | 47 code | 9 blank | 15 comment | 5 complexity | ceda20a1506fe75c145ab1f00f1bfcdc MD5 | raw file
 1<?php
 2/*
 3 * Various tools used within UserBase
 4 */
 5class UserTools
 6{
 7	// CSRF prevention variables
 8	public static $CSRF_NONCE;
 9
10	/*
11	 * Escapes strings making it safe to include user data in HTML output
12	 */
13	public static function escape($string)
14	{
15		return htmlentities($string, ENT_COMPAT, 'UTF-8');
16	}
17
18	public static function preventCSRF() {
19		$storage = new MrClay_CookieStorage(array(
20			'secret' => UserConfig::$SESSION_SECRET,
21			'mode' => MrClay_CookieStorage::MODE_ENCRYPT,
22			'path' => UserConfig::$SITEROOTURL,
23			'httponly' => true
24		));
25
26		/*
27		 * Preventing CSRFs in all POST requests by double-posting cookies
28		 */
29		if (count($_POST) > 0) {
30			if (!array_key_exists('CSRF_NONCE', $_POST)) {
31				error_log('POST request in admin interface without CSRF nonce. Make sure form includes CSRF_NONCE hidden field.');
32				header('HTTP/1.0 403 POST request origin check failed', true, 403);
33				exit;
34			}
35
36			$passed_nonce = $storage->fetch(UserConfig::$csrf_nonce_key);
37
38			if ($passed_nonce != $_POST['CSRF_NONCE']) {
39				error_log('[Possible CSRF attach] POST request with wrong nonce!!!');
40				header('HTTP/1.0 403 POST request origin check failed', true, 403);
41				exit;
42			}
43		}
44
45		self::$CSRF_NONCE = base64_encode(mcrypt_create_iv(50, MCRYPT_DEV_URANDOM));
46		$storage->store(UserConfig::$csrf_nonce_key, self::$CSRF_NONCE);
47	}
48
49	public static function renderCSRFNonce() {
50		?><input type="hidden" name="CSRF_NONCE" value="<?php echo self::escape(self::$CSRF_NONCE); ?>"/>
51<?php
52	}
53
54	/**
55	 * Debug wrapper for simplified debugging, call it like this:
56	 *
57	 *    UserTools::debug('... some message ...');
58	 */
59	public static function debug($message) {
60		if (UserConfig::$DEBUG) {
61			$trace = debug_backtrace();
62
63			error_log('[DEBUG] ' . $message .
64				' (' . $trace[1]['function'] .
65				'(' . var_export($trace[1]['args'], true) . ')' .
66				' on line ' . $trace[0]['line'] .
67				' in ' . $trace[0]['file'] .
68			')');
69		}
70	}
71}