Graph API Explorer: delete scores - facebook-graph-api

I'm trying to delete all "scores" from the "Graph API Explorer". I selected my application (at the top right), DELETE and wrote https://graph.facebook.com/APP_ID_OMITTED/scores (as request) but I get the error:
{
"error": {
"message": "(#15) This method must be called with an app access_token.",
"type": "OAuthException",
"code": 15
}
}
Where did I go wrong?

It's working now, here's the working code:
// Delete scores for all users
function get_app_access_token($app_id, $app_secret) {
$token_url = 'https://graph.facebook.com/oauth/access_token?'
. 'client_id=' . $app_id
. '&client_secret=' . $app_secret
. '&grant_type=client_credentials';
$token_response = file_get_contents($token_url);
$params = null;
parse_str($token_response, $params);
return $params['access_token'];
}
$app_id = 'OMITTED';
$app_secret = 'OMITTED';
$access_token = get_app_access_token($app_id, $app_secret);
$request_body = '';
$ch = curl_init('https://graph.facebook.com/'.$app_id.'/scores?access_token='.$access_token);
//curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$response = curl_exec($ch);
var_dump($response);

Like the error message says, make sure you're using the Application Access Token
If you just use the Graph API explorer, you probably have a user access token for your account

Related

cURL POST request in C++

I have cURL https request I am trying to send to my web server in a C++ program. I am getting back a "Bad Request" format response.
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl)
{
int res = 0;
snprintf(curl_url, sizeof(curl_url), "https://%s:8080/hello", results);
snprintf(curl_fields, sizeof(curl_fields),"\"name\":\"%s\", \"key\":\"%s\"", name, data);
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: application/json");
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "charset: utf-8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, curl_url);
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, curl_fields);
res = curl_easy_perform(curl);
if ( res )
{
---error---
}
curl_easy_cleanup(curl);
curl_global_cleanup();
}
Can I get some help ?
Are you trying to send the following json?
{
"name": name,
"data": data
}
from this line of code
snprintf(curl_fields, sizeof(curl_fields),"\"name\":\"%s\", \"key\":\"%s\"", name, data);
shouldn't it then be
snprintf(curl_fields, sizeof(curl_fields),"{\"name\":\"%s\", \"key\":\"%s\"}", name, data);
(add the curly braces)

Uploading files in a forum with a Web Service in Moodle

