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

		function Run($page, $matches) {
			if (isset($_REQUEST['ip']) || (isset($_SESSION['username']) && isset($_REQUEST['id']) && is_numeric($_REQUEST['id'])) )
			{
				if (isset($_SESSION['username']) && isset($_REQUEST['id']) && is_numeric($_REQUEST['id']))
				{
					$iq = get_db_rows("SELECT ip FROM blacklist WHERE id=".intval($_REQUEST['id']));
					if (!db_num_rows($iq))
						die('This is not a valid id to check for');
					else
					{
							$ipdata = get_db_tuple($iq);
							$ip = $ipdata['ip'];
					}	
				}
				else
					$ip = trim($_REQUEST['ip']);

				if (!is_valid_ip($ip))
					die('This is not a valid ip to check for');
					
				if (!isset($_REQUEST['ajax']))
				{
					_page_header(SITE_NAME.' :: Lookup :: ' . $ip);
					
					if (isset($_REQUEST['network']) || isset($_REQUEST['Network']))
					{
						$network = strip_tags(urldecode($_REQUEST['network'] ? $_REQUEST['network'] : $_REQUEST['Network']));
						if (preg_match('/^([A-Za-z0-9\.\-_]+)$/i', $network, $dmatches) == 0)
						{
							header('HTTP/1.1 403 Forbidden');
							exit;
						}

						$nq = get_db_rows("SELECT * FROM networks WHERE lower(name)=lower('".db_escape($network)."')");
						if (!db_num_rows($nq))
						{
							get_db_rows("INSERT INTO networks (name) VALUES('".db_escape($network)."')");
							$networkdata = array('name' => $network, 'logo_url' => '', 'web_url' => '', 'server' => '');
						}
						else
							$networkdata = get_db_tuple($nq);
							
						if (!empty($networkdata['logo_url']))
							echo '<img src="' . $networkdata['logo_url'] . '" alt="' . $networkdata['name'] . '" style="max-height:80px;max-width:300px" />' . PHP_EOL;
?>
<p>
	You have reached this page because you are unable to access <strong><?=(!empty($networkdata['web_url']) ? '<a rel="external" href="' . $networkdata['web_url'] . '">' . $networkdata['name'] . '</a>' : $networkdata['name'])?></strong>.
	You should note that we are not <?=(!empty($networkdata['web_url']) ? '<a rel="external" href="' . $networkdata['web_url'] . '">' . $networkdata['name'] . '</a>' : $networkdata['name'])?>, and cannot give you details on when being delisted from here will enable you to reconnect to <?=(!empty($networkdata['server']) ? '<a rel="external" href="irc://' . $networkdata['server'] . '" title="Attempt to connect to ' . $networkdata['server'] . ' using your chat client">' . $networkdata['name'] . ' (' . $networkdata['server'].')</a>' : $networkdata['name']) ?>.
</p>
<?php
					}
				}
			
				if (isset($_POST['iid']) && isset($_SESSION['uid']) && isset($_POST['todo'])) {
					$ids = array();
					foreach ($_POST['iid'] AS $id)
					{
						if (is_numeric($id))
							array_push($ids,$id);
					}
					if (empty($ids))
						echo '<p>Nothing to do.</p>' . PHP_EOL;
					else
					{
						$valid = array();
						$res = get_db_rows("SELECT * FROM blacklist WHERE id IN (".implode(',',$ids).")");
						while ($row = get_db_tuple($res))
						{
							if (_removeallowed($row))
								array_push($valid,$row['id']);
						}
						if (empty($valid))
							echo '<p>Nothing to do.</p>' . PHP_EOL;
						else
						{
							switch ($_POST['todo'])
							{
								case 'delist':
									$res = get_db_rows("UPDATE blacklist SET listed=0, ts_del=" . time() . ", uid_del='" . $_SESSION['uid'] . "' WHERE id IN (" . implode(',', $valid) . ")" );
									 _activity_log_add(0, 1, 'IP <strong>' . $_REQUEST['ip'] . '</strong> removed from ' . SITE_NAME . ' by <strong>' . _removeallowed($row) . '</strong>.');
									echo '<p>' . count($valid) . ' entries delisted</p>' . PHP_EOL;
									break;
								default:
									echo '<p>Illegal action requested.</p>' . PHP_EOL;
									break;
							}
						}
					}
				}
				$asn = _getasn($ip);
				$country = _getcountry($ip);
				$hostname = gethostbyaddr($ip);
?>
<p style="font-size:300%;color:red">A listing in <?=SITE_NAME?> is NOT always related to <a rel="external" href="https://google.com/search?q=spam+<?=$ip?>">spam</a>. But in most cases because of an <a rel="external" href="https://google.com/search?q=proxy+<?=$ip?>">open proxy</a> !!!</p>

<h2>Details about <?= $ip ?></h2>
<p>
	<strong>Country:</strong> <?=($country ? countryname($country).' ('.$country.')' : 'unknown')?><br />
	<strong>Reverse:</strong> <?=($hostname != $ip ? $hostname : 'none')?><br />
	<strong>Autonomous System Number:</strong> <?=($asn ? (_ownas($asn)?'<a href="/admin/asadmin/'.$asn.'" rel="external">':'').'AS'.$asn.(_ownas($asn)?'</a>':'') : 'none/unknown')?><br />
<?php
				if (isset($_SESSION['uid']))
				{
					$ports = implode(', ', explode(',',google_portsearch($ip)));
					echo "\t<strong>Google ProxyPortSearch:</strong> ".($ports ? $ports : 'none').PHP_EOL;
				}
?>
</p>
<p>&nbsp;</p>
<h2>Lookup results for <?= $ip ?></h2>
<?php
				$res = get_db_rows("SELECT b.*,(SELECT COUNT(*) FROM removerequest r WHERE r.incident=b.id) AS removecount FROM blacklist b WHERE b.ip='".db_escape($ip)."' ORDER BY listed DESC,id DESC;");
				$listed = db_num_rows($res) > 0;

				$res2 = get_db_rows("SELECT * FROM blacklist_cidr WHERE '".db_escape($ip)."' << cidr::cidr AND listed=1;");
				if (db_num_rows($res2))
				{
					$tuple2 = get_db_tuple($res2);
					echo "<p style=\"color:red\">This IP is part of a CIDR listing on <strong>".$tuple2['cidr']."</strong> as type <strong>".$tuple2['type']." (".ClassInfo($tuple2['type']).")</strong> ".($tuple2['comment'] ? " with comment <strong>".$tuple2['comment']."</strong>" : "")." since <strong>". gmdate("M-d-Y H:i:s T", $tuple2['timestamp'])."</strong> and can only be removed by contacting the maintainer.</p>".PHP_EOL;
				}
					
				if (!$listed)
				{
					echo "<p>No specific incidents regarding <strong>".$ip."</strong> were found in ".SITE_NAME."'s incident tracking system.".(!isset($tuple2) ? " This means that your IP is not listed in ".SITE_NAME.".":"")."</p>".PHP_EOL;
				}
				else
				{
					echo "<p>There are listings for <strong>".$ip."</strong> in ".SITE_NAME.
						 ". To get removed from our DNSBL, you will need to address <strong>all</strong> of these incident listings.</p>".PHP_EOL;

					if (isset($_SESSION['uid']))
					{
						$comments = get_db_tuple(get_db_rows("SELECT COUNT(*) FROM comments WHERE ip='".db_escape($ip)."'"));
?>
<form method="post" action="/lookup?ip=<?=$ip?>" id="multiform">
<input type="hidden" name="todo" id="todo" value="" />
<?php
					}
?>
<table class="listing stripe compact">
	<thead>
		<tr>
<?php
					if (isset($_SESSION['uid']))
					{
						echo	"\t\t<th colspan=\"".(_hasflag(FLAG_GLOBALADMIN)?9:8)."\">".
							"<button type=\"button\" accesskey=\"a\" onclick=\"tagAll();return false\">Select <u>A</u>ll</button>".
							"<button type=\"button\" accesskey=\"n\" onclick=\"tagNone();return false\">Select <u>N</u>one</button>".
							"<button type=\"button\" accesskey=\"r\" onclick=\"tagReverse();return false\"><u>R</u>everse selection</button>".
							"<button type=\"button\" accesskey=\"s\" onclick=\"doDelist();\">Delist <u>s</u>elected</button>".
							"<button type=\"button\" accesskey=\"c\" onclick=\"window.location = '/admin/comments/".$ip."'\"><u>C</u>omments (".$comments[0].")</button>".
							"</th>\n".
							"\t</tr>\n".
							"\t<tr>\n".
							"\t\t<th>&nbsp;</th>\n";
					}
?>
			<th>Incident ID</th>
			<th>Date</th>
			<th>Class</th>
			<th>Why?</th>
			<th>Comments</th>
			<th>Port</th>
<?php
					if (_hasflag(FLAG_GLOBALADMIN))
					{
						echo "\t\t<th>Added by</th>\n";
						$keys = array();
						$rkeys = get_db_rows("SELECT * FROM rpckey");
						while ($tkeys = get_db_tuple($rkeys))
							$keys['U'.$tkeys['id']] = $tkeys['notes'];
					}
?>
			<th>Remove</th>
		</tr>
	</thead>
	<tbody>
<?php
					$dbresult = array();
					$pending_submitters = array();
					while ($tuple = get_db_tuple($res))
					{
						$dbresult[] = $tuple;
						if (!in_array($tuple['uid_add'], $pending_submitters))
						{
							$cnt = $tuple['removecount'];
							if ($cnt[0] > 0)
								$pending_submitters[] = $tuple['uid_add'];
						}
					}
					
					foreach ($dbresult AS $tuple)
					{
?>
		<tr<?=($tuple['listed']?' style="color:#ff3300"':'')?>>
<?php
						if (isset($_SESSION['uid']))
							echo 	"\t\t<td>".($tuple['listed'] && !isset($tuple['cidr']) && _removeallowed($tuple) ? '<input type="checkbox" name="iid[]" value="' . $tuple['id'] . '" />' : '&nbsp;') . '</td>' . PHP_EOL;
?>
			<td><?= $tuple['id'] ?></td>
			<td><?= gmdate("M-d-Y H:i:s T", $tuple['timestamp']) ?></td>
			<td><?= $tuple['type'] ?></td>
			<td><?= ClassInfo($tuple['type']) ?></td>
			<td><?= $tuple['comment'] ? $tuple['comment'] : "<i>none</i>" ?></td>
			<td><?=(_removeallowed($tuple) && $tuple['port']?$tuple['port']:'-') ?></td>
<?php
						if (_hasflag(FLAG_GLOBALADMIN))
							echo "\t\t<td>".$keys['U'.$tuple['uid_add']]."</td>\n";
							
						if (!$tuple['listed'])
							echo "\t\t<td>listing not active</td>\n";
						else if (isset($tuple['cidr']))
							echo "\t\t<td>contact maintainer</td>\n";
						else if (immutable($tuple['type']))
							echo "\t\t<td>requires manual approval</td>\n";
						else if (in_array($tuple['uid_add'], $pending_submitters))
							echo "\t\t<td>pending removal</td>\n";
						else
						{
							$_SESSION['removesessionip'] = $ip;
							echo "\t\t<td><a href=\"/remove?incident=".$tuple['id']."\">request removal</a></td>\n";
						}
?>
		</tr>
<?php
					}
?>
	</tbody>
</table>
<?php
					if (isset($_SESSION['uid']))
					{
?>
</form>
<script type="text/javascript">
/*<![CDATA[*/
	target = document.getElementById('multiform');
	inputs = target.getElementsByTagName('input');
	function tagAll()
	{
		for (a=0;a<inputs.length;a++)
			inputs[a].checked = true;
	}

	function tagNone()
	{
		for (a=0;a<inputs.length;a++)
			inputs[a].checked = false;
	}

	function tagReverse()
	{
		for (a=0;a<inputs.length;a++)
			inputs[a].checked = !inputs[a].checked;
	}

	function doDelist()
	{
		if (confirm('Are you sure you want to delist the selected entries?'))
		{
			document.getElementById('todo').value='delist';
			document.getElementById('multiform').submit();
		}
		else
			return false;
	}
/*]]>*/
</script>
<?php
					}
				}
			}
			else
			{
				_page_header(SITE_NAME." :: IP Lookup");
?>
<h2>IP lookup form</h2>
<p>This form allows you to lookup <?=SITE_NAME?> entries by IP.</p>
<p>Please note that if you are listed here, you MUST follow the 
instructions here to become delisted. Your listing was automatically 
added to the system, and can't be removed by staff if you do not follow
the instructions you are given. <strong>Please do not ask in our IRC channel or
on our mailing list if you don't know what to do.</strong></p>
<?php
				if (isset($_REQUEST['nojs']))
				{
?>
<form method="get" action="/lookup">
	<table>
		<tr>
			<td>IP:</td>
			<td><input name="ip" type="text" value="<?=USERIP?>" onclick="this.value=''" /></td>
		</tr>
		<tr>
			<td>&nbsp;</td>
			<td><span style="font-size: 85%;">The IP you want to look up.</span></td>
		</tr>
		<tr>
			<td colspan="2" align="right"><input type="submit" value="Lookup IP" /></td>
		</tr>
	</table>
</form>
<?php
				}
				else
				{
?>
<noscript><p>The form on this page uses AJAX. You might consider using the <a href="?nojs=1">non-AJAX form</a>.</p></noscript>
<p>
	IP: <input id="ip" type="text" value="<?=USERIP?>" onclick="this.value=''" /> &nbsp;
	<input type="button" value="Lookup!" onclick="_do_lookup($('#ip').val())" />
</p>
<div id="result"></div>
<?php
				} 
			}
			if (!isset($_REQUEST['ajax'])) _page_footer();
		}
	};
	new LookupComponent;
?>
