Showing posts with label post. Show all posts
Showing posts with label post. Show all posts

Tuesday, December 17, 2013

get_page_by_slug in wordpress

I'm developing a wordpress site and I need a function that will retrieve the page information from a given slug. I'd been looking into wordpress functions but I can't find it, what I saw are just get_page_by_path and get_page_by_title which are not the perfect function I need for the functionality I need for the site.

So, here's what I did. I checked out the existing functionality which is most likely the same of what I wanted to achieve get_page_by_title then from there I was able to arrived a new function get_page_by_slug that will retrieve the page information from a slug.

Please see below, hope this helps a lot on building your wordpress site and hopefully this would be included on the next version of wordpress.

/**
 * Retrieve a page given its slug.
 * @uses $wpdb
 *
 * @param string $page_slug Page slug
 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
 * @param string $post_type Optional. Post type. Default page.
 * @return WP_Post|null WP_Post on success or null on failure
 */
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
    global $wpdb;
    $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, $post_type ) );
    if ( $page )
        return get_post( $page, $output );

    return null;
}


Please take note that you use this as well on retrieving post coz technically, page and post are the same but with different post type, you just need to pass on third parameter as "post". To make it much clearer with names, please see get_post_by_slug function below.

/**
 * Retrieve a post given its slug.
 * @uses $wpdb
 *
 * @param string $slug Post slug
 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT.
 * @param string $type Optional. Post type. Default page.
 * @return WP_Post|null WP_Post on success or null on failure
 */
function get_post_by_slug($slug, $output = OBJECT, $type = 'post' ) {
    global $wpdb;
    $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $slug, $type ) );
    if ( $post )
        return get_post( $post, $output );

    return null;
}

Sunday, October 16, 2011

JSP 101: How to make a POST and GET method request in JSP

I would like to share with you the GET and POST method request I created while doing some JSP coding.

The example below is a GET method request that will access a specific URL passing the parameters as query string. 


<%@ page language="java" session="false"
import="java.util.*"
import="java.io.*,java.net.*"
%>

<%
try {
        String strLine = "";
        String xmlReturn = "";
       
        URL url = new URL("http://www.example.com/yourscript.jsp?param1=testparam1¶m2=testparam2");

        // read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        while ((strLine = in.readLine()) != null) {
            xmlReturn += strLine;
        }

        // print out xml return by the server
        out.print(xmlReturn);
        in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

%>


The example below is a POST method request that will access a specific URL passing the parameters in a POST manner.


<%@ page language="java" session="false"
import="java.util.*"
import="java.io.*,java.net.*"
%>

<%
try {
        String strLine = "";
        String xmlReturn = "";

        URL url = new URL("http://www.example.com/yourscript.jsp");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
//      connection.setInstanceFollowRedirects(false);

        DataOutputStream xmlRequest = new DataOutputStream(connection.getOutputStream());
        xmlRequest.writeBytes("param1=testparam1&param2=testparam2");
        xmlRequest.flush();
        xmlRequest.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // server returned HTTP 200 and response okay.

                // read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                while ((strLine = in.readLine()) != null) {
                    xmlReturn += strLine;
                }


                // print out xml return by the server
                out.print(xmlReturn);
                in.close();
        } else {
                // server returned HTTP error code.
                out.print(connection.getResponseCode());
        }

} catch (MalformedURLException e) {
} catch (IOException e) {
}

%> 


Hope this helps you on your JSP endeavor. Happy coding!!

Quote for the day: The real heart of servanthood is security. Show me someone who thinks he is too important to serve, and I'll show you someone who is basically insecure. How we treat others is really a reflection of how we think of ourselves. - john m.

Thursday, March 3, 2011

How to make a form post request in PERL


The FORM POST is the most common method of transferring data to a web application. On this post, we will have this implement in PERL which is known to be a back-end processing script.

This is really simple, just follow the 3 simple steps below.

1. Install the Perl Library in your server.
  • LWP::UserAgent

2. Initialize user agent and headers.

require LWP::UserAgent;

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' => '<domain of where to do post request>',
             'User-Agent' => $user_agent);

3. Execute post request with the Parameters in array form and get the return by calling $object->content.

$response = $lwpua->post('<url of where to do post request>',
                            ['<parameter1>' => '<value1>',
                             '<parameter2>' => '<value2>',
                             '<parameter..n>' => '<value..n>'], @header);

$return = $response->content;

Hope you like it!! Please see code below for the complete implementation of form post request.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

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://domain.to.post.com',
             'User-Agent' => $user_agent);

$response = $lwpua->post('http://domain.to.post.com/some.action.page',
                            ['parameter1' => 'value1',
                             'parameter2' => 'value2',
                             'parameter3' => 'value3'], @header);

$return = $response->content;

print "$return\n\ndone!";



1;

Saturday, February 19, 2011

How to make a form post request in PHP using CURL

You can do form post by using CURL in PHP.

As stated below function do_post_request(), you only have 2 parameters to pass on which is $post_url and $post_data. The $post_url is the form action URL where to post the data and the $post_data are the input parameters or data to be posted in a form.

