Howtos Archives - Page 2 of 5 - Stay N Alive

How to Customize Your Facebook Page

static-fbml-2393296I get asked a lot how to customize your Facebook Page (that’s with a capital “P”, not to be confused with your personal profile).  I wrote an article over on Tamar Weinberg’s (author of “The New Community Rules”) blog showing you what you need to do to get the most from your Page, including how to build your own custom tabs using the Static FBML app.  This can be a great use for my book, FBML Essentials.  If you have a cool design and aren’t sure what to do to customize this stuff this is a service I offer when I consult for my clients.  I would be happy to help you with these efforts.

Check out the article here: http://www.techipedia.com/2009/create-facebook-page/

Oh, and please be sure to share the custom Pages you create with the Static FBML App – I’m doing a book giveaway to the best implementation of what you learned!

Introducing the FB Share Button WordPress Plugin for Facebook Share

FacebookToday Facebook launched a nifty little tool enabling website owners and bloggers to allow their users to better share and track their content on Facebook.  The new tool provides a piece of HTML and javascript that renders a little “Share” button.  When clicked, the post is tracked by Facebook, the number of shares is shown, and via an API comments, likes, shares, and more can be tracked across all of Facebook for items shared via that button.  Today I’m going to add to that by providing a WordPress plugin.

The FB Share Button WordPress plugin renders the Facebook share button of your choice on your blog.  Via admin settings in WordPress you can choose which Share button you would like to display, where you want to display it, and even provide the language for the link.  The plugin is based on the same Easy Retweet plugin by Sudar which you see on this blog.

To install, just download this link, untar and ungzip into your WordPress plugins directory.  Activate the plugin, adjust your settings to display where you like (or you can manually add it to your template or posts – see the readme), and it will display for every post you write on your blog.  You can even turn it on or off per blog post.

I’m also working to make this FBFoundations compatible so it will load as an optional XFBML tag if you like – expect that in a future revision.  Now WordPress bloggers everywhere have the capability to enable and track Facebook sharing on their blog.  You can download it here:

http://downloads.wordpress.org/plugin/facebook-fb-share-wordpress-plugin.zip

Stay tuned though – in the next revision I’m hoping to add Facebook API support so you can track and read the number of shares, comments, likes across all of Facebook from your WordPress admin.  That will all fit in with the FB Foundations plugin I wrote earlier.

FBFoundations Facebook Connect Plugin for WordPress

lego bricksOne of my biggest frustrations in adapting Facebook Connect into WordPress blogging has been the fact that most plugins out there either have too much, or too little incorporated into them.  When you add more than one, you end up calling the Facebook Javascript Client libraries more than once, and often reinvent the wheel for what other people have done.  I mentioned this in a wish-list I posted earlier.  I want building blocks – I should be able to add a foundation, and add basic building blocks on top of that foundation to get what I want out of Facebook Connect on my blog.

Today I’m giving you that foundation.  I’ve written a WordPress plugin called FBFoundations which sets up the bare-bones necessities of any Facebook Connect install.  Once you have installed this plugin, the user can log in, and you have access to their login credentials from then forward to do whatever you want with. It’s a foundation – something to build a house on top of, and my hope is that many more FBFoundations-compatible plugins can emerge from this.

For instance, my next step will be to create a simple plugin for WordPress that uses the stream.publish API to post your blog to Facebook, and enable others to do so (tracking the number of comments and likes along the way if possible).  There will be no need to add a user log in to that process, nor do I have to load the XFBML init scripts to render XFBML.  It will all have already been loaded for me.

