Blog Archive

Friday 22 June 2012

Tweeting from a FUEL CMS module

Recently a client asked if it were possible to tweet automatically from a news module, such that in publishing a news item, a tweet could optionally be sent too. This article will deal with the basics of creating a tweet relationship within a FUEL CMS news module.

What I envisaged was a checkbox in the module’s create/edit page that indicated the tweet option, and then some post processing to send it. OAUTH would be catered for preferably, and would be invisible to the administrator (eg permission to use the Twitter account would be a condition of being able to use the module in the first place). The link to the tweeted article could be auto generated and shortened using the an API, so again, no user intervention would be required.

The first task was to find a Twitter library, and after prodding several that either didn’t work as expected, or I didn’t understand in time, I used the one supplied by Simon Emms. This offered exactly what I wanted for the module, and was already developed for Codeigniter! Follow Simon’s instructions on how to make use of the library, and you will also need (obviously) a Twitter account to use, and the keys required to use the application including those to auto authenticate the account (ie the consumer key, consumer secret, access key and access secret).

Next,I needed a library to auto shorten the links to the news article. I considered two – one for Google and one for Bitly. Since the Bitly one was also from Simon Emms, that seemed appropriate, but either would have done.

To work

In addition to the checkbox option I had imagined, it seemed a good idea to store whether a tweet had occurred, so my news module MySQL table looked something like

   1:  CREATE TABLE `news` (
   2:    `id` int(11) NOT NULL auto_increment,
   3:    `date_added` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
   4:    `keywords` varchar(255) default NULL,
   5:    `description` varchar(320) default NULL,
   6:    `title` varchar(255) NOT NULL,
   7:    `publish_date` date NOT NULL,
   8:    `summary` varchar(2048) default NULL,
   9:    `content` text,
  10:    `url` varchar(255) default NULL,
  11:    `tweet` enum('yes','no') NOT NULL default 'no',
  12:    `tweeted` int(11) NOT NULL default 0,
  13:    `active` enum('yes','no') default 'no',
  14:    `last_updated` timestamp NULL default NULL,
  15:    PRIMARY KEY  (`id`),
  16:    UNIQUE KEY `id_UNIQUE` (`id`)
  17:  )

The column “tweeted” would store the number of times the article had been posted to twitter (probably only ever once, but you never know), and the “tweet” column would act as a switch to trigger a tweet.


I also made the “tweeted” field readonly, as there is no point rendering it as an editable field, so the news model’s form_fields() method was


   1:  function form_fields($values = array())
   2:  {
   3:    $fields = parent::form_fields($values);
   4:    $fields['tweeted'] = array('readonly' => TRUE, 'comment' => 'Times tweeted (read only)', 
   5:      'order' => 8, 'default' => 0);
   6:    return $fields;
   10:   }



To process the tweet I chose the on_after_save() hook that derives from the  MY_Model class of FUEL CMS. It was as simple as:


   1:  function on_after_save($values)
   2:  {
   3:    if($values['tweet'] == 'yes' && $values['active'] == 'yes')
   4:    {
   5:      $this->load->library('cache'); // required by Twitter lib below
   6:      $this->load->library('twitter');
   7:      if($this->twitter->is_logged_in()) {
   8:          $this->load->library('bitly');
   9:          $tweet = $values['summary'];
  10:          $shortUrl = '';
  11:          $shortUrl = $this->bitly->shorten(site_url('news/item/'. $values['id']));
  12:          $this->twitter->post_tweet($tweet. ' ' . $shortUrl);
  13:          $this->session->set_flashdata('success_other', 'This item has been tweeted successfully too!');
  14:          $this->_updateTweeted($values['id']);
  15:      }    
  16:    else
  17:          $this->session->set_flashdata('success_other', 'Not logged in to Twitter account!');        
  18:    }
  19:    // reset tweet status
  20:    $this->db->set('tweet', 'no');
  21:    $this->db->where('id', $values['id']);
  22:    $this->db->update('news');
  23:  }



The data posted by the module’s form is sent in the $values array. I test for the “tweet” field being positive, and also that the posted item is “active” (eg in published status). The magic with twitter authentication then happens, and if all is well, the Bitly url shortening proceeds, and then the post to Twitter. The _updateTweeted() method is not shown, but this just increments the tweeted field.


I’m using the news module’s “summary” field as the source for the tweet, (and in fact I added a character count to that textarea to warn the user when their limit was up, but I’m not detailing that here).


The success or otherwise of this process is represented in the flashdata messages. I had to edit a core FUEL CMS file (fuel/modules/fuel/views/_blocks/notifications.php) to represent these messages in the admin views, as setting flashdata messages in the on_after_save() method will otherwise see them overwritten by the standard system messaging (hence I use ‘success_other’ key to put them out of harm’s way!). Since tweeting is really only secondary in importance to the form as a whole being saved correctly, the “fail” message will appear after the “Data has been saved” message, rather than in an alert of it’s own.

No comments:

Post a Comment

My top artists