Tuesday, January 25, 2011

How to create an RSYNC script with configuration in PERL

RSYNC is really simple, you can do an RSYNC by a single command line on your console. so, probably now your thinking.., what's the difference of my script? the difference is that I was able to create a script that has configuration files for you to re-use it every time you have different directories and servers to SYNC on.

First, you have to know the basic command line to do RSYNC. please see below command line.

rsync -crtz --bwlimit=56 --stats -e "ssh -l [USERNAME] -p [PORT]" [SOURCE DIRECTORY] [DESTINATION IP]:[DESTINATION DIRECTORY]

[USERNAME] is your account username to the destination server. your username should be set in passwordless to make it run in background.

[PORT] is the port that you will be using to connect to destination server.

[SOURCE DIRECTORY] is the source directory of the files you want to SYNC on.

[DESTINATION IP] is the server ip of the destination server.

[DESTINATION DIRECTORY] is the destination directory of the files you want to SYNC on.

Once you know how the RSYNC works in background, next is to know how we want our configuration to work. we should have a script that reads configuration in a flat file.

In creating configuration file, you should consider the comment syntax. this is to easily comment the lines you wanted to skip on or disregard in the configuration file.

Usually in linux, commented lines are preceded by pound sign "#" and that should be one of your condition to disregard. please see below for the sample reading of file then check for pound sign "#" using REGEX, then disregard.

open FHFILE, "< $strConf";
@arrData = <FHFILE>;
close FHFILE;

