Story about Blue E, iFramed Web Application, Wastage of 6 hours, Missed Lunch and what not!

Long story short, I was developing a Facebook page application which runs from inside a page tab. Such applications runs inside an iframe on Facebook Fanpage. Everything was going perfectly, until, we started checking it in IE!! The symptoms were simple, PHP Session is not working when user logs in. The application works perfectly in Safari, Opera, Chrome and Firefox and only the Elite of the Elites Internet Explorer is not accepting any cookie generated from the application.

I was hungry, almost lunch time – client was kicking my ass, so I couldn’t even think to grab a bite. I was VERY HUNGRY, clueless, lost and I was feeling like yelling at everything that walks in front of me. Oh boy, I was absolutely clueless about what was done wrong to satisfy this King Blue E.

After discussing my problem with Uncle G for over 5 hours, trial and error, do this and that, I realized that the problem is actually related to p3p privacy policy and how Internet Explorer deals with it. It doesn’t accept any cookie from any web application which is running inside an iframe within another application. Let me clarify

1. Web application A with domain a.com has an iFrame in one of its page
2. Inside that iFrame, it loads another web application B with domain b.com
3. Now Internet Explorer doesnt accept any cookie which generates by Web Application B, resulting a catastrophe, a real disaster.

The Solution: send the following header in your web application which runs inside the iFrame.

[sourcecode language=”php”]
<?php
header(‘P3P: CP="CAO PSA OUR"’);
header(‘P3P: CP="HONK"’);
?>
[/sourcecode]

and it fixes this weird behavior of Internet Explorer. Freaking p3p! wastage of 6 hours, remaining hungry, missing lunch, get kicked on the ass and what not.

I hate you Internet Explorer. You are the worst thing ever made in the history of web development. I sincerely hate you. And Microsoft, with all the Blue E fan-boys out there, GO TO HELL and let us live our life.

Morons!

Working with Facebook events using Graph API, JS-SDK and PHP-SDK – part 1

Graph API from Facebook is a very interesting project based on open graph protocol. Facebook is gradually setting Graph API as the standard and deprecating the use of their old REST based APIs. To start working with Graph API doesnt need an extensive knowledge on how Facebook API works but its always good to have a sound knowledge on that. Graph API uses oAuth based authentication mechanism and using the auth token, they can identify who is making the API calls. I have been working on Facebook events using Graph API for last couple of days and I will be sharing my experience in this series of two or three posts where I am going to cover the following topics

1. Authenticating a user
2. How to create a Facebook Event with picture
3. How to post on Events Wall
4. How to manage users
5. How PHP SDK can be a life saver in some cases 🙂

Authenticating a user
Its very important that you know how to authenticate an user against Facebook and ask for appropriate permissions to be granted. To work with public events in Facebook, you need to ask for “create_event” permission from your visitors. Otherwise, in case of private events, you need to be granted permission for “user_events” and “friend_events”. For now, lets consider that we will be creating public events and we will ask for only “create_event” permission.

Lets create a new application in Facebook which will point to our working url. The following screenshot will show you which informations are necessary to create such an app. Once you are done, save the API_KEY/APP_ID and SECRET_KEY safe in somewhere for later use.

Facebook App Properties
Facebook App Properties

Now you are done with creating a Facebook app, its time to code 🙂 The following codeblock will prompt any visitor to log in with Facebook and grant the application some permissions. We are using our JS-SDK. We are also saving the auth token. You will soon find out why that would be necessary.

[sourcecode language=”javascript”]
<!html>
<head>
<title>My Facebook Event App</title>
<script src=’http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js’></script>
</head>
<body>
Welcome to our New Facebook App <span id=’fbinfo’><fb:name uid=’loggedinuser’ useyou=’false’></fb:name></span>
<div id=’fb-root’></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type=’text/javascript’>

var fbuserid, fbtoken;
var appid = "224818724242243";
var loggedin = false;
$(document).ready(function() {
//loginFB();
});

FB.init({appId: appid, status: true, cookie: true, xfbml: true});
FB.Event.subscribe(‘auth.sessionChange’, function(response) {
if (response.session) {
var session = FB.getSession();
fbtoken = session.access_token;
fbuserid = session.uid;
}
});

FB.getLoginStatus(function(response) {
if (response.session) {
var session = FB.getSession();
fbtoken = session.access_token;
fbuserid = session.uid;
}
else{
loginFB();
}
});

function loginFB() {
FB.login(function(response) {
if (response.session) {
var session = FB.getSession();
fbtoken = session.access_token;
fbuserid = session.uid;
}
}, {perms:’create_event’});
}

function logoutFB() {
FB.logout(function(response) {
// user is now logged out
});
}

</script>
</body>
</html>
[/sourcecode]

Now when you visit your application url, for example http://ev.tekzon.net in our case, you will be prompted an authentication windows like this

