Friday, August 24, 2012

Turning your server into a proxy using Squid



Squid is a fully-featured HTTP/1.0 proxy. Squid offers a rich access control, authorization and logging environment to develop web proxy and content serving applications.

 

 

 

Installing Squid

To install squid on CentOS, use yum install command (you must be logged in as root (If you're not familiar with yum and root access, you might want to check the following topic first: 15 most used linux commands and how to use them)):
yum install squid



If you can't install squid using yum, you can download it from http://www1.dk.squid-cache.org/Versions/ using wget command (how to use wget)
Next you have to extract the compressed archive file and change the working directory to the squid directory:
tar -xvzf squid-*-src.tar.gz
cd squid -*

Now enter the following commands in order to configure, compile and install squid
./configure
make
make install


This by default, will install it in "/usr/local/squid".
Type ./configure --help to view all available options.


Configuring Squid

In order to configure squid, we open the squid configuration file located in /etc/squid
vi /etc/squid/squid.conf



By default, squid will listen on port 3128, to make it listen on port 3128, 8080 and port 2083, we add the following:
http_port 3128
http_port 2083
http_port 8080

or if you want to define an IP to listen to instead of all IPs, replace YOUR_SERVER_IP by your server IP:
http_port YOUR_SERVER_IP:3128
http_port YOUR_SERVER_IP:2083
http_port YOUR_SERVER_IP:8080



By default all the http access are denied. The ACL rules must be modified to allow access only to trusted users or all users. This is important if you don't want everyone to use your proxy server and eventually consume resources.

To allow everyone to access and use the proxy server, append the following line to the configuration file:
http_access allow all
(make sure to remove the line http_access deny all for the above to work)


To allow a range of IPs instead of allowing everyone, add the following command
acl my_ranged_ips src 1.2.3.1-1.2.3.254/24
http_access allow my_ranged_ips
http_access deny all

Make sure that http_access deny all is the last statement, this is because the ACLs are checked from top to bottom. Users with IPs in the range of my_ranged_ips will be allowed to use the server, anyone else falls through to the "deny all" and gets a failure message.

Once the configurations are done, restart squid:
service squid restart

To stop squid
service squid stop

To start squid
service squid start


Any comments, questions or suggestions? Post below!


Wednesday, August 22, 2012

Facebook Registration Plugin (With Custom Fields and Examples)

Facebook Registration Plugin (With Custom Fields and Examples)

In this post, I will show you how to implement facebook registration plugin, and I will create some examples, with custom fields, with both the iframe version and XFBML.

You can check the examples directly in here: Facebook Registration Plugin Examples

Scroll down for the entire source code.

The facebook social plugin can be used for users with a facebook account, or users without a facebook account.
If the user does not have a facebook account, or if the user is not logged in to their facebook account, the below subscription form will be displayed.
Facebook Registration Plugin

If the user has a facebook account and is logged in, the registration form will be pre-filled to save the user time. This is very useful to register the user quickly with one mouse click.
Facebook Registration Plugin Pre-filled

Sometimes you might only want users with a facebook account to be able to register on your site. This can be specified with a parameter that will be explained later on. The following registration form will be displayed if the user is not logged in to facebook.
Facebook Registration Plugin Force Login


I will not go in the already explained details on facebook. In this post, I will assume that you have already read this: http://developers.facebook.com/docs/plugins/registration/

For this plugin to work, you will need a facebook app id and a facebook app secret, if you havne't created a facebook app yet, I suggest you read this tutorial first to create an app: Facebook App Tutorial - The Basics

You will also need to set the redirect URI, in my case, I'm going to set it to the same file location of the subscription form in order to display the output.

 

 

Facebook registration plugin (iframe) without custom fields:

In the first example, I'm going to build the registration plugin using iframe and without any custom fields. Simply the code will be as follows:

<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>Without Custom Fields</h2>
<iframe src="http://www.facebook.com/plugins/registration?
         client_id=<?php echo $API_KEY; ?>&
         redirect_uri=<?php echo $redirect_URI; ?>&
         fb_only=false&
         fields=name,birthday,gender,location,email"
    scrolling="auto"
    frameborder="no"
    style="border:none"
    allowTransparency="true"
    width="530"
    height="330"
>
</iframe>

<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

    }
}
?>