The script works a lot like Richard Miller’s “What Would Seth Godin Do” plugin from a UI perspective.  At a default (you can configure this in your preferences) the first 3 times a user visits your blog they will be presented with a popup dialog box encouraging them to connect with Facebook.  After those 3 times the popup no longer appears.  There will also always be a “Connect with Facebook” login button above your comments (assuming they’re wrapped in a #commentform div) that will appear until the user clicks on it and logs in.

Using this plugin encourages each reader to log in through Facebook (remember – there are over 300 million Facebook users.  Chances are most of your readers are on Facebook), and enables you to do cool stuff with each of those readers.  Hopefully this will inspire others to make other FBFoundations-compatible plugins so we’re not re-inventing the wheel any more.  Stay tuned for more plugins from me – what will you build with this as your foundation?

You can download the plugin here.  Just download it and unzip it into your plugins directory in WordPress, activate it, and then add the API key for your website.  (You’ll need to go to http://developers.facebook.com to add the developer app and add an app for your website if you haven’t done so already)

Or click here to download:

http://downloads.wordpress.org/plugin/fbfoundations-facebook-connect-plugin.zip

Please let me know in the comments if you see any issues.  This is 100% GPL so please make your own adjustments and let me know if I can fix mine!

UPDATE – v0.4 – 10/26/2009: The popup is no longer default and can be turned on/off. Also added meta tag support and better compatibility with 3rd-party comment systems.  See this blog post for more info on 0.4.

Here are some screenshots:

Screen shot 2009-10-10 at 6.21.49 PM

Screen shot 2009-10-10 at 6.19.47 PM

Screen shot 2009-10-10 at 6.19.13 PM

Social Coding: How to Code Twitter’s OAuth Using Net::OAuth and Perl

OAuthFor the non-developers in my readership, I’m going to get a little geeky on you here. So you can either tune this one out, or pass it onto your IT staff for use in their applications. I promise much more on the “Social” side here shortly. Or, maybe you’ll learn a little Perl.

For those not in the loop, my company, SocialToo.com codes in Perl, a powerful language that gives me the ability to abstract what I need at a very high level, or get down to the nitty-gritty if needed to in order to improve speed or communicate with other core Unix libraries and tools. To me, it’s a very powerful and important language that enables me to get done what I need to do without having to hire developers that know multiple languages. It’s also an amazing scripting language, and powers many of the scripts we run on the backend of SocialToo.

One of Perl’s weaknesses however is that it has never been very strong in the marketing department. For this reason, it is some times (and some times not) one of the last on the priority list for companies like Twitter when developing libraries to integrate with their API. Fortunately it has a very strong group of developers contributing to its very unique directory of open source libraries, CPAN.

Recently we launched a beta OAuth implementation on our Forgot Password page on SocialToo, which uses Twitter OAuth to identify a user and allow them to change their password based on their Twitter authentication. Fortunately with Twitter, we were able to use Net::OAuth, Perl’s OAuth libraries on CPAN, to connect with Twitter’s OAuth implementation. There were some tricks, so I’d like to share that here. It’s my hope that maybe at some point I can package this up at a much higher level to make the process even easier for Perl developers to use Twitter’s OAuth to authenticate.

Perl and OAuth – the basics

First of all, you need to understand the basic flow of the Twitter OAuth process. There are official OAuth terms for this (consumer, service provider, etc.) supposedly to make understanding the process easier, but for our purposes those terms really don’t matter. If you really want to learn more about that stuff, go over to OAuth.net and take the tutorials. What matters is that you get the Access Token you need, which you can use any time later to make requests to Twitter, such as authenticating the user, getting the user’s timeline, their profile info, friends, followers, and more. The entire goal of Twitter OAuth from a development standpoint is to get that Access Token. So here are some basic terms you need to know:

Token – a string of hashed data given to you as a unique ID to identify your application, and the user trying to use your application by Twitter. See below for the types of tokens you’ll need to get from Twitter and when.

Request Token – The token you get from Twitter before redirecting the user to authenticate with Twitter. If the user’s authentication is successful, Twitter creates an access token which identifies the user and associates them with your application. You can then access that access token later by sending another request after the user has authenticated with the request token and the request token secret key (defined below).

Request Token Secret – A string of hashed text, which only you (the developer) will ever see or use. You retrieve this when you get your Request Token, and will need to pass it with your request token when you request to get an access token. Consider this your password when trying to get an access token. Your Request Token is your ID for Twitter to identify your request with to verify the user authenticated successfully and your application has permission to access Twitter.

Access Token – Once you have your Request Token, your Request Token secret, and the user has authenticated successfully, and assuming your application has been given permission by Twitter to access the Twitter API, you can then make a request to Twitter to get your Access Token. You send Twitter your Request Token and your Request Token Secret, and the response returns your Access Token and an Access Token Secret Key for access to the Twitter API. This is a permanent key at the moment that you can use any time later. Store this in your database or a file or elsewhere once the user has authenticated and you’ll be able to authenticate on their behalf from that point on (assuming you have set your app up to do such on Twitter.com). After you have your Access Token, you can make requests to Twitter, via Net::OAuth, which perform any of the methods found via the API by sending Twitter your Access Token and Access Token Secret with the request. Use JSON::Any to parse the resulting JSON returned.

Access Token Secret – The secret key to pass with an Access Token when making API calls to Twitter. Consider this the password that goes along with the ID, which is the Access Token. Twitter looks up the Access Token ID, verifies the user is authenticated, and then checks that you also have a valid Access Token Secret Key. If both are correct and valid Twitter will send back the data you need to access the Twitter API.

Twitter Consumer Key – The unique ID of your application as identified by Twitter – you can get this in your OAuth set up on Twitter. You use this when asking for your Request Token.

Twitter Consumer Key Secret – The “password” to go with your Twitter Consumer Key when asking for your Request Token from Twitter. Twitter looks up your application by it’s ID (Consumer Key), and verifies it’s you by checking your Consumer Key Secret.

Flow of a Simple Twitter OAuth App in Perl

To understand what we’re doing, you’ll need to understand the order of things you’ll need to do in order to fully access the Twitter API through OAuth. This Flow, in plain english, should outline that process, and from here you should be able to adapt the code I provide for any use:

  1. Send a GET request to http://twitter.com/oauth/request_token asking for a request token from Twitter, and passing your appropriate Consumer Key and Consumer Key Secret to identify your application.
  2. If Twitter identifies the Application as legit (and isn’t down), parse out the request token and request token secret from the content of the returned page by Twitter. Here you’ll want to store that request token and request token secret somewhere, as you’ll need to access it again after the user returns back to your site from Twitter.
  3. Redirect to http://twitter.com/oauth/authorize, appending “?oauth_token=YOUR_REQUEST_TOKEN_GOES_HERE” to the URL, replacing YOUR_REQUEST_TOKEN_GOES_HERE with the request token you just got from Twitter. There is no need to send the Request Token secret at this point – this is simply to identify that you have received a request token from Twitter, and so Twitter can identify the user’s authentication (successful or not) with that Request Token.
  4. The user authenticates on Twitter (if not already authenticated through Twitter – if they want to authenticate through a different user they can do so here as well by logging out and re-authenticating).
  5. The user is given the option to “Allow” or “Deny” the request by the Application to access their account information on Twitter.
  6. Twitter then redirects back to the Callback URL you set up in your OAuth set up on Twitter.com – you’ll want to note this so you can write code at the location Twitter redirects to that gets the response token.
  7. Your Callback URL takes the Request Token from earlier, and Request Token Secret from earlier, and sends them to http://twitter.com/oauth/access_token to try and get an Access token. Twitter verifies that the user has authenticated successfully, that they have allowed your application to access their account, and that your Application is valid. If so, you’re returned a successful response from Twitter.
  8. You’ll want to parse out the Access Token, and Access Token Secret from the returned page, and store them somewhere with that user so you can access Twitter on their behalf later. Or, do something right then and there! You have all you need now to use the Twitter API for that user under OAuth.
  9. At this time is when I would authenticate the user if needed, making an OAuth request to access http://twitter.com/account/verify_credentials.json. To do so just send the request via Net::OAuth, along with that user’s Access Key and Access Key Secret (which hopefully you can retrieve from somewhere since you stored it somewhere earlier), and Twitter returns the data back as JSON-formatted data (or XML if you specified verify_credentials.xml) you can then parse out as necessary. You can do the same with any method in the Twitter API.

Example Code

Alright, now onto the juicy details. Assuming you’ve already set up an OAuth Twitter App under your settings tab on Twitter.com, and have your Consumer Key and Secret, you should be set to go. You’ll need to install Perl’s Net::OAuth (and any dependencies) via:

perl -MCPAN -e "install Net::OAuth"

Now, let’s get the Request Token. To do so, I’ve created a simple OAuth Accessor method to do all my OAuth handling. I use Catalyst as my MVC Framework, so all the $c and $self references refer back to the Catalyst environment. I’ll leave that up to you to figure out, or you could always try out Catalyst! So first, let’s set up this method:

=head2 oauth_request

Sends a generic request to the specified url

=cut

sub oauth_request : Private {

my $self = shift;
my $c = shift;
my $i = {
'type' => '',
'url' => '',
'extra_params' => {},
'token' => '',
'token_secret' => '',
'method' => 'GET',
@_,
};

my $request = Net::OAuth->request($i->{'type'})->new(
consumer_key => $c->config->{'twitter_consumer_key'},
consumer_secret => $c->config->{'twitter_consumer_secret'},
token => $i->{'token'},
token_secret => $i->{'token_secret'},
request_url => $i->{'url'},
request_method => $i->{'method'},
signature_method => 'HMAC-SHA1',
timestamp => time,
nonce => join('', rand_chars(size=>16, set=>'alphanumeric')),
extra_params => $i->{'extra_params'},
);

$request->sign;
$c->log->debug("URL: ".$request->to_url);

$c->log->debug("Request: ".Dumper($request));

my $ua = LWP::UserAgent->new;
my $response = '';
if ($i->{'method'} eq 'GET') {
$response = $ua->get($request->to_url);
}
else {
$response = $ua->post($request->to_url);
}
$c->log->debug("Response: ".Dumper($response));

return $response;

}

Basically, all this does is create a new Net::OAuth request object, signs it, and then sends it via a GET or POST request (via LWP) back to the specified URL. This method will handle all our OAuth requests. You’ll need to modify it to match your environment and configuration variables (like the consumer key and secret).

The token and token_secret variables can be either a request token, or access token (and secret), or neither. You won’t need to pass either when you’re trying to get your request token obviously. “type” will define what type of request it is you’re making – it can be either “request token” (to ask for a request token), “access token” (to ask for an access token), or “protected resource” (when accessing private data for a user from the Twitter API on their behalf). The “url” variable specifies the Twitter URL to request, based on the type of the request. You can get these from your OAuth settings page for your app on Twitter.com. Dont’ worry about the rest – that’s all used to generate the signature sent to Twitter with all the data you just gave it.

Now that we have that, we can make our requests to Twitter.  We’ll need to start with getting our Request Token.  We’re of course assuming this is the user’s first time authenticating through your App.  Here’s how we’ll do that using the above method:


$c->log->debug("getting request token...");

my $res = $self->oauth_request($c,
'url'       => $c->config->{'twitter_request_url'},
'type'      => "request token",
);

$c->user_session->{'oauth_redirect_url'} = uri_escape($c->req->param("redirect_url"));

if ($res->is_success) {
my $response = Net::OAuth->response('request token')->from_post_body($res->content);
if (defined $response->token) {
$c->user_session->{'request_token'} = $response->token;
$c->user_session->{'request_token_secret'} = $response->token_secret;
my $auth_url = $c->config->{'twitter_authorize_token_url'}."?oauth_token=" . $response->token;
$c->res->redirect($auth_url);
$c->detach;
return;
}
}
else {
$c->log->fatal("Something went wrong.");
# expire request tokens each time they are used
$c->user_session->{'request_token'} = '';
$c->user_session->{'request_token_secret'} = '';
}

In this example, we ask for a simple request token from Twitter to the request token URL we were given by Twitter in our OAuth settings. In this particular example (it may not be needed by yours), we allow the user to pass a redirect URL to our application via a “redirect_url” parameter in the URL. We store that in the session for later use so we can pass the user onto somewhere else if needed. You could store this in a cookie, a session, a file, or database – it’s up to you, and won’t be necessary if you never need to redirect the user later.

Assuming your app has been authorized to connect to Twitter with the Consumer Key specified, you should get a successful (200 OK) response back from Twitter. You’ll then need to parse out the Request Token and Request Token Secret keys from the response. You can do so by passing the returned content through Net::OAuth->response(‘request token’)->from_post_body() as specified.

Once you’ve got that token and a secret key for it, you’ll want to store it somewhere for later use. Twitter doesn’t give it back to your app later, so you’ll need to put it somewhere. In this example we store it in the Catalyst Session for the particular user’s session. You could store them in a cookie, session, file, or database, but you’ll need to put them somewhere. You’ll need this later.

Finally, we need to redirect the user to authenticate and authorize your App on Twitter. You send them to the authorize URL Twitter gives you in your App settings page when you set up OAuth, and append, “?oauth_token=”, followed by the Request Token you just received. Also note the error checking we do – don’t forget to cover your bases!

The user will get sent to Twitter, authenticate, and authorize your App. Finally Twitter will redirect the user back to your callback URL that you specified in your App’s settings when you set up OAuth on Twitter.com. In that URL’s logic, you’ll need to do something like the following:


$c->log->debug("request_token: ".$c->user_session->{'request_token'});
$c->log->debug("request_token_secret: ".$c->user_session->{'request_token_secret'});

my $res = $self->oauth_request($c,
'url' => $c->config->{'twitter_access_token_url'},
 'type' => "access token",
'token' => $c->user_session->{'request_token'},
'token_secret' => $c->user_session->{'request_token_secret'},
);

if ($res->is_success) {
my $response = Net::OAuth->response('access token')->from_post_body($res->content);
$c->user_session->{'access_token'} = $response->token;
$c->user_session->{'access_token_secret'} = $response->token_secret;

$c->log->debug("redirect_url: ".$c->user_session->{'oauth_redirect_url'});
$c->res->redirect(uri_unescape($c->user_session->{'oauth_redirect_url'}));
}
else {
$c->log->fatal("Could not get an Access Token: " . $res->as_string);
}

# expire request tokens each time they are used
$c->user_session->{'request_token'} = '';
$c->user_session->{'request_token_secret'} = '';

At our callback URL, our main goal now is to get that Access Token. We’re assuming the user has authenticated and approved the app. We know the request token and request token secret, but do not yet have an Access Token for the user. Let’s hope you stored the Request Token and Request Token Secret for that user somewhere. You’ll need it here.

To get the Access Token, you’ll need to send an access token request to Twitter, to the URL specified in your settings where you set up OAuth for your App on Twitter.com. In addition, you’ll want to pass into it the Request Token, and Request Token Secret we stored earlier. In this case we stored it in the session, but you’ll need to retrieve it from wherever you stored it earlier.

If your request is successful, you’ll then need to parse the Access Token and Access Token secret from Twitter by passing the returned content to the Net::OAuth->response(‘access token’)->from_post_body() method. You can then get your Access Token and Access Token Secret from the returned response, as shown in the example. You’ll then want to store those somewhere, often some place permanent to be accessed later on behalf of the user. In our specific case, since this is just a forgot password form, we only need to store it in the session for access later, which we do in the example.

Now, remember that redirect_url parameter we passed and stored in the session? Now we can retrieve that, and redirect the user wherever you intended them to go after starting the authentication process. In this case, we’ll probably pass them onto the Forgot password page for authentication verification and identification of the user. The code on the forgot password page will look something like this:


=head2 verify_credentials

Verifies the user's Twitter credentials and returns a user hashref if successful

=cut

sub verify_credentials : Private {

my ($self, $c) = @_;

if (!$c->user_session->{'access_token'}) {
return q{Access token must be retrieved from Twitter before we can run verify_credentials.};
}

my $response = $self->oauth_request($c,
'url' => 'http://twitter.com/account/verify_credentials.json',
'token' => $c->user_session->{'access_token'},
'token_secret' => $c->user_session->{'access_token_secret'},
'type' => "protected resource",
);

my $retval = '';
if ($response->is_success) {
$retval = eval { JSON::Any->jsonToObj( $response->content ) };
if ( !defined $retval ) {
return q{Twitter returned success but parsing of the response failed: }.$response->content;
}
}
else {
return $response->code;
}

return $retval;

}

In this example we simply send a protected resource request to Twitter’s verify_credentials call. We parse out the returned JSON response, and voila, we have an authenticated user and all their information! This particular method will return the full user’s data if they are authenticated. We can then use that on the forgot password form to identify who the user is, if they’re a SocialToo user, and it will work regardless if we even have their Twitter username correct, because it relies on the Twitter user id.

So, the final full code you’ll want to use will look something like this (again, I’m using the Catalyst framework):


=head2 authenticate_twitter

Redirects to Twitter to get OAuth Token

=cut

sub authenticate_twitter : Local {

my ($self, $c) = @_;

#This ensures we only run the following code the first time they authenticate - pass it ?init=1 in the "sign in to Twitter" link
unless ($c->user_session->{'request_token'} && $c->user_session->{'request_token_secret'} && !$c->req->param('init')) {
$c->log->debug("getting request token...");

my $res = $self->oauth_request($c,
'url' => $c->config->{'twitter_request_url'},
'type' => "request token",
);

$c->user_session->{'oauth_redirect_url'} = uri_escape($c->req->param("redirect_url"));

if ($res->is_success) {
my $response = Net::OAuth->response('request token')->from_post_body($res->content);
if (defined $response->token) {
$c->user_session->{'request_token'} = $response->token;
$c->user_session->{'request_token_secret'} = $response->token_secret;
my $auth_url = $c->config->{'twitter_authorize_token_url'}."?oauth_token=" . $response->token;
$c->res->redirect($auth_url);
$c->detach;
return;
}
}
else {
$c->log->fatal("Something went wrong.");
# expire request tokens each time they are used
$c->user_session->{'request_token'} = '';
$c->user_session->{'request_token_secret'} = '';
}
}
else {
$c->log->debug("request_token: ".$c->user_session->{'request_token'});
$c->log->debug("request_token_secret: ".$c->user_session->{'request_token_secret'});

my $res = $self->oauth_request($c,
'url' => $c->config->{'twitter_access_token_url'},
 'type' => "access token",
'token' => $c->user_session->{'request_token'},
'token_secret' => $c->user_session->{'request_token_secret'},
);

if ($res->is_success) {
my $response = Net::OAuth->response('access token')->from_post_body($res->content);
$c->user_session->{'access_token'} = $response->token;
$c->user_session->{'access_token_secret'} = $response->token_secret;

$c->log->debug("redirect_url: ".$c->user_session->{'oauth_redirect_url'});
$c->res->redirect(uri_unescape($c->user_session->{'oauth_redirect_url'}));
}
else {
$c->log->fatal("Could not get an Access Token: " . $res->as_string);
}

# expire request tokens each time they are used
$c->user_session->{'request_token'} = '';
$c->user_session->{'request_token_secret'} = '';
}

}

=head2 oauth_request

Sends a generic request to the specified url

=cut

sub oauth_request : Private {

my $self = shift;
my $c = shift;
my $i = {
'type' => '',
'url' => '',
'extra_params' => {},
'token' => '',
'token_secret' => '',
'method' => 'GET',
@_,
};

my $request = Net::OAuth->request($i->{'type'})->new(
consumer_key => $c->config->{'twitter_consumer_key'},
consumer_secret => $c->config->{'twitter_consumer_secret'},
token => $i->{'token'},
token_secret => $i->{'token_secret'},
request_url => $i->{'url'},
request_method => $i->{'method'},
signature_method => 'HMAC-SHA1',
timestamp => time,
nonce => join('', rand_chars(size=>16, set=>'alphanumeric')),
extra_params => $i->{'extra_params'},
);

$request->sign;
$c->log->debug("URL: ".$request->to_url);

$c->log->debug("Request: ".Dumper($request));

my $ua = LWP::UserAgent->new;
my $response = '';
if ($i->{'method'} eq 'GET') {
$response = $ua->get($request->to_url);
}
else {
$response = $ua->post($request->to_url);
}
$c->log->debug("Response: ".Dumper($response));

return $response;

}

=head2 verify_credentials

Verifies the user's Twitter credentials and returns a user hashref if successful

=cut

sub verify_credentials : Private {

my ($self, $c) = @_;

if (!$c->user_session->{'access_token'}) {
return q{Access token must be retrieved from Twitter before we can run verify_credentials.};
}

my $response = $self->oauth_request($c,
'url' => 'http://twitter.com/account/verify_credentials.json',
'token' => $c->user_session->{'access_token'},
'token_secret' => $c->user_session->{'access_token_secret'},
'type' => "protected resource",
);

my $retval = '';
if ($response->is_success) {
$retval = eval { JSON::Any->jsonToObj( $response->content ) };
if ( !defined $retval ) {
return q{Twitter returned success but parsing of the response failed: }.$response->content;
}
}
else {
return $response->code;
}

return $retval;

}

To run it, you’ll (assuming this is Catalyst) point your “Sign in With Twitter” link to /authenticate_twitter?init=1&redirect_url=http://yourdomain.com/forgot on your domain. Note that “init=1” identifies the user is not yet authenticated. That gets the request token, and redirects the user to Twitter to authenticate. Twitter then sends the user back to /authenticate_twitter on your domain. You detect that the request_token session variable has been set along with the secret key, so then run the code to get an access token. You get the access token from Twitter, store that in the session, and then redirect the user to http://yourdomain.com/forgot (identified by the redirect_url parameter in your original sign in link). http://yourdomain.com/forgot accesses the verify_credentials() method above, which takes the user session variable with the access token, verifies the user’s Twitter credentials, and returns user data for the individual. You can then display user data appropriately, and in this case allow the user to reset their password because you have officially confirmed it is them.

SocialToo Forgot Password Form

Like on Socialtoo, your forgot password form, or other OAuth instance will have a “Sign in With Twitter” link like this one that points to code similar to what I featured.

If you want to learn more, the documentation is pretty scarce at the moment. Hopefully myself or someone else will put together a much more abstract set of libraries targeting the Twitter platform soon surrounding this. I do recommend checking out OAuth.net and understanding the OAuth protocol a little more, along with the Net::OAuth documentation. Hopefully many more of you can share your experiences in the comments, or in your own blogs as you come across new experiences with Twitter’s OAuth in a Perl environment.

UPDATE: Looks like someone already has added an abstraction layer around all this. To simplify things even further, check out Net::Twitter::OAuth. It might be helpful to read this first anyway so you know what’s going on there.

Automatic Data Compression With DBIx::Class::CompressColumns

UPDATE: You can now get the DBIx::Class::CompressColumns module on CPAN here or via CPAN command-line shell.

Too Many PeopleI’m going to get geeky on you for a minute, but you should find this interesting.  One of the challenges I’ve had with SocialToo recently has been the massive Social Graph data we’ve had to story and process and track. We cache a lot of the data so we don’t have to hit Twitter’s servers as often, and also to enable us to track new follows and unfollows regularly on behalf of our users.

If you are a SocialToo user you may have noticed that your data hasn’t been as accurate lately as it should.  The reason for that is we have had a) 20,000+ users all wanting to auto-follow or have their follower base tracked, and b) all 20,000+ of those users have anywhere from 100 to near 1 million followers that we have to store and process.  It’s not an easy task!  And our database, set up in a relational manner of followers to users, just wasn’t cutting it in regards to being able to retrieve and process so many followers at a time.

