Saturday, April 20, 2013

Login into your site using facebook account

Step 1:

The primary step is to visit http://developers.facebook.com/apps.
If you are visiting this URL for the first time, you will have a window similar to the one shown below in which Facebook developer app will request your permission to access your basic information.

Click the ‘Allow’ button.

Step 2:

Now you be on a page that shows you your recently viewed app. Don’t worry if it doesn’t show any app. It just means that you haven’t created any app yet.
Now, click ‘Create New App’ button.


In the window that pops up, enter the name of your application. Mark the check box ‘I agree to Facebook Terms’ and click ‘Continue’ button.
Now you may be asked to solve a captcha which verifies that you are human.

Step 3:

You will be taken to the application basic settings page.
On the top portion of the page you will have your ‘App ID’ and ‘App Secret’.
Enter your domain name as ‘App Domain’. Please note that a ‘your-domain.com’ will include ‘*.your-domain.com’ also. That is, you can use the app on any of your sub-domains. You can even enter ‘localhost’ if you are testing your application on your local machine. If localhost not working you need to setup your virtual host in case you use apache as server.
In the ‘Website with Facebook Login’ section, you need to enter ‘Site URL’. ‘Site URL’ will be entry page for your application. As we are making a webpage that has f-connect enabled, we need to give the address of the webpage that we are about to make.Because of security reasons, Facebook will redirect users to this URL only. We will be creating webpage in the later sections. If you are not sure about what your URL will be, just leave the field blank as you can fill it any time later.











Step 4:
Now write your php application. Suppose file index.php.
Define your scopes to want from user:
https://developers.facebook.com/docs/reference/login/#permissions
email, read_stream, user_birthday, user_location, user_work_history, 
user_hometown, user_photos



<?php
session_start();
$app_id = "250395365104464";
$app_secret = "3b616d9db3dc586b5ed784ef89e5f1a5";
$my_url = "http://thecontactspace.com/site/fb";
$scope = "email";
if(isset($_GET["logout"])) {
    unset($_SESSION["__access_token"]);
}

if(isset($_SESSION["__access_token"])) {
    echo "<a href='?logout'>Logout</a>";
    $graph_url = "https://graph.facebook.com/me?" .  
        $_SESSION["__access_token"];
    $user = json_decode(file_get_contents($graph_url));
    print_r($user); 
    die();
} else {
    if(!isset( $_REQUEST["code"] ) ) {
        $dialog_url = "http://www.facebook.com/dialog/oauth?".
            "scope=$scope&client_id=" . 
            $app_id . "&redirect_uri=" .  
            "".rawurlencode($my_url);
        echo("<script> top.location.href='" . $dialog_url . "'</script>");
        return;
    } else {
        $code = $_REQUEST["code"];
        $token_url = "https://graph.facebook.com/oauth/access_token?client_id="
        . $app_id . "&redirect_uri=" . urlencode($my_url) . "&client_secret="
        . $app_secret . "&code=" . $code;

        $access_token = file_get_contents($token_url);
        $_SESSION["__access_token"] = $access_token;
        header('Location: ' . $my_url);
    }
}
?>

Friday, April 19, 2013

Check password strength / safety with PHP and Regex

<?php
function checkPasswordLength($password, &$message) {
    if(strlen($password) < 8) {
        $message = "Password too short!";
        return false;
    }
    if(strlen($password) > 20) {
        $message = "Password too long!";
        return false;
    }
    if( !preg_match("#[0-9]+#", $password) ) {
        $message = "Password must include at least one number!";
        return false;
    }
    if( !preg_match("#[a-z]+#", $password) ) {
        $message = "Password must include at least one letter!";
        return false;
    }
    if( !preg_match("#[A-Z]+#", $password) ) {
        $message = "Password must include at least one CAPS!";
        return false;
    }
    if( !preg_match("#\W+#", $password) ) {
        $message = "Password must include at least one symbol!";
        return false;
    }
    return true;
}
?>

Get google analytics data using google service account

Create service account
https://developers.google.com/analytics/devguides/reporting/core/dimsmets/time
<?php 
    $startDate = "2013-03-07";
    $endDate = "2013-04-06";
    $location = APP."libs".DS."google_api".DS."src".DS;

    require_once($location . 'Google_Client.php');
    require_once($location . 'contrib/Google_AnalyticsService.php');

    $CLIENT_ID = 'something.apps.googleusercontent.com';
    $SERVICE_ACCOUNT_NAME = 'something@developer.gserviceaccount.com';
    $KEY_FILE = $location . "something.p12";


    $client = new Google_Client();
    $client->setApplicationName("Project Name");

    if (isset($_SESSION['token'])) {
        $client->setAccessToken($_SESSION['token']);
    }

    $client->setAssertionCredentials(
        new Google_AssertionCredentials(
            $SERVICE_ACCOUNT_NAME, // email you added to GA
            array('https://www.googleapis.com/auth/analytics.readonly'),
            file_get_contents($KEY_FILE)
        )
    );
    $client->setClientId($CLIENT_ID);           // from API console
    $client->setAccessType('offline_access');  // this may be unnecessary?
    $client->setUseObjects(true);

    $service = new Google_AnalyticsService($client);

    $accounts = $service->management_accounts->listManagementAccounts();
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    $webProperties = $service->management_webproperties->listManagementWebproperties($firstAccountId);
    $items = $webProperties->getItems();
    $firstWebPropertyId = $items[0]->getId();

    $profiles = $service->management_profiles->listManagementProfiles($firstAccountId, $firstWebPropertyId);
    print_r($profiles);

    $data = $service->data_ga->get(
        "ga:51149337",
        $startDate,
        $endDate,
        "ga:visits,ga:bounces",
        array("dimensions" => "ga:date")
    );

    print_r($data); die();
