How can I save a comment made with facebook comments to a mysql database? I want to be able to search through the comments on another page.
you mean where you comment on, for example, your wall, the comment to get to your mysql database?
if so, you need to study Facebook API (Graph API)
<?php
// displays some comments for a certain url
$url = 'http://developers.facebook.com/docs/reference/fql/comment/';
// fql multiquery to fetch all the data we need to display in one go
$queries = array('q1' => 'select post_fbid, fromid, object_id, text, time from comment where object_id in (select comments_fbid from link_stat where url ="'.$url.'")',
'q2' => 'select post_fbid, fromid, object_id, text, time from comment where object_id in (select post_fbid from #q1)',
'q3' => 'select name, id, url, pic_square from profile where id in (select fromid from #q1) or id in (select fromid from #q2)',
);
// note format json-strings is necessary because 32-bit php sucks at decoding 64-bit ints :(
$result = json_decode(file_get_contents('http://api.facebook.com/restserver.php?format=json-strings&method=fql.multiquery&queries='.urlencode(json_encode($queries))));
$comments = $result[0]->fql_result_set;
$replies = $result[1]->fql_result_set;
$profiles = $result[2]->fql_result_set;
$profiles_by_id = array();
foreach ($profiles as $profile) {
$profiles_by_id[$profile->id] = $profile;
}
$replies_by_target = array();
foreach ($replies as $reply) {
$replies_by_target[$reply->object_id][] = $reply;
}
/**
* print a comment and author, given a comment passed in an an array of all profiles.
* #param object $comment as returned by q1 or q2 of the above fql queries
* #param array $profiles_by_id, a list of profiles returned by q3, keyed by profile id
* #returns string markup
*/
function pr_comment($comment, $profiles_by_id) {
$profile = $profiles_by_id[$comment->fromid];
$author_markup = '';
if ($profile) {
$author_markup =
'<span class="profile">'.
'<img src="'.$profile->pic_square.'" align=left />'.
''.$profile->name.''.
'</span>';
}
return
$author_markup.
' ('.date('r', $comment->time).')'.
': '.
htmlspecialchars($comment->text);
}
print '<html><body>';
// print each comment
foreach ($comments as $comment) {
print
'<div style="overflow:hidden; margin: 5px;">'.
pr_comment($comment, $profiles_by_id).
'</div>';
// print each reply
if (!empty($replies_by_target[$comment->post_fbid])) {
foreach ($replies_by_target[$comment->post_fbid] as $reply) {
print
'<div style="overflow:hidden; margin: 5px 5px 5px 50px">'.
pr_comment($reply, $profiles_by_id).
'</div>';
}
}
}
?>
There are several ways to do it.
The first way is to get all comments in one go. You have to do it periodically to get new comments, and avoid duplicating the old ones in your database.
This can be achieved by accessing the Graph API with the url of your page:
https://graph.facebook.com/comments/?ids=http://example.com/your_page
This returns comments in JSON which you have to parse. If there are too many, there will be an 'paging' hash telling you the address of the next page.
The second way is to track new comment and saves them immediately. This avoids the refetched duplicate problem. This will require the use of Javascript and Facebook js events.
FB.Event.subscribe('comment.create', function(response) {
var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
FB.Data.waitOn([commentQuery], function () {
text = commentQuery.value[0].text;
// Use your preferred way to inform the server to save comment
$.post( 'http://example.com/comment', text )
});
});
The example below fetches the comment at client side. But you can also do it at server-side.
Of course you'll need to include Facebook's Javascript library, and implement the posting action (http://example.com/comment) on your server.
FB.Event.subscribe('comment.create',
function(response) {
onCommentCreate(response.commentID,response.href); //Handle URL on function to store on database
alert(response.href); //it gives you url
}
);
function onCommentCreate(commentID,href) {
$.ajax({
type: 'POST',
url: 'handlecomment.php',
data: {commentid:commentID,href:href},
success: function(result)
{
alert(result);
}
});
}
//hadlecomment.php
<?php
error_reporting(E_ERROR);
$commentid=$_POST['commentid'];
$url=$_POST['href'];
$pid=substr($url,strpos($url, 'comments')+8);
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$accesstoken=$facebook->getAccessToken();
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$facebook->setAccessToken($accesstoken);
$fql = 'SELECT text from comment where id = ' . $commentid;
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,));
$comment= $ret_obj[0]['text'] ;
$insert_comment="insert into comments(pid,comment) values($pid,$comment)";
mysql_query($insert_comment);
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
?>
//YOu need to set data-href of comment should be look like this...
//i am using more comments on my website so i looped through to add comment
while($result=mysql_fetch_assoc(mysql_query($query)))
{
$pic_id=$result['pic_id']; // i have saved unique pic id in my database for all images so i am
//retrieving that here
<div class="fb-comments" style=' position:relative;left:55px;top:10px;' data-href="<?php echo 'http://www.lpuphotography.edulogics.in/votography.php/comments' . $pic_id; ?>" data-width="470" data-num-posts="2"></div>
}
//if you are using single comment
<div class="fb-comments" style=' position:relative;left:55px;top:10px;' data-href="<?php echo 'http://www.lpuphotography.edulogics.in/votography.php/comments101' ?>" data-width="470" data-num-posts="2"></div>
//101 is comment id , u can set what ever you want
Related
I am using PinterestPinner to create an script that could login once and post multiple pins, rather than login each time I want to post a pin.
This is how I am using it:
foreach ($links as $link)
{
$pinterest = new PinterestPinner($username, $password);
$result = $pinterest->pin(array(
'board' => $boardId,
'image' => $image,
'description' => $description,
'link' => $url,
));
if (false === $result) {
echo 'Error: ' . $pinterest->getError();
} else {
echo 'Pin Created, ID: ' . $pinterest->getPinID();
}
}
I think using it this way makes the script login to Pinterest for every single pin. So for example, if I want to post 3 pins in a single script run, then it logs in 3 times rather than logging in once. (Please let me know if I am wrong about this).
How can I modify the script to keep the login session alive while posting multiple pins on my board?
Use This
try {
$pinterest = new PinterestPinner\Pinner;
$pin_id = $pinterest->setLogin('Your Pinterest Login')
->setPassword('Your Pinterest Password')
->setBoardID('Pinterest Board ID')
->setImage('Image URL')
->setDescription('Pin Description')
->setLink('Pin Link')
->pin();
} catch (PinterestPinner\PinnerException $e) {
echo $e->getMessage();
}
i have a display that shows 6 random friends on facebook when using the app, however, what i would like to figure out is how to change the display, so that when the friend is clicked on, they are sent an invite to use the app.
Nothing flash, just some kind of notification to say something along the lines of 'Bob thinks you should use this app' and when clicked, they go to the app.
not sure if it will help, but here is the code i have to display friends of the user.
code:
<div class= "newboxbottom">
<h1>Why not share?</h1>
<?php
$user = $facebook->getuser();
if ($user) {
$user_profile = $facebook->api('/me');
$friends = $facebook->api('/me/friends?fields=first_name');
echo '<table>';
foreach (array_slice($friends["data"], 0, 6) as $value) {
echo '<td>';
echo '<div class="pic">';
echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture?type=normal"/>';
echo '</div>';
echo '<div align="center">','<font color="white">','<div class="picName">'.$value["first_name"].'</div>','</font>','</div>';
echo '</td>';
}
echo '</table>';
}
?>
</div>
many thanks to anyone who can help.
Try looking into the Notification API that Anvesh mentioned in a comment.
You'll want to be careful with notifications and follow the recommended best practices. You don't want to send notifications to users who would not want them in the first place. You could get hit with negative feedback and get shut down by Facebook.
As for how to actually make the call? I haven't actually used this particular API method, but from what I can gather, you should be able to do something like this:
<?php
$parameters = array(
'href' => ''
'template' => ''
'ref' => ''
);
try {
$response = $facebook->api('<enter recipient user facebook id here>/notifications', 'post', $parameters);
} catch (FacebookAPIException $e) {
$echo $e->getMessage();
}
Checkout the documentation on more information on the parameters you need to pass. Hope this helps.
I use this script here for my Facebook App.
It uploads a photo on a user's Facebook profile, and creates a new album for that photo.
The script returns "[APP NAME] Photos" as the Album name / title (without quotations).
- [APP NAME] being the name of my Facebook APP -
Basically, I don't want that Album title. I want to specify an Album title on the script.
What I want is :
... to be able to specify the Album's name / title to create, from the script.
And if possible, specify Album description too.
This is the script -
$root_url = "http://www.WEBSITE.COM/";
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
// Get image from URL
$img = $_GET['i'];
// Change location depending on which type of cover
if($get_set != 1) {
$photo = './PATH/'.$img.''; // Path to the photo on the local filesystem
} else {
$photo = './PATH/'.$img.'';
}
$message = 'THIS IS THE PHOTO CAPTION';
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
// Upload to a user's profile. The photo will be in the
// first album in the profile. You can also upload to
// a specific album by using /ALBUM_ID as the path
$ret_obj = $facebook->api('/me/photos', 'POST', array(
'source' => '#' . $photo,
'message' => $message,
)
);
// echo '<pre>Photo ID: ' . $ret_obj['id'] . '</pre>';
print "<script>window.location = '".$root_url."index.php?cover=uploaded'</script>";
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl( array(
'scope' => 'photo_upload'
));
echo '<script> window.location = "' . $login_url . '"; </script>';
error_log($e->getType());
error_log($e->getMessage());
}
echo '<br />logout';
} else {
// No user, print a link for the user to login
// To upload a photo to a user's wall, we need photo_upload permission
// We'll use the current URL as the redirect_uri, so we don't
// need to specify it here.
$login_url = $facebook->getLoginUrl( array( 'scope' => 'photo_upload') );
echo '<script> window.location = "' . $login_url . '"; </script>';
//echo 'Please login to continue.';
}
Seeing this one here, I am confident that is possible.
$album_name = 'YOUR_ALBUM_NAME';
$album_description = 'YOUR_ALBUM_DESCRIPTION';
I just don't know how to work it in there...
Looking forward to solutions. Thanks for your time!
As it says in the documentation of the Photo object:
you can upload a photo by issuing an HTTP POST request with the photo
content and an optional description to one these to Graph API
connections:
https://graph.facebook.com/USER_ID/photos - The photo will be published to an album created for your app. We automatically create an
album for your app if it does not already exist. All photos uploaded
this way will then be added to this same album.
https://graph.facebook.com/ALBUM_ID/photos - The photo will be published to a specific, existing photo album, represented by the
ALBUM_ID. Regular albums have a size limit of 200 photos. Default
application albums have a size limit of 1000 photos.
You are currently using the first option, using the 2nd one requires for you to have an album id, which you first need to create:
You can create an album for a user by issuing an HTTP POST request to
PROFILE_ID/albums with the publish_stream permissions and the
following parameters
(Albums connection of the User object)
The problem is that you'll have to save this album id for the user to use in the future when the app needs to upload again to the album.
This question already has answers here:
How to import photos from Facebook?
(5 answers)
Closed 9 years ago.
I am creating a site where a user that logs in with their Facebook account will see their pictures on the page . What code do i have to put in my website to see the loged in users pictures diplayed.
If someone can help me with a link to a tutorial or point me in the right direction.
I have read a lot of documentation from Facebook and on stack overflow but i cant find an answer,
You can do this two ways: on the server-side (in PHP in your case) or on the client-side with the JavaScript SDK.
Both assume you have the required access credentials. You need to sign up for an application account to get these at the Facebook Developer site
Server-Side
First-step is to get your application to participate in the OAuth authentication process. This is well-documented for PHP in the Facebook guide (see the Server-Side Flow section).
Once you've done that, you'll have an access token that you can call into the Graph API with. The endpoint to get the user's photos is https://graph.facebook.com/me/photos?access_token=<token>. In this case the me, is always the user who signed in to give your application the token.
In PHP, assuming you've stored the access token in $SESSION['token'] you can make a request for the photos payload with:
$url = "https://graph.facebook.com/me/photos?access_token=" . $SESSION['token'];
$photos = json_decode(file_get_contents($url));
The $photos object will be a list of Photo entities that are described in the Facebook docs.
Client-Side
You'll need to setup the JavaScript SDK on your web pages as documented here.
Authentication on the client-side is handled by JavaScript SDK, again documented in the authentication guide.
Using the SDK, you can make a client-side JavaScript call to the Graph API for the same photos structure:
FB.api('/me/photos', function(response) {
if(!response || response.error) {
// render error
} else {
// render photos
}
});
Check this other question on stack How to import photos from Facebook?
I think Now Facebook has changed the way to import photos and so we have to first get albums and than to import photos of that album. At-least i made it in this way. :) Below are the basic api call using PHP
get albums :- <?php $user_albums = $facebook->api('/me/albums', $params); ?>
get album photos :- <?php $user_album_photos = $facebook->api('/' . $album_id . '/photos', $params); ?>
Now here is a full code summary. Do copy this code in file and check for doing import photos
<?php
include 'facebook/facebook.php';
$config = array();
$config['appId'] = YOUR_APP_ID;
$config['secret'] = YOUR_APP_SECRET;
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
$access_token = $facebook->getAccessToken();
?>
<?php
if ($user_id && $access_token) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$params = array(
'method' => 'get',
'access_token' => $access_token
);
if (isset($_GET['aid']) && $_GET['aid'] != '') {
$aid = $_GET['aid'];
$user_album_photos = $facebook->api('/' . $aid . '/photos', $params);
//echo "Photos<br/>";
?>
<?php foreach ($user_album_photos['data'] as $key => $value) {
?>
<div class="album">
<div class="frame photo_frame">
<div class="edit-photo-nohover" style="display:block">
<div><input type="checkbox" id="fbimport_id<?php echo $value['id']; ?>" value="<?= $value['id'] . ',' . $value['images']['0']['source'] . ',' . $value['name'] ?>" name="fbimport[]" > <span>Import this Memory</span></div>
</div>
<table class="test">
<tr><td>
<img src="<?= $value['images']['0']['source'] ?>" height="100" width="100" />
</td>
</tr>
</table>
<h3 id='bottomcaption'><?php echo $value['name']; ?></h3>
</div><br/>
</div>
<?php }
?>
<?php
} else {
$user_albums = $facebook->api('/me/albums', $params);
echo '<h3 class="page-title">Select Your Facebook Album</h3><br/><br/>';
foreach ($user_albums['data'] as $key => $value) {
/* load album if not blank */
if (isset($value['count']) && $value['count'] != '' && $value['count'] != NULL && $value['count'] > 0) {
/* check if album has a cover photo. if not than load a default image */
if (isset($value['cover_photo']) && $value['cover_photo'] != '' && $value['cover_photo'] != NULL) {
$user_album_cover = $facebook->api('/' . $value['cover_photo'], $params);
$album_thumbnail = $user_album_cover['images']['0']['source'];
} else {
$album_thumbnail = 'default_thumb.gif';
}
/* check if album has cover photo end */
?>
<div class="album">
<div class="frame photo_frame">
<table class="test">
<tr><td>
<a href="?aid=<?= $value['id'] ?>" ><img src="<?= $album_thumbnail ?>" height="100" width="100" /></a>
</td>
</tr>
</table>
<h3 id='bottomcaption'><?php echo $value['name']; ?></h3>
</div><br/>
</div>
<?php
}//if(isset($value['count']) && $value['count'] != '' && $value['count'] != NULL && $value['count']>0)
/* load album if not blank end */
}
}
} catch (FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
I have created a fairly secure landing page for our clients to download copies of their contracts.
You hit retrieve.php, the EULA (jQuery Dialog) appears. After you sign and accept, the jQuery dialog disappears.
An AJAX call is sent to the server to get the hashed filename and a link is generated to view the PDF securely in your browser.
The problem is, now the company wants me to add a JPG version of the contract. The contract is either 2 or 3 pages, depending on what service they want to use with us.
The problem I am having is how do I generate the correct number of links for the jpg versions? Everything is done in AJAX, and I would prefer not to return the number of images from AJAX.
The image names are (same hash as pdf)-.jpg
Does anybody have a dynamic way to do this?
I wrote a function that does this in PHP, but since I am running the link generation on the client side, it will not work.
My question is:
I you were me, would you return all 3 or 4 links (pdf + however many jpgs there are) back through JSON?
Would you pass the number of pages back in json and create the links dynamically?
Do you have any better solutions?
Some code:
Here is the AJAX Call that gets sends the info to the server then creates the links:
$.ajax({ type: 'POST',
url: 'getContractAJAX.php',
data: {
'pin' : pin.val(),
'name' : signature.val().toUpperCase(),
'lead' : '<?php echo $_GET['lead']; ?>'
}, /* end data */
cache: false,
success: function(contractId) {
if (contractId['success'] == true) {
contractExpireDate = new Date(contractId['contractExpDate']);
today = new Date();
// Log the signature.
$.post('log.php', {
signature: $("#electronicSignature").val().toUpperCase(),
pin: $("#eSpin").val(),
lead: '<?php echo $_GET['lead']; ?>',
method: 'SIGNATURE'},
function(log) {
if(log['success'] == true) {
/* DOWNLOAD IMAGES LINKS */
$("#downloadLinks").prepend("<a href='#' onclick='log(\""+contractId['contract']+"\", \"DOWNLOAD\");'><img src='img/btnDownloadPdf.png' alt='Downdload PDF' /><br />Download Contract in Adobe © PDF</a>");
} else {
alert("There was a problem! Please contact customer support.");
showDisclosure();
} /* end else */
}); /* end function(log) */
$("#dialog-confirm").dialog("close");
getContractAJAX.php:
if (isset($_POST['pin']) && isset($_POST['name']) && isset($_POST['lead'])){
$pin = $_POST['pin'];
$name = trim($_POST['name']);
$email = $converter->decode($_POST['lead']);
/*
*
*
* PDO
*
*
*/
$stmt = $dbh->prepare("SELECT contract, contractExpireDate
FROM users
WHERE emailAddress=:email AND
pin=:pin AND
concat(firstName, ' ', lastName) LIKE :name AND
contractExpireDate > NOW()
LIMIT 1");
if ($stmt->bindParam(':email', $email, PDO::PARAM_STR) &&
$stmt->bindParam(':pin', $pin, PDO::PARAM_INT) &&
$stmt->bindParam(':name', $name, PDO::PARAM_STR)) {
$stmt->execute();
$found = 0;
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $el) {
$found++;
$contract = $el['contract'];
$contractExpDate = $el['contractExpireDate'];
}
$stmt = null;
}
if ($found > 0) {
$success = true;
} else {
$success = false;
$error = "NO MATCHES FOUND >>> $email >>> $pin >>> $name";
}
}else{
$success = false;
$error = "NOT ALL PASSED";
}
header('Content-type: application/json');
$json = array("contract" => $contract,
"contractExpDate" => $contractExpDate,
"success" => $success,
"messege" => $error);
echo json_encode($json);
Why not return a single compressed file (tar, zip, etc.) of all of the images? That would give you a single download and makes the download faster/smaller.