So I took a cue from Bret Taylor and FriendFeed, who talks about how they denormalized their database, and now reference “bags” of data that they can then process in their code.  I went for a hybrid model, and with each user entry I now have a single column on that table we reference, in BLOB format, which contains all the social graph data for that user.  In Perl, I simply create a hash structure of the data, freeze it, and then store it in the database in our social graph column.  To retrieve it, we pull it from the database, thaw it, and we have an entire social graph we can play around with and do with as we please.

The issue I was running into however is that plain text, stored in a single column, for a user with 1 million followers, gets to be quite a large amount of data we need to pull through the pipes.  I needed an easy way to compress the data before inserting into the database, storing it in binary format, and decompress.  I also wanted it to be automatic, so no coder would ever have to worry about this extra step – it would just happen magically.

So today I’m releasing DBIx::Class::CompressColumns for all you Perl coders out there.  What this module does is it sits on top of Perl’s DBIx::Class database abstraction libraries and allows you to monitor a single column.  Any inserts or updates into that column get compressed in Zlib format, and any selects/get_column calls to that data (you must use get_column) get de-compressed, meaning you don’t have to worry at all about that extra step, the data is a significantly smaller footprint, and your throughput is much less, causing much less load on the database.  For one-million followers, I measured just 4 Megabytes in space taken that has to go in and out of MySQL.

