Thursday, April 7, 2011

CakePHP: Create Twitter Widget

Pull feeds from Twitter and set time function: /controllers/components/twitter.php
<?php
function relativeTime($time) { 
 $SECOND = 1;
 $MINUTE = 60 * $SECOND;
 $HOUR = 60 * $MINUTE;
 $DAY = 24 * $HOUR;
 $MONTH = 30 * DAY;
 
 $delta = time() - $time; // change time to match with twitter time
 if ($delta < 2 * $MINUTE) {
  return "1 minute ago";
 }
 if ($delta < 45 * $MINUTE) {
  return floor($delta / $MINUTE) . " minutes ago";
 }
 if ($delta < 120 * $MINUTE) {
  return "about 1 hour ago";
 }
 if ($delta < 24 * $HOUR) {
  return floor($delta / $HOUR) . " hours ago";
 }
 if ($delta < 48 * $HOUR) {
  return "yesterday";
 }
 if ($delta < 30 * $DAY) {
  return floor($delta / $DAY) . " days ago";
 }
 if ($delta < 12 * $MONTH) {
  $months = floor($delta / $DAY / 30);
  return $months <= 1 ? "1 month ago" : $months . " months ago";
 } else {
  $years = floor($delta / $DAY / 365);
  return $years <= 1 ? "1 year ago" : $years . " years ago";
 }
}

function parse_cache_feed($usernames, $limit) {
 $username_for_feed = str_replace(" ", "+OR+from%3A", $usernames);
 $feed = "http://search.twitter.com/search.atom?q=from%3A".
          $username_for_feed."&rpp=".$limit;
 $usernames_for_file = str_replace(" ", "-", $usernames);

 // cache file directory
 $cache_file = TMP.'cache/views/'.$usernames_for_file.'-twitter'; 

 if (file_exists($cache_file)) {
  $last = filemtime($cache_file);
 }

 $now = time();
 $interval = 600; // ten minutes

 // check the cache file
 if ( !$last || (( $now - $last ) > $interval) ) {
  // cache file doesn't exist, or is old, so refresh it
  $cache_rss = file_get_contents($feed);
  if (!$cache_rss) {
   // we didn't get anything back from twitter
   echo "<!-- ERROR: Twitter feed was blank! Using cache file. -->";
  } else {
   // we got good results from twitter
   echo "<!-- SUCCESS: Twitter feed used to update cache file -->";
   $cache_static = fopen($cache_file, 'wb');
   fwrite($cache_static, serialize($cache_rss));
   fclose($cache_static);    
  }
  // read from the cache file
  $rss = @unserialize(file_get_contents($cache_file));
 }
 else {
  // cache file is fresh enough, so read from it
  echo "<!-- SUCCESS: Cache file was recent enough to read from -->";
  $rss = @unserialize(file_get_contents($cache_file));
 }
 // clean up and output the twitter feed
 $feed = str_replace("&", "&", $rss);
 $feed = str_replace("<", "<", $feed);
 $feed = str_replace(">", ">", $feed);
 $clean = explode("", $feed);
 $clean = str_replace(""", "'", $clean);
 $clean = str_replace("'", "'", $clean);
 $amount = count($clean) - 1;
 if ($amount) { // are there any tweets?
  for ($i = 1; $i <= $amount; $i++) {
   $entry_close = explode("", $clean[$i]);
   $clean_id_1 = explode("", $entry_close[0]);
   $clean_id = explode("", $clean_id_1[1]);
   $id = substr($clean_id[0], -17); 
   $clean_content_1 = explode("", $entry_close[0]);
   $clean_content = explode("", $clean_content_1[1]);
   $clean_name_2 = explode("", $entry_close[0]);
   $clean_name_1 = explode("(", $clean_name_2[1]);
   $clean_name = explode(")", $clean_name_1[1]);
   $clean_user = explode(" (", $clean_name_2[1]);
   $clean_lower_user = strtolower($clean_user[0]);
   $clean_uri_1 = explode("", $entry_close[0]);
   $clean_uri = explode("", $clean_uri_1[1]);
   $clean_time_1 = explode("", $entry_close[0]);
   $clean_time = explode("", $clean_time_1[1]);
   $unix_time = strtotime($clean_time[0]);
   $pretty_time = $this->relativeTime($unix_time);  

   $val[$i] = array('content'=>$clean_content[0], 
                    'date'=>$pretty_time, 
                    'id'=>$id);
   }
   return $val;
 } else { // if there aren't any tweets
  return false;
 }
}
?>
Note:
Relative Time Function
based on code from http://tinyurl.com/3cfdbrh
For use in the "Parse Twitter Feeds" code below

Parse Twitter Feeds
based on code from http://tinyurl.com/43yyzhm
and cache code from http://tinyurl.com/44kec57
and other cache code from http://tinyurl.com/re439b


Call pull feeds function: /controllers/feeds_controller.php

<?php
var $components = array('Twitter');

function get(){
$feed = $this->Twitter->parse_cache_feed('TWITTERNAME',10);
$this->set('feed', $feed);
}
?>


Auto-refresh function: /views/feeds/index.ctp
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js">
</script>
<script language="javascript">
 $(document).ready(function (){
 $("#twitter").load("/feeds/get");
 var refreshId = setInterval(function() {
 $("#twitter").load('/feeds/get?randval='+ Math.random());
 }, 300000);
 });
</script>
<div id="twitter"></div>

Display Feeds: /views/feeds/get.ctp
<?php
for($i=1; $i<=count($feed); $i++){
 echo $feed[$i]['content'].'
';
 echo '<a href="http://twitter.com/TWITTERNAME/statuses/'.$feed[$i]
['id'].'">'.$feed[$i]['date'].'</a> · <a href="http://twitter.com
/?status=@TWITTERNAME%20&in_reply_to_status_id='.$feed[$i]['id'].'&
in_reply_to=TWITTERNAME" target="_blank">reply</a>'; 
}
?>
 

3 comments:

  1. I'm still a beginner in PHP programming and my dream is to become an expert someday. I didn't know that Twitter can be modified through PHP though. Your tips are really helpful. I'm sure following them will help me achieve my dream faster. =)

    Lawrence Spring

    ReplyDelete
    Replies
    1. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry

      Delete
  2. @Lawrence
    Soon you will be if you have passion on this.
    Glad to hear that it helps. =)

    ReplyDelete