Importing Contacts from Google Mail using OAuth

This is my second post in the fetch contacts from email account series. In this post, we are going to fetch contacts from a Google account. This isn’t a detailed tutorial, but a quick 2 minute how-to.

$this->config->item(‘google_return_url’) is the url of the page to which user is returned after a login attempt.

1. Add the following code where the user has to select Google Mail to import contacts.

<a href="<?php echo $this->config->item('google_return_url').'?data=abc'; ?>&scope=">Fetch Google Contacts</a>

2. Include these 2 functions in your PHP code.
function make_api_call($url, $token)
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $curlheader[0] = sprintf("Authorization: AuthSub token=\"%s\"/n", $token);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheader);
    $output = curl_exec($ch);
    return $output;
function get_session_token($onetimetoken)
    $output = make_api_call("", $onetimetoken);
    if (preg_match("/Token=(.*)/", $output, $matches))
        $sessiontoken = $matches[1];
    } else {
        echo "Error authenticating with Google.";
    return $sessiontoken;

3. Add the following code to the return url file.

$sessiontoken = get_session_token($_GET['token']);
$contacts = make_api_call("", $sessiontoken);
$contacts = json_decode($contacts, TRUE);
foreach ($contacts['feed']['entry'] as $contact)
    $emails[] = $contact['gd$email'][0]['address'];
//$emails array has the email addresses of all the contacts.

4. That’s it folks. It is that simple.

Further reading :

Importing Contacts from Yahoo Mail using OAuth

Importing contacts from mail accounts using OAuth is a long solved problem which doesn’t have a good implementation. I googled and googled for a good library which imports contacts from Yahoo/GMail/Hotmail. Finally, I was forced to create one by myself. Here are the instructions on how to get it up and running for Yahoo Mail in your server in 2 mins.

1. You need a Yahoo API Key to fetch contacts from Yahoo. Proceed to Yahoo Developer Dashboard and create a key.

Application URL in the createKey page is the URL to which you will be redirected to after a successful/failed login attempt.
Application Domain is be your domain name.
Choose “This app requires access to private user data.” in the Access Scope and under the options which appear below that, select “Read” access for “Yahoo! Contacts”.
Store the API Key, Shared Secret and Application ID carefully.

2. Download Yahoo Social SDK for PHP from

$this->config->item(‘yahoo_consumerkey’) is your Yahoo API Key.
$this->config->item(‘yahoo_consumersecret’) is your Yahoo Shared Secret.
$this->config->item(‘yahoo_applicationurl’) is your Application URL you provided in Step 1.
$this->config->item(‘yahoo_applicationid’) is your Yahoo Application ID.

3. Add the following code where the user has to select Yahoo Mail

<a href="<?php echo YahooSession::createAuthorizationUrl($this->config->item('yahoo_consumerkey'), $this->config->item('yahoo_consumersecret'), $this->config->item('yahoo_applicationurl').'?data=abc'); ?>">Fetch Yahoo Contacts</a>

You may remove the ?data=abc if you don’t want to pass any data to Yahoo. Anything you pass here can retrieved back at Application URL as GET parameters.

4. Include the required files from the opensocial SDK library and then add the following snippet to the Application URL you provided in Step 1.

if (YahooSession::hasSession($this->config->item('yahoo_consumerkey'), $this->config->item('yahoo_consumersecret'), $this->config->item('yahoo_applicationid')))
    $session = YahooSession::requireSession($this->config->item('yahoo_consumerkey'), $this->config->item('yahoo_consumersecret'), $this->config->item('yahoo_applicationid'));
    $user = $session->getSessionedUser();
    $contacts = $user->getContacts(0, 1000);
    foreach ($contacts->contacts->contact as $contact)
        foreach ($contact->fields as $field)
            if ($field->type == "email")
                $emails[] = $field->value;
    //$_GET['data'] will be equal to "abc" at this page.
//$emails array has the email addresses of all the contacts.

5. That’s it folks. It is that simple.

Further reading :

Security settings for a LAMP Server : Iptables

Security is the major concern for anyone hosting a website on the internet. These are the preliminary security settings to be performed to protect your server.

Our server stack is LAMP. Hence iptables as the firewall is the most natural choice. The requirements are like

1. Block everything except Ping, SSH, Apache, and SSL.
2. Enabled SSH only from the selected IP addresses.

The following script takes care of all iptables settings. (Idea copied from here)

Note: Please enter the command one by one. Make sure you replace IP1.IP2.IP3.IP4 with your own IP address.

# Establish a clean slate
iptables -P INPUT ACCEPT
iptables -F # Flush all rules
iptables -X # Delete all chains
# Disable routing. Drop packets if they reach the end of the chain.
iptables -P FORWARD DROP
# Drop all packets with a bad state
iptables -A INPUT -m state --state INVALID -j DROP
# Accept any packets that have something to do with ones we've sent on outbound
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# Accept any packets coming or going on localhost (this can be very important)
iptables -A INPUT -i lo -j ACCEPT
# Accept ICMP
iptables -A INPUT -p icmp -j ACCEPT
# Allow ssh
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow httpd
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
# Allow mysql
iptables -A INPUT -p tcp --dport 3306 -j ACCEPT
# Allow SSL
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Block all other traffic
iptables -A INPUT -j DROP

I guess the above script should take care of the basic security issues. Hope it helps.

Apache Fix : NameVirtualHost *:80 has no VirtualHosts

I get this error every time I install apache web-server in an ubuntu machine. We use LAMP stack at Interviewstreet and this error was nagging me all the this while.

The error message shows up something like this.

root@interviewstreet:~# /etc/init.d/apache2 restart
* Restarting web server apache2 apache2: Could not reliably determine the server's fully qualified domain name, using for ServerName
[warn] NameVirtualHost *:80 has no VirtualHosts ... waiting apache2: Could not reliably determine the server's fully qualified domain name, using for ServerName
[warn] NameVirtualHost *:80 has no VirtualHosts [ OK ]

After some googling, I found the actual solution at

The reason why this happens is because of having NameVirtualHost in more than one place. In this case, it occurs at 2 different files, sites-available/default and ports.conf.

So, this is how we fixed this issue.

1. Removed the line “NameVirtualHost *” from sites-available/default.
2. Changed “NamedVirtualHost *:80” to “NamedVirtualHost *” in ports.conf

Done. That fixes the problem. Now apache restart shows something like this.

root@interviewstreet:/etc/apache2/sites-available# /etc/init.d/apache2 restart
* Restarting web server apache2 ... waiting [ OK ]

This is sweet :)