<?php
function parse_signed_request($signed_request, $secret)
{
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

    // decode the data
    $sig = base64_url_decode($encoded_sig);
    $data = json_decode(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, '-_', '+/'));
}
?>



Facebook registration plugin (iframe) with custom fields:

In this example, I'm going to build the registration plugin using iframe and with custom fields
To use custom fields, we will need to use JSON arrays 
The below example is an array from facebook tutorial, you can define checkbox, date, select, captcha to be filled...

[
 {'name':'name'},
 {'name':'email'},
 {'name':'location'},
 {'name':'gender'},
 {'name':'birthday'},
 {'name':'password'},
 {'name':'like',       'description':'Do you like this plugin?', 'type':'checkbox',  'default':'checked'},
 {'name':'phone',      'description':'Phone Number',             'type':'text'},
 {'name':'anniversary','description':'Anniversary',              'type':'date'},
 {'name':'captain',    'description':'Best Captain',             'type':'select',    'options':{'P':'Jean-Luc Picard','K':'James T. Kirk'}},
 {'name':'force',      'description':'Which side?',              'type':'select',    'options':{'jedi':'Jedi','sith':'Sith'}, 'default':'sith'},
 {'name':'live',       'description':'Best Place to Live',       'type':'typeahead', 'categories':['city','country','state_province']},
 {'name':'captcha'}
]

The code will be as follows:

<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>With Custom Fields</h2>
<iframe src="http://www.facebook.com/plugins/registration?
         client_id=<?php echo $API_KEY; ?>&
         redirect_uri=<?php echo $redirect_URI; ?>&
         fb_only=false&
         fields=[
    {'name':'name'},
    {'name':'birthday'},
    {'name':'gender'},
    {'name':'location'},
    {'name':'email'},
    {'name':'favoriteFood', 'description':'Favorite Food', 'type':'select', 'options':{'0':'Pizza','1':'Burger','2':'Hot Dog','3':'Tuna'}},
    {'name':'graduated', 'description':'Graduation Date', 'type':'date'},
]"
    scrolling="auto"
    frameborder="no"
    style="border:none"
    allowTransparency="true"
    width="530"
    height="400"
>
</iframe>
<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //custom fields
        $favoriteFood = $response['registration']['favoriteFood'];
        $graduated = $response['registration']['graduated'];


        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

        //print custom fields
        echo '<h3>Custom Fields Values</h3>';
        echo 'Favorite Food: ' . $favoriteFood . '<br />';
        echo 'Graduated: ' . $graduated . '<br />';
    }
}
?>


<?php
function parse_signed_request($signed_request, $secret)
{
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

    // decode the data
    $sig = base64_url_decode($encoded_sig);
    $data = json_decode(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, '-_', '+/'));
}
?>

Facebook registration plugin (iframe) without custom fields and only for facebook users:

Sometimes you might only want to allow facebook users to register on your website, you can use the attribute fb_only=true to achieve this.


<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>Without Custom Fields - Only Facebook users allowed.</h2>
<iframe src="http://www.facebook.com/plugins/registration?
         client_id=<?php echo $API_KEY; ?>&
         redirect_uri=<?php echo $redirect_URI; ?>&
         fb_only=true&
         fields=name,birthday,gender,location,email"
    scrolling="auto"
    frameborder="no"
    style="border:none"
    allowTransparency="true"
    width="530"
    height="330"
>
</iframe>


<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

    }
}
?>


<?php
function parse_signed_request($signed_request, $secret)
{
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

    // decode the data
    $sig = base64_url_decode($encoded_sig);
    $data = json_decode(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, '-_', '+/'));
}
?>



Facebook registration plugin (XFBML) with custom fields: 

If you wish to use XFBML instead of iframe, with custom fields, you can use the below example:


<?php
$API_KEY = '463292747036958';
$API_SECRET = 'GET_YOUR_APP_SECRET';
$redirect_URI = 'http://lab.tech-and-dev.com/facebookRegistration.php';
?>

<script src="https://connect.facebook.net/en_US/all.js#appId=<?php echo $API_KEY; ?>&xfbml=1"></script>
<div id="fb-root"></div>