Approaching Graph optimization in this manner has significantly sped up our processes, and I’m already seeing huge benefits from it.  There is much less load on the database, it’s much faster to retrieve and process the data, and we’re getting through our users’ followers much faster now.

The module namespace is currently being applied for on CPAN at the moment, and I’ll post a link there as soon as it is approved, but for now you can download the Makefile-compatible gzipped library here.  I hope some of you find this useful, and please feel free to modify or send me any updates or bugs you think I missed!

The link for the download is http://socialtoo.com/DBIx-Class-CompressColumns-0.01000.tar.gz

Oh, and TMTOWTDI so please if you have better ways of approaching this I’d love to hear your ideas!

Photo courtesy rp72

Check Out My New Twitter Avatar!

If you check out my Twitter Profile, you’ll notice a new, winter-themed, festive Avatar. Yes, it’s animated, and everyone is going to hate me now for revealing how to do this. Check out my post on LouisGray.com to learn how it’s done. Consider it my second gift to you this Christmas!

Social Coding Series: I’m In Your Social Graph, Hacking Your Life – a Howto

As the first entry to my Social Coding series I’m going to cover Google’s Social Graph API. I saw a demo of this at Google I/O in San Francisco and was so impressed that I immediately started hacking on it when I got home. Little did I know how powerful this API was and how much information it could pull off the web about a single individual!

