bakedproject.com Blog Not just another WordPress weblog

9May/120

Use batch request to grab and save Facebook test user information

Facebook opened up their platform for application developers in 2007 and became one of the most accessed platforms via an API set. Over last few years functional modules were added both to the core API and developers tools offered by the social network giant. One of these amazing developer tool is the test users suite. Other than a few platform limitations and a few reported bugs, it works as expected. The interface for managing test users is not the greatest but it works.

Probably even 2 years ago application developers needed to create a plethora of fake accounts just check usual social sharing and other activities. Facebook deals with fake accounts very strictly now and building and/or testing applications using fake accounts is violation of platform terms.

A Facebook test user can only interact with other test users and application the user is added by the application administrator. A test user can not like a fan page - a lot of the time applications require users to like the fan page it is hosted on. Application developers can bypass the "like gate" for test users by simply matching the incoming user ID with the ones saved in the database as test user.. Also, while building the application, it is better to have data to manipulate. It is a capital mistake to theorize before you have data.

Here is an example using my own jQuery based AJAX call to communicate to Facebook graph API end point, but you can also use Facebook JavaScript SDK is FB.api method. I am using batch API call(or the batch request) to

  1. gather all test users for the application
  2. gather their public information and access token

Initially my script was calling for all test users and after calls the graph API to gather information. The second call was a batch request for all the users. This approach was inefficient for 2 reasosns

  1. making 2 graph API calls
  2. the batch request has a 50 call limit, this approach is useless for an application with more than 50 users. I could however, batch the batch request(will post shortly).

The latest fix for the script did all of it within 1 batch request. I simply specified a dependency  between my requests, my second request is dependent on my first one.

1
2
3
4
5
6
7
8
9
10
11
        args.batch.push({
            method                      : "GET",
            name                        : "get-users",
            relative_url                : "/"+app.id+"/accounts/test-users",
            omit_response_on_success    : false
        });
 
        args.batch.push({
            method        : "GET",
            relative_url  : "?ids={result=get-users:$.data.*.id}"
        });

Specifying omit_response_on_success : false is very important as otherwise the API returns a NULL value for the call. I need the first response as it has the access_token for the users.

Here is the link for the entire script.

I am using Mustache engine to generate and display MySQL statements to the browser window.

10Oct/110

WordPress URL update script

I always had trouble with the WordPress options table after moving WordPress sites between domains. I used to run the MySQL update commands directly from the query browser and very recently realized that it is not updating the serialized fields saved on the wp_options table.

Here (gist)is my approach to this problem. Implementation is pretty straight forward. The script can be accessed via CLI or browser.

10Mar/111

Adding ColorPicker jQuery plugin to a WordPress plugin admin panel

I was working on a WordPress plugin and needed to add a color picking ability for the admin panel. After doing some research I ended up with a few choices but decided to go with ColorPicker jQuery plugin. Installation required nothing extraordinary, just made changes to the CSS file. I like to keep my resources in separate folders so instead of having everything under images folder, I have them under "images/colorpicker" folder.

The WP plugin I am built has the ability to set default color for the color picker from the plugin settings page. The preset color would load during the colorpicker initial load. I selected "#faaf40" as the default color but started to have a really weird error! My form would not submit with the set color. On Safari I wasn't getting any feedback, but on Chrome I could see a message saying

Please shorten the text to 3 characters or less (you are currently using 17 characters).

Initially I did not even notice this, I thought something from the jQuery side of things were failing on form submit. I looked into the colorpicker code and realized the RGB/HSB text fields are limited to 3 characters. I figured out the conversion of the hex "#faaf40" was causing the issue. So I slightly modified the "fillHSBFields" assignment(starting on line 35)

1
2
3
4
5
6
fillHSBFields = function  (hsb, cal) {
	$(cal).data('colorpicker').fields
		.eq(4).val(Math.round(hsb.h)).end()
		.eq(5).val(Math.round(hsb.s)).end()
		.eq(6).val(Math.round(hsb.b)).end();
}

I simply rounded the calculated HSB values!

8Mar/110

Building Facebook application with Kohana 3.0.9

