WebAppNiche

We dont just develop applications, we build business

Blogs - WebAppNiche

Twitter Application in Cakephp

Recently I developed a cakephp based Twitter application for automating Twitter. The application LetUsFollow allows users to meet new people whom they can follow and in return they are awarded some credits. They can in turn offer some credits to others for following them. Thus the application lets users get free Twitter followers and grow their social network. The application also allows one to schedule tweets for future post. As there are not many decent tutorials over the net describing how to develop a Twitter app/mashup in cakephp, I decided to share a few code snippets so that someone can reuse them.

So to get started with our Twitter application, first register a new application on Twitter developer website. Give a suitable name to your Twitter application, some information about the purpose of the application in the description, address of the website where you want to host the app. Most fields are self-explanatory. The one to care about is the Callback URL. This is the url where Twitter should return to after successfully authenticating. More on this in coming paragraphs.

After setting up your application, note down your consumer key and secret. We will need this for authenticating any of our oauth calls. Now create a configuration file in your cakephp app/config directory named twitter.php and save your consumer key and secret :-

<?php
$config = array(
  'Tweets' => array(
    'consumer_key' => 'CONSUMER_KEY',
    'consumer_secret' => 'SECRET',
  )
);
Now download this wonderful php sdk - Twitter-async which is a high performance wrapper for Twitter's OAuth API and provides parallel/asynchronous calls. It can be downloaded from here. Save the files EpiCurl.phpEpiOAuth.phpEpiTwitter.php inside your app/vendors directory. We shall import these files in our app_controller beforeFilter function :-
function beforeFilter(){
App::import('Vendor','EpiCurl',array('file' =>'EpiCurl.php'));
App::import('Vendor','EpiOAuth',array('file' =>'EpiOAuth.php'));
App::import('Vendor','EpiTwitter',array('file' =>'EpiTwitter.php'));
Configure::load('twitter');
//Twitter configuration
$twitterConfig = Configure::read("Twitter");
$this->set('consumer_key', $twitterConfig['consumer_key']);
$this->set('consumer_secret', $twitterConfig['consumer_secret']);
$this->twitterObj = new EpiTwitter($twitterConfig['consumer_key'], $twitterConfig['consumer_secret']);
$this->set('twitterObj',$this->twitterObj);
}
Note that we have initialized a twitter client object using our consumer key and secret. The next step is to create a controller for handling twitter authentication. We shall name it Twitters. Here is the controller code:-
<?php
class TwittersController extends AppController {
	var $name = 'Twitters';
	
	function beforeFilter(){
		parent::beforeFilter();
		$twitterId = $this->Auth->user('twitter_id');
		if(!isset($twitterId) || $twitterId == ''){
			 $this->redirect($this->twitterObj->getAuthorizationUrl());
		}	
		$this->Auth->allow('register');
	}
		
	function register(){
		
	}
}
?>
Needless to say, your users table must contain a field called twitter_id for storing the user's twitter id. In the beforeFilter function, we check if the user is logged in via Twitter i.e., whether twitter_id Auth variable is set or not. If not we redirect him to register action. Inside the register action we simply display him our Twitter authorization link :-
<?php echo '<a href="' . $twitterObj->getAuthorizationUrl() . '">Authorize with Twitter</a>'; ?>
When the user logins in with his Twitter account, he is redirected back to our callback url that we had set in the settings of our Twitter application. In my case, I wrote an action in my users controller to handle the Twitter registration. You must have guessed it by now that this action is the callback url of my Twitter application. Here is the code snippet:-

<?php
class UsersController extends AppController {

	var $name = 'Users';
    
	function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('registerTwitterUser');
	}

	function registerTwitterUser(){
		$this->twitterObj->setToken($_GET['oauth_token']);
		$token = $this->twitterObj->getAccessToken();
		$this->twitterObj->setToken($token->oauth_token, $token->oauth_token_secret);
		$twitterInfo= $this->twitterObj->get_accountVerify_credentials();
		$data = array();
		$data['twitter_id'] = $twitterInfo->id;		
		$id = $this->Auth->user('id');
		if(!isset($id) || $id == ''){
			$count = $this->User->find('count',array('conditions' => array('twitter_id' => $data['twitter_id'])));
			if($count<1){
				$this->User->create();
				$this->User->save($data);
				$this->Auth->login($this->User->id);
			}else{
				$data = $this->User->find('first',array('conditions' => array('twitter_id' => $data['twitter_id'])));
				$this->Auth->login($data['User']['id']);
			}
		}else{
			$data['id'] = $this->Auth->user('id');
			$this->User->save($data);
			$this->Auth->login($data['id']);
		}
		$this->redirect(array('controller'=>'twitters','action'=>'home'));
	}
}

