We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 18913
    • 654 Posts
    I needed to tweak TweetLines to output the status link as well as make the timestamp a bit more user-friendly. Here’s the code, with lines I changed/added ending in my initials. Hope it helps someone ...
    MattC
    Edit : This is for EVO, btw ...

    <?php
    /**
     * @name TweetLines
     * @author Philippe Delberghe
     * @license GPLv3
     * @version 0.1+
     * This version : 12/3/2010 by Matt Considine; add link from Tweet, use "human elapsed time", add rel=nofollow
     * This snippet returns the last tweets from the user twitter in the current
     * page. 
     * 
     * &name=`ArtImpulsion`
     * Pass through a name to the snippet. You can use your own Twitter ID by
     * prefixing the name with an @. mandatory if you want to get something.....
     * 
     * &nbt=`5` 
     * number of tweets to show. Optional.
     * 
     * example : [!TweetLines?&name=`ArtImpulsion`&nbt=`10`!]
     */
    
    //
    // based on a publish on www.acornartwork.com turned into a ModX snippet
    // By FildeFer (Philippe Delberghe) for VD Graphics (France) www.vdgraphics.com
    // 
    // ---------------------------------------------------
    //  Check input variables
    // ---------------------------------------------------
    $name = (isset($name)) ? $name : '';
    
    if (isset($nbt)) {
        if (!is_numeric($nbt)) {
            $modx->logEvent(1, 3, 'TweetLines: &nbt was not numeric: ' . $nbt, 'TweetLines - Snippet');
        }
    } else {
        $nbt ="5";
    }
    
    $mytweets = fetch_tweets($name, $nbt);
    $twit = "";
    $twit = $twit . '<ul class="twitter-updates">';
    foreach ($mytweets as $k => $v) {
     $twit = $twit . '<li>';
    $twit = $twit .  '<span class="update">' .$v['desc']. '</span>';
    $twit = $twit . ' <span class="date"><a href="'.$v['link'].'"  style="display:block;color:#666666;font-size:11px;" >' .$v['date']. '</a></span>';  //MattC ala CNN
    $twit = $twit .  '</li>';
    }
    $twit = $twit .  '</ul>';
    
    return $twit;
    
    function humanTiming ($origltime)  //MattC from stackoverflow.com
    {
        $timehurdle = 2*3600; //MattC e.g. anything older than 2 hours will just show the timestamp
    
        $time = time() - $origltime; // to get the time since that moment
    
        $tokens = array (
            31536000 => 'year',
            2592000 => 'month',
            604800 => 'week',
            86400 => 'day',
            3600 => 'hour',
            60 => 'minute',
            1 => 'second'
        );
    
        foreach ($tokens as $unit => $text) {
            if ($time < $unit) continue;
            $numberOfUnits = floor($time / $unit);
            if ($time < $timehurdle)  //MattC
            {
            $timestamp = 'about '.$numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';  //MattC
            }
            else
            {
              //date_default_timezone_set('America/New_York');
              $timestamp = date('M j, Y h:i:s A e',$origltime);  //MattC
            }
            return $timestamp; //MattC
        }
    
    }
    
    
    
    function fetch_tweets($username, $maxtweets) {
         //Using simplexml to load URL
         $tweets = simplexml_load_file("http://twitter.com/statuses/user_timeline/" 
             . $username . ".rss");
    
         $tweet_array = array();  //Initialize empty array to store tweets
         foreach ( $tweets->channel->item as $tweet ) { 
              //Loop to limitate nr of tweets.
              if ($maxtweets == 0) {
                   break;
              } else {
                   $twit = $tweet->description;  //Fetch the tweet itself
    
                   //Remove the preceding 'username: '
                   $twit = substr(strstr($twit, ': '), 2, strlen($twit));
    
                   // Convert URLs into hyperlinks
                   $twit = preg_replace("/(http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*)/", 
                          "<a href=\"\\0\" rel=\"nofollow\">\\0</a>", $twit);  //MattC
    
                   // Convert usernames (@) into links 
                   $twit = preg_replace("(@([a-zA-Z0-9\_]+))", 
                        "<a href=\"http://www.twitter.com/\\1\">\\0</a>", $twit);
    
                   // Convert hash tags (#) to links 
                   $twit = preg_replace('/(^|\s)#(\w+)/', 
                        '\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', $twit);
    
                   //Specifically for non-English tweets, converts UTF-8 into ISO-8859-1
                   $twit = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $twit);
    
                   //Get the date it was posted
                   $pubdate = strtotime($tweet->pubDate); 
                   $propertime = humanTiming($pubdate);  //MattC
    
                   //Store tweet and time into the array
                   $tweet_item = array(
                         'desc' => $twit,
                         'date' => $propertime,
                         'link' => $tweet->link  //MattC
                   );
                   array_push($tweet_array, $tweet_item);
    
                   $maxtweets--;
              }
         }
         //Return array
         return $tweet_array;
    }
    ?>
    
      • 18913
      • 654 Posts
      Here’s a variant, using a different method of getting the feed, but using the same sort of output format. May be quicker as a lot of reformatting is not done. Also gives access to the avatar. A bit rough vis-a-vis styling/formatting flexibility, passing parameters, but easy to adjust. Hope it helps,
      MattC
      <?php
      //fetchTweets
      //Snippet author : Matt Considine 12/3/2010
      //Based on http://scriptplayground.com/tutorials/php/Twitter-Integration-Class-Using-PHP5-and-cURL/
      
      class Twitter 
      {
        public $tweets = array();
        public function __construct($user, $limit = 5) 
        {
          $user = str_replace(' OR ', '%20OR%20', $user);
          $feed = curl_init('http://search.twitter.com/search.atom?q=from:'. $user .'&rpp='. $limit);
          curl_setopt($feed, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($feed, CURLOPT_HEADER, 0);
          $xml = curl_exec($feed);
          curl_close($feed);
          $result = new SimpleXMLElement($xml);
          foreach($result->entry as $entry) 
          {
              $tweet = new stdClass();
              $tweet->id = (string) $entry->id;
              $user = explode(' ', $entry->author->name);
              $tweet->user = (string) $user[0];
              $tweet->author = (string) substr($entry->author->name, strlen($user[0])+2, -1);
              $tweet->title = (string) $entry->title;
              $tweet->content = (string) $entry->content;
              $tweet->updated = (int) strtotime($entry->updated);
              $tweet->permalink = (string) $entry->link[0]->attributes()->href;
              $tweet->avatar = (string) $entry->link[1]->attributes()->href;
              array_push($this->tweets, $tweet);
          }
          unset($feed, $xml, $result, $tweet);
        }
        public function getTweets() { return $this->tweets; }
      }
      
      if (!function_exists('humanTiming')) {
      function humanTiming ($origltime)  //MattC from stackoverflow.com
      {
          $timehurdle = 2*3600; //MattC e.g. anything older than 2 hours will just show the timestamp
      
          $time = time() - $origltime; // to get the time since that moment
      
          $tokens = array (
              31536000 => 'year',
              2592000 => 'month',
              604800 => 'week',
              86400 => 'day',
              3600 => 'hour',
              60 => 'minute',
              1 => 'second'
          );
      
          foreach ($tokens as $unit => $text) {
              if ($time < $unit) continue;
              $numberOfUnits = floor($time / $unit);
              if ($time < $timehurdle)  //MattC
              {
              $timestamp = 'about '.$numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'').' ago';  //MattC
              }
              else
              {
                //date_default_timezone_set('America/New_York');
                $timestamp = date('M j, Y h:i:s A e',$origltime);  //MattC
              }
              return $timestamp; //MattC
          }
      }
      } //if exists
      
      $feed = new Twitter('modxcms', 5);  //change this for feed and number desired
      $tweets = $feed->getTweets();
      
      $twit = "";
      $twit .= '<ul class="twitter-updates">';
      foreach ($tweets as $tweet) 
      {//available fields : id, user, author, title, content, updated, permalink, avatar
        $twit .= '<li>';
        //$twit .= 'Id : '.$tweet->id.' User : '.$tweet->user.' Title : '.$tweet->title;
        //$twit .= '<img src="'.$tweet->avatar.'" />';
        $twit .= '<span class="update">' .$tweet->content. '</span>';
        $twit .= ' by '.$tweet->author;
        $twit .= ' <span class="date"><a href="'.$tweet->permalink.'"  style="display:block;color:#666666;font-size:11px;" >' .humanTiming($tweet->updated). '</a></span>';  //MattC ala CNN
        $twit .= '</li>';
      }
      $twit .= '</ul>';
      
      return $twit;
      ?>
      
        • 11055 ☆ A M B ☆
        • 3,112 Posts
        The Revo version is monTwitter, made by the same author.
          Rico
          Genius is one percent inspiration and ninety-nine percent perspiration. Thomas A. Edison
          MODx is great, but knowing how to use it well makes it perfect!

          www.virtudraft.com

          Security, security, security! | Indonesian MODx Forum | MODx Revo's cheatsheets | MODx Evo's cheatsheets

          Author of Easy 2 Gallery 1.4.x, PHPTidy, spieFeed, FileDownload R, Upload To Users CMP, Inherit Template TV, LexRating, ExerPlan, Lingua, virtuNewsletter, Grid Class Key, SmartTag, prevNext

          Maintainter/contributor of Babel

          Because it's hard to follow all topics on the forum, PING ME ON TWITTER @_goldsky if you need my help.
          • 25519
          • 265 Posts
          Quote from: goldsky at Dec 03, 2010, 08:41 PM

          The Revo version is monTwitter, made by the same author.
          Fantastic, thanks for bringing that new gem to my attention.

          One question, and it will probably be ’of course, why didn’t i look there’ when i eventually find out:- Where can i find my twitter member id number? I looked all over my account and googled/searched etc but to no avail ...
            • 11055 ☆ A M B ☆
            • 3,112 Posts
            is twitter using ID?
            have you looked at its doc page?
              Rico
              Genius is one percent inspiration and ninety-nine percent perspiration. Thomas A. Edison
              MODx is great, but knowing how to use it well makes it perfect!

              www.virtudraft.com

              Security, security, security! | Indonesian MODx Forum | MODx Revo's cheatsheets | MODx Evo's cheatsheets

              Author of Easy 2 Gallery 1.4.x, PHPTidy, spieFeed, FileDownload R, Upload To Users CMP, Inherit Template TV, LexRating, ExerPlan, Lingua, virtuNewsletter, Grid Class Key, SmartTag, prevNext

              Maintainter/contributor of Babel

              Because it's hard to follow all topics on the forum, PING ME ON TWITTER @_goldsky if you need my help.
              • 25519
              • 265 Posts
              Quote from: goldsky at Dec 06, 2010, 08:14 PM

              is twitter using ID?
              have you looked at its doc page?
              Yep, thanks, had a look.
              But from all that documentation I can’t see how to simply extract my public_timeline rss number, as required in monTwitter:
              http://twitter.com/statuses/user_timeline/162369603.rss

              Guess i’m missing a fairly obvious trick ... rolleyes
                • 9674
                • 170 Posts
                Hi redplanet !

                To get your rss feed on twitter :

                go to www.twitter.com/YOUR_TWITTER_NAME

                exemple : http://twitter.com/ArtImpulsion

                Down on the right side, you will see an orange RSS sign .

                Click on it !

                you will get in your browser adress bar something like : http://twitter.com/statuses/user_timeline/162369603.rss

                Copy it into your parameters.

                It will do the trick


                Merry christmas

                Philippe
                  • 25519
                  • 265 Posts
                  Hey Fildefer57

                  Thanks! I knew it was most likely really simple rolleyes - it’s appreciated

                  Joyeux Noël
                  rp
                    • 6537
                    • 70 Posts
                    Has anyone else experienced any problems with this snippet (or with Twitter via the snippet)?

                    I read this earlier:
                    ... Twitter limits you to 70 requests per 60 sixty minute interval ...

                    I can only think that I hit the max number of requests that Twitter allow in a certain time, but I was suddenly getting an error - the site was hanging for ages, eventually resolving to a MODX parse error page. I setup the snippet a couple of hours ago and didn’t change anything with it, but have been refreshing the site a fair bit as I have been testing other things throughout the day.

                    The reason I think it was TweetLines/Twitter causing the problem was that those pages that didn’t include the snippet call (including the Manager) were fine, and when I removed the snippet call, the problem pages were also fine.

                    It would be good to hear if anyone else has encountered this, and if they have, what solution they used. I guess what is needed is to cache or store the result(s) - if I figure something out I will post here, but I’m not really a developer!

                    Dan
                      • 12013
                      • 61 Posts
                      I am having the same issue, just went to check a few things on the site to get an error message, I removed the the tweet lines call and all works fine.

                      any ideas?

                      Hendo