<h2>With Custom Fields - XFBML</h2>
<fb:registration
fields="[
    {'name':'name'},
    {'name':'birthday'},
    {'name':'gender'},
    {'name':'location'},
    {'name':'email'},
    {'name':'favoriteFood', 'description':'Favorite Food', 'type':'select', 'options':{'0':'Pizza','1':'Burger','2':'Hot Dog','3':'Tuna'}},
    {'name':'graduated', 'description':'Graduation Date', 'type':'date'},
]"
  redirect-uri="<?php echo $redirect_URI; ?>"
  width="530">
</fb:registration>
<?php
if ($_REQUEST['signed_request'])
{
    $response = parse_signed_request($_REQUEST['signed_request'], $API_SECRET);//secret

    if($response)
    {
        //Fields values
        $email=$response['registration']['email'];
        $name=$response['registration']['name'];
        $gender=$response['registration']['gender'];
        $user_fb_id=$response['user_id'];
        $location=$response['registration']['location']['name'];
        $bday = $response['registration']['birthday'];

        //custom fields
        $favoriteFood = $response['registration']['favoriteFood'];
        $graduated = $response['registration']['graduated'];


        //print entire array response
        echo '<h3>Response Array</h3>';
        echo '<pre>';
        print_r($response);
        echo '</pre>';

        //print values
        echo '<h3>Fields Values</h3>';
        echo 'email: ' . $email . '<br />';
        echo 'Name: ' . $name . '<br />';
        echo 'Gender: ' . $gender . '<br />';
        echo 'Facebook Id: ' . $user_fb_id . '<br />';
        echo 'Location: ' . $location . '<br />';
        echo 'Birthday: ' . $bday . '<br />';

        //print custom fields
        echo '<h3>Custom Fields Values</h3>';
        echo 'Favorite Food: ' . $favoriteFood . '<br />';
        echo 'Graduated: ' . $graduated . '<br />';
    }
}
?>


<?php
function parse_signed_request($signed_request, $secret)
{
    list($encoded_sig, $payload) = explode('.', $signed_request, 2);

    // decode the data
    $sig = base64_url_decode($encoded_sig);
    $data = json_decode(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, '-_', '+/'));
}
?>



More info about the facebook registration plugin can be found in here: http://developers.facebook.com/docs/plugins/registration/
Examples can be found in here: Facebook Registration Social Plugin Examples

Any questions or suggestions, please post them below!

Sunday, August 19, 2012

Facebook App Tutorial - The Basics

Facebook applications gives you the opportunity to deeply integrate into the core Facebook experience. Your app can integrate with many aspects of Facebook.com, including the News Feed, Notifications, open-graph and all of the core Facebook Platform technologies, such as Social Plugins, like the registration plugin, like plugin, login.

To create your first facebook application:


Go to https://developers.facebook.com/apps
Click on "Go to app"
Facebook Go To App


On the top right side click on "Create new App"
Facebook Create New App



Choose the name of your app, this can be anything.
Choose the namespace of your app, this is a unique name, so it might be already taken.
Uncheck Web Hosting with Huroku. Huroku allows you to host your app on their servers for free. We won't be using Heroku for this tutorial. I will write a tutorial in the future on how to use Heroku with facebook apps. 
Click "Continue".

Facebook App Name


You might need to verify your facebook account by adding your mobile phone number or credit card.
Facebook Verify App



This is the interface of our new app:
Facebook App Interface


The most important two things in the new app are the "App ID" and the "App Secret". Never share your App Secret with anyone.

Let's go to "Edit Settings"

In "Edit Settings", we can see all the app's important info.
If you want your app to be accessed from one or more website, you can define those websites in the "App Domains". For this tutorial, I'm gonna allow the app to be accessed from tech-and-dev.com, which also includes the subdomains of this site.
Facebook App Edit Settings



If you want to use the facebook login button on your website, you will have to set the URL in the "Website with Facebook Login" section.
Facebook App Website With Facebook Login



If you want your app to be part of facebook, that is, your app displayed in a facebook canvas, you can set the url of your facebook canvas. (I will explain more about this in my next tutorial)
Facebook App Canvas




Let's go to the "Auth Dialog" and configure it. The "Auth Dialog" link is on the left sidebar.
Facebook App Auth Dialog