Google’s Social Graph API takes a cache of the rich storage of links, information, and URLs on Google’s servers, and determines which of those contain information about actual people. It combines OpenID for confirming an individual’s identity, and XFN and FOAF XML protocols to determine links between those identities. With a simple tag on a user’s website, a user can determine other websites that also identify them. If you link to one URL identifying that location as you, and at the linked website, it links back to you, Google can tell for sure both of those websites are yours, and identify you as a person. Not only that, but you can similarly provide XFN information or FOAF information via similar tags or a separately linked file identifying who your friends are. If they link back to you via similar metadata Google can tell for sure that the two of you are friends.

The Social Graph API lives and breaths this data. There are actually quite a few Social networks that use this protocol to identify you and your friends. Sites like Digg, Twitter, and FriendFeed all utilize these protocols to identify your friends. The Google Social Graph API scans this data and organizes it in an easy way for you, as a developer, to access.

Let’s try a simple example, and you don’t even have to be a developer to try it. Google has provided a simple playground to see how the Social Graph API works. If you go to http://socialgraph-resources.googlecode.com/svn/trunk/samples/exploreapi.html, enter in a few URLs of your blogs, social networking profiles, and other identifying locations on the web, leave “Follow ‘me’ Links”, “Pretty Output” checked, and click, “Find connections”. For me, just “twitter.com/jessestay” was all I needed to enter in the textarea.

