Cached Twitter Feed Tag - Version 0.1

Do something cool with CMS? Show us ...
This board is for 'Answers', and the discussion of answers... Not for questions.
Post Reply
nhaack

Cached Twitter Feed Tag - Version 0.1

Post by nhaack »

Hi there,

I am currently playing around with the APIs of different services. To output the content of a twitter feed, separated into locations and regular status messages, I wrote this user tag:

Code: Select all


/*
	CTFT (Cached Twitter Feed Tag) - Version 0.1
	
	A UDT to download the feed of a single twitter user.
	This file is examined and different smarty objects
	are given back.
	
	You get locations seperated from the status messages.
	You can use this UDT for a google maps mashup for example.
	
	The locations contain nothing but location names, which makes 
	them easy to process for geocoding.
	
	You need to call the UDT with the following parameters:

	============================================================================
	ALL PARAMETERS ARE REQUIRED FOR THIS TAG TO WORK PROPERLY:
	
	{api_twitterfeed url="..." name="..." ttl=60}

	ttl=seconds (e.g. ttl=60)
	Setting the time the file is cached. A setting of 60 seconds is save in regards to twitter quota
	(whichI think is 70 requests per hour per IP-Address) and comply even with heavy posters
	
	name=twitter_username (e.g. name="opticalvalve")
	The username to be filtered from the feed, because all message contain the user's name.
	But we do not want it this time, so chop it away
	
	url=url_of_feed (e.g. url="http://twitter.com/statuses/user_timeline/---id---.rss")
	The url from where the twitter feed is taken from

	============================================================================	
	
	Thanks to "viebig" for the inspiration.
	
	This UDT is free for everyone to use, modify, distribute.
		
	============================================================================	
	
	This UDT is probably only interesting for you when you post your locations on twitter (with a "L: " prefix).
	You should easily be able to limit the tags to just output the feed without splitting locations from the 
	messages.
	
	Have fun
	Nils Haack 2008 (September)
	
*/

global $gCms;

//
//	SETTING CONFIGURATION 
//	--> To do: location of cache needs to be created before use
//

$cachefolder="_apicache";
// ^Folder for caching the feed data
$cache_file = $cachefolder.'/twitter.xml';
// ^Name of cached file

//
//	GETTING UDT PARAMETERS
//

$cache_time_sec = $params[ttl];
$feed_url = $params[url];
$filter_user_string = $params[name].": ";

//
//	Get time (seconds) difference (=cache age) between cached file last update and now
//

$timedif = @(time() - filemtime($cache_file));

//
//	Create cache info object and store cache age and time-to-live [=ttl]
//

$cacheinfo= new StdClass;
$cacheinfo->cache_age = $timedif;
$cacheinfo->ttl = $cache_time_sec;

//	//
//	Caching mechanics:
//	//

if ($timedif < $cache_time_sec) 
{

//
//	^If cache age is younger than ttl assign stored feed copy to simplexml for processing
//	afterwards set info cache object status information (data comming from cache)
//

		$twitterfeed = simplexml_load_file($cache_file);
		$cacheinfo->is_cached = "delivering cached data from: ".$cache_file;

} else {

//
//	^If cache is too old assign file and write contents of live url data into storage file
//	Close file and assign stored/updated feed copy to simplexml for processing
//	afterwards set info cache object status information (data has been renewed)
//

	$feedbuffer = file($feed_url);
	
	if ($f = @fopen($cache_file, 'w')) {
	
		for ($i=0; $i<=count($feedbuffer); $i++){
			fwrite ($f, $feedbuffer[$i], strlen($feedbuffer[$i]));
		}
		fclose($f);
		
		$twitterfeed = simplexml_load_file($cache_file);
		
		$cacheinfo->is_cached ="cache outdated - cache reloaded";
	}
}

//	//
//	Create arrays for locations and simple status messages
//	//

$locations= array();
$tweets= array();

//	//
//	Walk trough all feed xml data elements "item" (twitter rss feed item)
//	//