For the $post_data, parameters are delimited by ampersand "&" like query string. Ex. username=...&password=...

This is very simple but very powerful which can really help you doing a back-end processing.

Please see below for the sample POST request.

<?

$post_url = 'http://www.example.com/post-here.php';
$post_data = 'username=myusername&password=mypassword';

do_post_request($post_url, $post_data);

function do_post_request($post_url, $post_data)
{
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "$post_url");
        curl_setopt($ch, CURLOPT_POSTFIELDS, "$post_data");
        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");
        $response = curl_exec($ch);

        return $response;
}

?>

Tuesday, February 15, 2011

How to post tweet using OAuth access Token in PERL

OAuth access Token was gain from my previous post - How to exchange requested Token for an access Token from Twitter in PERL

In posting a tweet, we will use the resource URL - http://api.twitter.com/1/statuses/update.json and the POST method.

Just follow the steps below to post tweet on users behalf.

1. Install the following libraries.
  • LWP::UserAgent
  • HTTP::Cookies
  • Digest::MD5
  • Digest::SHA
  • POSIX

2. Initialize the libraries.

require LWP::UserAgent;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

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

3. Setup the UserAgent and HTTP header with the name "Authorization" equal to "OAuth".

my $uagent = "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' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

4. Build the signature base and signing key. Please take note that some parameters should be URL Encoded, see the post for the PERL function that you can use - URLENCODE sub function in PERL.

You need the consumer key and secret which was generated by Twitter upon registration.

You also need the Oauth Token and Secret which you get when exchanging the requested token for an access token.

To generate NONCE, we use Digest::MD5::md5_base64() passing the localtime(). We do it twice to make it much UNIQUE.

Timestamp was generated by using POSIX::strftime() with date format UNIXTIME as "%s".

Signing key was generated by combining the 2 parameters: Consumer Secret and OAuth Token Secret delimited by ampersand "&"

my $strToken = "<your oauth access token>";
my $strSecret = "<your oauth access token secret>";
my $strStatus = "<your tweet>";

my $post_url = "http://api.twitter.com/1/statuses/update.json";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);
my $status_enc = &urlencode($strStatus);

my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_version=$version&status=$status_enc";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&".$strSecret;

5. Generate the OAuth Signature using HMAC-SHA1 method.

my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

6. Post an OAuth request with all the parameters you passed on step #4.

my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'status' => $strStatus,
                         'oauth_version' => $version], @header);

print $response->content;

7. To know if successful, you can print the response and it should be look like this.

{
    "geo":null,
    "created_at":"Mon Apr 26 23:45:50 +0000 2010",
    "in_reply_to_user_id":null,
    "truncated":false,
    "place":null,
    "source":"&lt;a href=\"http://dev.twitter.com\" rel=\"nofollow\"&gt;OAuth Dancer&lt;/a&gt;",
    "favorited":false,
    "in_reply_to_status_id":null,
    "contributors":null,
    "user":
    {
        "contributors_enabled":false,
        "created_at":"Wed Mar 07 22:23:19 +0000 2007",
        "description":"Reality Technician,
         Developer Advocate at Twitter,
         Invader from the Space.",
        "geo_enabled":true,
        "notifications":false,
        "profile_text_color":"000000",
        "following":false,
        "time_zone":"Pacific Time (US &amp; Canada)",
        "verified":false,
        "profile_link_color":"731673",
        "url":"http://bit.ly/5w7P88",
        "profile_background_image_url":"http://a3.twimg.com/profile_background_images/19651315/fiberoptics.jpg",
        "profile_sidebar_fill_color":"007ffe",
        "location":"San Francisco,
         CA",
        "followers_count":1220,
        "profile_image_url":"http://a3.twimg.com/profile_images/836683953/zod_normal.jpg",
        "profile_background_tile":true,
        "profile_sidebar_border_color":"bb0e79",
        "protected":false,
        "friends_count":1275,
        "screen_name":"episod",
        "name":"Taylor Singletary",
        "statuses_count":5733,
        "id":819797,
        "lang":"en",
        "utc_offset":-28800,
        "favourites_count":89,
        "profile_background_color":"000000"
    },
    "in_reply_to_screen_name":null,
    "coordinates":null,
    "id":12912397434,
    "text":"setting up my twitter \u79c1\u306e\u3055\u3048\u305a\u308a\u3092\u8a2d\u5b9a\u3059\u308b"
}


Please see the complete code below.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);


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

my $uagent = "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' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

# build signature base
my $strToken = "<your oauth access token>";
my $strSecret = "<your oauth access token secret>";
my $strStatus = "<your tweet>";

my $post_url = "http://api.twitter.com/1/statuses/update.json";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);
my $status_enc = &urlencode($strStatus);
my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_version=$version&status=$status_enc";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&".$strSecret;

# oauth signature
my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

# post oauth request
my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'status' => $strStatus,
                         'oauth_version' => $version], @header);

print $response->content;



1;