I need to upload files into a forum in moodle through Web Services, I have been searching and I found that exist a WS called core_files_upload(). I looked at the code of this WS and the context level of this WS is only (block, course, coursecat, system, user or module), the context forum not exist and this WS is deprecated.
I also found that in Moodle 3.0 there are 2 new WS related to forums, they are mod_forum_add_discussion and mod_forum_add_discussion_post but I also looked at the code and they don't allow upload.
Then I decided that the best solution would be to create a new one, but I don't know much about uploading files in Moodle and can't find much information. I'm a little bit familiar with the structure of the WS in Moodle because I have made 2 very simple WS but I don't know how to do this.
If anyone knows how to do it or have any examples or documentation that may be useful, it would be helpful.
Thanks in advance.
You can look up for the file
/webservice/upload.php
this file is for uploading files
$params = array('token'=>$token, 'filepath' => $filepath
, 'filearea'=>'draft') + $_FILES ;
$serverurl = <domainname>. '/webservice/upload.php'. '?token=' . $token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, $serverurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
or this can code can help you, that will create a file in moodle data and record in file table from temp file.
$fs = get_file_storage();
$target_path = <target-path>;
$context = get_context_instance(CONTEXT_USER, $userID, MUST_EXIST);
$cm = get_coursemodule_from_instance('forum', $forum->id);
$modcontext = context_module::instance($cm->id, MUST_EXIST);
//saving in draft
$item = rand();
$file_record = array('contextid'=>$context->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$item,
'filepath'=>"/", 'filename'=><filename>, 'userid'=>$userID);
$fs->create_file_from_pathname($file_record, $CFG->dirroot."/".$target_path.<filename>);
// saving for post
$file_record = array('contextid'=>$modcontext->id, 'component'=>'mod_forum', 'filearea'=>'post', 'itemid'=>$post->id,
'filepath'=>"/", 'filename'=><filename>, 'userid'=>$userID);
$fs->create_file_from_pathname($file_record, $CFG->dirroot."/".$target_path.$imagefileEnc);
At the request of #insightful i I'm going to publish my code, I hope this helps somebody
First the externallib.php of the WS
externallib.php
require_once($CFG->libdir . "/externallib.php");
require_once($CFG->libdir . "/filelib.php");
class local_upload_tfg_external extends external_api {
/**
* Returns description of method parameters
* #return external_function_parameters
*/
public static function upload_tfg_parameters() {
return new external_function_parameters(
array('community_key' => new external_value(PARAM_TEXT, 'Comunidad a la que se subira el TFG o TFM.', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
'username' => new external_value(PARAM_TEXT, 'Usuario que sube el archivo.', VALUE_REQUIRED, '', NULL_NOT_ALLOWED),
'folder_name' => new external_value(PARAM_TEXT, 'Directorio donde se subira el archivo.', VALUE_REQUIRED, '', NULL_NOT_ALLOWED))
);
}
public static function upload_tfg($community_key, $username, $folder_name) {
global $CFG, $DB, $USER;
require_once($CFG->dirroot . "/mod/forum/lib.php");
$params = self::validate_parameters(self::upload_tfg_parameters(),
array(
'community_key' => $community_key,
'username' => $username,
'folder_name' => $folder_name
));
//Context validation
//OPTIONAL but in most web service it should present
$contextoUser = get_context_instance(CONTEXT_USER, $USER->id);
self::validate_context($contextoUser);
$fs = get_file_storage();
$warnings = array();
//We get the course to which the file must be uploaded
$sql = "SELECT id FROM mdl_course WHERE idnumber = ?";
$result = $DB->get_records_sql($sql, array($community_key));
foreach ( $result as $n ) {
$courseid = $n->id;
}
if( is_null($courseid)){
throw new moodle_exception('no_course','No existe el curso');
}
//e get the forum to upload the file
$sql = "SELECT f.id FROM mdl_forum f , mdl_course c WHERE c.idnumber = ? AND c.id = f.course AND f.name = ?";
$result = $DB->get_records_sql($sql, array($community_key, $folder_name));
foreach ( $result as $n ) {
$forumid = $n->id;
}
if( is_null($forumid)){
throw new moodle_exception('no_forum','No existe el foro');
}
//We get the user who wants to upload the file
$sql = "SELECT id FROM mdl_user WHERE username = ?";
$result = $DB->get_records_sql($sql, array($username));
foreach ( $result as $n ) {
$userid = $n->id;
}
if( is_null($userid)){
throw new moodle_exception('no_user','No existe el usuario');
}
//We check if the user belongs to the course
$contextCourse = context_course::instance($courseid);
$enrolled = is_enrolled($contextCourse, $userid, '', true);
if( !$enrolled){
throw new moodle_exception('user_no_enrolled','El usuario no está en el curso');
}
//Files received
$numFiles = count($_FILES);
if($numFiles > 0){
// Request and permission validation.
$forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
list($course, $cm) = get_course_and_cm_from_instance($forum, 'forum');
$context = context_module::instance($cm->id);
self::validate_context($context);
// Normalize group.
if (!groups_get_activity_groupmode($cm)) {
// Groups not supported, force to -1.
$groupid = -1;
} else {
// Check if we receive the default or and empty value for groupid,
// in this case, get the group for the user in the activity.
if ($groupid === -1 ) {
$groupid = groups_get_activity_group($cm);
} else{
$groupid = -1;
}
}
if (!forum_user_can_post_discussion($forum, $groupid, -1, $cm, $context)) {
throw new moodle_exception('cannotcreatediscussion', 'forum');
}
$thresholdwarning = forum_check_throttling($forum, $cm);
forum_check_blocking_threshold($thresholdwarning);
foreach ($_FILES as $fieldname=>$uploaded_file) {
// check upload errors
if (!empty($_FILES[$fieldname]['error'])) {
switch ($_FILES[$fieldname]['error']) {
case UPLOAD_ERR_INI_SIZE:
throw new moodle_exception('upload_error_ini_size', 'repository_upload');
break;
case UPLOAD_ERR_FORM_SIZE:
throw new moodle_exception('upload_error_form_size', 'repository_upload');
break;
case UPLOAD_ERR_PARTIAL:
throw new moodle_exception('upload_error_partial', 'repository_upload');
break;
case UPLOAD_ERR_NO_FILE:
throw new moodle_exception('upload_error_no_file', 'repository_upload');
break;
case UPLOAD_ERR_NO_TMP_DIR:
throw new moodle_exception('upload_error_no_tmp_dir', 'repository_upload');
break;
case UPLOAD_ERR_CANT_WRITE:
throw new moodle_exception('upload_error_cant_write', 'repository_upload');
break;
case UPLOAD_ERR_EXTENSION:
throw new moodle_exception('upload_error_extension', 'repository_upload');
break;
default:
throw new moodle_exception('nofile');
}
}
/*$file = new stdClass();
$file->filename = clean_param($_FILES[$fieldname]['name'], PARAM_FILE);
// check system maxbytes setting
if (($_FILES[$fieldname]['size'] > get_max_upload_file_size($CFG->maxbytes))) {
// oversize file will be ignored, error added to array to notify web service client
$file->errortype = 'fileoversized';
$file->error = get_string('maxbytes', 'error');
} else {
$file->filepath = $_FILES[$fieldname]['tmp_name'];
// calculate total size of upload
//$totalsize += $_FILES[$fieldname]['size'];
}
$files[] = $file;*/
$filename = $_FILES[$fieldname]['name'];
$filepath = $_FILES[$fieldname]['tmp_name'];
// Create the discussion.
$discussion = new stdClass();
$discussion->course = $course->id;
$discussion->forum = $forum->id;
$discussion->message = "<p>".$filename."</p>";
$discussion->messageformat = FORMAT_HTML; // Force formatting for now.
$discussion->messagetrust = trusttext_trusted($context);
$discussion->itemid = 0;
$discussion->groupid = $groupid;
$discussion->mailnow = 0;
$discussion->subject = $filename;
$discussion->name = $discussion->subject;
$discussion->timestart = 0;
$discussion->timeend = 0;
if ($discussionid = forum_add_discussion($discussion)) {
$discussion->id = $discussionid;
//We update the user of the discursion to the one of the user received
$sql = "UPDATE mdl_forum_discussions SET userid= ? WHERE id = ?";
$DB->execute($sql, array($userid, $discussionid));
/*
// Trigger events and completion.
$params = array(
'context' => $context,
'objectid' => $discussion->id,
'other' => array(
'forumid' => $forum->id,
)
);
$event = \mod_forum\event\discussion_created::create($params);
$event->add_record_snapshot('forum_discussions', $discussion);
$event->trigger();
$completion = new completion_info($course);
if ($completion->is_enabled($cm) && ($forum->completiondiscussions || $forum->completionposts)) {
$completion->update_state($cm, COMPLETION_COMPLETE);
}
$settings = new stdClass();
$settings->discussionsubscribe = false; //discussionsubscribe (bool); subscribe to the discussion?, default to true
forum_post_subscription($settings, $forum, $discussion
//se guardara el fichero
// Get any existing file size limits.
//$maxareabytes = FILE_AREA_MAX_BYTES_UNLIMITED;
//$maxupload = get_user_max_upload_file_size($context, $CFG->maxbytes);
// Check the size of this upload.
//if ($maxupload !== USER_CAN_IGNORE_FILE_SIZE_LIMITS && $totalsize > $maxupload) {
// throw new file_exception('userquotalimit');
//}
*/
//We get the course to which the file must be uploaded
$sql = "SELECT id FROM mdl_forum_posts WHERE discussion = ? ORDER BY id ASC LIMIT 1";
$result = $DB->get_records_sql($sql, array($discussionid));
foreach ( $result as $n ) {
$postid = $n->id;
}
if( is_null($postid)){
throw new moodle_exception('no_post','No existe el post');
}
//We update the post to put the user that they send us and indicate that they have a file
$sql = "UPDATE mdl_forum_posts SET userid= ?, attachment= 1 WHERE id = ?";
$DB->execute($sql, array($userid, $postid));
$user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
$file_record = new stdClass;
$file_record->component = 'mod_forum';
$file_record->contextid = $context->id;
$file_record->userid = $userid;
$file_record->filearea = 'attachment';
$file_record->filename = $filename;
$file_record->filepath = '/';
$file_record->itemid = $postid;
$file_record->license = $CFG->sitedefaultlicense;
$file_record->author = fullname($user);
$file_record->source = $filename;
//Check if the file already exist
$existingfile = $fs->file_exists($file_record->contextid, $file_record->component, $file_record->filearea,
$file_record->itemid, $file_record->filepath, $file_record->filename);
if ($existingfile) {
throw new file_exception('filenameexist');
} else {
$stored_file = $fs->create_file_from_pathname($file_record, $filepath);
}
} else {
throw new moodle_exception('couldnotadd', 'forum');
}
}
}else{
throw new moodle_exception('nofile');
}
$result = array();
$result['discussionid'] = $discussionid;
$result['warnings'] = $warnings;
return $result;
}
/**
* Returns description of method result value
* #return external_multiple_structure
*/
public static function upload_tfg_returns() {
return new external_single_structure(
array(
'discussionid' => new external_value(PARAM_INT, 'New Discussion ID'),
'warnings' => new external_warnings()
)
);
}
}
And an example to call this WS maybe this:
$target_url = "http://localhost/pruebaMoodle/webservice/rest/server.php";
//$target_url = "http://localhost/upload.php";
$username = "raula"; //User uploading the file (must belong to the course)
$community_key = "c15c033a43976gPT"; //custom identifier of course
$folder_name = "Course 2016"; //Name of the forum to which the file will be uploaded
$fname = 'Prueba.txt'; //Name of the file or path where it is located but is in the same directory as this file
$token = "28b054f102a75a0eab2a0053fd930d62"; //token created for ws
$file_name_with_full_path = realpath($fname);
$cfile = new CURLFile($file_name_with_full_path);
$post = array (
'username' => $username,
'community_key' => $community_key,
'folder_name' => $folder_name,
'wstoken' => $token,
'wsfunction' => 'upload_tfg_tfm',
'moodlewsrestformat' => 'json',
'upload_file' => $cfile
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15','Referer: http://localhost','Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result = curl_exec ($ch);
if ($result === FALSE) {
echo "Error sending " . $fname . " " . curl_error($ch) . "\n";
curl_close ($ch);
}else{
curl_close ($ch);
echo "<br><br>Result: " . $result. "<br>";
}
I hope this can serve you

Curl not writing cookie and http code 404, why?

I want to curl cookies
cookie file is created but empty, why?
And agent_http_code value: 404, why?
Thanks.
$url ="https://example.com";
$xmlfile = '/home/*******/public_html/2.xml';
$cookie_file = '/home/******/public_html/cookie.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('action-xmlagentxmlfile'=>'#' . $xmlfile));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
if (file_exists($cookie_file) && filesize($cookie_file) > 0) {
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
}

HowTo: send app request, and get data from request (to redirec to to a specific link) without user accepting the app?

let's say user send app requests to his friends,
this request will be targeting something /my_app/catalog.php?ID=25
(not the index page)
the only way to store specific link in app request is to use "data" field of the request.
when user follow app request it will end up on index.php (not catalog.php?ID=25)
how could i extract data field from request without knowing user id? (and without him accepting the app ?)
i can get request_ids and also app_token (not user_access_tocken)
by using
https://graph.facebook.com/oauth/access_token?client_id=".$GLOBALS['app_id']."&client_secret=".$GLOBALS['app_secret']."&grant_type=client_credentials
but without the user id and him accepting the app it is impossible to get "data" field
so instead of user been able to see a product in my app that his friend recommended him , he sees auth forms and accept the app dialogs whiout knoing what is this app about.
this is not a right behavor and to my undestanding first user had to see a link on my page and later on if he want to do actions or my app need permissions for user's info - only when should the "accept dialog" be used.
UPDATE:
I guess Juicy right and where is no other way to get app request url but to either store it in your own database or require user to accept the app
in case if someone else looking for this workaround
here is some usefull stuff:
//to deal with app requests: (this is part of overall page output preparation)
$rqlink="";
if((strlen($_REQUEST['request_ids'])>0)&&(strlen($user->id)>0))//user is logged no need for database
{
if(($rq=getfbres("https://graph.facebook.com/?ids=".$_REQUEST['request_ids']."&access_token=".$_SESSION['access_token'] ))!==false)
{
$rqj = json_decode($rq);
$request_ids = explode(',', $_REQUEST['request_ids']);
foreach ($request_ids as $request_id)
{
$full_request_id=$request_id.'_'.$user->id;
if(isset($rqj->$request_id->data)) $rqlink=$rqj->$request_id->data;
//if(getfbres("https://graph.facebook.com/$full_request_id?method=delete&access_token=".$_SESSION['access_token'])===false)
//{ echo "delete request error:". $GLOBALS['err']; exit;}
break;
}
}
}
elseif(strlen($_REQUEST['request_ids'])>0) //user is not logged, try to extract url from database
{
$request_ids = explode(',', urldecode($_REQUEST['request_ids']));
foreach ($request_ids as $request_id)
{
if(!isset($conn)){include_once "conn.php"; $conn=init_conn();}
if(!($rez=mysql_query("select * from ff_app_rq where rq='".str_replace("'","''",$request_id)."'",$conn))) die ("Database error");
if(mysql_num_rows($rez)>0)
{
$row=mysql_fetch_assoc($rez);
$rqlink=$row['url'];
mysql_free_result($rez);
break;
}
else //request not found for some reason and user is not authorized
{ //force pop-up authorization in order not to loose req_ids
mysql_free_result($rez);
echo("<script LANGUAGE='javascript'>window.open('/fblogin.php','_blank','width=900,height=450');</script>");
break;
}
}
}
if(strlen($rqlink)>0)
{
session_write_close();
echo("<script LANGUAGE='javascript'>document.location.href='".$rqlink."';</script>");
// echo("<script LANGUAGE='javascript'>top.location.href='http".(getenv("HTTPS") == 'on'?"s":"")."://apps.facebook.com/".$GLOBALS['app_namespace']."/".$rqlink."';</script>");
exit;
}
this is how you promote:
function fire_promo()
{
FB.init({appId:'<?php echo $GLOBALS['app_id'];?>',status:true,cookie:true,frictionlessRequests:true,oauth:true});
//(this will display popup with list of fb friends)
getpage('ajforms.php?ID=<?php echo $id;?>&stage=promote_app','subcontent,-100,10,560,500,2,zzz');
return false;
}
function sendRequestToManyRecipients()
{
var f=document.send_inv; //(this form lists all checked users)
var ids="";
for(var z=0;z<f.length;z++) if(f[z].name=='p') if(f[z].checked) {if(ids.length>0) ids+=',';ids+=f[z].value;}
FB.ui({method:'apprequests',data:'catalog.php?ID=<?php echo $id;?>',message:'You have been invited to bla-bla',to:"'"+ids+"'"}, requestCallback);
}
here is app request javascript callback:
function requestCallback(response)
{
if(response === undefined) return;
//if(response.request===undefined) return;
var req = getconn(); if(req) {req.open("HEAD",'fb_req.php?rq='+response.request+'&url='+encodeURIComponent('catalog.php?ID=<?php echo $id;?>',true));req.send(null);}
//console.log(response.request);
if(response.to.length === undefined) {} else if(response.to.length>0) alert('You have successfully promoted to '+response.to.length+' friends.\nThank You!');
}
(getconn is a standart ajax function to initialize ajax communications)
here is fb_req.php to log app requests:
<?php
if((strlen($_REQUEST['rq'])>0)&&(strlen($_REQUEST['url'])>0))
{
include_once "conn.php";
$conn=init_conn();
$rez=mysql_query("insert into my_app_rq_table (rq,url,rq_date) VALUES('".str_replace("'","''",$_REQUEST['rq'])."','".str_replace("'","''",urldecode($_REQUEST['url']))."',now())",$conn);
//if(!$rez) die ("Database error".mysql_error());
}
exit;
?>
and finnaly here is fblogin.php for pop-up authorization and when refreshing opener window:
<?php
session_start();
include_once "params.php";
$code = $_REQUEST["code"];
if(strlen($code)>2)
{
$my_url = "http".(getenv("HTTPS")=='on'?"s":"")."://".getdom().((($_SERVER['SERVER_PORT']=="80")||($_SERVER['SERVER_PORT']=="443"))?(""):(":".$_SERVER['SERVER_PORT']))."/fblogin.php?fb_redirect_url=".urlencode($_REQUEST['fb_redirect_url']);
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".$GLOBALS['app_id']."&redirect_uri=".urlencode($my_url)."&client_secret=".$GLOBALS['app_secret']."&code=".$code;
$access_token = getfbres($token_url);
$graph_url = "https://graph.facebook.com/me?".$access_token;
$rr=strpos($access_token,"&");
if($rr>0) $access_token=substr($access_token,0,$rr);
$access_token=str_replace("access_token=","",$access_token);
$user = json_decode(getfbres($graph_url));
if(strlen($user->id)>0)
{
$_SESSION['access_token']=$access_token;
if(strlen($_REQUEST['fb_redirect_url'])>0)
echo "<SCRIPT LANGUAGE='javascript'>\nwindow.opener.location.href='".urldecode($_REQUEST['fb_redirect_url'])."';\nwindow.close();</script>";
else
echo "<SCRIPT LANGUAGE='javascript'>\nwindow.opener.location.reload(true);\nwindow.close();</script>";
exit;
}
}
if(strlen($_SESSION['access_token'])>2)
{
$graph_url = "https://graph.facebook.com/me?access_token=".$_SESSION['access_token'];
$user = json_decode(getfbres($graph_url));
if(strlen($user->id)>0)
{
if(strlen($_REQUEST['fb_redirect_url'])>0)
echo "<SCRIPT LANGUAGE='javascript'>\nwindow.opener.location.href='".urldecode($_REQUEST['fb_redirect_url'])."';\nwindow.close();</script>";
else
echo "<SCRIPT LANGUAGE='javascript'>\nwindow.opener.location.reload(true);\nwindow.close();</script>";
exit;
}
}
$my_url = "http".(getenv("HTTPS")=='on'?"s":"")."://".getdom().((($_SERVER['SERVER_PORT']=="80")||($_SERVER['SERVER_PORT']=="443"))?(""):(":".$_SERVER['SERVER_PORT']))."/fblogin.php?fb_redirect_url=".urlencode($_REQUEST['fb_redirect_url']);
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id=".$GLOBALS['app_id']."&redirect_uri=".urlencode($my_url).$GLOBALS['app_scope'];
//echo "<h1>".$_SESSION['log_attempts']."</h1>";
$_SESSION['log_attempts']=intval("0".$_SESSION['log_attempts'])+1;
if(intval("0".$_SESSION['log_attempts'])<5)
echo("<script>document.location.href='".$dialog_url."';</script>");
else echo "<center><br><br><br><h1>Facebook Login failed</h1><br>Please refresh web page and try again.</center>";
exit;
function getdom()
{
return strtolower(str_replace("www.","",$_SERVER['SERVER_NAME']));
}
function getfbres($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
if(curl_error($ch)) $err=curl_error($ch); else $err="";
curl_close($ch);
//echo "<pre>info:<br>"; var_dump($info); echo "<br>output:<br>"; echo $output; if (strlen($err)>0) echo "<br>error:<br>$err"; echo "</pre><br>";
if ($output === false || $info['http_code'] != 200)
{
// $GLOBALS['err']=$output."\nhttp code:".$info['http_code']."\n".$err;
// echo "<pre>info:<br>"; var_dump($info); echo "<br>output:<br>"; echo $output; if (strlen($err)>0) echo "<br>error:<br>$err"; echo "</pre><br>";
// exit;
return false;
}
return $output;
}
?>
Event if the data cannot be retrieved (which should not be the case according to my tests using application access_token in older format APP_ID|APP_SECRET) you can easily save this details at your end linked to request id you get while sending it to user and later issue redirection based on data you already have.

Debug photo like system

I have this error: Fatal error: Uncaught OAuthException: Invalid OAuth access token signature.
I can't get the system (like button to do the like in a photo (page photo - no permissions require I guess) work.. Can somebody help me?
test.php:
<?php
//include "dbc.php";
require './src/facebook.php';
$url = (!empty($_SERVER['HTTPS'])) ? 'https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].$_SERVER['REQUEST_URL'] : 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'].$_SERVER['REQUEST_URL'];
$facebook = new Facebook(array(
'appId' => '******',
'secret' => '******',
'cookie' => true, // enable optional cookie support
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
//$pageInfo = $facebook->api('/'.$pageid.'?access_token='.$_SESSION['fb_112104298812138_access_token].');
//$pageInfoUser = $user_profile[id];
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
/* */
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$params = array(
scope => 'read_stream,publish_stream,publish_actions,offline_access',
redirect_uri => $url
);
$loginUrl = $facebook->getLoginUrl($params);
}
$access_token = $facebook->getAccessToken();
// $access_token = $_SESSION['user_id'];
//$_SESSION['fb_135669679827333_access_token'];
if(!$user){
echo ' : Login ';
}else{
echo 'Logout';
}
?>
<?
function GetCH(){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/oauth/access_token?client_id=112115512230132&client_secret=ef3d2a30aa9a3f799130565b8391d42dT&grant_type=client_credentials");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT_MS,20000);
if(substr($url,0,8)=='https://'){
// The following ensures SSL always works. A little detail:
// SSL does two things at once:
// 1. it encrypts communication
// 2. it ensures the target party is who it claims to be.
// In short, if the following code is allowed, CURL won't check if the
// certificate is known and valid, however, it still encrypts communication.
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
}
$sendCH = curl_exec($ch);
curl_close($ch);
return $sendCH;
};
echo "Access_token : ".$access_token;
$app_access_token = GetCH();
if($_GET['postid']){
$postid = $_GET['postid'];
echo "test1";
}else{
$postid = "ERROR";//'135669679827333_151602784936066';
}
if($access_token){
echo "test2";
$pageLike = $facebook->api('/'.$postid.'/likes?access_token='.$access_token.'&method=post', 'POST');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>
Update from OP post, below:
I have changed my code,
Now I have this code:
require_once './src/facebook.php';
class photo_liker {
function __construct()
{
$this->facebook = new Facebook( array('appId' => fb_appID, 'secret' => fb_secret, 'fileUpload' => true, 'cookie' => true));
}
function postPhotoLike($photoid)
{
try {
$args = array('access_token' => $this->facebook->getAccessToken());
$upload_photo = $this->facebook->api('/' . $photoid . '/likes', 'post', $args);
} catch (FacebookApiException $e) {
var_dump($e);
}
}
function login()
{
try {
$uid = $this->facebook->getUser();
} catch (Exception $e) {
var_dump($e);
}
if($uid) {
try {
$user = $this->facebook->api('/me');
} catch (Exception $e) {
var_dump($e);
}
return true;
} else {
$login_url = $this->facebook->getLoginUrl(array('scope' => 'email,publish_stream'));
ob_clean();
echo("<script>top.location.href='" . $login_url . "'</script>");
exit ;
}
return false;
}
}
$test = new photo_liker();
$test->login();
$test->postPhotoLike('103273136379847');
I got the getUser() == 0... I read that is a bug of SDK 3.* .. how can I solve it?