?>

Thursday, April 18, 2013

Parse XML using java


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bd.com.pritom.xml.XmlSimpleParser;

import java.io.ByteArrayInputStream;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author User
 */
public class ParseXmlString {
    public static void main(String[] args) throws Exception {
        String xmlString = "<?xml version=\"1.0\"?>\n" +
            "<Users>\n" +
            " <User id=\"1001\">\n" +
            "  <firstname>Pritom</firstname>\n" +
            "  <lastname>Kumar Mondal</lastname>\n" +
            "  <nickname>pritom</nickname>\n" +
            " </User>\n" +
            " <User id=\"2001\">\n" +
            "  <firstname>Pallob</firstname>\n" +
            "  <lastname>Mondal</lastname>\n" +
            "  <nickname>mondal</nickname>\n" +
            " </User>\n" +
            "</Users>";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        
        /* If you want to parse xml from a string variable */
        Document doc = dBuilder.parse( new ByteArrayInputStream(xmlString.getBytes()) );
        /* If you want to parse xml from file */
        /* File fXmlFile = new File("C:\\tmp\\Users.xml");
        Document doc = dBuilder.parse(fXmlFile); */
        
        doc.getDocumentElement().normalize(); 
        System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 
        NodeList nList = doc.getElementsByTagName("User");
        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            System.out.println("----------------------------");
            System.out.println("Current Element :" + nNode.getNodeName());
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element eElement = (Element) nNode;
                System.out.println("User id : " + eElement.getAttribute("id"));
                System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
                System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
                System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
            }
        }
    }
}

And output would be like this:


Root element :Users
----------------------------
Current Element :User
User id : 1001
First Name : Pritom
Last Name : Kumar Mondal
Nick Name : pritom
----------------------------
Current Element :User
User id : 2001
First Name : Pallob
Last Name : Mondal
Nick Name : mondal

This is a simple xml parse technique. If you want recursively want to parse an unknown xml (xml tag unknow to you, any type of xml) and store to a java hashmap, please follow the link, full source code written for you.

Java: convert a string to MD5 encryption

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DemoMD5
{    
    private static String convertedToHex(byte[] data)
    {
        StringBuffer buf = new StringBuffer();
       
        for (int i = 0; i < data.length; i++)
        {
            int halfOfByte = (data[i] >>> 4) & 0x0F;
            int twoHalfBytes = 0;
           
            do
            {
                if ((0 <= halfOfByte) && (halfOfByte <= 9))
                {
                    buf.append( (char) ('0' + halfOfByte) );
                }
               
                else
                {
                    buf.append( (char) ('a' + (halfOfByte - 10)) );
                }

                halfOfByte = data[i] & 0x0F;

            } while(twoHalfBytes++ < 1);
        }
        return buf.toString();
    }

    public static String MD5(String text)
    throws NoSuchAlgorithmException, UnsupportedEncodingException 
    {
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        byte[] md5 = new byte[64];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md5 = md.digest();
        return convertedToHex(md5);
    }
}

Get Unix timestamp in Java, Python, Erlang, JavaScript, Php

To Get Unix timestamp value in seconds
Java:
long timestamp = System.currentTimeMillis()/1000
Python:

import time
timestamp = int(time.time())
Erlang:

{Mega, Secs, _} = now(),
Timestamp = Mega*1000000 + Secs,
JavaScript:

var ts = Math.floor(Date.now()/1000);
// You can also use new Date().getTime()/1000 but this one is faster
Php:
$stamp = time();

Java - sending HTTP parameters via POST method Using HttpClient


HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://something.com/login");
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("username", "username"));
list.add(new BasicNameValuePair("password", "password"));
httppost.setEntity(new UrlEncodedFormEntity(list));

HttpResponse response = client.execute(httppost);
System.out.println("STATUS LINE: "+response.getStatusLine());
System.out.println("STATUS PHRASE: "+response.getStatusLine().getReasonPhrase());
System.out.println("STATUS METHOD: "+httppost.getMethod());
HttpEntity entity = response.getEntity();

if (entity != null) {
    System.out.println("CONTENT:\n");    
    InputStream inputStream = entity.getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println("LINE: "+line);
    }
    br.close();
}