<?php

if (isset ($_GET['callback'])) {
	header("Content-type: text/javascript");
} else {
	header("Content-type: application/json");
}


include_once 'common.php';
use Abraham\TwitterOAuth\TwitterOAuth;
use Stash\Pool;
use Stash\Driver\Sqlite;

$cacheDriver = new Stash\Driver\Sqlite(array('path' => sys_get_temp_dir()."/polemictweet_cache.db"));
$cachePool = new Stash\Pool($cacheDriver);

/**
 * Check for a POSTed status message to send to Twitter
 */
if (!empty($_GET)
&& isset($_SESSION['TWITTER_ACCESS_TOKEN'])) {

    $itemCachePath="search/tweets?" . http_build_query($_GET);

    $cachedStatusesResp = $cachePool->getItem($itemCachePath);

    $statusesStr = $cachedStatusesResp->get();

    if ($cachedStatusesResp->isMiss()) {
        $cachedStatusesResp->lock();
        
        $token = unserialize($_SESSION['TWITTER_ACCESS_TOKEN']);
        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token['oauth_token'], $token['oauth_token_secret']);
    
    
        $statuses = $connection->get("search/tweets", $_GET);
        $statusesStr = json_encode($statuses);

        $cachedStatusesResp->set($statusesStr)->expiresAfter(3);
        $cachePool->save($cachedStatusesResp);
    }

    echo($statusesStr);

} else {
    /**
     * Mistaken request? Some malfeasant trying something?
     */
    exit('Invalid tweet request. Oops. Sorry.');
}
?>