foreach ($twitterfeed->channel->item as $item) 
{
 if (stristr($item->title, " L: ") == true) {
 
//
// ^If the string of the items title (the single twitter message) contains " L: " it indicates that
// the message contains only a location (e.g. your message content was "L: 12th Ave, New York")
//

//
// Filter User Name string from twitter message (delete from message)
//

		$item->title = str_replace($filter_user_string, "", $item->title);

//
// Create new location object and store data
//

		$locationfeeditem = new StdClass;
// Remove "L: " from location message to have location description string only
		$locationfeeditem->title = str_replace("L: ", "", $item->title);
// Format Date String
		$locationfeeditem->date = strftime('%A, %e %B %Y',strtotime("$item->pubDate"));
//Pass Twitter message URL
		$locationfeeditem->link = $item->link;

//
// Add location object to array of locations
//

		$locations[] = $locationfeeditem;
		$locationcount = $locationcount +1;

} else {

//
// ^Ok, this is not a location message, so its a regular tweet (twitter message)
// Your message can contain mostly anything.
//

//
// Create new tweet object and store data
//

		$twitterfeeditem= new StdClass;
//Filter User Name
		$twitterfeeditem->title = str_replace($filter_user_string, "", $item->title);
//Format Date String
		$twitterfeeditem->date = strftime('%A, %e %B %Y',strtotime("$item->pubDate"));
//Pass Twitter message URL
		$twitterfeeditem->link = $item->link;

//
// Add tweet object to array of tweets
//

		$tweets[] = $twitterfeeditem;
		$tweetcount= $tweetcount+1;
		
}

} // END OF FOR EACH WITHIN XML

//
// Assign the result to smarty so we can conveniently process the data in our template/content
//

		$smarty = &$gCms->GetSmarty();
		$smarty->assign(tweets, $tweets);
		$smarty->assign(locations, $locations);
		$smarty->assign(cacheinfo, $cacheinfo);
		
return;


You can call the user tag (when saved as "api_twitterfeed") as follows:

Code: Select all


{api_twitterfeed url="http://twitter.com/statuses/user_timeline/---ID----.rss" ttl=75 name="user_name"}

You can try the UDT with my testing twitter feed:

Code: Select all


{api_twitterfeed url="http://twitter.com/statuses/user_timeline/15770798.rss" ttl=75 name="opticalvalve"}

Place this in your page to output all know data:

Code: Select all


<table width="100%" padding="5" border="2">
<tr>
<td colspan="2">
Twitter RSS cached? -> {$cacheinfo->is_cached} <br/>
Age of cached data? -> {$cacheinfo->cache_age} seconds <br/>
Configured time to live? -> {$cacheinfo->ttl} seconds
</td>
</tr>
<tr>
<td colspan="2">
(left: Locations // right: Status messages)
</td>
</tr>
<tr>
<td width="35%" valign="top">
{foreach from=$locations item=location}
{$location->title}<br/>
{$location->date}<br/>
<a href="{$location->link}">jump to</a><hr/>
{/foreach}
</td>
<td>
{foreach from=$tweets item=tweet}
{$tweet->title}<br/>
{$tweet->date}<br/>
<a href="{$tweet->link}">jump to</a><hr/>
{/foreach}
</td>
</tr>
</table>

As you are using smarty for the output, you can also generate the required javascript for a nice google maps mashup. I will post a sample soon. Need to set up a clean install for you - but not tonight :)

Hopefully the one or other can use this. For example, you have a washing saloon and your machines twitter whether they are free right to your homepage. Or you track your holiday trip by sending twitter messages via mobile and have your friends at home follow you on a google map. You will surely come up with some nice ideas.

However, the tag only processes the current messages. If you want to show a longer trail of locations/messages, you might want to switch to a DB version.

What do you think?

Best
Nils
Last edited by nhaack on Tue Sep 16, 2008 12:16 am, edited 1 time in total.
viebig

Re: Cached Twitter Feed Tag - Version 0.1

Post by viebig »

great piece of code, congratulations!
nhaack

Re: Cached Twitter Feed Tag - Version 0.1

Post by nhaack »

edit:

hehe, forgot to mention: Thanks for the feedback :)

________
You can find a working google maps mash-up under the following address:

(url no longer available)

I do not know about browser compatibility of the javascripting. It is not my primary subject field ;). But feel free to post your comments on it. To get the data on the map, I created a template with nothing in it except a content block. I use this page to generate the JS with the single locations in it and link it from my pages head section as javascript. And voilá


Best
Nils
Last edited by nhaack on Fri Jul 24, 2009 10:13 pm, edited 1 time in total.
Post Reply

Return to “Tips and Tricks”