limits.php 9.07 KB
Newer Older
Scott committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	Description: Monitoring and rate-limiting user actions (application level)


	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
*/

Scott committed
22
if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser
23
	header('Location: ../../');
Scott committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
	exit;
}


define('QA_LIMIT_QUESTIONS', 'Q');
define('QA_LIMIT_ANSWERS', 'A');
define('QA_LIMIT_COMMENTS', 'C');
define('QA_LIMIT_VOTES', 'V');
define('QA_LIMIT_REGISTRATIONS', 'R');
define('QA_LIMIT_LOGINS', 'L');
define('QA_LIMIT_UPLOADS', 'U');
define('QA_LIMIT_FLAGS', 'F');
define('QA_LIMIT_MESSAGES', 'M'); // i.e. private messages
define('QA_LIMIT_WALL_POSTS', 'W');


/**
 * How many more times the logged in user (and requesting IP address) can perform an action this hour.
 * @param string $action One of the QA_LIMIT_* constants defined above.
 * @return int
 */
function qa_user_limits_remaining($action)
{
47 48 49
	$dbSelect = qa_service('dbselect');
	$userlimits = $dbSelect->getPendingResult('userlimits', qa_db_user_limits_selectspec(qa_get_logged_in_userid()));
	$iplimits = $dbSelect->getPendingResult('iplimits', qa_db_ip_limits_selectspec(qa_remote_ip_address()));
Scott committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

	return qa_limits_calc_remaining($action, @$userlimits[$action], @$iplimits[$action]);
}

/**
 * Return how many more times user $userid and/or the requesting IP can perform $action (a QA_LIMIT_* constant) this hour.
 * @deprecated Deprecated from 1.6.0; use `qa_user_limits_remaining($action)` instead.
 * @param int $userid
 * @param string $action
 * @return mixed
 */
function qa_limits_remaining($userid, $action)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'db/limits.php';

	$dblimits = qa_db_limits_get($userid, qa_remote_ip_address(), $action);

	return qa_limits_calc_remaining($action, @$dblimits['user'], @$dblimits['ip']);
}

/**
 * Calculate how many more times an action can be performed this hour by the user/IP.
 * @param string $action One of the QA_LIMIT_* constants defined above.
 * @param array $userlimits Limits for the user.
 * @param array $iplimits Limits for the requesting IP.
 * @return mixed
 */
function qa_limits_calc_remaining($action, $userlimits, $iplimits)
{
	switch ($action) {
		case QA_LIMIT_QUESTIONS:
			$usermax = qa_opt('max_rate_user_qs');
			$ipmax = qa_opt('max_rate_ip_qs');
			break;

		case QA_LIMIT_ANSWERS:
			$usermax = qa_opt('max_rate_user_as');
			$ipmax = qa_opt('max_rate_ip_as');
			break;

		case QA_LIMIT_COMMENTS:
			$usermax = qa_opt('max_rate_user_cs');
			$ipmax = qa_opt('max_rate_ip_cs');
			break;

		case QA_LIMIT_VOTES:
			$usermax = qa_opt('max_rate_user_votes');
			$ipmax = qa_opt('max_rate_ip_votes');
			break;

		case QA_LIMIT_REGISTRATIONS:
			$usermax = 1; // not really relevant
			$ipmax = qa_opt('max_rate_ip_registers');
			break;

		case QA_LIMIT_LOGINS:
			$usermax = 1; // not really relevant
			$ipmax = qa_opt('max_rate_ip_logins');
			break;

		case QA_LIMIT_UPLOADS:
			$usermax = qa_opt('max_rate_user_uploads');
			$ipmax = qa_opt('max_rate_ip_uploads');
			break;

		case QA_LIMIT_FLAGS:
			$usermax = qa_opt('max_rate_user_flags');
			$ipmax = qa_opt('max_rate_ip_flags');
			break;

		case QA_LIMIT_MESSAGES:
		case QA_LIMIT_WALL_POSTS:
			$usermax = qa_opt('max_rate_user_messages');
			$ipmax = qa_opt('max_rate_ip_messages');
			break;

		default:
			qa_fatal_error('Unknown limit code in qa_limits_calc_remaining: ' . $action);
			break;
Scott committed
131 132
	}

Scott committed
133
	$period = (int)(qa_opt('db_time') / 3600);
Scott committed
134

Scott committed
135
	return max(0, min(
Scott committed
136 137
		$usermax - (@$userlimits['period'] == $period ? $userlimits['count'] : 0),
		$ipmax - (@$iplimits['period'] == $period ? $iplimits['count'] : 0)
Scott committed
138 139
	));
}
Scott committed
140

Scott committed
141 142 143 144 145 146 147
/**
 * Determine whether the requesting IP address has been blocked from write operations.
 * @return bool
 */
function qa_is_ip_blocked()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
148

Scott committed
149
	global $qa_curr_ip_blocked;
Scott committed
150

Scott committed
151 152 153
	// return cached value early
	if (isset($qa_curr_ip_blocked))
		return $qa_curr_ip_blocked;
Scott committed
154

Scott committed
155 156 157
	$qa_curr_ip_blocked = false;
	$blockipclauses = qa_block_ips_explode(qa_opt('block_ips_write'));
	$ip = qa_remote_ip_address();
Scott committed
158

Scott committed
159 160 161 162
	foreach ($blockipclauses as $blockipclause) {
		if (qa_block_ip_match($ip, $blockipclause)) {
			$qa_curr_ip_blocked = true;
			break;
Scott committed
163
		}
Scott committed
164 165
	}

Scott committed
166 167 168 169 170
	return $qa_curr_ip_blocked;
}