The other day, I was poking a few sites on the web lazily, looking how they’ve designed the CSS, HTML etc blah blah blah..

I take a quick look at the tumblr source code and find this in the header 🙂


3 interesting Codeigniter tips

Finally we’ve started doing all our development using a framework, Codeigniter. It has a small learning curve, simple to use and very flexible with how much you want to adhere to MVC pattern. You have the control to code every damn thing in the controller or have proper models and views to help the controller.

Three nice tips/tricks I found in Codeigniter after googling a lot.

1. How to print the last query executed by codeigniter when using active record?

The following function returns the sql query executed. You may need this for debugging purposes.


2. How to add a function in controller which can’t be accessed through URL?

Usually, if you add a function func in controller c, then it can be accessed by /c/func. If you want to code a function, which you don’t want people to access, then you need to name the function _func(). If you have a function named with a _ in front of it, then you can’t access it through the URL.

3. How to store the string generated by a view in a variable?

When you load a view using $this->load->view(‘view.php’, $data); the view gets rendered in the browser. But if you want to store the HTML string generated by the view in a variable, then add a third parameter TRUE, which will return the generated string.

The code will be
$output = $this->load->view("view.php", $data, TRUE);

Photolog 7…

Sambar Rice

Disclaimer :

  1. I didn’t cook this.
  2. This samba rice tastes like heaven!!!
  3. According to the person who made this, I’ve have been friend with a great person, coz she can cook this.
  4. This is called awesomeness 😉

Social Life Limits

Social Networking sites like Facebook, Twitter, and Mail services like GMail, Yahoo Mail and Hotmail play a big role in our Internet Life.

What is the limits these sites impose on us? By how much can we push our internet life using these sites?


1. The maximum limit on the number of friends you can have on Facebook is 5,000.
2. A status update in Facebook is limited to 420 characters (including spaces).