Authentication Dialog
Authentication Dialog

So now users are successfully authenticated to our new Facebook application, lets move to the next part

Creating a Facebook event using JS-SDK
To create a Facebook event, we need to pass the following parameters to “/me/events” graph url.

  • name: Name of the event
  • start_time: Start time of the event in UNIX timestamp format, or in “mm/dd/yyyy H:i” format 🙂
  • end_time: End time of the event in UNIX timestamp format, or in “mm/dd/yyyy H:i” format 🙂
  • location: Location of the event, as a string
  • description: Description of the event
  • picture: Profile picture for the event, we can not use that with JS SDK.
  • privacy: either “OPEN” or “PRIVATE”, we will use “OPEN” in this example

So, here is a Javascript function which can create this event. In the following codeblock you will find a wrapper javasript function “createEvent()” to create this event and an example function to use that createEvent() function

[sourcecode language=”javascript”]
function createEvent(name, startTime, endTime, location, description) {
var eventData = {
"access_token": fbtoken,
"start_time" : startTime,
"end_time":endTime,
"location" : location,
"name" : name,
"description":description,
"privacy":"OPEN"
}
FB.api("/me/events",’post’,eventData,function(response){
if(response.id){
alert("We have successfully created a Facebook event with ID: "+response.id);
}
})
}

function createMyEvent(){
var name = "My Amazing Event";
var startTime = "10/29/2011 12:00 PM";
var endTime = "10/29/2011 06:00 PM";
var location = "Dhaka";
var description = "It will be freaking awesome";
createEvent(name, startTime,endTime, location, description);
}
[/sourcecode]

Now once you invoke this “createMyEvent()” function, it will show you the event id of your newly created event, if successful. Lets see how that would look like.

Successfully created a new event
Successfully created a new event

Ok, we can see that the event id of our newly created event is “253320941378247” – we can check it out in Facebook by going to http://facebook.com/events/253320941378247 – Meanwhile we can also check this same event using open graph protocol by going to http://graph.facebook.com/253320941378247

Ok, so now we know how to create a Facebook Event using JS-SDK and Graph API. But there is a major problem in creating a Faceboko event using JS-SDK and that is, you cannot attach any Profile Picture with this event. And you have to use a server side SDK (we will be using PHP-SDK in the following example) to do that. Lets see how can we create a Facebook event with a profile picture.

Creating a Facebook event with Profile Picture
We need to post the event parameters (use Ajax) to our server side script. Lets assume that the image file we are planning to use as the Profile Picture for our Facebook event resides in “/path/to/my/image.jpg”.

Here is a very important information for you and that is such an image’s minimum width MUST BE 100px – There is no documentation on that, and apparently I had to waste almost 4 hours to find what is the problem with my code. I just wish Facebook API documentation were better mentioning such things which may lead developers to waste huge time.

Ok, in the following codeblock, we will be using a new javascript function “createMyEventWithPHP()” which will post the event data to our server side php script event.php – Before that, download the PHP-SDK of Facebook from http://github.com/facebook/php-sdk, unzip and place in the same path where you are keeping this “events.php”

[sourcecode language=”javascript”]
function createEventWithPHP(name, startTime, endTime, location, description) {
var eventData = {
"access_token": fbtoken,
"start_time" : startTime,
"end_time":endTime,
"location" : location,
"name" : name,
"description":description,
"privacy":"OPEN"
}
$.post("/events.php",eventData,function(response){
if(response){
alert("We have successfully created a Facebook event with ID: "+response);
}
})
}
[/sourcecode]

And here is the source code of our events.php

[sourcecode language=”php”]
<?php
include_once("facebook-php-sdk/src/facebook.php");

define("FACEBOOOK_API_KEY","224818724242243");
define("FACEBOOK_SECRET_KEY","d57acde94xxxxc3d50a2x2yya9004476");

$name = $_POST[‘name’];
$token = $_POST[‘access_token’];
$startTime = $_POST[‘start_time’];
$endTime = $_POST[‘end_time’];
$location = $_POST[‘location’];
$description = $_POST[‘description’];

$fileName = "./me2.jpg"; //profile picture of the event

$fb = new Facebook(array(
‘appId’ => FACEBOOOK_API_KEY,
‘secret’ => FACEBOOK_SECRET_KEY,
‘cookie’ => false,
‘fileUpload’ => true // this is important !
));

$fb->setAccessToken($token);

$data = array("name"=>$name,
"access_token"=>$token,
"start_time"=>$startTime,
"end_time"=>$endTime,
"location"=>$location,
"description"=>$description,
basename($fileName) => ‘@’.$fileName
);
try{
$result = $fb->api("/me/events","post",$data);
$facebookEventId = $result[‘id’];
echo $facebookEventId;
}catch( Exception $e){
echo "0";
}
?>
[/sourcecode]