After hearing a lot of good things about Kohana I started to look into it. I did a little history reading and realized it used to be an active fork of CodeIgniter but has changed entirely since version 3, or KO3. At the time of writing this blog, I have spent about 12 hours studying the HMVC framework, so I might be wrong but like always am not in doubt.

As this is my very first encounter with this framework, I decided to follow a series of very helpful tutorials. Currently version 3.1.1.1 is the stable release, but I used the older 3.0.9. I do not see much difference other than how to handle view from the controller. Certainly I have to do more research on this!

Coming from using CodeIgniter for a long time my obvious interest was in the configuration side of things and I am very impressed with Kohana! The configuration was simple and less "variables" to configure.

As I was working with Facebook, my first concern was nice URLs! I had some serious trouble with this and wrote about my experience here. Kohana needed no configuration. Not only that, seems like the SEO friendly URL structure works very nicely with the GET!

Database configuration was ok, nothing special. Maybe it was a little confusing when I had to copy the config files from another location, “database.php” from “modules/database/config/” to “application/config/”.

For PHP syntax errors Kohana is giving me a 324 error and it is a little hard to debug. There might be some ways to enable proper error console.

The naming convention for controllers and models is very interesting, I can't tell if it is any better, but I had no issue so far. Using _ for finding proper location for classes is an old trick but it is done nicely here. Separating the class folder  from the views is a good point.

The before and after methods of the controller is amazing! My approach was using the constructor, but before method provides a good way of initializing my variables. I briefly looked into the template controller which seems to be very efficient. I am not using that controller however.

The most amazing thing about Kohana I think is the ease of  including 3rd party libraries! I created the "vendor/Facebook" folder under the application folder and just dropped the facebook.php file from the Facebook PHP SDK.  Here is the call to include the class

1
2
3
4
5
6
7
include Kohana::find_file('vendor/Facebook', 'facebook');
 
$this->facebook = new Facebook(array(
	'appId'  => $this->app_id,
	'secret' => $this->secret,
	'cookie' => true,
));

This sample application is good as fullwidth (720px) application and a smaller(520px) tab application. The difference is actually not on the CSS, but the way I am handling the permission dialog. From the application, I am redirecting the user to the Graph API authorization page. I could use the JavaScript API but the latter actually fires a browser pop-up window! I am using the JavaScript SDK for permission on the application installed in the tab however. Using this on application installed on a page tab gives a much smoother user experience.

Some interesting Facebook (new)issues I have discovered:

  1. If I am the admin to the page or developer for the application the permission mechanism doesnt work at all sometimes. Even after "liking" the page it is still showing that I have yet to "like" it.
  2. Almost the same thing happens with the permission. When I am the developer I have to keep providing the permission every time I am visiting the app.
  3. If I do not allow the application authorization, it keeps it to that state for a bit and do not let me fire the authorization window again. It does after a few minutes however!

Here is the zip file. The database file(fbkohana.sql) is also included here. I am using jQuery 1.4.4, which is also included in the "assets" folder. Please comment! Find my mistakes and do let me know.

Happy coding!

26Dec/102

iFrame on Facebook application tab

Using iFrame with Facebook is tricky. The FBML fb:iframe works only on application pages but not on the application tabs. Sometimes it is necessary to build an application that is only installable on a profile tab so it is running from within the fan page instead of a stand alone.

There are 2 main advantages of using an iFrame

  1. The CSS is not cached, so debugging and deployment is much easier
  2. Use of jQuery is POSSIBLE!

Facebook parser will generate an error in case of direct implementation of the iframe FBML on a tab. However there is a way to add the iFrame element via FBJS event. Facebook requires user interaction before any automated method execution on a profile tab. The iFrame that loads the content needs a clickable element, preferably an image of the actual frame output. When the user clicks on it, the frame loads with all it's glory!

1
2
3
4
5
6
<script type="text/javascript"><!--mce:0--></script>
<h2>TEST iFRAME</h2>
<div id="iframe_container">
	<a style="cursor: pointer;" onclick="iframe_container.setInnerFBML(iframe_link);">
		click to load iFrame<!-- the clickable element! -->
	</a></div>