The resulting structure is organized in a format called JSON – if you’re a Perl developer you might be familiar with this, as it is formatted the same way as a Perl Hash structure. You’ll see under “nodes” a bunch of URLs with different metadata about the URL – these are URLs that Google thinks, based on the metadata in the URL you provided, are you or contain info about you. I’ve found that only those with a “profile” attribute are actual Social Network profiles for yourself, so be sure to pay attention to those.

You can also go back and click “show inbound links” and “show outbound links” – this will then return URLs with links to sites you have identified as yourself, as well as sites you own that claim other sites as identifying for you. Play around with it – there’s a wealth of information it will give you about people!

Now, if you’re not a developer, you can skip over this next section because I’m going to get technical by showing an example. I’m a Perl developer so I’ll show one in Perl.

In Perl it’s simple – you need to install Net::SocialGraph with a command similar to this:

perl -MCPAN -e “install Net::SocialGraph”

Then, a bit of code like this will give you the data you need:

my $sg = Net::SocialGraph->new(‘fme’ => 1);

my @urls = ();
push (@urls,’http://twitter.com/jessestay’);
push (@urls,’http://facebook.com/profile.php?id=683545112′);

my $res = $sg->get(@urls);
my @profiles = ();
foreach my $node (keys %{$res->{‘nodes’}}) {
  if ($res->{‘nodes’}->{$node}->{‘attributes’}->{‘profile’}) {
    push (@profiles, $res->{‘nodes’}->{$node}->{‘attributes’}->{‘profile’});
  }
}

In the above example I instanciate my $sg object, telling it to follow “me” attributes in the response. I add a couple URLs to identify the individual I want profile information for (in this case, me), and then make the call to the SocialGraph API to go get my info based on those URLs with the “get” method provided by the API. Then, I just traverse the response and I can do whatever I want with it. After this, I could take the response information and list all of the user’s profiles as links, or perhaps I could scan those profiles for more information and provide information about each identified profile. You’ll also note that it’s not always correct so you’ll want to let the user intervene. Also, note I’m looking for only links with a “profile” attribute – I’ve found these to be most accurate.

Beyond that, that’s it. Ideally, you could take the Playground example above and look at the resulting URL. The basics of the Social Graph API are just that URL – plug in whatever you want and you’ll get back whatever information you need. You could then parse it with Javascript, Perl, PHP, or just leave it in the “pretty” format the Playground provides you by default.

Now, imagine taking that data and combining it with, say the Twitter API to pull out all of an individual’s friends on Twitter, then applying the Social Graph API to each of those individuals. Soon, you have a tool which can identify which of a user’s friends are on which networks, and if there are any of your friends you have not yet added on those networks. This API is powerful!

The Social Graph API can be an excellent utility to find out more information about any individual using your applications. No longer do you have to ask the individual for that information – so long as they are active on Web 2.0 that information can be provided for them to choose from!

You can learn more about the Social Graph API here.

Please note I too am new to this API – any inaccuracies in this document please let me know in the comments and I will correct them for others to benefit.

New Series: Social Coding

I’ve been contemplating for awhile now a good way to share what I know about Social Software Development and helping business owners, marketers, and developers learn how to set up their own social apps. Especially for developers, I know there are many out there looking for howtos and ways to learn more about starting their own App, promoting it, and getting it off the ground. As the author of FBML Essentials, I feel I am well suited for the task so in the next few days I’m going to start doing howtos and overviews on how you can get your own Apps together. If you’re “the business type”, I may get a little technical on you, but I do recommend you keep watching and forward these onto your IT personell – your CIO, CTO, and the like should read these so they can learn what’s possible to integrate into your existing environments. I’ll also try to throw in a little goodie here and there for “the business type”.

So, I’ve created a new category to the right, “Social Coding” – if you want to track just that, click on the category name and add it to your RSS. I’ve also started a new FriendFeed Room where those involved or that want to get involved in Social Coding can discuss, learn, and talk with each other. You can subscribe to that here.

Let’s start by going over the types of sites I could cover. Here are just a few – let me know if you have a particular interest in learning about how to code for any one in particular:

  • Facebook
  • OpenSocial
  • Google Friend Connect
  • Twitter
  • FriendFeed
  • Pligg
  • Digg
  • LinkedIn
  • MySpace
  • WordPress
  • MoveableType
  • Google App Engine
  • Bungee Connect

Stay tuned! I’ll keep posting news and other rants as we go forward – I’ll just be adding in some good howtos at the same time. Oh, and if you’re a developer and would like to do a howto in your preferred language for us, contact me – I’d love to let you do a guest post.

Utah Startup Series: Bungee Labs

logo_bungeelabs-flat_md.png(Sorry it’s been awhile since my last blog – it took me several days to figure out how to get my Flip video imported and exported to and from iMovie. To make a long story short, if you want to export from iMovie and have both picture and sound, you must import your source as something other than MP4 or AVI.)

This is the first article in my “Utah Startup Series“. Starting today I will be circling Utah to find the best and most innovative startups in Utah, and featuring them here on Stay N’ Alive. If you have a hot startup (early to even late stage) and would like to demo for me what your product can do, please contact me – if I have the time and like your idea I’d love to come out and take a look at it!

While at Web 2.0 Expo I had the opportunity to meet with Bungee Labs, a local, well funded Utah company who had “Platform as a Service” down before Google even started thinking about their App Engine. In our meeting they demoed their Bungee Connect “IDE” (written entirely on the web). You can see the video below.

My thoughts – you have to see this stuff in person to understand the full ramifications of what they’re doing. One of the cool things about their service vs. Google’s is they actually integrate with Amazon’s EC2 service (which was announced during Web 2.0 Expo), so you can actually host your other stuff on Amazon’s EC2 platform with the same licensing as your Bungee Connect account. Their licensing structure is very appealing as well – Bungee only charges based on the number of registered user sessions using their platform, not traffic, not bandwidth. If I understand correctly, it’s all based on the number of users actively using your application on their platform. For Facebook and Social Media developers this is appealing, as most Applications are rated based on Application use, not number of users or traffic. With Bungee you only pay for the users that actively use your system.

Overall, the guys at Bungee were Rockstars at Web 2.0 Expo. With their announcements about EC2 integration, flexible licensing terms, features on TechCrunch, EWeek magazine, and a dozen other publications, you can bet Google has a watchful eye on them. Ironically, it was interesting seeing Kevin Marx, head guy over the OpenSocial (and other) efforts at their party on Thursday evening.

Bungee will be presenting at our Social Media Developers meeting this coming Tuesday, showing us a simple “Hello World” example on how to build a Facebook App using their platform. Follow me on Twitter and if we can stream it live you can watch it via my Ustream channel. After demo I may just write my own Facebook App to try out their system – it should be interesting.

Bungee Connect Demo – Web 2.0 Expo from Jesse Stay on Vimeo.

Using Perl/Catalyst and Want to Use Sometrics? Try This.

logo-7866293I’ve been analyzing various Social Applications Analytics tools lately, and have recently stumbled upon Sometrics. Sometrics handles full Analytics for your Facebook, Bebo, and MySpace applications, and will actually utilize the Facebook API to retrieve demographic info about those visiting your Application. As I examine the other Analytics solutions for Facebook and other Social Network Applications, I’ll try to post my findings of their strengths and weaknesses here, OpenSocialNow, and FacebookAdvice.com. If you’re not a techie, you may want to skip the next part, or forward it onto your IT department.

One thing I noticed about Sometrics is it seems to only provide code to paste on your Application pages for PHP, Ruby, and ASP.net. The code they provide is relatively simple, but in case you’re wondering how to do it in Perl, here is how I did it in Template Toolkit under Catalyst on Perl:

Enter this on all Application pages (I do it in my “footer” file):


[% IF Catalyst.request.param("installed") %]

[% ELSE %]

[% END %]

Then add this in the “post-remove url” subroutine for your Applicaiton (or create one and add the URL in your App’s config):

=head2 remove

  Page that handles App removal

=cut

sub remove : Local {

  my ( $self, $c ) = @_;

  if ($c->req->param(“fb_sig_uninstall”)) {

    $c->res->redirect(qq{http://halo.sometrics.com/met.gif?a=u&app=}.$c->req->param(“fb_sig_api_key”).qq{&uid=}.$c->req->param(“fb_sig_user”).qq{&age=&sex=&city=&state=&country=&friend=&src=fb});

    $c->detach();

  }

  return;

}