<?php
error_reporting(0);

header("Content-type: text/javascript");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

date_default_timezone_set('Etc/GMT');

function replace_newline($string) {
	return (string)str_replace(array("\r", "\r\n", "\n"), '', $string);
}

function buildBaseString($baseURI, $method, $params)
{
    $r = array(); 
    ksort($params); 
    foreach($params as $key=>$value){
        $r[] = "$key=" . rawurlencode($value); 
    }            

    return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r)); //return complete base string
}

function buildAuthorizationHeader($oauth)
{
    $r = 'Authorization: OAuth ';
    $values = array();
    foreach($oauth as $key=>$value)
        $values[] = "$key=\"" . rawurlencode($value) . "\""; 

    $r .= implode(', ', $values); 
    return $r; 
}

function ago($time)
{
   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");

   $now = time();

       $difference     = $now - $time;
       $tense         = "ago";

   for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
       $difference /= $lengths[$j];
   }

   $difference = round($difference);

   if($difference != 1) {
       $periods[$j].= "s";
   }

   return "$difference $periods[$j] ago";
}


$filename = 'cache/json_extranet.txt';
$delta = time() - filemtime($filename);


if (file_exists($filename)) {	
	if($delta > 300) {			
						
		$url = "https://api.twitter.com/1.1/statuses/user_timeline/CityofMarion.json";
		
		$oauth_access_token = "62447831-Ce3Dl4961FVzG4xtLO6MLqF2eXeIK5QKbAPAhFgHg";
		$oauth_access_token_secret = "kJtATJ3om1fDyZIoAo2iTtQpRCf7ABmtSZlv9yzc";
		$consumer_key = "m7IY8NZAIkvyyuGTyfPSvQ";
		$consumer_secret = "O4apRTsjAEpC62S2rGuugsMoGPPEkq34i2IhjJy6o";
		
		$oauth = array( 'oauth_consumer_key' => $consumer_key,
		                'oauth_nonce' => time(),
		                'oauth_signature_method' => 'HMAC-SHA1',
		                'oauth_token' => $oauth_access_token,
		                'oauth_timestamp' => time(),
		                'oauth_version' => '1.0');
		
		$base_info = buildBaseString($url, 'GET', $oauth);
		$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
		$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
		$oauth['oauth_signature'] = $oauth_signature;
		
		
		$header = array(buildAuthorizationHeader($oauth), 'Expect:');
		$options = array( CURLOPT_HTTPHEADER => $header,
		                  CURLOPT_HEADER => false,
		                  CURLOPT_URL => $url,
		                  CURLOPT_RETURNTRANSFER => true,
		                  CURLOPT_SSL_VERIFYPEER => false);
		
		$feed = curl_init();
		curl_setopt_array($feed, $options);
		$json = curl_exec($feed);
		curl_close($feed);
		
		$twitter_data = json_decode($json);
		$m=0;
		$html = '';
		
		
		for($i = 0; $i < sizeof($twitter_data); $i++) {
				
			//if($twitter_data[$i]->in_reply_to_status_id == "") {	
				$time = $twitter_data[$i]->created_at;
				$time = strtotime($time);
				$ago = ago($time);		
				$tweet = $twitter_data[$i]->text;
				$tweet = addslashes($tweet);
				
				$tweet = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\" rel=\"nofollow\">\\0</a>", $tweet);
				$tweet = preg_replace('/(^|\s)@([a-z0-9_]+)/i','$1<a href="http://www.twitter.com/$2">@$2</a>',$tweet);		
				//$html = '<p>' . $tweet . ' <a href="http://twitter.com/CityofMarion/statuses/' . $twitter_data[$i]->id . '">about ' . $ago . '</a></p>';												
				
				$html = $html . '<li class="t' . $m . '"><span>' . $tweet . '</span><br /><a style="font-size:85%" href="http://twitter.com/CityofMarion/statuses/' . $twitter_data[$i]->id . '" class="link">about ' . $ago . '</a></li>';
						
				$m++;
				
				if($m ==4) {
					break;		
				}
				
			//}
			
		}
				
		file_put_contents($filename, $html, LOCK_EX);
		//echo $html;
		echo "$('#twitter_update_list').append('" . replace_newline($html) . "');";
		
		
		
		
	} else {		
		$html = file_get_contents('cache/json_extranet.txt');
		//echo $html;			
		echo "$('#twitter_update_list').append('" . replace_newline($html) . "');";
		
	}
}



?>