Wednesday, February 9, 2011

How to make a form post request in jQuery

Download the latest jQuery http://code.jquery.com/jquery-1.4.4.min.js save that in your server, set it as your source file, then call the method $.ajax() with parameters as follows:
  • URL as your form action
  • TYPE as your form method
  • DATA as your input parameters.
You can also set the callback function for successful and error transactions.

<script type="text/javascript" src="http://domain.url.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
        function form_post() {
                $.ajax({
                        url : 'http://domain.url.com/form.php',
                        type: 'post',
                        data: {'param1' : 'param1_value', 'param2' : 'param2_value'},
                        success: function(data){
                                alert(data);
                        },
                        error: function(data){
                                alert(data);
                        }
                });
        }
</script>

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

Thursday, December 23, 2010

How to post facebook status via backend in PERL

We know that facebook site is a secured and very strict with regards to their website and other site components. There is so much happening on the site that users doesn't realize it changes constantly and that is also for security reason, why? that is because hackers do some research, checking the site constantly as well and if your site is not changing, they can come up with a plan and boom!! before you know it, you're doom already.

Enough with the applaud to the company coz they were great already.

I'm not here to lecture about hacking, but how to submit facebook status right? so, just follow the steps below and you can have a BOT that will send facebook status without human intervention.

1. First thing you have to do is to know the structure of the wap site, this time the facebook wap site http://m.facebook.com

2. Since we are using PERL, we have to install some libraries for sending HTTP request and cookies. install the libraries below:
  • LWP::UserAgent
  • HTTP::Cookies

3. After installing the 2 libraries into your server, we are now ready to do the coding. The code below is just a standard coding that we do in PERL.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;


4. After we require the libraries, we need to initialize the variables we need.

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

5. Set your facebook username/email, password, and your status. please see below.

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


6. Set up user agent that we will use to send HTTP request.

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);


7. Set up cookie file and jar.

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

$lwpua->cookie_jar($cookie_jar);


8. Setup the code for log-in to facebook. Please take note that you should know the link of the login page of the site which is http://m.facebook.com/login.php. The important thing here is to look for the FORM element in which the site is submitting the credentials. You also have to get all the important INPUT parameters for submission to the FORM. I pasted here the FORM element of the login page source as of today as reference. Below also are the ONLY details you need to login.

=begin
<form method="post" action="https://login.facebook.com/login.php?m=m&amp;refsrc=http%3A%2F%2Fm.facebook.com%2login.php&amp;fbb=rac4881b1&amp;refid=9">
<input class="input" name="email" value="" type="text"/>
<input class="input" name="pass" type="password"/>
<input type="submit" value="Log In" class="btn btnC" name="login"/>
</form>
=cut

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


9. After logging in, we have to extract the COOKIES and use it on our next SESSION or PAGE.

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


10. After saving the COOKIES, accessing the facebook home page should direct you to the home page where in you can send your STATUS. You can check that if you print the $response->content. I also pasted the code snippet of the content below as reference.

$response = $lwpua->get('http://m.facebook.com/home.php', @header);
my $form_data = $response->content;

=begin
<form method="post" id="composer_form" action="/a/home.php?fbb=r488fb708&amp;refid=7"><input type="hidden" name="fb_dtsg" value="DdtLy" autocomplete="off" /><input type="hidden" name="post_form_id" value="726fdf3c15403500a70f64960565e305" /><input type="hidden" name="charset_test" value="€,´,€,´,æ°´,Д,Є" /><div>What&#039;s on your mind?<br /><textarea class="composerInput" name="status" rows="2" onfocus="" onblur=""></textarea></div><input type="submit" value="Share" class="btn btnC" name="update" /></form>
=cut


11. Same thing here with the login page but this time, we need to know how the page sends a status message. find the FORM that submits STATUS. please take note that the site is frequently changing so you should know how to do the REGEX to catch all the PARAMETERS you need and for the benefit of this post, the above content is the updated content as of today and my REGEX below should be able to catch parameters such as: FORM ACTION, FB_DTSG, and POST_FORM_ID.

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

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


12. Send now the STATUS message with the PARAMETERS needed below.

@header = ('Referer' => 'http://m.facebook.com/',
           'User-Agent' => $user_agent);

$response = $lwpua->post('http://m.facebook.com'.$form_action,
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'status' => $strStatus,
                            'update' => 'Share'], @header);

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

1;


13. And, that's it!! below is the whole script. hope you were able to get it. next will be in PHP. yeah men!!

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

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

my $strUser = "<your facebook username>";
my $strPass = "<your facebook password>";
my $strStatus = "<your facebook status>";

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 $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/home.php', @header);

my $form_data = $response->content;

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

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

@header = ('Referer' => 'http://m.facebook.com/',
           'User-Agent' => $user_agent);

$response = $lwpua->post('http://m.facebook.com'.$form_action,
                           ['fb_dtsg' => $form_fbdtsg,
                            'post_form_id' => $form_id,
                            'status' => $strStatus,
                            'update' => 'Share'], @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.