The code is pretty simple. When the users authorizes our application with his twitter credentials, Twitter sends him back to this callback url with a signed request containing his oauth token. We then fetch the user's Twitter id and validate the user. In my case, I had facebook integrated too so the user might have already been logged in so I had to check whether he is a logged-in user and if so update the record with his Twitter id. If however he is a new user, I create a new record in the users table for this user and login in him.

You can see a live demo of this code in work here at LetUsFollow. Login in with your Twitter account and you can also get a few more targeted followers free :)

I hope this would be helpful for someone out there. Feel free to comment and suggest any code improvement.

Get free Twitter followers and fans for your Facebook pages.

These days Twitter and Facebook pages have become very effective tools for online marketing and promotion of products and services. Every other company has it's profile on Twitter and Facebook page, which allows them to interact with millions of real people at no extra cost. Social Networks like Twitter and Facebook have created an effective niche for marketing and as such one can easily guess the importance of growing your Twitter followers and Facebook page likes.

Keeping this in mind, we at WebAppNiche have developed this free service which we call LetUsFollow which lets you get more Twitter followers and Facebook page Likes. LetUsFollow works on the principle of mutual likes and follows and to promote this exchange, users offer virtual currency (credits) as incentive. When a user joins letusfollow.com he/she is given a certain number credits. To encourage users to follow you, you offer them some credits when they follow you and you receive credits when you follow someone else. Users can earn more credits by following others or by referring your friends.

Users are allowed to target their audience and can set their preference based on age, gender, country and interests. They can also decide how much credits to offer for following their account or liking their facebook page. Thus users have full control on who can follow them and how fast they want to grow.

At it's current state, LetUsFollow allows you to grow your social networking reach in Twitter and Facebook. In near future, more services including but not limited to Youtube, Digg etc. may be introduced including several other services. We hope that people will find this service useful.

Facebook Application Development using Graph Api and Cakephp

In this article I will show you how to write a iframe based facebook application using popular php framework cakephp and facebook graph api. I chose cakephp because of it's excellent ORM which is similar to that of Ruby on Rails. I prefer iframe as it supports my favorite javascript library - jquery.

I assume that you are familiar with cakephp and facebook graph api. So without any delay, lets jump into the steps:-

1) Set up a new facebook application -

New Facebook Application

Complete the visual verification in the next step which will create the new facebook application and bring up the setting screen for the new application.

2) Go to the Facebook Integration tab and note down the Application ID and Application Secret, set the Canvas Page url which will be your facebook application url. Now set the Canvas URL to something like http://localhost/cakephp-app or the appropriate url where your cakephp installation is going to reside -

Click on Save Changes. Now we are done with facebook application setup. Now it's time to dive into cakephp.

3) Install cakephp in your web-server document root to the location you just mentioned in canvas URL.

4) Create a configuration file facebook.php inside app/config folder for storing our facebook settings. The contents of the file are :-

<?php
$config['appId'] = 'APP ID';
$config['apiKey'] = 'API KEY';
$config['secret'] = 'APP SECRET';
$config['canvasPage'] = 'CANVAS PAGE URL';
?>

5) Download facebook php-sdk from github and store it in your app/vendors folder.

6) Now edit cake/libs/controller/apps_controller.php file with these contents :-

class AppController extends Controller {

var $components = array('Session');
var $facebook;

function beforeFilter() {
App::import('Vendor', 'facebook');
Configure::load('facebook');

$appId = Configure::read('appId');
$apiKey = Configure::read('apiKey');
$secret = Configure::read('secret');

$this->set('appId',$appId);

$this->facebook = $facebook = new Facebook(array(
'appId' => $appId,
'secret' => $secret,
'cookie' => true
));
$this->checkFbAuthorization();
$this->set('facebookId', $this->Session->read('facebookId'));
$this->set('id', $this->Session->read('id'));
}

function checkFbAuthorization(){
$session = $this->facebook->getSession();

if (!$session) {
$url = $this->facebook->getLoginUrl(array(
'req_perms' => 'publish_stream,offline_access,email,user_birthday,user_education_history,user_hometown,user_location,user_website,user_work_history,friends_work_history,friends_education_history',
'canvas' => 1,
'fbconnect' => 0,
'next' => '/users/home'
));
echo "<script type='text/javascript'>top.location.href = '$url';</script>";
} else {
try {
$me = $this->facebook->api('/me');
$facebookId = $this->Session->read('facebookId');
//if facebookId session variable is not set or a different user has logged in, check if user is present in our db or not
if(!isset($facebookId) || $facebookId != $me['id']){
$user = ClassRegistry::init('User')->updateFacebookUser($me);
$this->Session->write('id',$user['id']);
$this->Session->write('facebookId',$user['facebook_id']);
}
} catch (FacebookApiException $e) {
echo "Error:" . print_r($e, true);
}
}
}
}