You can check how will the app dialog will appear by clicking on the Preview Current Dialog.


It's very important to set a logo for your application, otherwise later on, when you decide to work with Open Graph, facebook will reject your application.
Adding a privacy policy and terms of service is a facebook requirements now, and any app that does not have a privacy policy or terms of use URL will receive a warning to add one or the application will be banned from facebook.

You can google for privacy policy and terms & conditions if you don't have any.

A warning will look like the following:
Notice of Violation: Privacy Policy (App ID: [YOUR_APP_ID])

Hi,

We've found the following policy violation with your app and you need to address this issue by [DATE] at [TIME] or your app may be subject to enforcement action.

Our policies require that your app has a privacy policy that tells users what user data you are going to use and how you will use, display, share, or transfer that data and you will include your privacy policy URL in the Developer Application (See Platform Policy II.3, http://developers.facebook.com/policy).

It has come to our attention that your app is missing a privacy policy in the permissions dialogue. Please update the privacy policy URL field in the Developer Application at developers.facebook.com/apps/[YOUR_APP_ID]/auth. Also, please review your app to ensure you are also displaying your privacy policy on your web site or within your app.

Thanks,
Platform Policy Teamen 


Let's add some permissions in the Configure how Facebook refers users to your app:
Facebook App Permissions

All the permissions and their description can be found in here:


You can check the app canvas in here: http://apps.facebook.com/tech-and-dev/
Facebook App

Notice how there is a privacy policy and terms and conditions link on the bottom, and all the permissions we've added.


That's it for our basic tutorial!

In my next tutorial, I will show you to build a php facebook app and work with the permissions and login.

Any questions or suggestions? Leave a comment below!


Wednesday, August 15, 2012

How to install eAccelerator on linux

php eaccelerator
 eAccelerator works in a way that whenever there is request to a webpage, eAccelerator will parse all the php files and cache them in a shared memory in their compiled state. This way, anytime a request is made, eAccelerator will serve those compiled files from the memory, and thus will almost eliminate the entire parsing process.

eAccelerator is a very useful extension to reduce the CPU overloads, serve the requests faster, and optimize the php performance.
According to php eAccelerator official website, eAccelerator can speed up the php code by 1-10 times and reduce server load.

Installing eaccelerator is an easy process, just follow the below steps to install your eaccelerator on  linux.
In this tutorial, I will be installing eAccelerator on a CentOS.

First, make sure you have the php extension php-devel installed, you can install it using yum (More about linux commands here):
yum install php-devel

Now let's download eAccelerator to a temporary directory
cd /tmp
wget http://acelnmp.googlecode.com/files/eaccelerator-0.9.6.1.tar.bz2

Extract it:
tar xvfj eaccelerator-0.9.6.1.tar.bz2

Change the directory to eAccelerator dir:
cd eaccelerator-0.9.6.1

Now let's use PHPize to prepare a PHP extension for compiling:
phpize
./configure

Let's install eAccelerator:
make
make install

eAccelerator should now be installed.
Let's tell php to read it and start caching:
In this step, we can either create a separate file for the eaccelerator configuration or we can append them to php.ini, I will use the first method in this example.
We create the eaccelerator ini file:
vi /etc/php.d/eaccelerator.ini

and we write the following
extension="eaccelerator.so"
eaccelerator.shm_size="64"
eaccelerator.cache_dir="/var/cache/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

In the above example, I'm allowing eAccelerator to allocate up 64MB in memory. If you want to allow it to allocate less or more, change the value of eaccelerator.shm_size, setting it to 0 will use the default value.

Now we need to define a directory to be used for eAccelerator caching.
Let's create a new directory:
mkdir -p /var/cache/eaccelerator

and change permissions to read, write and execute:
chmod 0777 /var/cache/eaccelerator

Now let's restart apache:
service httpd restart
or
/etc/init.d/httpd restart


Congratulations, you now have eAccelerator installed. You can check in your phpinfo() for the eaccelerator section.





If you are unable to restart Apache server, and you receive an error, make sure your server allows you to allocate enough memory. Check this article for more details: Increase shared memory on linux (shmmax)


Follow us on facebook or twitter for the latest updates!