<?php
	class RemoveComponent extends Component {
		function GetUUIDs() {
			$uuids[] = 'remove(\.do){0,1}$';
			return $uuids;
		}
		
		function preError($error)
		{
			if (isset($_SESSION['removesessionip']))
				unset($_SESSION['removesessionip']);
				
			_page_header(SITE_NAME." :: Remove :: Request denied");
			echo "<p>".$error."</p>";
			_page_footer();

			exit;
		}

		function Run($page, $matches) {
			global $frameworks_path;
			
			if (!isset($_REQUEST['incident']))
				$this->preError('You need to specify an incident id to remove.');

			if (empty($_SERVER['HTTP_REFERER']))
				$this->preError('Nice try, but thats not the way we roll nowadays. (REF)');

			$incident = intval($_REQUEST['incident']);
			$res = get_db_rows("SELECT * FROM blacklist WHERE id='" . $incident . "';");
			$tuple = get_db_tuple($res);
			if (!$tuple)
				$this->preError('The ID you are trying to remove does not exist.');
				
			if (!isset($_SESSION['removesessionip']) || $_SESSION['removesessionip'] != $tuple['ip'])
				$this->preError('Nice try, but thats not the way we roll nowadays. (SES)');
			
			if (immutable($tuple['type']))
				$this->preError('Your IP is not removable using this tool. Please contact <a rel="external" href="mailto:'.MAINTAINER_EMAIL.'">'.MAINTAINER_NAME.'</a>');
				
			$res2 = get_db_tuple(get_db_rows("SELECT COUNT(*) FROM removerequest WHERE incident='" . $incident . "';"));
			if ($res2[0] > 0)
				$this->preError('The ID you are trying to remove is already being handled.<br/>If you feel this is in error, or you did not get a response, contact <a rel="external" href="mailto:'.MAINTAINER_EMAIL.'">'.MAINTAINER_NAME.'</a>');
			
			_page_header(SITE_NAME." :: Remove :: ".$tuple['ip']);
			
			$reCaptcha = new reCaptcha();

			if (isset($_POST['ok']))
			{
				if (!_removeallowed($tuple))
				{
					$captcha = $reCaptcha->verify();
					if (!$captcha)
					{
						echo "<p>You did not successfully completed the captcha challenge.</p>";
						_page_footer();
						exit;
					}
					
					$fields = ['email','name','notes'];
					foreach ($fields AS $field)
					{
						if (!isset($_POST[$field]) || empty($_POST[$field]))
						{
							echo "<p>You have not filled in all the fields of the form. Please <a href=\"".$_SERVER['HTTP_REFERER']."\">try again</a>.</p>\n";
							_page_footer();
							exit;
						}
					}
					
					$email = strip_tags($_POST['email']);
					$name = strip_tags($_POST['name']);
					$notes = strip_tags($_POST['notes']);
					
					$vmail = is_valid_email(db_escape($email));
					if ($vmail != 0) {
						echo "<p>The email address you stated failed for the following reason:<br/>".$vmail."</p>";
						_page_footer();
						exit;
					}
					
					$get = get_db_tuple(get_db_rows("SELECT * FROM rpckey WHERE id='".$tuple['uid_add']."'"));
					if (!$get)
						$get = ['id' => 169, 'email' => 'outsider@scarynet.org'];
					
					$ins = get_db_rows("INSERT INTO removerequest (incident,assigned,remotename,remotemail,remotereason) VALUES (".$incident.",".$get['id'].",'".db_escape($name)."','".db_escape($email)."','".db_escape($notes)."')");
					$ticketid = db_insert_id($ins);
					
					$subject = '['.SITE_NAME.' #'.$ticketid.'] Manual remove request incident '.$incident.' IP:'.$tuple['ip'];
					
					$body = '';
					foreach (array_keys($_POST) as $field)
					{
						if ($field != 'g-recaptcha-response' && $field != 'ok')
							$body .= $field.": ".$_POST[$field]."\r\n";
					}
					$body .= "Server      : ".MIRROR_NAME."\t\n";
					$body .= "Incident IP : https://dronebl.org/lookup?ip=".$tuple['ip']." (".countryname(_getcountry($tuple['ip'])).")\r\n";
					$body .= "User IP     : ".USERIP." (".countryname(_getcountry(USERIP)).")\r\n";
					$body .= "\r\nReply only works if you use your email addresses as known by ".SITE_NAME."!\r\n";

					$headers = "From: ".SITE_NAME." Tickets <ticket@dronebl.org>\r\nReply-To: ticket@dronebl.org\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=\"UTF-8\"\r\n";
					$receiver = $get['email'];
					
					$mailstatus = mail($receiver, $subject, $body, $headers, '-f ticket@dronebl.org');
					
					echo "<p>Your request has ".($mailstatus?'been sent and will be dealt with shortly. You will receive a reply if it has been processed':'NOT been send due to mail issues').".</p>";
				} else {
					$res = get_db_rows("UPDATE blacklist SET listed=0,ts_del=now()::abstime::int4,uid_del='".(isset($_SESSION['uid'])?$_SESSION['uid']:0)."' WHERE id='" . $incident . "';");
					_activity_log_add(0, 1, "IP <strong>".$tuple['ip']."</strong> removed from ".SITE_NAME." by <strong>"._removeallowed($tuple)."</strong>.");
					$_SESSION['removesessionip'] = '';
					echo "<p>This incident has been removed from ".SITE_NAME.". Please make sure that you have fixed ".
						"your problem, or it will reappear here. Have a great day.</p>".
						"<p>You may have other incidents in ".SITE_NAME." reported, ".
						"in which case you will need to remove them as well.</p>";
				}
				unset($_SESSION['removesessionip']);
			}
			else
			{
				if (!_removeallowed($tuple))
				{
					$labelstyle="display:block;float:left;width:150px;margin:2px;";
					$inputstyle="margin:2px;width:450px";
?>
<p>Please note the following before even considering filling in this form:</p>
<ul>
	<li>
		If it's a shellaccount (eggdrop/bnc/whatever): Have your shelladmin perform the request!
		We get tons of requests from users who complain about their shell being banned.
		Think about the fact you are not the only one on that box using it's IP's.
		So maybe someone else on the box fucked it up for you.
	</li>
	<li>
		Shelladmins should always aquire delegation of their ranges in order to have them listed
		at the appropiate IP registry (RIPE/ARIN/LACNIC/APNIC). With proper and usable email adress.
		As per 1-1-2011, we will no longer accept removal requests from shelladmins who have not
		taken the neccessary steps in order to show their 'ownership' of certain IP ranges.
	</li>
	<li>Don't paste gline messages, we know how gline messages look like.</li>
	<li>There is no need to specify the ip in the comment, it's part of the removal request already.</li>
	<li>
		Note that if you have become listed, it means the IP you currently use HAS DONE SOMETHING WRONG AT THE TIME OF THE LISTING ENTRY.
		Also note that <?=SITE_NAME?> is not the one who added you, but one of it's users/contributors.
	</li>
	<li>
		If the ISP you use provides you with highly dynamical IP's (as in, IP rotating very often) and you suddenly 
		show up listed. Then it's probably not your fault, but the fault of the one who previously used that IP.
	</li>
	<li>
		Please check your server for the existance of drones, trojans, backdoors, misconfigured proxies.
		Do NOT assume you have been listed just because a user has been abusing your server for email spamming!
		We get tons of request from people that claim there has been no spam while the ip in question is listed
		for other reasons.
	</li>
	<li>
		If the comment contains 'Scraped' this means your IP is listed as open anonymous proxy on one or more
		popular proxy listing sites. Again for this, see the previous comment!
	</li>
	<li><strong>We already know what IP you are asking about, no need to remention it.</strong></li>
	<li><strong>If your IP is marked as type 17, please read <a href="/blog/23">this blogentry</a></strong></li>
	<li><strong>If your IP is marked as type 18, please read <a href="/blog/33">this blogentry</a></strong></li>
	<li><strong>Forms that have not been decently filled in will be trashed!</strong></li>
	<li><strong>NEVER EVER simply assume your entry is related to spam!</strong></li>
</ul>
<form action="" method="post" id="newstyle">
	<fieldset>
		<legend>Manual removal request form</legend>
		<input type="hidden" name="incident" value="<?= $incident ?>" />
		<label for="name" style="<?=$labelstyle?>">Your name:</label>
		<input type="text" id="name" name="name" style="<?=$inputstyle?>" /><br/>
		<label for="email" style="<?=$labelstyle?>">Email:</label>
		<input type="text" id="email" name="email" style="<?=$inputstyle?>" /><br/>
		<p>
			Please use the textarea below to describe why you are unable to remove this incident yourself.
			Also specify why you are currently unable to use the ip you want to remove. ENGLISH ONLY!
		</p>
		<textarea name="notes" cols="57" rows="10" style="width:600px;margin:2px"></textarea><br/>
		<?= $reCaptcha->create(); ?>
		<input type="submit" name="ok" value="Submit" />
	</fieldset>
</form>
<?php
				}
				else
				{
?>
<p>You are requesting the delisting of incident <?= $incident ?> involving <?= $tuple['ip'] ?>.  Please confirm.</p>
<form action="" method="post">
	<input type="submit" name="ok" value="confirm" />
</form>
<?php
				}
			}
			_page_footer();
		}
	};
	new RemoveComponent;
?>