/**
 * Return an array of the clauses within $blockipstring, each of which can contain hyphens or asterisks
171
 * @param string $blockipstring
Scott committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
 * @return array
 */
function qa_block_ips_explode($blockipstring)
{
	$blockipstring = preg_replace('/\s*\-\s*/', '-', $blockipstring); // special case for 'x.x.x.x - x.x.x.x'

	return preg_split('/[^0-9A-Fa-f\.:\-\*]/', $blockipstring, -1, PREG_SPLIT_NO_EMPTY);
}

/**
 * Checks if the IP address is matched by the individual block clause, which can contain a hyphen or asterisk
 * @param string $ip The IP address
 * @param string $blockipclause The IP/clause to check against, e.g. 127.0.0.*
 * @return bool
 */
function qa_block_ip_match($ip, $blockipclause)
{
Scott committed
189 190 191 192 193 194 195 196
	$ipv4 = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
	$blockipv4 = filter_var($blockipclause, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;

	// allow faster return if IP and blocked IP are plain IPv4 strings (IPv6 requires expanding)
	if ($ipv4 && $blockipv4) {
		return $ip === $blockipclause;
	}

Scott committed
197 198
	if (filter_var($ip, FILTER_VALIDATE_IP)) {
		if (preg_match('/^(.*)\-(.*)$/', $blockipclause, $matches)) {
Scott committed
199
			// match IP range
Scott committed
200
			if (filter_var($matches[1], FILTER_VALIDATE_IP) && filter_var($matches[2], FILTER_VALIDATE_IP)) {
Scott committed
201
				return qa_ip_between($ip, $matches[1], $matches[2]);
Scott committed
202 203
			}
		} elseif (strlen($blockipclause)) {
Scott committed
204
			// normalize IPv6 addresses
Scott committed
205 206 207 208
			if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
				$ip = qa_ipv6_expand($ip);
				$blockipclause = qa_ipv6_expand($blockipclause);
			}
Scott committed
209

Scott committed
210
			// expand wildcards; preg_quote misses hyphens but that is OK here
Scott committed
211
			return preg_match('/^' . str_replace('\\*', '([0-9A-Fa-f]+)', preg_quote($blockipclause, '/')) . '$/', $ip) > 0;
212 213 214
		}
	}

Scott committed
215 216 217 218
	return false;
}

/**
Scott committed
219
 * Check if IP falls between two others.
220 221 222
 * @param string $ip
 * @param string $startip
 * @param string $endip
Scott committed
223
 * @return bool
Scott committed
224
 */
Scott committed
225
function qa_ip_between($ip, $startip, $endip)
Scott committed
226
{
Scott committed
227 228 229 230 231 232 233
	$uip = unpack('C*', @inet_pton($ip));
	$ustartip = unpack('C*', @inet_pton($startip));
	$uendip = unpack('C*', @inet_pton($endip));

	if (count($uip) != count($ustartip) || count($uip) != count($uendip))
		return false;

Scott committed
234
	foreach ($uip as $i => $byte) {
Scott committed
235 236 237
		if ($byte < $ustartip[$i] || $byte > $uendip[$i]) {
			return false;
		}
Scott committed
238
	}
Scott committed
239 240

	return true;
Scott committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
}

/**
 * Expands an IPv6 address (possibly containing wildcards), e.g. ::ffff:1 to 0000:0000:0000:0000:0000:0000:ffff:0001.
 * Based on http://stackoverflow.com/a/12095836/753676
 * @param string $ip The IP address to expand.
 * @return string
 */
function qa_ipv6_expand($ip)
{
	$ipv6_wildcard = false;
	$wildcards = '';
	$wildcards_matched = array();
	if (strpos($ip, "*") !== false) {
		$ipv6_wildcard = true;
	}
	if ($ipv6_wildcard) {
Scott committed
258
		$wildcards = explode(':', $ip);
Scott committed
259 260 261 262
		foreach ($wildcards as $index => $value) {
			if ($value == "*") {
				$wildcards_matched[] = count($wildcards) - 1 - $index;
				$wildcards[$index] = "0";
263 264
			}
		}
Scott committed
265
		$ip = implode(':', $wildcards);
266 267
	}

Scott committed
268 269
	$hex = unpack("H*hex", @inet_pton($ip));
	$ip = substr(preg_replace("/([0-9A-Fa-f]{4})/", "$1:", $hex['hex']), 0, -1);
270

Scott committed
271
	if ($ipv6_wildcard) {
Scott committed
272
		$wildcards = explode(':', $ip);
Scott committed
273 274 275 276
		foreach ($wildcards_matched as $value) {
			$i = count($wildcards) - 1 - $value;
			$wildcards[$i] = "*";
		}
Scott committed
277
		$ip = implode(':', $wildcards);
Scott committed
278 279
	}

Scott committed
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
	return $ip;
}

/**
 * Called after a database write $action performed by a user identified by $userid and/or $cookieid.
 * @param int $userid
 * @param string $cookieid
 * @param string $action
 * @param int $questionid
 * @param int $answerid
 * @param int $commentid
 */
function qa_report_write_action($userid, $cookieid, $action, $questionid, $answerid, $commentid)
{
}

/**
 * Take note for rate limits that a user and/or the requesting IP just performed an action.
298
 * @param int|null $userid User performing the action.
Scott committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
 * @param string $action One of the QA_LIMIT_* constants defined above.
 * @return mixed
 */
function qa_limits_increment($userid, $action)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'db/limits.php';

	$period = (int)(qa_opt('db_time') / 3600);

	if (isset($userid))
		qa_db_limits_user_add($userid, $action, $period, 1);

	qa_db_limits_ip_add(qa_remote_ip_address(), $action, $period, 1);
}