Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Sign In
Not a member yet? Click here to register.

Facebook Integration

I have a feeling this might be popular ;) I want to develop an infusion that will integrate a site with Facebook, so you will be able to do things like use Facebook as the security, its a sure way to get a lot of new visitors to your site.

I've done quite a bit of the work and just about had it working (not as an infusion) with 7.1 when 7.2 came along, so I've bitten the bullet and upgraded my site and now need to think about how to recode.

What I've done so far
I've got a new facebook application created (and can produce documentation on how to do this). There were a couple of bits here and there that I've mustered together and got a panel with a button that will go to Facebook, get an authentication key, then bring it back to the site.

The code then checks if the user exists, and if not creates a new user in the database with a password and mails it to the new user.

What needs finishing
I need help now, to get the rest of it working with 7.2. The code will recognise that there is a valid facebook user on the site, but it needs to then use the details to log in properly.

Once its working all the code then needs to be made generic so an infusion can be developed.

If anybody is interested then I'll happily put all I've done so far into this thread. I figure that more heads will help debug my code and get this finished off.

Thanks in advance.

Mick

Merged on May 09 2011 at 12:09:06:
The first thing you need to do is to create a new Facebook application. You can do this from the URL http://developers.facebook.com/. From this you will get an application ID number, an application secret key number and an API key which you will use in your customised code.

Here's a summary of code so far

The Login Button
You need a button something like this on a panel:-

CodeDownload  
   
echo "<div style='text-align: center'>"<br />
<a href='https://www.facebook.com/dialog/oauth?   
client_id=<Your Facebook appID>&redirect_uri=facebook_system.php
&scope=email,user_photos,publish_stream& response_type=token'>
<img src='".INFUSIONS."facebook_login_panel/facebook_1.png' /></a></div>";



Substitute in your application ID from above and the redirect URI (needs to be a fully referenced URL) but send it to a page called facebook_system.php. The scope will define just how much access from Facebook you want the user to grant you, here I've asked for permission for the users email details, photos and the ability to publish back to Facebook. The more you ask for the less likely the user will grant you the access, but scope=email is the minimum you should ask for.

What you will get returned is a Facebook token which you can subsequently use to make calls back to Facebook to get details you need.

Facebook_System.php
Unfortunately what gets returned is a "new" style URI where the parameter is passed by a # character rather than a ? character which is what PHP needs. So the following code is required to convert it and then pass it to the page that will work out the log in details.
CodeDownload  

<HTML>
<HEAD>
<SCRIPT LANGUAGE = JavaScript>
var myurl=document.URL;
myurl=myurl.replace('#','?');
myurl=myurl.replace('system.php','system2.php');
this.location.href = myurl</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>



The details never get passed onto the server so you have to use a simple bit of Javascript to do the replacement.

Facebook_system2.php
This is the page that will check if the user exists already, if it doesn't it will create a new ID. There are two new fields that have been added to the Users table:-

USER_FACEBOOK_USERID and USER_FACEBOOK_HASH, both as text fields.

This bit of the code all works and it will either create a new user, or retrieve the user details back by matching on Facebook ID.


CodeDownload  
<?
require_once "maincore.php";

require_once THEMES."templates/header.php";

// the php facebook api downloaded at step 3
require_once INCLUDES."facebook/facebook.php";

// Check if locale file is available matching the current site locale setting.
if (file_exists(INFUSIONS."facebook_login_panel/locale/".$settings['locale'].".php")) {
    // Load the locale file matching the current site locale setting.
    include_once INFUSIONS."facebook_login_panel/locale/".$settings['locale'].".php";
} else {
    // Load the infusion's default locale file.
    include_once INFUSIONS."facebook_login_panel/locale/English.php";
}


$access_token=$_REQUEST['access_token'] ;

$url='https://graph.facebook.com/me/?access_token='.$access_token;

$fb_user=json_decode(file_get_contents($url));

$out="";
$avatarname="";