When we will invoke createEventWithPHP() javascript function, it will post all the event data to our PHP script. Then PHP script will create that event with Facebook PHP-SDK and print the newly created event id. Say for example, this newly created event id is 129312137169841, so we can go to http://facebook.com/events/129312137169841 and see how it looks with the profile picture

Facebook event with profile picture
Facebook event with profile picture

So thats for today, folks. I will be coming back with more of Facebook Events and Graph API in my next part. Stay Tuned.

Shameless Promotion 🙂 : By the way, if you are looking for a beautiful Admin Panel Theme for your PHP based projects/web-applications, you may want to check out Chameleon Circuit, which is developed by our Themio Team 🙂

Chameleon Circuit - Full Featured Admin Theme from Themio
Chameleon Circuit - Full Featured Admin Theme from Themio

jShutterBox plugin for some cool animation + content display, together

jShutterBox is a jQuery plugin I have developed two or three months ago. But I didnt release it because It was complex and users had to supply content for every animated images. Though it was ok with me that time, but last week I thought that I could make it even simpler to use. For example, just a &ltdiv> containing an image and an anchor can be converted into an animated content box 🙂

to use jShutterBox is simple. Just download the package from Box.net, include jshutterbox.js in your page, and run the following code 🙂

[sourcecode lang=”html”]
<div class="animated">
<img src="http://scripts.ofhas.in/jshutterbox/images/image2.jpg"/>
<a href="http://leevio.com" title="Leevio">Welcome to Leevio</a>
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".animated").jShutterBox({slide:"random"});
});
</script>
[/sourcecode]

You can configure other options, like “height”, “width”, “duration”, “borderWidth”, “borderColor”, “slide”. You can pass “random” as a value of “slide” to see the random animation. You can also specify any value of the “up,”down”,”left”,”right”,”up-left”,”up-right”,”down-left”,”down-right”for “slide” to see any specific animation too 🙂

You can view the demo at http://scripts.ofhas.in/jshutterbox/demo.html

I hope you will like it 🙂 – by the way, this plugin depends on jQuery Easing plugin.

Download jShutterBox from DropBox

Shameless Note 🙂 : By the way, if you are looking for a beautiful Admin Panel Theme for your PHP based projects/web-applications, you may want to check out Chameleon Circuit, which is developed by our Themio Team 🙂

Why I dont like Version 2 of Springloops

I am a longtime user of Springloops, since 2008/2007 for all my PHP applications. I love their plans and features so much that I had upgraded to a paid plan and using that for last 1.5 years. Now, they have introduced the plan2 which looks strange and funnier to me. Let me tell you why.

I am using the Flowerpot plan of their old version 1, which has the following features
Storage: 2GB
Number of Projects: 10
Servers per project: 3
Number of users: unlimited
Price: $9/mo

Now, the new Flowerpot plan in version 2 offers the following
Storage: 3GB
Number of Projects: 10
Servers per project: 1
Number of users: 4
Price: $15/mo

Springloops V2 has Tickets and Milestones feature in V2, included with all plans. But for that, you will have to pay an extra $6 than what you were paying currently. And the funny thing is that not only the number of active servers decreases from 3 to 1, but also number of users will be reduced from unlimited for AWFUL 4? You gotta be kidding me, eh?

One of the springloops employee ( Szymon Szczepankowski ) had emailed me why do I hate v2 of springloops and didnt opt-in to upgrade to v2 from my v1 plans, immediately after I twitted about my frustration. And this blog post is written just in reply of that.

Stay in V1, enjoy a beautiful springloops. Never upgrade 🙂

RSA Encrypting and Decrypting data with Zend_Crypt_Rsa Library

Public/private key based encryption is very popular because of the strength it sets in encryption, specially above 1024 bits. Now there are external library to encrypt data using RSA encryption like RSA in phpclasses.org – the fun is we were also using this library in one of our ZF based project. But last week I’ve found that there is a hidden gem in the Library/Zend/Crypt folder (Zend_Crypt_Rsa) which can do the same thing using openssl library. The bad thing is that there is no official documentation on how to use this library 🙁 Thats why I’ve decided to write a blog post to show you how to use Zend_Crypt_Rsa and encrypt your data with your public/private key and decrypt to get it back in original form.

Step 1: Create your RSA public/private key using ssh-keygen
[sourcecode lang=”bash”]
cd /path/to/keyfolder/
ssh-keygen -t RSA
[/sourcecode]

