Here is the official and excercised Facebook Connect modification. We plan to add a lot more in, and this code will be updated through time as well as the versioning.
Features:
- Allow users to signup via Facebook
- Properly formatted fields (for Facebook data)
- Display to user if their connected through facebook or not (yes/no)
- Fetch users Facebook photo (Incomplete, only shows photo cant insert into signup)
- Manage multiple querys to serve for other puposes (Auto-message new user, connected query, etc)
- Version: 1.0
Introduction:
Using the previous modification (based upon) the 2.08 mod from Lee, this needed work so I share with you the changes so far in better connecting your TorrentTrader community to Facebook services.
While considering the changes, our own verison seemed appropiate. What this will allow you to have in the end, is a image link that connects with Facebook then returns the data to fill in the signup fields.
The code has been modified for everyone else to use so there is no confusion. If you see any bloated/dirty code or anything else that seems unethical, please reply with your solution.
Installation:
1.) execute SQL query:
ALTER TABLE `users` ADD `facebook_connected` ENUM( 'yes', 'no' ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'no';
2.) open
/themes/default/header.php and insert this anywhere you need:
<? if (isset($CURUSER)){ ?><? }else{ ?><a href='/join/facebook/' style='outline:0;'><img src='/images/facebook_connect.gif' border='0' title='Connect with Facebook' /></a><? } ?>
3.) open .htaccess and add:
RewriteRule ^join/([^/]*)/$ /account-signup.php?do=$1 [L]
4.) Add this anywhere on your site. This just tells the user if they connected through Facebook or not:
<? if ($CURUSER["facebook_connected"] == "yes"){print("yes");}else{print("no");}?>
5.) save this as class.facebook.php and copy to /backend
<?
//
// Facebook Connect v1.0 - Lee (with changes from Cody)
// https://wiilikefree.com/
//
class Facebook
{
private $_path = array('login' => 'https://www.facebook.com/dialog/oauth?', 'token' => 'https://graph.facebook.com/oauth/access_token?', 'graph' => 'https://graph.facebook.com/me?');
private $_info = array('apikey' => 'YOUR_APP_KEY', 'secret' => 'YOUR_APP_SECRET');
public function getAuth()
{
$data = array(
'client_id' => $this->_info['apikey'],
'redirect_uri' => 'http://YOUR_DOMAIN/account-signup?do=facebook',
'scope' => 'email,publish_stream'
);
header('Location: ' . $this->_path['login'] . http_build_query($data));
}
public function getToken($code = null)
{
$data = array(
'client_id' => $this->_info['apikey'],
'redirect_uri' => 'http://YOUR_DOMAIN/account-signup?do=facebook',
'client_secret' => $this->_info['secret'],
'code' => $code
);
$path = $this->_path['token'] . http_build_query($data);
if (($token = $this->_request($path)) && ($user = $this->_request($this->_path['graph'] . $token))) {
return array(
'token' => $token,
'user' => json_decode($user)
);
}
return (bool) false;
}
private function _request($path)
{
if (extension_loaded('curl')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $path);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$data = curl_exec($ch);
curl_close($ch);
} else {
$data = file_get_contents($path);
}
return $data;
}
}
?>
6.) open account-signup.php and make the following changes:
Find:
require_once("backend/functions.php");
Under, add:
require_once("backend/class.facebook.php");
Find:
if ($takesignup == "1") {
Add directly before:
$data = null;
if ( $_REQUEST['do'] == 'facebook' )
{
$Facebook = new Facebook();
if ( isset($_REQUEST['code']) )
{
if (!($data = $Facebook->getToken($_REQUEST['code'])))
{
show_error_msg('Error', 'Facebook Auth failed.', 1);
}
$oauth = $data['token'];
$data = $data['user'];
}
else
{
$Facebook->getAuth();
}
}
Find:
$signupclass = '1';
Add after:
$avatar = null;
if ( isset($data->username) || isset($data->id) ) {
$avatar = 'https://graph.facebook.com/' . (isset($data->username)) ? $data->username : $data->id . '/picture';
}
$token = null;
if (isset($oauth))
{
$token = $oauth;
}
$ret = mysql_query("INSERT INTO users (username, password, secret, email, status, added, age, country, gender, client, stylesheet, language, class, ip, avatar, token) VALUES (" .
implode(",", array_map("sqlesc", array($wantusername, $wantpassword, $secret, $email, $status, get_date_time(), $age, $country, $gender, $client, $site_config["default_theme"], $site_config["default_language"], $signupclass, getip(), $avatar, $token))).")");
$id = mysql_insert_id();
if (is_object($data))
{
// Insert query after facebook signup (successful)
$queries[] = "INSERT INTO shoutbox (msgid, user, message, date, userid) VALUES (NULL, '$avatar', ' ".$wantusername." has signed up', now(), '0')";
$queries[] = "UPDATE `users` SET `facebook_connected` = 'yes' WHERE `id` = " . $id . "";
if ($site_config["WELCOMEPMON"]){
$dt = sqlesc(get_date_time());
$msg = sqlesc($site_config["WELCOMEPMMSG"]);
$queries[] = "INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $id, $dt, $msg, 0)";
}
foreach ($queries as $query) {
mysql_query($query);
}
logincookie($id, $wantpassword, $secret);
header("Refresh: 0; url=http://YOUR_DOMAIN/userhome");
die;
}
7.) Replace your entire <form> ..contents.. </form> with:
<form method="post" action="/account-signup?takesignup=1" enctype="multipart/form-data" name="signup">
<? if ($invite_row) { ?>
<input type="hidden" name="invite" value="<? echo $_GET["invite"]; ?>" />
<input type="hidden" name="secret" value="<? echo htmlspecialchars($_GET["secret"]); ?>" />
<? } ?>
<? if ($data != null): ?>
<input type="hidden" name="do" value="facebook" />
<input type="hidden" name="code" value="<? echo $_GET['code'] ?>" />
<body onload="document.signup.wantpassword.focus();">
<?
if (isset($data->username))
{
$avatar = 'https://graph.facebook.com/'.$data->username.'/picture';
print("<div style='display:inline;float:left;'>");
print("<img src=$avatar width=65 height=65 /><br />");
print("</div>");
print("<div style='display:inline;float:left;padding:10px;font-size:13px;background:#F0F8FF;border:1px solid #68D3F3;width:477px;margin-left:10px;height:43px;'>Hello, <b><a href='https://www.facebook.com/$data->username' target='_blank'>$data->username</a></b><br />You are connected via Facebook - <i><b><small><font color=orange>BETA</font></small></b></i></div>");
print("<div style='clear:both;'></div>");
}
?>
<? endif; ?>
<table cellSpacing="0" cellPadding="2" border="0">
<tr>
<td style="padding-bottom:10px;">Username:</td><td style="padding-bottom:10px;"><input value="<? echo (isset($data->username)) ? $data->username : null; ?>" <? echo (isset($data->username)) ? 'readonly="readonly"' : null; ?> type="text" size="40" name="wantusername" id="wantusername" style="<? if ($data != null): ?>background:#F0F0F0;font-size:13px;<? endif; ?>border-bottom:3px solid #33CCFF;border-top:1px solid #c0c0c0;border-right:1px solid #c0c0c0;border-left:1px solid #c0c0c0;padding:4px;width:300px;" />
<? if ($data != null): ?><img src='/images/signup_facebook_connect.png' style='vertical-align:middle;height:27px;' /><? endif; ?>
<div id="userdiv"></div>
</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Email: <font class="small"><font color="#FF0000">*</font></td>
<td style="padding-bottom:10px;"><input type="text" size="40" name="email" style="<? if ($data != null): ?>background:#F0F0F0;font-size:13px;<? endif; ?>border-bottom:1px solid #c0c0c0;border-top:1px solid #c0c0c0;border-right:1px solid #c0c0c0;border-left:1px solid #c0c0c0;padding:4px;width:300px;" value="<? echo (isset($data->email)) ? $data->email : null; ?>" <? echo (isset($data->email)) ? 'readonly="readonly"' : null; ?> />
<? if ($data != null): ?><img src='/images/signup_facebook_connect.png' style='vertical-align:middle;height:27px;' /><? endif; ?>
</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Password: <font class="small"><font color="#FF0000">*</font></td>
<td style="padding-bottom:10px;"><input type="password" size="40" name="wantpassword" style="border-bottom:1px solid #c0c0c0;border-top:1px solid #c0c0c0;border-right:1px solid #c0c0c0;border-left:1px solid #c0c0c0;padding:4px;width:300px;" title='Enter a strong password' /></td>
</tr>
<tr>
<td style="padding-bottom:10px;">Confirm: <font class="small"><font color="#FF0000">*</font></td>
<td style="padding-bottom:10px;"><input type="password" size="40" name="passagain" style="border-bottom:1px solid #c0c0c0;border-top:1px solid #c0c0c0;border-right:1px solid #c0c0c0;border-left:1px solid #c0c0c0;padding:4px;width:300px;" title='Enter password again' /></td>
</tr>
<tr>
<? if ($site_config['AVATAR']) { ?>
<td style="padding-bottom:10px;">Avatar: <font class='small' color='#ff0000'>*</font></td>
<? } else { ?>
<td>Avatar</td>
<? } ?>
<br /><td style="padding-bottom:10px;"><input type="file" size="40" name="avatar" style="width:90px;" /></td>
</tr>
<tr>
<td>Gender: <? echo (isset($data->gender) && $data->gender == 'male') ? '(Facebook: <b>Male</b>)' : null; ?><? echo (isset($data->gender) && $data->gender == 'female') ? '(Facebook: <b>Female</b>)' : null; ?></td>
<td style="padding-top:9px;padding-bottom:9px;">
<input type="radio" name="gender" value="Male" <? echo (isset($data->gender) && $data->gender == 'male') ? '' : null; ?> <? if ($data != null): ?> checked="checked" disabled <? endif; ?> > Male
<input type="radio" name="gender" value="Female" <? echo (isset($data->gender) && $data->gender == 'female') ? '' : null; ?> <? if ($data != null): ?> checked="checked" disabled <? endif; ?> > Female
</td>
</tr>
<tr style='display:none;'>
<td>TimeZone:</td>
<td>
<select name='tzoffset' style='margin-bottom:10px;width:235px;'>
<?
ksort($tzs);
reset($tzs);
while (list($key, $val) = each($tzs)) {
if ($site_config["tzoffset"] == $key)
$tz .= "<option value="$key" selected>$val</option>n";
else
$tz .= "<option value="$key">$val</option>n";
}
?>
<?=$tz?>
</select></td>
</tr>
<tr>
<td style='display:none;'>Country:</td>
<td>
<select name="country" size="1" style="width:235px;visibility:hidden;">
<?
/*
$countries = "<option value="0">---- None selected ----</option>n";
$ct_r = mysql_query("SELECT id,name,domain from countries ORDER BY name") or die;
while ($ct_a = mysql_fetch_array($ct_r)) {
$countries .= "tttttt<option value="$ct_a[id]"";
if ($dom == $ct_a["domain"])
$countries .= " SELECTED";
$countries .= ">$ct_a[name]</option>n";
}
*/
?>
<?//=$countries ?>
</select>
</td>
</tr>
<tr style='display:none;'>
<td>Preferred Client:</td>
<td style="padding-bottom:4px;"><input type="text" size="40" name="client" maxlength="20" style="border:1px solid #c0c0c0;padding:2px;" /></td>
</tr>
<tr>
<td align="right" colSpan="2">
<input type="submit" value="Create Account">
</td>
</tr>
</table>
</body>
</form>
Lastly.. find:
$message = "That doesn't look like a valid email address.";
Add directly under:
elseif ($site_config['AVATAR'] && $_FILES['avatar']['name'] == '')
$message = "You forgot to upload your avatar.";
/* Avatar Vars */
$avatar = '';
$types = array (
'image/gif' => 'gif',
'image/pjpeg' => 'jpg',
'image/jpeg' => 'jpg',
'image/jpg' => 'jpg',
'image/png' => 'png'
);
$size = 512000 * 4;
$path = getcwd() . '/images/avatar/';
/* End */
if (!($_FILES['avatar']['name'] == '')) {
if (!array_key_exists($_FILES['avatar']['type'], $types))
$message = 'Invalid image extenstion.';
if (!preg_match('/^(.+).(jpg|gif|png)$/si', $_FILES['avatar']['name']))
$message = 'Invalid image.';
if ($_FILES['avatar']['size'] > $size)
$message = 'Image cannot be more than ' . mksize($size);
$sql = mysql_query('SHOW TABLE STATUS LIKE "users"');
$row = mysql_fetch_array($sql);
$uid = $row['Auto_increment'];
$ext = substr($_FILES['avatar']['name'], strlen($_FILES['avatar']['name']) - 4, 4);
$copy = copy($_FILES['avatar']['tmp_name'], $path . $uid . $ext);
if (!$copy)
$message = 'Image could not be copied to location.';
$avatar = $site_config['SITEURL'] . '/images/avatar/' . $uid . $ext;
}
[/code]
Create directory
/images/avatar and CHMOD 777
/avatar
Save this and upload to
/images
Screenshot in action: