<?php

require_once('include/admin.inc.php');

auth_redirect(); // Require logged in user to access this page.

if( isset($_POST['action']) && $_POST['action'] == 'new' ) {
	check_nonce('new-twitter-user');

	if(! $dbConnection->executeUpdate('INSERT INTO twitter_user (username) VALUES (?)', array(md5( microtime() ) ))) {
		adminlog("Error on insertion of new twitter user.", MTS_TWITTER, MTA_INSERT, E_WARNING);
		mtdie("Error on insertion of new twitter user: ". $dbConnection->errorCode(), 'SQL Error');
	} else {
		//$name = sanitize_username($_POST['name']);

		$id = $dbConnection->lastInsertId();

		$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
		$request_token = $connection->getRequestToken(OAUTH_CALLBACK . "&id=$id");

		if ($connection->http_code !== 200 ) {
			adminlog("Twitter getRequestToken failed. HTTP code: $connection->http_code", MTS_TWITTER, MTA_MODIFY);
			mtdie("Could not connect to twitter.com.");
		}

		echo $id . '<br/>';

		setOAuthTokens( $id, $request_token['oauth_token'], $request_token['oauth_token_secret'], md5(microtime()) );

		adminlog("New twitter user created successfully.", MTS_TWITTER, MTA_ADD);

		$url = $connection->getAuthorizeURL($request_token['oauth_token']);
		//echo $url;
		_redirect($url);
		exit();

	}
}

if( isset($_REQUEST['action']) && $_REQUEST['action'] == 'twittercallback' && isset($_REQUEST['id'])) {
	# twitter userID = ID
	$id = (int)$_REQUEST['id'];
	$row = $dbConnection->executeQuery('SELECT id, username, oauth_token, oauth_token_secret, oauth_access_token FROM twitter_user WHERE id = ? LIMIT 1', array($id))->fetch();

	# Compare token in database with token from twitter. If they differ, bail.
	if( $row->oauth_token != $_REQUEST['oauth_token'] ) {
		# token is old, drop from database
		if(!$dbConnection->executeUpdate('DELETE FROM twitter_user WHERE id = ?', array($id))) {
			adminlog('Error deleting temporary twitter user ' . $id, MTS_TWITTER, MTA_DELETE, E_ERROR);
			mtdie('Error deleting temporary twitter user.', 'SQL Error');
		}
		$error.='<p>OAuth Token are Old</p>';
	} else {
		# token is good, save the new Access Token to the database
		$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $row->oauth_token, $row->oauth_token_secret);

		$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);

		if (200 == $connection->http_code) {
			# successful
			$info.='<p>Successfully obtained OAuth Access Token.</p>';
			$content = $connection->get('account/verify_credentials');
			$username = $content->screen_name;

			setOAuthTokens($id, $access_token['oauth_token'], $access_token['oauth_token_secret'], $username);
			adminlog("Successfully received OAuth Access Tokens for twitter user.", MTS_TWITTER, MTA_MODIFY, E_WARNING);

			//print_r($content);

		} else {
			# fail
			if( !$dbConnection->executeUpdate('DELETE FROM twitter_user WHERE id = ?', array($id))) {
				adminlog('Error deleting specified twitter user ' . $id, MTS_TWITTER, MTA_DELETE, E_ERROR);
				mtdie('Error deleting the specified twitter user.', 'SQL Error');
			}
			$info.='<p>Failed to get OAuth Access Token for ' . $username . '.</p>';
			adminlog("Failed to get OAuth Access Tokens for twitter user.", MTS_TWITTER, MTA_MODIFY, E_ERROR);
		}

	}
}

$twitter_users = $dbConnection->fetchAll('SELECT id, username, oauth_token, oauth_token_secret, oauth_access_token FROM twitter_user ORDER BY username');

adminhead('Manage Twitter Users');
adminmenu();

?>

<h2>Manage Twitter Users</h2>
<p>Make changes to the twitter accounts which we can post to.</p>

<p><a href="post-twitter.php">&lt;- Done</a></p>

<table class="widefat">
	<thead>
	<tr>
	<th scope="col" style="text-align: center;">ID #</th>
	<th scope="col">Twitter.com Username</th>
	<th scope="col">oauth_token</th>
	<th scope="col">Authorized</th>
	<th scope="col"></th>
	</tr>
	</thead>

	<tbody id="the-list">
	<?php
	$alternate=false;
	foreach( $twitter_users as $s ) {
		$alternate=!$alternate;

		?>
		<tr id="twitteruser-<?php echo $s->id; ?>" <?php if($alternate) echo 'class="alternate"'; ?>>
		 <th scope="row" style="text-align: center;"><?php echo $s->id; ?></th>
		 <td><?php echo htmlentities($s->username); ?></td>
		 <td><?php echo htmlentities($s->oauth_token); ?></td>
		 <td><?php
			$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $s->oauth_token, $s->oauth_token_secret);
			$content = $connection->get('account/verify_credentials');
			if( isset($content->profile_image_url)) {
				echo '<img src="' . $content->profile_image_url . '" />';
			} else {
				echo 'Not Authorized';
			}
		 ?></td>
		 <td style="text-align: center;"><a class="delete" href="delete-twitter-user.php?id=<?php echo (int)$s->id; ?>">Delete</a></td>
		</tr>
		<?php
	}
	?>
	</tbody>
</table>


<form enctype="multipart/form-data" name="create-user" id="create-user" action="manage-twitter-users.php" method="post">
<?php nonce_field('new-twitter-user'); ?>
<input type="hidden" name="action" value="new" />

<h3>Add Twitter User</h3>
<!-- <div class="narrow">
	<table class="editform" width="100%" cellspacing="2" cellpadding="5">
	<tr>
	<th scope="row" width="33%">Username</th>
	<td width="66%">@<input name="name" type="text" id="name" value="" /></td>
	</tr>
	</table>
-->
	<p class="submit"><input type="submit" value="Add Twitter User &raquo;" name="submit" /></p>
<!-- </div> -->
</form>

<?php
adminfooter();
?>
