Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

All other Modules /

Discuss all other Modules here.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Recent Tweets + Blog function - already working


Go to End


951 Views

Avatar
borriej

Community Member, 267 Posts

5 September 2012 at 9:05pm

If someone wants this code, or wants to build a nice module with it.. go ahead.
I wanted a function that shows the the most recent blog-entry's + latest tweets. Sort them on date and limit them to 5.

class Homepage_Controller extends Page_Controller {
		
	function twitterStatusUrlConverter($status,$targetBlank=true,$linkMaxLen=250){
	  // The target
	  $target=$targetBlank ? " target=\"_blank\" " : "";
		// convert link to url
		$status = preg_replace("/((http:\/\/|https:\/\/)[^ )
	]+)/e", "'<a href=\"$1\" title=\"$1\"  $target >'. ((strlen('$1')>=$linkMaxLen ? substr('$1',0,$linkMaxLen).'...':'$1')).'</a>'", $status);
		// convert @ to follow
		$status = preg_replace("/(@([_a-z0-9\-]+))/i","<a href=\"http://twitter.com/$2\" title=\"Follow $2\" $target >$1</a>",$status);
		// convert # to search
		$status = preg_replace("/(#([_a-z0-9\-]+))/i","<a href=\"http://search.twitter.com/search?q=%23$2\" title=\"Search $1\" $target >$1</a>",$status);
		// return the status
		return $status;
	}

	function NewsTwitter(){
		/* twitter */
		$username = 'lancearmstrong';
		$tweet_count = '5';
		$url = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=' . $username . '&count=' . $tweet_count . '&include_entities=1&include_rts=1';
		//https://api.twitter.com/1/statuses/user_timeline.json?screen_name=robvaneckdesign&count=10&include_entities=1&include_rts=1
		$server = $_SERVER["SERVER_NAME"];
		$cache_path =  "/public/sites/$server/silverstripe-cache/twitter/twitter";
		$cache_time = filemtime($cache_path);
		$cache_time_plus = $cache_time+300;
		$now = time();
		/*
		var_dump($server);
		var_dump($cache_path);
		var_dump($cache_time);
		var_dump($cache_time_plus);
		var_dump($now);
		*/
		if ($now < $cache_time_plus){
			$data = file_get_contents($cache_path);
			//var_dump('difference < 5 min - use cache file');
		}else{
			$ch = curl_init();//Initialise CURL
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_URL, $url);//Set the url
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);//We want the data to return
			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);//Of course, we don't want your script to run forever, so set a timeout
			$data = curl_exec($ch);//Execute and get the page
			curl_close($ch);//Close curl connection
			$cachefile = fopen($cache_path, 'wb');
			fwrite($cachefile, $data);
			fclose($cachefile);
			//var_dump('difference > 5 min - update cache file');
		}
		$json = json_decode($data); //Decode the json	
		/*
		var_dump ($url);		
		var_dump ($data);
		var_dump ($json);
		*/
		$twitterOutput = new DataObjectSet();
		foreach($json as $tweet){
			$datetime = $tweet->created_at;
			//$date = date('M d, Y', strtotime($datetime));
			//$time = date('g:ia', strtotime($datetime));
			$ss_datetime = date('Y-m-d H:i:s', strtotime($datetime));;
			$date = date('d M', strtotime($datetime));
			$tweet_text = $tweet->text;
			$tweet_text = $this->twitterStatusUrlConverter($tweet_text);
			$tweet_link = "http://twitter.com/".$tweet->user->id."/status/".$tweet->id_str;
			
			$twitterOutput->push(
				new ArrayData(
					array(
						'Title' => $tweet_text,
						'Date' => $ss_datetime,
						'Tweet' => true,
						'Posted' => $date,
						'Link' => $tweet_link,
					)
				)
			);
		}

		/* news */
		$newsOutput = new DataObjectSet();
		$blogentrys = DataObject::get('BlogEntry');
		$newsOutput->merge($blogentrys);
		
		/* merge twitter + news */
		$Output = new DataObjectSet(); 
		$Output->merge($twitterOutput);
		$Output->merge($newsOutput);
		$Output->sort('Date', 'DESC');
		$OutputLimited = $Output->getRange(0, 5);
		return $OutputLimited;
	}

in your template you can use:



<% if NewsTwitter %>
    <ul id="NewsTwitter">
        <% control NewsTwitter %>
        <% if Tweet %>
            <li class="newsItem clickable tweet <% if Last %>last<% end_if %>" data-url="$Link">
                <span class="date">$Posted | </span><span class="msg">$Title</span><span class="arrow"></span>
                <noscript><br /><a href="$Link" class="arrow" ><small>Lees meer</small></a></noscript>
            </li>
        <% else %>     
            <li class="newsItem clickable web <% if Last %>last<% end_if %>" data-url="$Link" data>
                <span class="date">$Date.FormatI18N(%e %b) | </span> <span class="msg">$Title</span><span class="arrow"></span>
                <noscript><br /><a href="$Link" class="arrow" ><small>Lees meer</small></a></noscript>
            </li>
        <% end_if %>
        <% end_control %>
    </ul>
<% end_if %>