A few important points about this snippet

  1. It is FBML, so this code does not have a body tag.
  2. The JavaScript code on top is not necessary for the profile tab, but if user is viewing the actual application, this will automatically load the iframe component, else they have to click on the clickable element.
  3. It is simply loading the fb:js-string which holds the fb:iframe implementation, inside the ifrmae_container.

29Oct/100

Baked json_encode… write your own for PHP 5.1.x

PHP's json_encode is a very handy function for encoding any associative array to JSON. This function comes bundled with PHP 5.2.x. I been working with a client who has PHP 5.1.6. I would install all the necessary tools, but client was not very willing to make changes and I been wanting to write my own JSON encoder for the longest time!

So here is my baked approach...

1
2
3
4
5
6
7
8
9
function my_json_encode($json_array) {
 $json = "[";
 for($i=0; $i1) $json .= ',';
   $json .= '"'.addslashes($key).'":"'.addslashes($row[$key]).'"';
  $i++;
 }
 $json .= "}";
 return $json;
}// end of my_json_encode

and the call

1
2
3
4
5
while($row = mysql_fetch_assoc($result)) {
 $json_row[] = $row;
} 
 
echo my_json_encode($json_row);

15Sep/1010

User ID from Facebook application installed on profile tab

Facebook platform does not give direct access to the user ID through a (Ajax or http form)post from an application installed on a profile tab(mainly fan page, Facebook removing user's profile tab soon). So application installed on a profile tab can not record user activity, can not get the user to permit the application either.

But, using the new OAuth 2.0 for canvas pages, it is pretty easy and efficient. This feature could be activated from the applications advanced settings. Once activated the platform sends only one POST variable called signed_request. I found the following code on the developer's forum. This code can re-generate the viewing user ID. If the ID is not present, the user never provided(added) the application!

function parse_signed_request($signed_request, $secret) {
 list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
 
 // decode the data
 $sig = $this->base64_url_decode($encoded_sig);
 $data = json_decode($this->base64_url_decode($payload), true);
 
 if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
  error_log('Unknown algorithm. Expected HMAC-SHA256');
  return null;
 }
 
 // check sig
 $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
 if ($sig !== $expected_sig) {
  error_log('Bad Signed JSON signature!');
  return null;
 }
 
 return $data;
}
 
function base64_url_decode($input) {
 return base64_decode(strtr($input, '-_', '+/'));
}

5Aug/100

CodeIgniter – organizing controllers into sub-folders a wild card _remap function

For a "hello world" project it is really not important, but building a CMS using the most amazing framework requires an organized "controllers" set. Implementing sub-folder for organizing controllers is probably the most efficient way to do this.

Here is an example...

I am writing a new "users" controller. The controller has following methods
login
logout
register
profile

So, instead of writing all these methods in the "users.php" controller file, I am going to create a "users" folder and create corresponding php files those methods. So my "users" folder directory tree going to look something like this
users
->login.php
->logout.php
->register.php
->profile.php

My controllers usually have "index" method, which is the default method for the controller. The URL 'http://yourdomain.com/users/profile' will reach the 'index' method. By default that is how the most amazing framework works. But, the URL 'http://yourdomain.com/users/profile/' will cause a 404 error! If we have a method called "view", 'http://yourdomain.com/users/profile/view/' is going to work, but for some reason, we may absolutely need the URL to be 'http://yourdomain.com/users/profile/'.

This is doable via the awesome "_remap" function!

For 'wild card' function matching,

function _remap($method) {
 if(method_exists ($this, $method)) {
  $this->$method();
  } else {
  $this->index();
 }
}

13Jul/101

Codeigniter form validation “French” messages

Here are all the CodeIgniter form validation messages in French. Well I do not speak the language so I turned to the language expert! I am not sure about the grammar, so info for a better solution would be appreciated.