1. A status update in Twitter is limited to 140 characters (of course, everyone knows this)
2. The maximum limit on the number of followers you can add in twitter is 1,000 per day.
3. The maximum limit on the total number of followers is 2,000 or 110% of your follower count, whichever is higher.


1. The maximum limit on the number of contacts you can have in Google is 10,000.
2. The maximum limit on the number of emails you can send from Gmail is 500 recipients per day for the Gmail web interface, or 100 recipients per day if you are using an email client software.
3. The maximum limit of the attachment size in Google Mail/Talk is 25MB.
4. There’s no limit to the number of people you can chat with in a group chat.


1. The maximum limit on the number of contacts you can have in Yahoo Messenger is 1,000.
2. The maximum limit on the number of emails you can send from Yahoo Mail is 100 recipients per hour.
3. A personal status message on Yahoo is restricted to 250 characters.


1. The maximum limit on the number of emails you can send from Hotmail is 100 recipients per day.
2. A personal status message on Windows Live Messenger is restricted to 128 characters.


1. The maximum limit on the number of participants you can have in a conference call in Skype is 25.
2. The maximum limit on the number of participants you can have in a public chat in Skype is 150.

Note: Of course, the numbers are bound to change. Please update in the comments if you want to add anything.

Advanced Bash Scripting – Part 1

Shell Script

Hello everyone, I’m planning to solve the problems in the Advanced Bash-Scripting Guide, say like one problem per week. Why am I doing this?

1. The problems there are very interesting.
2. Working in windows all the time, I feel I’m losing my shell scripting abilities. This will keep me updated.

The problem we are going to solve this week is “Testing Passwords”. The problem statement is as follows.

Write a script to check and validate passwords. The object is to flag “weak” or easily guessed password candidates.
A trial password will be input to the script as a command-line parameter. To be considered acceptable, a password must meet the following minimum qualifications:

1. Minimum length of 8 characters
2. Must contain at least one numeric character
3. Must contain at least one of the following non-alphabetic characters: @, #, $, %, &, *, +, -, =

Do a dictionary check on every sequence of at least four consecutive alphabetic characters in the password under test. This will eliminate passwords containing embedded “words” found in a standard dictionary.
Enable the script to check all the passwords on your system. These probably do not reside in /etc/passwd.

The command I’m planning to use for this is grep, with a few for loop constructs and string operations.

Let’s check the constraints one by one.

