<?php

/* ---------------- Set Header -------------------------*/
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');





get_posts();









/* ---------------- General Functions -------------------------*/

	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";
	}













/* ---------------- Get Posts -------------------------*/



	function get_posts() {


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

		if (file_exists($filename)) {
			if($delta > 300) {

				$html = '';

				//$twitter = twitter_posts();
				$facebook = facebook_posts();


				foreach($facebook as $post) {
					$html .= $post;
				}

//				foreach($twitter as $post) {
//					$html .= $post;
//				}



				// recreate cache files
				file_put_contents($filename, $html, LOCK_EX);

				//echo "updated";
				//echo $html;

				echo "$('#social-media').append('" . replace_newline($html) . "');";


			} else {

				// Get content from cache

				$html = file_get_contents('cache/cache.txt');
				//echo "from cache";
				//echo $html;
				echo "$('#social-media').append('" . replace_newline($html) . "');";
			}
		}





	}





/* ---------------- Twitter Functions -------------------------*/


	function twitter_posts() {

		$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);

		$c = 0;

		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);

				$tweet = preg_replace('|https?://www\.[a-z\.0-9]+|i', '', $tweet);
				$tweet = preg_replace('|https?://\.[a-z\.0-9]+|i', '', $tweet);
				$tweet = truncate($tweet,170);

				//$html = '<p>' . $tweet . ' <a href="http://twitter.com/CityofMarion/statuses/' . $twitter_data[$i]->id . '">about ' . $ago . '</a></p>';
				//$html = '<li><span>' . $tweet . '</span> <a style="font-size:85%" href="http://twitter.com/CityofMarion/statuses/' . $twitter_data[$i]->id . '">about ' . $ago . '</a></li>';

				$tweet = strip_tags($tweet, "<p><li><span><div><br><a>");


				$html = '
<li class="tw">
	<div class="section-title withborder">CITY OF MARION ON TWITTER</div>
	<div class="when"><img src="https://www.marion.sa.gov.au/webdata/graphics/signage_icon_twitter.svg" /> ' . $ago . '</div>
	<p>' . $tweet . '</p>
	<p class="call-to-action">Follow us on Twitter <br><span class="lower">twitter.com/CityOfMarion</span></p>
</li>

';

				$posts[$c] = $html;
				$c++;
				if($c == 3) {
					break;
				}

			}

		}

		return $posts;

	}




/* ---------------- Facebook Functions -------------------------*/


	function truncate($text, $length) {
	    $length = abs((int)$length);
	    if(strlen($text) > $length) {
	        $text = preg_replace("/^(.{1,$length})(\s.*|$)/s", '\\1...', $text);
	    }
	    return($text);
	}

	function facebook_posts() {

	    $page_id = '1093652130652845';
	    $app_id  = '1523395767919224';
	    $app_secret = 'd022f0e91e4d0503937e060c5928a1dd';
	    $limit = 10;

        include_once('libraries/facebook/facebook.php');
        $facebook = new Facebook(array( 'appId'	 => $app_id, 'secret'	=> $app_secret, ));
        $access_token = $facebook->getAccessToken();
		$json = $facebook->api('/' . $page_id . '/posts/',array('access_token' => $access_token,'limit'=>$limit, 'fields'=>'id,object_id,message,picture,story,link'));

		//print_r($json);

        $c=0;

        foreach($json['data'] as $post) {

        	if (!empty($post['message'])) {
	        	@$cache[$c]['id'] = $post['id'];
	        	@$cache[$c]['object_id'] = $post['object_id'];

	        	//@$cache[$c]['story'] = $post['story'];
	        	//@$cache[$c]['link'] = $post['link'];
	        	@$cache[$c]['date'] = date("d.m.Y", strtotime($post['created_time']));

	        	if (!empty($post['picture']) && !empty($post['object_id'])) {
	        		@$images = $facebook->api('/' . $post['object_id'] . '/',array('access_token' => $access_token,'limit'=>100, 'fields'=>''));

	        		if (!empty($images['images'][0]['source'])) {
	        			@$cache[$c]['picture'] = $images['images'][0]['source'];
	        		}
	        	}

	        	/*
	        	if(empty($cache[$c]['picture']) && !empty($post['picture'])) {
	        		@$cache[$c]['picture'] = $post['picture'];
	        	}
	        	*/


	        	$cache[$c]['ago'] = ago(strtotime($post['created_time']));

	        	if(!empty($cache[$c]['picture'])) {
	        		@$cache[$c]['message'] = truncate($post['message'],360);
	        		$show_image = '<div class="fb-pic" style="background-image:url('  . $cache[$c]['picture'] . '); "/></div>';
	        	}
	        	else {
	        		@$cache[$c]['message'] = truncate($post['message'],170);
	        		$show_image = '';
	        	}


	        	@$cache[$c]['message'] = str_replace("\n", " - ", @$cache[$c]['message']);


	        	$html = '
<li class="fb">
	<div class="section-title withborder">CITY OF MARION LIBRARIES ON FACEBOOK</div>
	' . $show_image . '
	<div class="when"><img src="https://www.marion.sa.gov.au/webdata/graphics/signage_icon_facebook.svg" /> ' . $cache[$c]['ago'] . '</div>
	<p>' .addslashes($cache[$c]['message']) . '</p>
	<p class="call-to-action">Like us on Facebook <br><span class="lower">facebook.com/CityofMarionLibraries</span></p>
</li>
';


				$html = strip_tags($html, "<p><li><span><div><br><img>");
				$posts[$c] = $html;
	        	$c++;


	        	if($c ==3) {
	        		break;
	        	}
        	}
        }

        return $posts;

	}







?>