if($fb_user){
//method 1:
    if (iMEMBER) {
        if ($userdata['user_fb_userid']=="") {
            dbquery("UPDATE ".DB_USERS." SET user_fb_userid='".$fb_user->id."' WHERE user_id='".$userdata['user_id']."'");
        }
    }
//method 2:
    $result=dbquery("UPDATE ".DB_USERS." SET user_fb_userid=".$fb_user->id." WHERE user_email='".$fb_user->email."'");
//
// with the user id from facebook retrived with the API,
// search for a user already registered with this process:

    $rs = dbquery("SELECT * FROM ".DB_USERS." WHERE user_fb_userid='".$fb_user->id."'");
    if (dbrows($rs)) { $u = dbarray($rs); } else $u="";
   
    if (is_array($u)) {
        //
        // this is a user connected with facebook
        // and already existing on your community.
        // So, log in automatically with user and password of
        // your community. These lens print a form and submit it
        // to your real login page:
        // (change the address in the action to match your normal login page)
        $out.="log in...";
        $out.="<form id='loginform' method='post' action="".FUSION_SELF."">";
        $out.="<input type='hidden' name='user_name' value="".$u['user_name'].""/>";
        $out.="<input type='hidden' name='user_fb_hash' value="".$u['user_password'].""/>";
        $out.="<input type='hidden' name='login' value="login"/>";
        $out.="</form>";

        $out.="<script type="text/javascript">document.getElementById('loginform').submit();</script>";

    } else {
        //
        // this is a user logged in on facebook
        // but it doesn't exists on your community,
        // it's new!
        // So let's create automatically the user and log in!
        $out = '<fb:profile-pic class="fb_profile_pic_rendered FB_ElementReady"' . 'facebook-logo="true" size="square" uid="' . $fb_user->id . '"></fb:profile-pic>';
        //
        /* adding above already ->
        // get some user details from facebook api
        //
        */
        // write out some message to welcome the new user:
        $out.= $fb_user->first_name." ".$fb_user->last_name.", welcome on ".$settings['siteurl']."<br/>";
        $out.= "creating your account on ".$settings['siteurl']."... wait...";
        $tempuser = preg_replace("/[^a-z0-9]/i","",strtolower( $fb_user->first_name."_".$fb_user->last_name));
$found = false;
        $i=0;
        while (!$found) {
        //
        // search for a valid username
        // not already used in your community
        // this username is created with first name and last name
        // from facebook and with a counter:
            $user = $tempuser.($i==0?"":$i);
            $rs = dbquery("SELECT COUNT(*) FROM ".DB_USERS." WHERE user_name='".$user."'");
            $c = mysql_fetch_row($rs);
            if ( $c[0] > 0 ) $i++; else $found = true;
        }
        // generate random password for new user:
        $pass = substr(md5(rand(1,2000)),0,8);
       
        $sql = "INSERT INTO ".DB_USERS." (user_name, user_password, user_admin_password, user_email, user_hide_email, user_avatar, user_posts, user_threads, user_joined, user_lastvisit, user_ip, user_rights, user_groups, user_level, user_status, user_fb_userid, user_fb_hash) VALUES('".$user."', '".md5(md5($pass))."', '', '".$fb_user->email."', '1', '".$avatarname."', '0', '0', '".time()."', '0', '".USER_IP."', '', '', '101', '0','".$fb_user->id."','".md5(md5($pass))."');";

        $result = dbquery($sql);
       
        include_once INCLUDES."sendmail_include.php";
        $subject=sprintf($locale['fb_login_020'],$settings['siteurl']);

        //those are to change locales to real variables
        $find=array("[USER]","[PASS]","[LOGINURL]","[SIGNATURE]");
        $replace=array($user,$pass,$settings['siteurl']."login.php",$settings['siteusername']);

        $html_email_content ="<html><head><style type="text/css">";
        $html_email_content.="<!--";
      $html_email_content.="a { color: #0000ff; text-decoration:none; }";
      $html_email_content.="a:hover { color: #0000ff; text-decoration: underline; }";
      $html_email_content.="body { font-family:Verdana,Tahoma,Arial,Sans-Serif; font-size:10px; }";
      $html_email_content.="p { font-family:Verdana,Tahoma,Arial,Sans-Serif; font-size:10px; }";
      $html_email_content.=".td { font-family:Verdana,Tahoma,Arial,Sans-Serif; font-size:10px; }";
      $html_email_content.="-->";
      $html_email_content.="</style></head>".nl2br(str_replace($find,$replace,$locale['fb_login_02']))."</body></html>";
      
      sendemail($user, $user_details[0]['email'],$settings['siteusername'],$settings['siteemail'],$subject,$html_email_content,"html",$cc="",$bcc="");
      
      $result=dbquery("SELECT user_id FROM ".DB_USERS." WHERE user_email='".$user_details[0]['email']."'");
      
      $data=dbarray($result);
      $data=dbarray(dbquery("SELECT user_id FROM ".DB_USERS." WHERE user_name='".$user."'"));
      
      $result = dbquery("INSERT INTO ".DB_MESSAGES." (message_to, message_from, message_subject, message_message, message_smileys, message_datestamp) VALUES ('".$data['user_id']."', '1', '$subject', '".str_replace($find,$replace,$locale['fb_login_03'])."', '1', '".time()."')");

        //
        // new user created, log him in:

        $out.="log in...";
        $out.="<form id='loginform' method='post' action="".FUSION_SELF."">";
        $out.="<input type='hidden' name='user_name' value="".$user.""/>";
        $out.="<input type='hidden' name='user_fb_hash' value="".md5(md5($pass)).""/>";
        $out.="<input type='hidden' name='login' value="login"/>";
        $out.="</form>";
        $out.="<script type="text/javascript">document.getElementById('loginform').submit();</script>";   

       
       
    }
   
   

}
echo $out;

require_once THEMES."templates/footer.php";
?>
?>



I hope at least this is helpful to somebody, even if nobody is able to assist any further.
Thread Information
Author
Replies
1 post
Views
2,881 times
Last Post
Last updated on 9 years ago
You can view all discussion threads in this forum.
You cannot set up a bounty in this discussion thread.
You can start a new discussion thread in this forum.
You cannot reply in this discussion thread.
You cannot start on a poll in this forum.
You cannot upload attachments in this forum.
You can download attachments in this forum.
You cannot up or down-vote on the post in this discussion thread.
Users who participated in discussion: Honest Mick