<?php
	class RPCVersion1Component extends Component {
		function GetUUIDs() {
			$uuids[] = 'rpc(\.do){0,1}$';
			return $uuids;
		}

		function Run($page, $matches) {
			if (!isset($_REQUEST['rpckey']))
			{
				header('Location: /docs/rpc');
				die();
			}

			header('Content-type: text/plain');
			
			$rpckey = db_escape(strip_tags($_REQUEST['rpckey']));	
			$tuple = get_db_tuple(get_db_rows("SELECT * FROM rpckey WHERE rpckey = '".$rpckey."' LIMIT 1"));
			if (!$tuple[0])
				die('Invalid RPCKEY');
				
			if (!$action = db_escape(strip_tags($_REQUEST['action'])))
				die('No RPC ACTION given.');

			$rpcid = $tuple['id'];
			$rpckey = $tuple['rpckey'];
			
			get_db_rows("UPDATE rpckey SET last_used=now()::abstime::int4 WHERE id='".$rpcid."'");
				
			switch(strtolower($action))
			{
				case 'add':
					$fields = array('listed', 'uid_add');
					$values = array(1, $rpcid);

					if (isset($_REQUEST['ip']))
					{
						$ip = db_escape(strip_tags($_REQUEST['ip']));

						if (!is_valid_ip($ip))
							die('IP invalid');

						if (_isprivate($ip))
							die('IP not allocated');

						if (whitelisted($ip))
							die('IP whitelisted');
							
						if (_istor($ip))
							die('IP is a tor exit node');

						$fields[] = 'ip';
						$values[] = $ip;
					}
					else
						die('No IP');

					if (isset($_REQUEST['type']))
					{
						$type = intval($_REQUEST['type']);

						if (!is_valid_type($type))
							die('Unknown type');

						$fields[] = 'type';
						$values[] = $type;
					}
					else
						die('No type');

					if (isset($_REQUEST['port']))
					{
						$port = intval($_REQUEST['port']);

						if ($port < 1 || $port > 65535)
							die('Invalid port');

						$fields[] = 'port';
						$values[] = $port;
						if (newFilter($ip, $type, $rpcid, $port))
							die('You already reported '.$ip.':'.$port.' as type '.$type);
					}
					else if (newFilter($ip, $type, $rpcid))
						die('You already reported '.$ip.' as type '.$type);

					if (isset($_REQUEST['comment']))
					{
						$fields[] = 'comment';
						$values[] = db_escape(strip_tags($_REQUEST['comment']));
					}

					if ($asn = _getasn($ip))
					{
						$fields[] = 'asn';
						$values[] = $asn;
					}

					if ($country = _getcountry($ip))
					{
						$fields[] = 'country_code';
						$values[] = db_escape($country);
					}

					$query = "INSERT INTO blacklist (".implode(",", $fields).") VALUES ('".implode("','", $values)."')";
					$res = get_db_rows($query);
					if (db_insert_id($res))
					{
						_activity_log_add(0, 1, "IP <strong>".$ip."</strong> added as type <strong>".$type."</strong> by RPC call.");
						die($ip.' added as type '.$type);
					}
					break;

				default:
					die('Unknown ACTION');
					break;
			}
		}
	};

	new RPCVersion1Component;
?>
