<?php
	class RPCKeyManagerComponent extends Component {
		function GetUUIDs() {
			$uuids[] = 'admin\/rpckey$';
			$uuids[] = 'admin\/rpckey\/([^\/]*)';
			return $uuids;
		}

		function Spam($id, $email, $rpckey=null) {
			$row = get_db_tuple(get_db_rows("SELECT * FROM keyrequests WHERE id='" . db_escape($id) . "'"));
			$firstname = $row['firstname'];
			$fullname = $firstname.' '.$row['lastname'];
			$justification = str_replace(PHP_EOL,PHP_EOL.'> ',stripslashes($row['justification']));
			$quoted_req = '> '.$fullname.' wrote:'.PHP_EOL.PHP_EOL.'>'.PHP_EOL.'> '.wordwrap($justification, 80, PHP_EOL.'> ');

			$headers = 'From: '.SITE_NAME.' Staff <no-reply@dronebl.org>'.PHP_EOL.'Reply-To: no-reply@dronebl.org'.PHP_EOL;
			$subject = SITE_NAME.' RPCKey request '.($rpckey ? 'granted' : 'denied');

			$body = 'Dear '.$firstname.','.PHP_EOL.PHP_EOL;

			if ($rpckey)
			{
				$body .= 'Your request for a '.SITE_NAME.' RPCKey has been granted.  Your key is as follows:'.PHP_EOL.
					$rpckey.PHP_EOL.PHP_EOL.
					'If you have questions, please visit us at http://'.$_SERVER['HTTP_HOST'].'/.'.PHP_EOL.PHP_EOL.
					'Thank you for contributing to '.SITE_NAME.'!';
			}
			else
			{
				$body .= 'Your request for a '.SITE_NAME.' RPCKey has been denied, or is pending more information.'.PHP_EOL.
					'If you would like to discuss this decision further, please contact us on IRC (see http://'.$_SERVER['HTTP_HOST'].' for details).'.PHP_EOL.PHP_EOL.
					'If your intentions are beneficent, it is still likely that you can obtain a key by speaking with us on IRC. We sincerely appreciate your interest in supporting '.SITE_NAME.', and we hope that you will discuss the details of this decision with us.';
			}

			$body .= PHP_EOL.PHP_EOL.'Cordially,'.PHP_EOL.PHP_EOL.
					'The '.SITE_NAME.' Staff'.PHP_EOL.PHP_EOL.
					$quoted_req;

			$res = get_db_rows("DELETE FROM keyrequests WHERE id='" . db_escape($id) . "'");
			return mail($email, $subject, $body, $headers, '-f no-reply@dronebl.org');
		}

		function Run($page, $matches) {
			if (!isset($_SESSION['username']))
			{
				$_SESSION['needlogin'] = 1;
				header('Location: /admin/login');
				die();
			}
			
			if (!_hasFlag(FLAG_RPCKEY))
			{
				header('Location: /admin/');
				die();
			}

			$action = isset($matches[1]) ? $matches[1] : 'list';

			if ($action == 'list')
			{
				_page_header(SITE_NAME.' :: Admin :: RPCKey Manager');
?>
<a href="/">home</a> / <a href="/admin">administrate</a> / rpckey manager
<h2>RPCKey Manager</h2>
<p>
	This is a list of the granted RPCKeys. 
	<?= (_hasflag(FLAG_RPCKEY_REVOKE) ? 'You may revoke them if they have become compromised.' : '') ?>
	<?= (_hasflag(FLAG_RPCKEY_ADD) ? 'Alternatively, you might consider <a href="/'.$page.'/add">adding a new RPC key</a>.' : '') ?>
</p>
<table class="listing2 stripe compact top10">
	<thead>
		<tr>
			<th>Notes</th>
			<th>RPCKey</th>
			<th>E-mail</th>
			<th>Username</th>
			<th>Options</th>
		</tr>
	</thead>
	<tbody>
<?php
				$res = get_db_rows("SELECT * FROM rpckey ORDER BY notes ASC");
				$color = 0;
				while($tuple = get_db_tuple($res))
				{
?>
		<tr style="vertical-align:top" class="<?=($color++%2 ? 'odd' : 'even')?>">
			<td><?= $tuple['notes'] ?></td>
			<td><?= $tuple['rpckey'] ?></td>
			<td><a href="mailto:<?= $tuple['email'] ?>"><?= $tuple['email'] ?></a></td>
			<td><?= $tuple['username'] ?></td>
			<td>
				<?= (_hasflag(FLAG_GLOBALADMIN)?'<a href="/'.$page.'/edit?id='.$tuple['id'].'" title="Edit '.$tuple['notes'].'\'s Details"><img src="/images/admin/edit.png" alt="Edit" style="border:0x" /></a>':'') ?>
				<?= (_hasflag(FLAG_GLOBALADMIN) && $tuple['entries'] ?'<a href="/admin/keyentries/'.$tuple['id'].'" title="Entries of '.$tuple['notes'].' ('.$tuple['entries'].')"><img src="/images/admin/list.png" alt="List" style="border:0x" /></a>':'') ?>
				<?= (_hasflag(FLAG_RPCKEY_REVOKE) && !($tuple['flags'] & FLAG_GLOBALADMIN)?'<a href="/'.$page.'/revoke?r='.$tuple['rpckey'].'" title="Revoke '.$tuple['notes'].'\'s Key"><img src="/images/admin/revoke.png" alt="Revoke Key" style="border:0x" /></a>':'') ?>
				<?= (_hasflag(FLAG_GLOBALADMIN) && $tuple['flags'] & FLAG_ASADMIN ? '<a href="/admin/asadmin/'.$tuple['id'].'/assign" title="AS Admin"><img src="/images/admin/asadmin.png" alt="'.$tuple['notes'].' is an AS Admin" /></a>':'') ?>
				&nbsp;
			</td>
		</tr>
<?php
				}
?>
	</tbody>
</table>
<?php
				_page_footer();
			}
			else if ($action == 'edit' && _hasflag(FLAG_GLOBALADMIN) && is_numeric($_REQUEST['id']))
			{
				$res = get_db_rows("SELECT * FROM rpckey WHERE id=".$_REQUEST['id']." LIMIT 1");
				if (db_num_rows($res) > 0)
				{
					$tuple = get_db_tuple($res);
					if ($_POST)
					{
						$update = "UPDATE rpckey SET ";
						if (!empty($_POST['notes']))
							$update .= "notes='".db_escape($_POST['notes'])."',";
						if (!empty($_POST['email']))
							$update .= "email='".db_escape($_POST['email'])."',";
						if (!empty($_POST['username']))
							$update .= "username='".db_escape($_POST['username'])."',";
						if (!empty($_POST['pass1']))
						{
							$p = hash('sha512', $_POST['pass1']);
							$update .= "password='".db_escape($p)."',";
						}
						else if (!empty($_POST['pwdcrypt']))
							$update .= "password='".db_escape($_POST['pwdcrypt'])."',";
						if (!empty($_POST['flags']))
						{
							$newflags = 0;
							foreach ($_POST['flags'] AS $flag)
								$newflags += $flag;
							$update .= "flags=".$newflags.",";
						}
						$update = substr($update,0,-1)." WHERE id=".$_REQUEST['id'];
						get_db_rows($update);
						header('Location: /admin/rpckey');
					}
					else
					{
_page_header(SITE_NAME.' :: Admin :: RPCKey Manager (Edit)');
?>
<a href="/">home</a> / <a href="/admin">administrate</a> / <a href="/admin/rpckey">rpckey manager</a> / edit rpckey
<h3>Edit user details</h3>
<script type="text/javascript">
	function doEditCheck() {
		if (!$('#notes').val().length)
		{
			alert('A description is required');
			$('#notes').focus();
			return false;
		}
		if (!$('#email').val().length)
		{
			alert('An email adres is required');
			$('#email').focus();
			return false;
		}
		if ($('#password1').val() != $('#password2').val())
		{
			$('#password1').val('');
			$('#password2').val('');
			alert('The entered passwords don\'t match');
			$('#password1').focus();
			return false;
		}
		return true;
	}
</script>
<form method="post" action="" onsubmit="return doEditCheck()">
	<table>
		<tbody>
			<tr>
				<th colspan="4">Edit Userid <?=$tuple['id']?></th>
			</tr>
			<tr>
				<td><label for="notes">Description</label></td>
				<td colspan="3"><input type="text" id="notes" name="notes" value="<?=$tuple['notes']?>" /></td>
			</tr>
			<tr>
				<td><label for="email">Email</label></td>
				<td colspan="3"><input type="text" id="email" name="email" value="<?=$tuple['email']?>" /></td>
			</tr>
			<tr>
			<td><label for="username">Username</label></td>
				<td colspan="3"><input type="text" id="username" name="username" value="<?=$tuple['username']?>" /></td>
			</tr>
			<tr>
				<td><label for="password1"><?=(!empty($tuple['password'])?'Change':'Assign')?> password</label></td>
				<td><input type="password" id="password1" name="pass1" value="" autocomplete="off" /></td>
				<td><label for="password2">Retype</label></td>
				<td><input type="password" id="password2" name="pass2" value="" autocomplete="off" /></td>
			</tr>
			<tr>
				<td><label for="pwdcrypt">Crypted (md5/sha512)</label></td>
				<td colspan="3"><textarea name="pwdcrypt" id="pwdcrypt" cols="80" rows="2"></textarea></td>
			</tr>
			<tr>
				<th colspan="4">&nbsp;<br/>Userflags</th>
			</tr>
			<tr>
				<td colspan="4" style="padding-left:30px">
					<strong>General features:</strong><br/>
					<input type="checkbox" name="flags[]" value="<?=FLAG_GLOBALADMIN?>"<?=($tuple['flags'] & FLAG_GLOBALADMIN?' checked="checked"':'')?>/> User is a global admin<br/>
					<input type="checkbox" name="flags[]" value="<?=FLAG_MASSIMPORT?>"<?=($tuple['flags'] & FLAG_MASSIMPORT?' checked="checked"':'')?>/> User can do massimports<br/>
					<input type="checkbox" name="flags[]" value="<?=FLAG_BLOG?>"<?=($tuple['flags'] & FLAG_BLOG?' checked="checked"':'')?>/> User can manage blog<br/>
					<input type="checkbox" name="flags[]" value="<?=FLAG_ASADMIN?>"<?=($tuple['flags'] & FLAG_ASADMIN?' checked="checked"':'')?>/> User is AS administrator<br/>
					<br/>

					<strong>RPC Key related:</strong><br/>
					<input type="checkbox" name="flags[]" value="<?=FLAG_RPCKEY?>"<?=($tuple['flags'] & FLAG_RPCKEY?' checked="checked"':'')?>/> User can view rpckeys/requests<br/>
					<input type="checkbox" name="flags[]" value="<?=FLAG_RPCKEY_REVOKE?>"<?=($tuple['flags'] & FLAG_RPCKEY_REVOKE?' checked="checked"':'')?>/> User can revoke rpckeys<br/>
					<input type="checkbox" name="flags[]" value="<?=FLAG_RPCKEY_ADD?>"<?=($tuple['flags'] & FLAG_RPCKEY_ADD?' checked="checked"':'')?>/> User can add rpckeys<br/>
				</td>
			</tr>
			<tr>
				<th colspan="4">&nbsp;<br/><input type="submit" value="Submit Changes" /></th>
			</tr>
		</tbody>
	</table>
</form>
<?php
						_page_footer();
					}
				}
				else
					header('Location: /admin/rpckey');
			}
			else if ($action == 'revoke' && _hasflag(FLAG_RPCKEY_REVOKE))
			{
				if (!empty($_POST['email']) && !empty($_POST['id']))
				{
					$this->Spam($_POST['id'], $_POST['email']);
					header('Location: /admin/rpckey');
				}
				else
				{
					if ($_REQUEST['confirm'] == 'true')
					{
						$res = get_db_rows("UPDATE rpckey SET rpckey='".db_escape($_REQUEST['r'])."_revoked' WHERE rpckey='".db_escape($_REQUEST['r'])."';");
						header('Location: /admin/rpckey');
					}
					else
					{
						_page_header(SITE_NAME.' :: Admin :: RPCKey Manager (Revoke)');
?>
<a href="/">home</a> / <a href="/admin">administrate</a> / <a href="/admin/rpckey">rpckey manager</a> / revoke rpckey
<h2>Revoke RPCKEY</h2>
<p>Are you sure you want to revoke the RPC key: <code><?= $_REQUEST['r'] ?></code>?
RPC keys which have been revoked cannot be used again or un-revoked later.</p>
<p><a href="/<?= $page ?>?r=<?= $_REQUEST['r'] ?>&amp;confirm=true">Yes, revoke it!</a></p>
<p><a href="/admin/rpckey">No, don't do that!</a></p>
<?php
						_page_footer();
					}
				}
			}
			else if ($action == 'add' && _hasflag(FLAG_RPCKEY_ADD))
			{
				if (!isset($_POST['rpckey']))
				{
					_page_header(SITE_NAME.' :: Admin :: RPCKey Manager (Add)');
?>
<a href="/">home</a> / <a href="/admin">administrate</a> / <a href="/admin/rpckey">rpckey manager</a> / add rpckey
<h2>Add rpckey</h2>
	<fieldset>
		<legend>Add RPC Key</legend>
		<input type="hidden" id="id" value="" />
		<label for="rpckey">RPC Key:</label>
		<input type="text" id="rpckey" size="50" value="<?= md5($_SESSION['username'].time()) ?>" /><br />

		<label for="notes">Notes:</label>
		<input type="text" id="notes" size="50" /><br />
		<small>(usually contact information)</small><br />

		<label for="email">Email:</label>
		<input type="text" id="email" size="50" value="" />
		<input type="button" value="Do it!" onclick="addkey()" />
	</fieldset>

<?php
					/* added by rojo 2008.09.27 */
					$pending = get_db_rows("SELECT * FROM keyrequests ORDER BY timestamp DESC");
					$result = array();
					if (db_num_rows($pending) > 0)
					{
						// Prepare for eventual pre processing
						while ($row = get_db_tuple($pending)) {
							$result[] = $row;
						}
?>
<h3>Current Requests</h3>
<table class="listing2 stripe">
	<thead>
		<tr>
			<th>Timestamp</th>
			<th>Name</th>
			<th>Justification</th>
			<th>E-mail Address</th>
			<th>Requester IP</th>
			<th>Action</th>
		</tr>
	</thead>
	<tbody>
<?php
						$color = 0;
						foreach ($result as $row) {
							$name = $row['firstname'] . " " . $row['lastname'];
							$just = str_replace("\n", "<br/>", stripslashes($row['justification']));
							$email = $row['email'];
							$ip = $row['requester_ip'];
							$id = $row['id'];
?>
		<tr id="entry_<?=$row['id']?>" class="<?=$color++%2?'odd':'even'?>">
			<td><?= date('d-m-Y H:i:s', $row['timestamp']) ?></td>
			<td rel="name"><?= $name ?></td>
			<td><?= $just ?></td>
			<td><a rel="email" href="mailto:<?= $email ?>?subject="<?=SITE_NAME?> RPCKey request"><?= $email ?></a></td>
			<td><?= $ip ?></td>
			<td>
				<input type="button" onclick="fillform(<?= $id ?>)" value="Populate form" />
				<form method="post" action="/admin/rpckey/revoke" onsubmit="return confirm('Are you sure you wish to deny this request?')">
					<input type="hidden" name="id" id="id_<?=$id?>" value="<?= $id ?>">
					<input type="hidden" name="email" id="email_<?=$id?>" value="<?= $email ?>">
					<input type="submit" value="Deny">
				</form>
				<input type="button" onclick="delete_request(<?= $id ?>)" value="Delete" />
			</td>
		</tr>
<?php
						}
?>
	</tbody>
</table>
<script type="text/javascript" src="/js/md5.min.js"></script>
<script type="text/javascript">
	function addkey()
	{
		id = $('#id').val();
		$.ajax({
			url: 'add',
			method: 'POST',
			data: { id : id, rpckey: $('#rpckey').val(), notes: $('#notes').val(), email: $('#email').val() },
		}).done(function(data) {
			$('#entry_'+id).hide();
			$('#rpckey').val(md5(new Date()));
			$('#notes').val($('#entry_'+id+' *[rel="name"]').html());
			$('#email').val($('#entry_'+id+' *[rel="email"]').html());
			$('#id').val('');
		});
	}
	
	function fillform(id)
	{
		$('#notes').val($('#entry_'+id+' *[rel="name"]').html());
		$('#email').val($('#entry_'+id+' *[rel="email"]').html());
		$('#id').val(id);
	}
	
	function delete_request(id)
	{
		if (confirm('Are you sure you wish to delete this request?'))
		{
			$.ajax({
				url: 'delete_request',
				method: 'POST',
				data: { id : id },
			}).done(function(data) {
				$('#entry_'+id).hide();
			});
		}
	}
</script>
<?php
					}
					else
					{
?>
<h3>No pending web requests.</h3>
<?php
					}
					_page_footer();
				}
				else
				{
					$rpckey = db_escape($_POST['rpckey']);
					$notes = db_escape($_POST['notes']);
					$email = db_escape($_POST['email']);
					$ins = get_db_rows("INSERT INTO rpckey (rpckey, notes, email) VALUES ('".$rpckey."','".$notes."','".$email."')");
					if (isset($_POST['id']) && !empty($email))
						$this->Spam($_POST['id'], $email, $rpckey);
				}
			}
			else if ($action == 'delete_request' && _hasflag(FLAG_GLOBALADMIN))
				get_db_rows("DELETE FROM keyrequests WHERE id=".intval($_POST['id']));
		}
	};

	new RPCKeyManagerComponent;
?>