$lang['required'] = "Le champ %s est nècessaire.";
$lang['isset'] = "Le champ %s doit avoir une valeur.";
$lang['valid_email'] = "Le champ %s doit contenir une adresse email valide.";
$lang['valid_emails'] = "Le champ %s doit contenir toutes les adresses e-mail valide.";
$lang['valid_url'] = "Le champ %s doit contenir une URL valide.";
$lang['valid_ip'] = "Le champ %s doit contenir une adresse IP valide.";
$lang['min_length'] = "Le champ %s doit Ítre au moins %s caractères de longueur.";
$lang['max_length'] = "Le champ %s ne peut pas dÈpasser %s caractères.";
$lang['exact_length'] = "Le champ %s doit Ítre exactement de %s caractères.";
$lang['alpha'] = "Le champ %s ne peut contenir que des caractères alphabÈtiques.";
$lang['alpha_numeric'] = "Le champ %s ne peut contenir que des caractères alpha-numÈriques.";
$lang['alpha_dash'] = "Le champ %s ne peut contenir que des caractères alphanumÈriques, tirets et les tirets.";
$lang['numeric'] = "Le champ %s doit contenir uniquement des nombres.";
$lang['is_numeric'] = "Le champ %s ne doit contenir que des caractères numÈriques.";
$lang['integer'] = "Le champ %s doit contenir un nombre entier.";
$lang['matches'] = "Le champ %s ne correspond pas au champ %s.";
$lang['is_natural'] = "Le champ %s ne doit contenir que des nombres positifs.";
$lang['is_natural_no_zero'] = "Le champ %s doit contenir un nombre supÈrieur ‡ zÈro.";

6Jul/100

BUILDING FACEBOOK AND FACEBOOK CONNECT APPLICATION WITH CODEIGNITER – Mixing segment-based URL with query strings (GET)

After Facebook user "allows" the application, Facebook redirects users to the application canvas (or the calling controller) URL with Facebook generated authentication code.

For example, controller "invite", requires (Facebook) user authentication. The controller probably going to have something like this

$CI->load->library('Facebook'); // Facebook API library
$CI->facebook = new Facebook($this->fb_api_key, $this->fb_secret);//initialize facebook class
$this->fb_client = $CI->facebook->api_client;
$this->fb_user_id = $CI->facebook->require_login(); // get the FB user id

After the "require_login" call, Facebook will ask for the user to provide permission, and if the user allows the app to access user's personal data, facebook will redirect the user to

http://apps.facebook.com/facebook-application-name/invite/?installed=1&session={%22session_key%22:%222.besQb6tf33wpIJ7hQTnx_Q__.3600.1278370800-
1678407106%22,%22uid%22:1678407106,%22expires%22:1278370800,%22se
cret%22:%22KxSIVxKfjafJeJRdRa40aA__%22,%22sig%22:%2238a96471694e9c63
6192f93bfb2333cb%22}

By default, CodeIgniter would throw a 404 cause it is designed to work only with segmented URI. But it is absolutely impossible to build a Facebook application with such setup. Well, saying absolutely impossible is quite the thing,in fact it is. Application with regular setup may work but chances are, would break very frequently as Facebook keeps sending session variable(I saw entire file binary data once) over GET.

So we need to customize CodeIgniter to make sure the (most amazing) framework can accept such mixed input.

Step 1: Open application/config.php file, and search for $config['uri_protocol'] and change the value to "PATH_INFO". So that line would look like
$config['uri_protocol'] = "PATH_INFO";

Step 2: In same application/config.php file, search for $config['enable_query_strings'] and change the value to "TRUE". So that line would look like
$config['enable_query_strings'] = "TRUE";

Step 3: Now, in thesame application/config.php file, search for $config['permitted_uri_chars'] and change the value to a suitable combination.

"a-z 0-9~%.:_\-+?=!,${}"\'[]&" works really great. The session variable is technically a JSON dump from Facebook, so this combination has a few unusual characters.

So now you can access both the segmented URI variables and GET variables via "$this->uri->uri_to_assoc(n)" and "$_GET" respectively.

VERY IMPORTANT: Above mod(I could say "customization" or something else!!!) would make the (most amazing) framework vulnerable to SQL injection and many other unethical injections, so take necessary steps to secure it!