The code is pretty straight forward, we import our facebook php-sdk and load facebook settings. We then initialize facebook object with our appId and secret. Next we check if our user has authorized our facebook app or not.

We try to fetch active facebook session using $session = $this->facebook->getSession(); , if no active session is found, we build our facebook login url. We ask the user for all extended permissions which we shall be needing in our application in the 'req_perms' parameter. For more information about Extended Permissions visit facebook documentation. Another important parameter is 'next' which is the url to which facebook should redirect our user after (s)he authorizes our application.

If the user has granted our application access permissions, we try to create a facebook user object using $me = $this->facebook->api('/me'); . Now $me would contain all information about our app user. While this should be enough for most simple applications, but for applications which require storing the user information in our database, we can do so with the next steps.

First we check if we already have a session variable - facebookId set. If no session variable is set or if a different user has logged in from the same machine, we check if our database to see if the user is already stored in our users table and if not save it in our database. The code should be simple and hence not documented here. The function returns the facebookId and our native userId which is set in session.

Now we are ready to take over with our own logic.

7) We shall fetch user's information in our home action of users controller:-

	function home(){
//fetch data
$this->set('userInfo' , $this->facebook->api('/me'));
}

8) A basic home.ctp for getting you started :-

<div class="container">
<div class="profile-pic">
<img src="https://graph.facebook.com/<?php echo $facebookId;?>/picture" />
</div>
<div class="user-details">
Welcome <?php echo $userInfo['name']; ?>
</div>
</div>

9) For automatically resizing the iframe, we will update our default layout file (cake/libs/view/layouts/default.ctp) and paste the following code just before the ending </body> tag :-

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo $appid?>', status: true, cookie: true, xfbml: true});
FB.Canvas.setAutoResize();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>

That's it, we are done with our cakephp based facebook application. This is a very basic application but should be enough to get you started. If you have any questions or suggestions for bettering the code, feel free to comment.

Installing ferret gem in Ubuntu running Rails version 2

The other day I was trying to install ferret gem for one of my projects on my Ubuntu system. For those who haven't heard of ferret, “Ferret is a high-performance, full-featured text search engine library written for Ruby.” It can be said to be the Ruby counterpart of zend search lucene library.
The documents said simply running a sudo apt-get install ferret should suffice. But to my frustration it was not so easy and being new to ruby, I had a tough time figuring out waht was going wrong. However thanks to Google and many helpfull developers, I finally managed to install ferret on my system. So I thought, it might be useull for someone else who gets struck with ferret.

First of all you will need to install ruby-dev package (in case you havn't done so already)

sudo apt-get install ruby1.8-dev

Thereafter you also need to install the libc6-dev package (offcourse in case you havn't done so already)

sudo apt-get install libc6-dev


Both done, now you should be able to install ferret without any issues

sudo apt-get install ferret

Hope this saves someone's time out there :)

Facebook Developer Garage New Delhi

Facebook Developer Garage New Delhi held on 29th of November, 2008 at Gurgaon was the first Facebook Developer conference in India organized by Tekriti. The other sponsors for the event were travelboutiqueonline.com and  sourceit.com. The event which was organized at the office premises of Tekriti started at around 11 A.M. was a great learning experience for many Facebook Developers and other Social Network application developers and website developers and designers in general.

 

The first spokesperson for the event was Kelly Winters from Facebook who gave a brief overview of Facebook, the Platform and Facebook Connect. It was amazing to know how Facebook expanded its user base from 90M to 120M within a span of just four months and how the user demographics has changed from 50% US and 50% international to 38% US and 62% international netizens, thus emphasizing Facebook's motive of globalization.

Page 1 of 2

  • «
  •  Start 
  •  Prev 
  •  1 
  •  2 
  •  Next 
  •  End 
  • »
 
You are here: Blogs
 

facebook application development social applications joomla commerce business developers portal community software websites webappniche twitter network management requirement install drupal project services experience networking internet custom platform developer networks portals engines wordpress shopping customization android client optimization mobile ecommerce myspace companies windows joominvite virtuemart ferret develop installation opensocial google customers promote library service cakephp questions server quality technologies projects solutions travel company hosting providers professional traffic analysis apache solution maintenance programming linkedin framework marketing products