When it will ask for the path of the key file, input “./id_rsa” . It will then prompt for passphrase which actually works like a password and you cant retrieve your data if you forget this. So input something like “MySecretWord” – This will output something like this
[sourcecode lang=”bash”]
ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/hasinhayder/.ssh/id_rsa): ./id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in ./id_rsa.
Your public key has been saved in ./id_rsa.pub.
The key fingerprint is:
c8:dc:cd:a8:90:98:67:42:65:45:20:f8:58:39:74:66 [email protected]
The key’s randomart image is:
+–[ RSA 2048]—-+
| oo.E+o |
|. +B |
| +.. |
|…o + o + |
| + = + S o |
| + . . |
| . |
| |
| |
+—————–+
[/sourcecode]

After a while you will see that there are two files in the same directory named “id_rsa” and “id_rsa.pub”. First one is your private key and the second one is the public key.

Step 2: Encrypt data using your public key
As we have our RSA public and private keys in our hand, its time to start playing with these. We will now encrypt our data with our public key. In that way you can only decrypt it with your private key. I hope it is clear now that why we should encrypt using public key only? If now, let me clarify it a bit more. Your public key is “public” to the world. Now if you encrypt your data with your private key, anyone will be able to decrypt it with your public key – so that’s plain meaningless 🙂

[sourcecode lang=”php”]
public function encAction(){
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$zrsa =new Zend_Crypt_Rsa(array("passPhrase"=>"MySecretWord","pemPath"=>"/path/to/your/keyfolder/id_rsa")); //thats the path to the private key file
$string = "Yeah, this is my SECRET MESSAGE";
$enc = $zrsa->encrypt($string, $zrsa->getPublicKey(),Zend_Crypt_Rsa::BASE64);
echo "Secret Message: {$enc}";
}
[/sourcecode]

In the code above, we are generating output in BASE64 format, because that is readable to everyone 🙂 – after you execute this action in your browser, you can see something like the following (it will differ based on your key)

[sourcecode lang=”shell”]
jYMRM4jQedQgCdN7T9y6gNfLYZ49F+cSMz2tgLPsflQOE2XhVg98yvoQ/
PvUtBYGceEubYLuhYufgQE6VZpsOvvGcXt6WWE97HDGisQXXHhvnvQBzb
QQyF0WphCGH/0y2JviVb5zcQGhFIQ6oazztHonIxtdF4Fgaa0
M++jCymMSSI8vfOMUoL8s00fxVcqvJ7EVbYrFvUUMCH77HtBAYMziQotS
YddiMzb5AqEl8cN0N5Aao7dpOSzzumyuiRRoAA0NGtXnSlqQr5hAfdQ0V
vUKkqQHfd64Cfs+T8U9FmPTZUi7XE8jGgYFD0k4H9CJHl1EoVRNsqr3kt
4CNntQ==
[/sourcecode]

Thats your encrypted string in base64 format. Plain gibberish, eh? 🙂

Now its time to decrypt the ciphered text 🙂

Step 3: Decrypt the cipher
Well, now we have our encrypted string. Lets decrypt it

[sourcecode lang=”php”]
$dec = $zrsa->decrypt($enc, $zrsa->getPrivateKey(),Zend_Crypt_Rsa::BASE64);
echo $dec;
[/sourcecode]

Now it will output the original message “Yeah, this is my SECRET MESSAGE” 🙂

So here is everything together 🙂
[sourcecode lang=”php”]
public function encAction(){
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$zrsa =new Zend_Crypt_Rsa(array("passPhrase"=>"MySecretWord","pemPath"=>"/path/to/your/keyfolder/id_rsa")); //thats the path to the private key file
$string = "Yeah, this is my SECRET MESSAGE";
$enc = $zrsa->encrypt($string, $zrsa->getPublicKey(),Zend_Crypt_Rsa::BASE64);
echo "Secret Message: {$enc}";
echo "<hr/>";
$dec = $zrsa->decrypt($enc, $zrsa->getPrivateKey(),Zend_Crypt_Rsa::BASE64);
echo $dec;
}
[/sourcecode]

Hope you’ve enjoyed this article. I just wish that the documentation team of Zend Framework would have added this in the manual of Zend Framework for the rest of us 🙂

Shameless Note 🙂 : By the way, if you are looking for a beautiful Admin Panel Theme for your PHP based projects/web-applications, you may want to check out Chameleon Circuit, which is developed by our Themio Team 🙂

Planning to write a book on Titanium and Phonegap.

I have been planning to write a book on Appcelerator Titanium and Phonegap for last six months. This time I am not going to publish it through any publishing company. I want to do some crowd sourcing for a nice TOC and I will publish each of these chapters as PDF as soon they are done, for free.

I hope it will be cool to write a boon in open-source style, free as in beer, free as in freedom. Wish me good luck.

Project 365

Happy Couple (1/365)lonesome reader.... (2/365)Strafe the Transformer (3/365)Cactus (4/365)I need your help... (5/365)

Project 365, a set on Flickr.

I’ve started my Projec 365. I will take at least one shot everyday for next 365 days and upload them whenever I come online.

The rule is simple, each photo must be taken on that very same day.