foreach $strData (@arrData)
{
      chomp $strData;
      if ($strData !~ /^\s*\#/)
      {
              print "okay here";
      }
}

The simple REGEX above checks if you have pound sign "#" on each lines and print okay if you don't.

The last thing you should know is how to pass the configuration file in command line. SYNTAX will be <YOUR SCRIPT> <space> <YOUR CONFIG FILE>. If you are new to LINUX, all parameters you passed on after your PERL SCRIPT will be catched by the ARRAY variable $ARGV. print that on your script with zero "0" as index will give you the first parameter you passed on, then succeeding index will the next parameter and so on and so forth.

Hope you were able to follow. Now we're ready to do the actual code.

Please see the recommended configuration FORMAT below that works on my RSYNC script. You will notice that I have a header which is setup to be the [DESTINATION IP] and [DESTINATION PORT]. This is for me to have it organize in a per SERVER configuration, then succeeding lines will be the actual SOURCE and DESTINATION directories.

- conf.txt as configuration file

[DESTINATION IP]:[DESTINATION PORT]
[SOURCE DIRECTORY 1]:[DESTINATION DIRECTORY 1]
[SOURCE DIRECTORY 2]:[DESTINATION DIRECTORY 2]
[SOURCE DIRECTORY n..]:[DESTINATION DIRECTORY n..]

- rsync.pl as your perl script

#!/usr/bin/perl

### reading conf files
$strConf = $ARGV[0];
if (-e $strConf)
{
    &do_rsync($strConf);
}
else
{
    print "conf: $strConf does not exist!!\n";
}
###

sub do_rsync
{
  my ($strConf) = @_;
  my ($ip, $port, $cmd, $strData, $strIncomingDir, $strOutGoingDir, $strReturn);
  my @arrData;

  open FHFILE, "< $strConf";
  @arrData = <FHFILE>;
  close FHFILE;

  $ip_port = shift @arrData;
  chomp $ip_port;

  # reading the ip and port as header
  while ($ip_port =~ /^\s*\#/)
  {
    $ip_port = shift @arrData;
    chomp $ip_port;
  }
  # end

  ($ip, $port) = split /\:/, $ip_port;

  if ($ip =~ /[^0-9|.]/)
  {
    print "ip not valid..\n\n";
  }
  elsif ($port =~ /[^0-9]/)
  {
    print "port not valid..\n\n";
  }
  else
  {
    # reading each line after the header
    foreach $strData (@arrData)
    {
      chomp $strData;

      if ($strData !~ /^\s*\#/)
      {
        ($strIncomingDir, $strOutGoingDir) = split /\:/, $strData;

        $cmd = "rsync -crtz --bwlimit=56 --stats -e \"ssh -l contents -p $port\" $strIncomingDir $ip:$strOutGoingDir";

        $strReturn = `$cmd`;
      }
    }
    # end
  }
}



1;

To execute, please see command line below. you can also put this in CRON, provided that the USERNAME is set to be PASSWORDLESS.

<path to the script>/rsync.pl <path to the config file>/conf.txt


Hope you like it!! Please leave a comment if you find this helpful. Thanks!!

Tuesday, January 18, 2011

How to post facebook status using OAuth with permanent TOKEN via backend in PERL and PHP

This post will teach you how to post facebook status using OAuth process via back-end. This is actually a revised version of the script I made on my previous post How to submit facebook status via back-end using PERL but instead of saving the users credentials, you just need to save the token which we get from the OAuth process.

You just need to have a web server coz facebook OAuth will require application to have a site URL as to be the callback URL in passing information. just for the sake of our testing we can use our local domain.

Just follow the simple steps below and we will be able to submit facebook status via back-end using OAuth process the "LEGAL WAY".

1. Same with my previous post, you should register your application on facebook - http://www.facebook.com/developers/createapp.php again, type in the application name and other details then once created, modify the site URL under web site tab.

2. Once you have the 3 details such as: app ID, app Secret, and site URL. we can now start coding the authorization script which will request permission for our app to do the status update.

app ID - 182635521758593
app Secret - 495625ad928ea277548d0f423f420ef0
site URL - http://localhost/facebook/

3. Since we're using PERL, you have to install the following libraries needed to run the script.
  • LWP::UserAgent;
  • HTTP::Cookies;
4. After installing the libraries, initialize UserAgent and Cookies to do HTTP request. please see below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://m.facebook.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

5. Login to the wap site via the URL - http://m.facebook.com/login.php then save the cookies.

my $strUser = '<your facebook username/email>';
my $strPass = '<your facebook password>';
my $strStatus = '<your facebook status>';

# login to facebook
my $response = $lwpua->post('http://m.facebook.com/login.php',
                      ['email' => $strUser,
                       'pass' => $strPass,
                       'login' => 'Login'], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

6. Request for permission to post facebook status with the app ID, and site URL of your application where app ID being the "app_id" parameter and site URL being the "next" parameter. just for this testing, we can use the application "Hotshots Point Of View". the application details are stated on step no. 2.

$response = $lwpua->get('http://m.facebook.com/connect/uiserver.php?app_id=182635521758593&method=permissions.request&display=wap&next=http%3A%2F%2Flocalhost%2Ffacebook%2F&response_type=code&fbconnect=1&perms=user_photos%2Cuser_videos%2Cpublish_stream', @header);

7. Get the $response->content and parse the "form action", "post_form_id", and "fb_dtsg" via REGEX implementation below. take note that this might change as the facebook wap changes. take note as well that the $response->content might not return as expected if the user already allow the application. hence, the $response->content will be the return output of your callback or site URL. if this is the first time that the user will allow the application, expect a return page with the details we need below.

my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /form id="uiserver_form" action="(.*?)"(.*?)name="post_form_id" value="(.*?)"(.*?)name="fb_dtsg" value="(.*?)"/ig;

my $form_action = $1;
my $form_id = $3;
my $form_fbdtsg = $5;

8. Once we have the "form action", "post_form_id", and "fb_dtsg", we can now trigger user to allow our application. please see below with other details we have from step no. 2, then clear the cookies by unlink() function.

$response = $lwpua->post('http://m.facebook.com/connect/uiserver.php',
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'app_id' => '182635521758593',
                            'display' => 'wap',
                            'redirect_uri' => 'http://localhost/facebook/',
                            'response_type' => 'code',
                            'fbconnect' => '1',
                            'perms' => 'user_photos,user_videos,publish_stream',
                            'from_post' => '1',
                            '__uiserv_method' => 'permissions.request',
                            'grant_clicked' => 'Allow'], @header);

$form_data = $response->content;
unlink($cookie_file);

9. Okay, we are just halfway there.. now that we are able to allow the app to update facebook status, next step will be the script to post facebook status, but before that, here is the complete code of the PERL script as detailed on the steps above.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://m.facebook.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
                file => $cookie_file,
                autosave => 1,
                ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = '<your facebook username/email>';
my $strPass = '<your facebook password>';

# login to facebook
my $response = $lwpua->post('http://m.facebook.com/login.php',
                      ['email' => $strUser,
                       'pass' => $strPass,
                       'login' => 'Login'], @header);
$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://m.facebook.com/connect/uiserver.php?app_id=182635521758593&method=permissions.request&display=wap&next=http%3A%2F%2Flocalhost%2Ffacebook%2F&response_type=code&fbconnect=1&perms=user_photos%2Cuser_videos%2Cpublish_stream', @header);

my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /form id="uiserver_form" action="(.*?)"(.*?)name="post_form_id" value="(.*?)"(.*?)name="fb_dtsg" value="(.*?)"/ig;

my $form_action = $1;
my $form_id = $3;
my $form_fbdtsg = $5;

$response = $lwpua->post('http://m.facebook.com/connect/uiserver.php',
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'app_id' => '182635521758593',
                            'display' => 'wap',
                            'redirect_uri' => 'http://localhost/facebook/',
                            'response_type' => 'code',
                            'fbconnect' => '1',
                            'perms' => 'user_photos,user_videos,publish_stream',
                            'from_post' => '1',
                            '__uiserv_method' => 'permissions.request',
                            'grant_clicked' => 'Allow'], @header);

$form_data = $response->content;
unlink($cookie_file);



1;

10. Succeeding steps will then teach you how to submit facebook status in PHP which was triggered by facebook upon allowing our application. if you notice on our authorize URL on step no. 6, we set the "next" parameter to be the same as the value of our facebook app site URL. the "next" parameter will be used by facebook to return the CODE which we can exchange for a TOKEN that we will be using to post facebook status. please see below authorize URL from step no. 6.

http://m.facebook.com/connect/uiserver.php?app_id=182635521758593&method=permissions.request&display=wap&next=http%3A%2F%2Flocalhost%2Ffacebook%2F&response_type=code&fbconnect=1&perms=user_photos%2Cuser_videos%2Cpublish_stream

11. In back-end, the URL below was executed by our PERL script but if this link was clicked by the user, the user will be redirected to the page where in our facebook application is requesting for permission to post facebook status on users profile. if the user will allow it, facebook will then redirect it to the "next" parameter we specify on the URL above. please see facebook redirection URL format below.

http://localhost/facebook/?code=...

12. Your index page should be able to capture the CODE parameter returned by facebook and exchange it with TOKEN on the access token URL below then parse the return data to get the TOKEN. again, app ID will be the "client_id" parameter, site URL will the "redirect_uri" parameter, and the app Secret will be the "client_secret" parameter.

$code = $_GET['code'];
$oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&redirect_uri=http://localhost/facebook/&client_secret=495625ad928ea277548d0f423f420ef0&code=$code";

$url_handler = fopen("$oauthurl", 'r');
$url_contents = stream_get_contents($url_handler);
fclose($url_handler);

$ret = explode("&", $url_contents);
$token = preg_replace('/^access_token=/', '', $ret[0]);

13. Once you have the TOKEN, you will now be able to post facebook status using CURL. please see below implementation.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/me/feed');
curl_setopt($ch, CURLOPT_POSTFIELDS,'access_token='.urlencode($token).'&message='.urlencode($status));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
curl_setopt($ch, CURLOPT_REFERER, "http://m.facebook.com");
$page = curl_exec($ch);

14. Please take note that the TOKEN you just pulled from facebook is NOT yet permanent. Hence, you need to call another access token with the parameter grant_type=client_credentials.

$oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&client_secret=495625ad928ea277548d0f423f420ef0&grant_type=client_credentials";

$url_handler = fopen("$oauthurl", 'r');
$url_contents = stream_get_contents($url_handler);
fclose($url_handler);

$ret = explode("&", $url_contents);
$token = preg_replace('/^access_token=/', '', $ret[0]);

15. Please see below for the complete PHP script.

<?

$status = "damn!! i'm good!! i was able to crack facebook oauth process via backend using perl and php! - http://paulgonzaga.blogspot.com";

$code = $_GET['code'];

if ($code) {
        // get access token
        $oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&redirect_uri=http://localhost/facebook/&client_secret=495625ad928ea277548d0f423f420ef0&code=$code";

        $url_handler = fopen("$oauthurl", 'r');
        $url_contents = stream_get_contents($url_handler);
        fclose($url_handler);

        $ret = explode("&", $url_contents);
        $token = preg_replace('/^access_token=/', '', $ret[0]);

        if ($token) {
                // get user info
                $infourl = "https://graph.facebook.com/me?access_token=$token";
                $url_handler = fopen("$infourl", 'r');
                $return = json_decode(stream_get_contents($url_handler));
                fclose($url_handler);

                $userid = $return->id;
                $name = $return->name;
                $fname = $return->first_name;
                $mname = $return->middle_name;
                $lname = $return->last_name;
               
                $oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=182635521758593&client_secret=495625ad928ea277548d0f423f420ef0&grant_type=client_credentials";

                $url_handler = fopen("$oauthurl", 'r');
                $url_contents = stream_get_contents($url_handler);
                fclose($url_handler);

                $ret = explode("&", $url_contents);
                $token = preg_replace('/^access_token=/', '', $ret[0]);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/$userid/feed');
                curl_setopt($ch, CURLOPT_POSTFIELDS,'access_token='.urlencode($token).'&message='.urlencode($status));
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3");
                curl_setopt($ch, CURLOPT_REFERER, "http://m.facebook.com");
                $page = curl_exec($ch);
        }
}

?>

Save the USERID and TOKEN for succeeding facebook status. Hope you like it!! Enjoy!! yeah men!! - http://paulgonzaga.blogspot.com

Sunday, January 16, 2011

The TOP 15 most important social networking sites.

The following list are the most important social networking sites as of today. The list are not based on the popularity of the sites nor how old the website is running. This is based on its importance to people's lives, self improvement, business, friendship, and how we live our lives.

  • Facebook - Initially intended for college students, then branched out by invite, and continuously growing with over 500 million members.
  • Twitter - A free social networking service that allows users to send "updates" (text-based posts that are up to 140 characters long) via SMS, instant messaging, email, the Twitter website, or an application such as Twitterrific. The site has become very popular in only a few months with over 75 million members.
  • MySpace - Over 130 million members. this site is massive, boasting the largest membership of any social networking site on the internet.
  • Linkedin - Over 75 million members. a powerful for business networking. mainly used by businessmen and organizations.
  • Foursquare - Foursquare is a social networking site build by Google that shares your global location by checking in, sending shout out, and even promote the location by leaving tips.
  • Friendster - It was considered the top online social networking service until it was overtaken by MySpace at around April 2004. Demographic studies shows that users are between 17 to 30 years of age and over 90 million members.
  • StumbleUpon - Boasting over 13 million users, StumbleUpon is a web browser plugin that allows its users to discover and rate web pages, photos, videos, and news article. We usually see this plugin on social bookmarking tools like addThis, shareThis, etc.. A great way to promote websites. It was bought by eBay for $75 million in May 2007.
  • Delicious - The website delicious which is formerly known as "del.icio.us" is a social bookmarking web service for storing, sharing, and discovering web bookmarks. The site was founded by Joshua Schachter in late 2003, and is now part of Yahoo!
  • Digg - Digg is a website made for people to share and discover content on the internet by submitting links and stories, then people votes and comments on submitted contents in a social and democratic spirit.
  • Orkut - Orkut is an Internet social networking service run by Google and named after its creator, Google employee Orkut Büyükkökten. It claims to be designed to help users meet new friends and maintain existing relationships. Now has a membership of 100 million.
  • Classmates - Over 50 million members. One of the oldest social networking sites around, Classmates was kicked off in 1995, and has proven to be a great way for members to to connect with old friends and acquaintances from throughout their lives.
  • Meetup - Over 2 million members. Meetup.com is an online social networking portal that facilitates offline group meetings in various localities around the world. Meetup allows members to find and join groups unified by a common interest, such as politics, books, games, movies, health, pets, careers or hobbies.
  • Yahoo! Pulse - Formerly known as Yahoo! 360° (a.k.a Yahoo! Days) is a personal communication portal similar to Orkut and MySpace -- it is now launched for public used already. It integrates features of social networking, blogging and photo sharing sites.
  • Xanga - Over 27 million members. Xanga the blogging community is a free Web-based service that hosts weblogs, photoblogs, videoblogs, audioblogs, and social networking profiles.
  • Care2 - Over 14 million members. Care2 is a social networking website that was founded to help connect activists from around the world.
In all, there are over 100 social networking sites on the Internet. Some of the other social networking sites that I have not included in the list above are:

Ryze, Bebo, BlackPlanet.com, Flickr.com, Reunion.com, aSmallWorld, Bebo, BlackPlanet.com, Blue Dot, Bolt, Broadcaster.com, Buzznet, CarDomain, Consumating, Couchsurfing, Cyworld, Dandelife, DeadJournal, DontStayIn, Doostang, Ecademy, eSPIN, Faceparty, Flirtomatic, Fotki, Friends Reunited, Gaia Online, Geni.com, GoPets, Graduates.com, Grono.net, Hyves, imeem, Infield Parking, IRC-Galleria, iWiW, Joga, Bonito, Last.fm, LibraryThing, LiveJournal, LunarStorm, MEETin, MiGente.com, Mixi, MOG, Multiply, My Opera Community, myYearbook, Netlog, Nexopia, OUTeverywhere, Passado, Piczo, Playahead, ProfileHeaven, Pownce, RateItAll, Searchles, Sconex, Shelfari, Soundpedia, Sportsvite, Studivz, TagWorld, TakingITGlobal, The Doll Palace, The Student Center, Threadless, TravBuddy.com, Travellerspoint, Tribe.net, Vampire Freaks, Vox, WAYN, WebBiographies, Windows Live Spaces, Woophy, XING, Xuqa, Yelp, Zaadz, Zooomr

Saturday, January 15, 2011

How to submit facebook status via OAuth.

You should read my last 2 previous post before this to know how the OAuth process works.
This post will teach you how to submit facebook status using OAuth. just follow the simple steps below with the complete code at the end for your implementation.

1. Same with my previous post, you need to have an app ID, site URL, and app Secret to submit facebook status on users profile. just for this testing, you can use the details below from the facebook app "Hotshots Point Of View".

app ID - 182635521758593
site URL - http://localhost/facebook/
app Secret - 495625ad928ea277548d0f423f420ef0

2. After having the 3 details, you should have to request permission for your app to be able to access users profile, but this time an added permission to post status. to do that, an additional parameter SCOPE=user_photos,user_videos,publish_stream should be added on your authorize URL. again, app ID will be your client_id, and site URL will be your redirect_uri. please see below authorize URL with the permission to post status on users profile.

https://graph.facebook.com/oauth/authorize?client_id=182635521758593&redirect_uri=http://localhost/facebook/&scope=user_photos,user_videos,publish_stream

3. User should click the URL above and authorize your application to access profile and submit status. facebook will return to the redirect_uri http://localhost/facebook/ with the parameter CODE as part of query string. capture the CODE parameter and exchange it for an access TOKEN for the next step below.

4. To get an access token, you should pass the app ID, site URL, app Secret, and the CODE parameter value you get from the authorize URL. please see the access token URL below. you should replace the <CODE> with the CODE parameter you get from the authorize URL above.

https://graph.facebook.com/oauth/access_token?client_id=182635521758593&redirect_uri=http://localhost/facebook/&client_secret=495625ad928ea277548d0f423f420ef0&code=<CODE>

5. From the URL above, facebook will echo the access TOKEN which you will need to post facebook status. you will need to get the user id of the user you wish to post facebook status, and to do that, just replace the <TOKEN> with the access TOKEN on the URL below.

https://graph.facebook.com/me?access_token=<TOKEN>

6. Once you have the USER ID, and TOKEN, you can now finally post facebook status on users profile. execute the CURL script below with your facebook STATUS.

curl -F 'access_token=<TOKEN>' -F 'message=<STATUS>' https://graph.facebook.com/<USERID>/feed

For you to have a working script in submitting facebook status. please see below script that does all in 1 page: authorize app, access token, get user info, and post facebook status.

<?
$client_id = '182635521758593';
$redirect_uri = 'http://localhost/facebook/';
$client_secret = '495625ad928ea277548d0f423f420ef0';

$status = 'How to submit facebook status via OAuth - http://paulgonzaga.blogspot.com/2011/01/how-to-submit-facebook-status-via-oauth.html';
$code = $_GET['code'];

if ($code) {
        // get access token
        $oauthurl = "https://graph.facebook.com/oauth/access_token?client_id=$client_id&redirect_uri=$redirect_uri&client_secret=$client_secret&code=$code";
        $data = do_get_request($oauthurl);

        $ret = explode("&", $data);
        $token = preg_replace('/^access_token=/', '', $ret[0]);

        // get user info
        $infourl = "https://graph.facebook.com/me?access_token=$token";
        $data = do_get_request($infourl);

        $ret = json_decode($data);
        $userid = $ret->id;

        $result = shell_exec("curl -F 'access_token=$token' -F 'message=$status' https://graph.facebook.com/$userid/feed");

        echo "done!</br>";
}

function do_get_request($get_url)
{
        $url_handler = fopen("$get_url", 'r');
        $url_contents = stream_get_contents($url_handler);
        fclose($url_handler);

        return $url_contents;
}

?>

<html>
<head>
</head>
<body>
<a href="https://graph.facebook.com/oauth/authorize?client_id=<?=$client_id?>&redirect_uri=<?=$redirect_uri?>&scope=user_photos,user_videos,publish_stream">authorize app</a>
</body>
</html>


Hope you like it!! happy coding.

How to use facebook application into your site.

I assume you know already how to create a facebook application from my previous post, coz on this post, I will tell you how to use it in your own website.

We will be using the OAuth process which is the legal way in posting facebook status.

Just follow the simple steps below and we can have our simple facebook app working in our own website.

1. first, you have to get your facebook app ID from - http://www.facebook.com/developers/apps.php

2. register the URL of your site by clicking the "Edit Settings" link. go to Web Site Settings by clicking the "Web Site" tab, then type in the URL of your site. just for testing, we can always use our local domain, coz facebook allows it. ex. http://localhost/facebook/

3. after registering our site URL, we can now create a simple app that will request to allow our facebook application to access profile and submit status.

4. just for testing purposes, I am allowing everyone to use my own created facebook application "Hotshots Point Of View". this application is configured to use your own local domain. please see details below.

app ID -  182635521758593
app Secret - 495625ad928ea277548d0f423f420ef0
site URL - http://localhost/facebook/

5. if you will use my facebook app, you must create a "facebook" directory under your localhost domain. copy the code below and save it as index.php. on the URL below, app ID will be your client_id and the site URL will be your redirect_uri.

<html>
<head>
</head>
<body>
<a href="https://graph.facebook.com/oauth/authorize?client_id=182635521758593&redirect_uri=http://localhost/facebook/">authorize app</a>
</body>
</html>

6. this is just a simple interface with a link labeled as "authorize app". go to your created app - http://localhost/facebook/ then click the "authorize app" link. you should be redirected to facebook page requesting permission to allow "Hotshots Point Of View" to access your basic information, if you are not currently logged-in, you will be prompted to log-in.

7. If the user authorizes your application, facebook will redirect the user back to the redirect URI we specified with a verification string in the parameter CODE - http://localhost/facebook/?code=.... the CODE parameter can be exchanged for an OAuth access token for us to be able to access users profile.

8. to capture the value of the CODE parameter, we will modify our index.php as below. use the CODE to access token URL. pass the same client_id and redirect_uri as in the previous step together with the CODE and App Secret as stated above. this will now be the content of our index.php.

<?
$code = $_GET['code'];
?>

<html>
<head>
</head>
<body>
<? if (!$code) : ?>
<a href="https://graph.facebook.com/oauth/authorize?client_id=182635521758593&redirect_uri=http://localhost/facebook/">authorize app</a>
<? else : ?>
<a href="https://graph.facebook.com/oauth/access_token?client_id=182635521758593&redirect_uri=http://localhost/facebook/&client_secret=495625ad928ea277548d0f423f420ef0&code=<?=$code?>">access token</a>
<? endif; ?>
</body>
</html>

9. if CODE parameter doesn't have value, the link will be labeled as "authorize app" and if it has, the link will be labeled as "access token". try accessing your app again - http://localhost/facebook/

10. after clicking the "access token", it will goes back again to your site and echo the access_token which you will be use to access users profile.

11. save the access_token returned by facebook then use it to access profile. please see simple code below in PHP to get the users profile.

<?
$token = '<access token>';

// get user info
$infourl = "https://graph.facebook.com/me?access_token=$token";

$url_handler = fopen("$infourl", 'r');
$url_contents = stream_get_contents($url_handler);
fclose($url_handler);

$return = json_decode($url_contents);

$userid = $return->id;
$fname = $return->first_name;
$mname = $return->middle_name;
$lname = $return->last_name;

echo "$fname $mnane $lname\n";

?>

12. now, that you were able to get the users profile, you can have that integrated within your site.

Hope you were able to follow the steps I made. submission of facebook status will NOT be able work on this post coz we have to specify a SCOPE to authorize our application to publish stream but don't you worry coz that will be next. Enjoy!! yeah men!!

How to create a facebook application.

To create a facebook application, first thing you have to do is to have a facebook account. this is for your application to have an admin or owner to manage the configuration and settings.

Once you have your account, login to facebook, then go to link - http://www.facebook.com/developers/apps.php

Just follow the simple steps below and you can have your facebook application in seconds.

You will see the list of application you created. you can either edit your existing app or create a new one by clicking the "Set Up New App" button found on the upper right corner of the page.

Click the "Set Up New App" button then that will lead you to Create Application page, wherein you have to type your App Name, agree to the Facebook Terms, then submit by clicking "Create App".

Upon submission, you will be redirected to Security Check page wherein you have to type in the words in captcha then submit.

After Security Check, your app is now created and enables you to edit some of the details, then Save.

Each application will have a unique App ID, API Key, App Secret which you will use to access of transact with facebook from your own website.

Thursday, January 13, 2011

What to use best: Flash or jQuery?

Some developers are confuse or having difficulties on what to use best in putting animation for their websites and hope this post will probably help developers to decide on that.

Listed below are the Pros and Cons in using Flash and jQuery.

Pros in using Flash:
  • Extensive features
  • 3D capabilities
  • Consistent appearance in supported browsers
  • Supports vector artwork
  • Built-in UI and other features
  • Many free and commercial tools available
  • More font options 
Cons in using Flash:
  • Not compatible with all browsers including IPhone, IPad and Cellphones
  • Moderate learning curve to use
  • Very expensive flash software
  • Flash player version problems
  • Large file size
  • Possible security issues with Flash Player
  • Tracking stats for Flash elements is limited
Pros in using jQuery:
  • Small file size
  • Comply with HTML standards which reduces learning curve
  • Hundreds of free professional quality programs
  • Can add interactivity to web page elements and tags
  • Skinnable Form Components UI
  • Compatible with more browsers than Flash including iPhone, cell phones, PS3, PSP
Cons in using jQuery:
  • Features not as extensive as Flash
  • Complex features may not perform as quickly as flash
  • 3D features are limited
  • Users can disable Javascript support
  • Source Code Not Protected

Listed below are the list of animations/functions/areas when to use Flash and jQuery.

When to use Flash?
  • Video and Audio player
  • Complex animation
  • 3D
  • Complex multimedia
When to use jQuery?
  • Slide Show
  • Form Validation
  • Dropdown Menus
  • Tabbed Panels
  • Popups and Tooltips
  • Expandable/Collapsible Elements

If you are still confuse of what to use best, the best advise that I can give is to try it first with jQuery, thou there's still a few areas to use flashes, if you think that it can be done in jQuery, then do it with jQuery coz jQuery is definitely easy to implement and a much lighter for your website.

Wednesday, January 12, 2011

Setting up a web service CLIENT script in native PHP

For this post, we will be using a native PHP to create a web service client. please follow the steps below and you we're able to connect and transact in a web service.

1. first thing you have to do is to get the end-point URL of the web service server. let say the end-point wsdl - http://mydomain.com/wservice.wsdl use it to initialize SoapClient with parameters: trace and exceptions.

$this->client = new SoapClient('http://mydomain.com/wservice.wsdl', array('trace' => 1, 'exceptions' => 1));

2. once you have a client object, call the method the same as calling a usual object. let say the method name is helloWorld then passing the parameter 'world', your code should be like this.

$this->client->helloWorld('world');

3. please see the simple code below using class.

<?php
class wservice_client
{
    private $endpoint = "http://mydomain.com/wservice.wsdl";   
    private $client;

    function wservice_client() {
            $param = array (
                            'trace' => 1,
                   'exceptions' => 1
            );

            $this->client = new SoapClient($this->endpoint, $param);
    }

    function helloWorld ( $world ) {
        try {
                $response = $this->client->helloWorld($world);
        } catch (Exception $e) {
                return $response;
        }

        return (array)$response;
    }
}

?>

Setting up a web service SERVER script in native PHP

This post will assist you on how to setup a web service server script using native PHP library. please follow the steps below.

1. create a class with all the methods you want to be accessible via web service. i created a simple class with a simple helloWorld method just for us to have it work.

class wservice {
    public function helloWorld($world) {
        return 'hello ' . $world;
    }
}

2. create WSDL of your web service. please take note that PHP doesn't support automatic generation of WSDL. hence, you should do it manually. WSDL should be created based on the function of your class above and definitions composes of the following elements: message, portType, binding, and service. save the file as wservice.wsdl for the next step.

<?xml version='1.0' encoding='UTF-8'?>
<definitions name="HW" targetNamespace="urn:HW" xmlns:typens="urn:HW" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/">
        <message name="helloWorld">
                <part name="world" type="xsd:string"/>
        </message>
        <message name="helloWorldResponse">
                <part name="return" type="xsd:integer"/>
        </message>
        <portType name="HWPortType">
                <operation name="helloWorld">
                        <documentation>
                        </documentation>
                        <input message="typens:helloWorld"/>
                        <output message="typens:hellowWorldResponse"/>
                </operation>
        </portType>
        <binding name="HWBinding" type="typens:HWPortType">
                <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
                <operation name="helloWorld">
                        <soap:operation soapAction="urn:HWAction"/>
                        <input>
                                <soap:body namespace="urn:HW" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
                        </input>
                        <output>
                                <soap:body namespace="urn:HW" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
                        </output>
                </operation>
        </binding>
        <service name="HWService">
                <port name="HWPort" binding="typens:HWBinding">
                        <soap:address location="webservice.php"/>
                </port>
        </service>
</definitions>

3. once your done with your WSDL, it's time to initialize the server, pass the path of the WSDL file that you just created and the name of the class that you just created.

ini_set("soap.wsdl_cache_enabled", "0");
$server = new SoapServer("wservice.wsdl",array('soap_version' => SOAP_1_2));
$server->setClass("wservice");
$server->handle();

4. and that's it! please see the complete code below for the server end-point script and wsdl.

- wservice.php

<?php

class wservice {
    public function helloWorld($world) {
        return 'hello' . $world;
    }
}

ini_set("soap.wsdl_cache_enabled", "0");

$server = new SoapServer("wservice.wsdl",array('soap_version' => SOAP_1_2));
$server->setClass('wservice');
$server->handle();

?>

- wservice.wsdl

<?xml version='1.0' encoding='UTF-8'?>
<definitions name="HW" targetNamespace="urn:HW" xmlns:typens="urn:HW" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/">
        <message name="helloWorld">
                <part name="world" type="xsd:string"/>
        </message>
        <message name="helloWorldResponse">
                <part name="return" type="xsd:integer"/>
        </message>
        <portType name="HWPortType">
                <operation name="helloWorld">
                        <documentation>
                        </documentation>
                        <input message="typens:helloWorld"/>
                        <output message="typens:hellowWorldResponse"/>
                </operation>
        </portType>
        <binding name="HWBinding" type="typens:HWPortType">
                <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
                <operation name="helloWorld">
                        <soap:operation soapAction="urn:HWAction"/>
                        <input>
                                <soap:body namespace="urn:HW" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
                        </input>
                        <output>
                                <soap:body namespace="urn:HW" use="encoded" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
                        </output>
                </operation>
        </binding>
        <service name="HWService">
                <port name="HWPort" binding="typens:HWBinding">
                        <soap:address location="wservice.php"/>
                </port>
        </service>
</definitions>

Saturday, January 8, 2011

Creating a socket client in PHP

Hey!! Good thing that PHP supported SOCKET extension on PHP 5.0.0. It really help us developers to develop a socket server and client using only PHP libraries.

First, your server should be able to connect to socket server ip and port. a socket port was provision for client to connect in socket.

Once you have established your connection, you can now follow the simple steps below for you to be able to develop a socket client in PHP.

1. Define the socket server ip and port.

$socket_port = '<socket server port>';
$socket_ip = '<socket server ip>';


2. Create a TCP/IP socket. to get the error, you can use socket_sterror() function passing the error code parameter using socket_last_error().

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
echo socket_sterror(socket_last_error());


3. After the socket was successfully created, you can now send input data request using socket_write() function, parameters are the created socket object, the input data request, and the input data length.

$in = "<input data request>";
$len = strlen($in);
socket_write($socket, $in, $len);


4. To get the return data of the socket server request from no.3, you can use socket_read() function, parameters are the socket and the maximum length of the binary data.

$out = socket_read($socket, 2048);


5. And lastly, closing the socket by socket_close() function.

socket_close($socket);


Hope you were able to follow the steps above, you can try the complete code below, just define the socket server ip and port with a valid input data request.

<?php
error_reporting(E_ALL);

/* define socket server ip and port here.. */
$socket_port = '<socket server port>';
$socket_ip = '<socket server ip>';

/* create a tcp/ip socket.. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
   $error = socket_strerror(socket_last_error());
   echo "socket_create() failed: [$result] $error\n";
} else {
   echo "socket_create() ok.\n";
}

/* connect to socket server ip and port */
$result = socket_connect($socket, $socket_ip, $socket_port);
if ($result === false) {
   $error = socket_strerror(socket_last_error($socket));
   echo "socket_connect() failed: [$result] $error\n";
} else {
   echo "socket_connect() ok.\n";
}

$in = "<input data request>";
$len = strlen($in);

echo "sending input data request.\n";
socket_write($socket, $in, $len);
echo "socket_write() ok.\n";

echo "reading return data.\n";
while ($out = socket_read($socket, 2048)) {
   echo "socket_read() : $out";
}

echo "closing the socket.";
socket_close($socket);
echo "socket_close() ok.\n\n";
?>

Tuesday, January 4, 2011

How to post tweet on twitter via backend using PERL

Just like from my previous post, you should know how the wap site works, from log-in up to sending your tweets.

If you still have no idea on how the twitter works, just follow the steps below and you will be able to send tweets in minutes.

1. Same on how we do it on facebook, we need to install the following libraries on our server.
  • LWP::UserAgent
  • HTTP::Cookies

2. Once installed, we are now ready to do the coding part. we have to require and initialize the libraries and variables that we will be using.

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://mobile.twitter.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
file => $cookie_file,
autosave => 1,
ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);


3. Input your twitter account username, password, and your tweet you wish to be posted.

my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";
my $strTweet = "<your tweet>";


4. Get the authenticity_token using REGEX from the twitter session url http://mobile.twitter.com/session/new. token will be use as parameter in submitting your credentials to the wap site. i also pasted the form element of the login page below as reference.

=begin
<form action="https://mobile.twitter.com/session" method="post">
<input name="authenticity_token" type="hidden" value="22a9872b3a17abd635a4" />
<input autocapitalize="off" autocorrect="off" id="username" name="username" type="text" />
<input id="password" name="password" type="password" />
<input class="signup" type="submit" value="Sign in" />
</form>
=cut

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;


5. Use the token to login by posting it to the form action url above: https://mobile.twitter.com/session and save the cookie for the nest session.

# logged in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
['username' => $strUser,
'password' => $strPass,
'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://mobile.twitter.com', @header);
$form_data = $response->content;


6. Upon submission of credentials, you should be able to log-in successfully. to check it, you should be able to see the "What's happenning?" and the textarea in which you will input your tweet. again, get the authenticity token using REGEX below for the next session.

=begin
<form action="http://mobile.twitter.com/" class="new_tweet" id="new_tweet" method="post">
<input name="authenticity_token" type="hidden" value="22a9872b3a17abd635a4" />
<div class="tweetbox-head">What's happening?</div>
<textarea class="tweet_input" cols="44" id="tweet_text" name="tweet[text]" rows="2"></textarea>
<input class="tweet-btns" type="submit" value="Tweet" />
</form>
=cut

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

$auth_token = $1;


7. And now, you are ready to post your tweet. by passing tweet[text] parameter together with the authenticity_token.

# posting tweet on twitter
@header = ( 'Referer' => 'http://mobile.twitter.com/', 'User-Agent' => $user_agent );
$response = $lwpua->post('http://mobile.twitter.com/',
['tweet[text]' => $strTweet,
'authenticity_token' => $auth_token], @header);

$form_data = $response->content;
unlink($cookie_file);


8. To get the complete code, please see below. hope you were able to follow. happy coding!!

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

my $lwpua = LWP::UserAgent->new;

my $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ( 'Referer' => 'http://mobile.twitter.com/','User-Agent' => $user_agent);

my $cookie_file = "cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
file => $cookie_file,
autosave => 1,
ignore_discard => 1);

$lwpua->cookie_jar($cookie_jar);

my $strUser = "<your twitter username>";
my $strPass = "<your twitter password>";
my $strTweet = "<your tweet>";

# get authenticity token
my $response = $lwpua->get('http://mobile.twitter.com/session/new', @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

my $auth_token = $1;

# logged in to twitter
$response = $lwpua->post('https://mobile.twitter.com/session',
['username' => $strUser,
'password' => $strPass,
'authenticity_token' => $auth_token], @header);

$cookie_jar->extract_cookies( $response );
$cookie_jar->save;

$response = $lwpua->get('http://mobile.twitter.com', @header);
$form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /input name="authenticity_token" type="hidden" value="(.*?)"/ig;

$auth_token = $1;

# posting tweet on twitter
@header = ( 'Referer' => 'http://mobile.twitter.com/', 'User-Agent' => $user_agent );
$response = $lwpua->post('http://mobile.twitter.com/',
['tweet[text]' => $strTweet,
'authenticity_token' => $auth_token], @header);

$form_data = $response->content;
unlink($cookie_file);



1;

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.