#Minimum length of 8 characters
if [ ${#password} -lt 8 ]
  echo "$password: $weakString"

#Must contain at least one numeric character
if [ `echo $password | grep -c -E "[0-9]+"` -eq 0 ]
  echo "$password: $weakString"

#Must contain at least one of the following non-alphabetic characters: @, #, $, %, &, *, +, -, =
if [ `echo $password | grep -c -E "[@#$%&*=+-]+"` -eq 0 ]
  echo "$password: $weakString"

#Do a dictionary check on every sequence of at least four consecutive alphabetic characters in the password under test. This will eliminate passwords containing embedded "words" found in a standard dictionary.
for((i=4;i<=${#password};i++)) do   for((j=0;j<=${#password}-$i;j++))   do     if [ `grep -c -E "^${password:$j:$i}$" dict.txt` -gt 0 ]     then       echo "$password: $weakString"       return     fi   done done

That's about it, we have checked all the constraints. Now, we will combine all the checks in one function and then we will pass all the command line parameters to this function one by one.

You can take a look at the final script here.

Can you make it any better or reduce the code size? Feel free to add it in the comments section.

Best Google Talk Status Awards :) :) :)

Trophy I’ve been watching (and storing) lots and lots of useful, fun and interesting Google Talk status messages for the last few months. It’s short, informative and the main reason why I never logout of Google Talk. So I was wondering what I might do IF I was given the responsibility to pick the top status messages like a film-fare festival and give away awards to the best ones.. So here we go…

We will begin the show with Brilliant Questions. There were way too many contenders for this category. It was very difficult to pick the best one. First, let’s take a look at the final 5 contenders who made it.

1. Abilash Prabhu - Why does Superman stop bullets with his chest, but ducks when you throw a revolver at him?
2. Dhruvkaran Meta - If electricity comes from electrons, does morality come from morons?
3. Akshay Kumar - I was the best man at the wedding. If I'm the best man, why is she marrying him?
4. JV - Why do couples hold hands during their wedding? It’s a formality just like two boxers shaking hands before the fight begins!
5. Nitin Isloorkar - How do you see yourself five years down the line?" "If I had foresight, I wouldn't be here now, would I?

And the Best Brilliant Question Award goes to Dhruv for his electrons and morons question. What an idea sar ji! 🙂

Next, we move on to Frustration category. Status message is first the place where people vent out their frustrations and we got ample messages to justify that.

1. Nitin Isloorkar - After Monday and Tuesday even calendar says W T F
2. Krithika Ravichandran - labs are like black holes.. once can never get out..
3. Lavanya Tejaswy - I want to see a ghost, real one!! *bored* with normal things.
4. Taggy - For want of a logo a night was lost. #photoshop

And the Best Frust status message goes to Krithika. It’s simple, but true. Happens to all of us all the time.

Next we have Funny Quotes status messages here.

1. Saurabh Gupta - Friendship b/w gals - A girl came home late, told dad she was at frnd's place.. Dad called 10 friends but all say she wasn't there... Friendship b/w boys - A boy didn't come home one night n told dad he was at frnd's flat... Dad called 10 of his frnds. 6 confirmed he had slept at their place... and 4 told he's still there.. ;)
2. Harishankaran - "I love Facebook. It's the only place I can talk to a wall and not look like an idiot"
3. PK- "Chuck Norris can parse HTML with regex"
4. Akshay Kumar - "Don't drink and drive. You might hit a bump and spill your drink."
5. Manish - 2b or not 2b is a decision you have to take when you enter 2nd grade

And the Best Funny Quote award goes to Akshay. The concern for the few drops of drink he might spill is mind blowing. 🙂

Next, we will pick the best Interesting Links. Here again, we got hundreds of nominations at the first step. After filtering and filtering, we got the final 4

1. Ajitha - Lol......U gota be Kidding me!!!!!
2. Arun - Please don't click on this link
3. Interviewstreet - Resume vs CV - What's the difference?
4. Indus Khaitan - Who is an entrepreneur?

And the award goes to Indus Khaitan. Excellent presentation with awesome images. Congrats 🙂

Next we will pick the best from Cricket. With an excellent 200 from Sachin, nothing else made to the top.

1. Abilash Prabhu - Reducing the number of atheists in India since 1989 - Sachin Tendulkar!
2. Swetha - Cricket. Sachin. Happiness. One guy- the ability to tug at the heartstrings of a billion. Divine!
3. Subbu - my only prospective achievement in life: when sachin scored a double century, i tweeted about it. #sachinisgod

And Abilash get’s the award. A fitting tribute to our little master blaster.

Now, we will pick the best from the Inspirational Quote

1. Sankara - To move quickly, go alone. To move far, go together." African Proverb
2. Poorna - Don't ever let somebody tell you... You can't do something. People can't do somethin' themselves, they wanna tell you you can't do it. If you want somethin', go get it. Period.
3. Sundarrajan : I look at my life as a seed investor.. I give seed capital for my interests.. knowing well that the odds are 1:10 for success.. but I am willing to do it.. coz.. that one in ten will become my passion

The best Inspirational Quote award goes to Poorna. I simply love that quote. In fact, I started storing status messages after I seeing that.

Finally, a few other special mentions in various other categories.

Madhu - I really don get y Mr.Cameroon waited so long.. I mean optical fibers were discovered a loooong time ago!!

Funny Quote
Lavanya Tejaswy - The fascination of shooting as a sport depends almost wholly on whether you are at the right or wrong end of the gun. P. G. Wodehouse

Job Offers
Manas Garg - Want to work for MS? Ping me.

Punch Dialogue
Karnan - I am not HANDSOME guy, but i can give my HAND to SOME guy who needs my help - ABDUL KALAM.

Personal Damage
Ajitha - Hari and his friends = Losers!!!!!
Doniv - You are a goat, why are you a goat ? Because you shout maee...

Bodhayan - Spider Annual Report 2008-09.. :) :)

Want to add more? Add them in the comments here. 🙂 Keep them coming.. 🙂