cURL throws an exception at Facebook API SDK - facebook

I'm trying to post an image as the user from my Facebook application.
Currently, this feature is still under development, and when I'm trying to test it using WAMP server on localhost, one of the cURL functions in the Facebook API SDK class, throws an exception error:
{"error_code":60,"error":{"message":"SSL certificate problem, verify
that the CA cert is OK. Details:\nerror:14090086:SSL
routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify
failed","type":"CurlException"}}null0.90752005577087
145684992172054|e259ec293812a5276a61d3181c395077
I have checked, and I have the correct settings at php.ini both at the Apache and PHP directories.
I tried to run this Both on Easy PHP with PHP 5.4 and on WAMP with PHP 5.3. (cURL extension enabled).
I have open SSL installed on both of the local servers.
I understand that you can solve this by changing the configuration of the CURL_opt, but modifying a Facebook base class, and compromising the security of my application (middle man attack), is really a last resort for me.
Thanks in advance for any help!.
My code:
test.php:
<?php
session_start();
require 'FB_auth.php';
require 'includes.php';
require 'functions_fb.php';
$start = (float) array_sum(explode(' ',microtime()));
//echo json_encode(photoToFacebook(299, 402, 134));
// echo json_encode(photoToFacebook(724, 402, 165));
// postToFacebook($db, 402, 134);
$end = (float) array_sum(explode(' ',microtime()));
$duration = ($end-$start);
echo $duration;
echo "<br/>" . $facebook->getAccessToken();
?>
functions_fb.php
<?php
function photoToFacebook($hr_id, $user_id, $job_id){
global $db, $FEED_PATH, $JOB_IMAGES_FOLDER , $facebook;
$path = $_SERVER['DOCUMENT_ROOT'] . "/";
$JOB_IMAGES_FOLDER = "images/job_images/";
$company = $db->getCompany($hr_id);
// perapre the job photo.
$photo = $db->getJobPhoto($job_id);
if (empty($photo)){
$photo = $db->getLogo($hr_id);
}
else{
$photo = $JOB_IMAGES_FOLDER . $photo;
}
try{
// At the time of writing it is necessary to enable upload support in the Facebook SDK, you do this with the line:
$facebook->setFileUploadSupport(true);
// Get album id if exists.
$album_uid = $db->getAlbumId($user_id);
$fb_user_id = $db->getFBUserId($user_id);
if (empty($album_uid)){
// Create an album
$album_details = array(
'message'=> 'Check out my company\'s job opportunities',
'name'=> "Job opportunities at {$company}"
);
$create_album = $facebook->api("/{$fb_user_id}/albums", 'post', $album_details);
echo json_encode($create_album);
$album_uid = $create_album["id"];
$db->saveAlbumId($user_id, $create_album["id"]);
}
$job_title = $db->getJobTitle($job_id);
$link = Bitly::make_bitly_url($FEED_PATH . "show_job.php?jid={$job_id}&th_uid={$user_id}&tp=1&pc=1", BITLY_APP_USERNAME,BITLY_APP_KEY,'json');
$photo_details = array(
'message'=> $job_title . "!\n" . $company . " is looking for you.\nOpen the link for details and apply.\n" . $link
);
$path .= $photo;
$photo_details['image'] = '#' . $path; //realpath($file);
// echo $album_uid;
$upload_photo = $facebook->api("{$fb_user_id}/photos", 'post', $photo_details);
// $db->updateAutoPostActivity($user_id, $job_id,1, json_encode($upload_photo));
// $db->updateAutoPostJob($job_id, $user_id);
return $upload_photo;
}
catch (FacebookApiException $e) {
echo "error:" . json_encode($e->getResult());
// $db->updateAutoPostActivity($user_id, $job_id,1, json_encode($e->getResult()));
// AtavMail::SendRichedMail(null , "", "Error on auto process - posting photo to FB", "Where - Job Id: {$job_id} , User Id: {$user_id}", json_encode($e->getResult()));
}
}
?>

I solved this by adding the following line into the base_facebook.php file:
public static $CURL_OPTS = array(
//
//
//
CURLOPT_SSL_VERIFYPEER => false,
);
Please notice that this is an development - environment solution only, and using this on your actual application can cause a security risk.
Please take the time to review the fullp proper solution on this link:
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/

Setting SSL verification to false defeats the purpose of SSL.
A proper solution is to set the CA certs for CURL.
Solution 1 (Changes to PHP.ini):
Download CA bundle (cacert.pem) from http://curl.haxx.se/docs/caextract.html
Place it on your local system (for eg: C:\xampp\cacert.pem)
Open your php.ini
Set the curl.ca_info options to point to the location of the cacert.pem
Example: curl.ca_info="C:\xampp\cacert.pem"
Restart Apache
Solution 2 (Set options before each CURL call)
Download CA bundle (cacert.pem) from http://curl.haxx.se/docs/caextract.html
Place it on your local system (for eg: C:\xampp\cacert.pem)
Write the following code:
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
curl_setopt ($ch, CURLOPT_CAINFO, "pathto\cacert.pem");
Source: http://tumblr.wehavefaces.net/post/52114563111/environment-windows-xampp-curl-library

Related

error 404: while deploying slim framework rest API on plesk shared hosting

I need help, while deploying slim framework on plesk shared hosting below mentioned issue is coming up.
actually it is working fine at local wamp server.
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
here is my code.
index.php:
require '../vendor/autoload.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Max-Age: 86400');
$config = ['settings' => [
'addContentLengthHeader' => true,
'displayErrorDetails' => true
]];
$app = new \Slim\App($config);
require '../src/routes/hostUser.php';
require '../src/routes/user.php';
$app->run();
hostUser.php:
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\Http\Message;
include_once 'Database.php';
var_dump($app);
$app->get('/loadprofile', function (Request $request, Response $response) {
$user_email = $_GET['emailid'];
$userid = $_GET['usertypeid'];
$database = new Database();
$db = $database->getConnection();
try {
$stmt = $db->prepare("SELECT * FROM user_details WHERE userid='".$userid."' AND email='".$user_email."'");
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
return json_encode($res);
$db = null;
} catch(PDOException $e){
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
The control reached till var_dump($app) but it is not executing loadprofile service.
enter image description here

Get Email state using codeigniter & sendgrid Webhook

I have integrated sendgrid for send mail. I also want to track whether a user has opened the mail and click the link inside the mail or not.
that's why I used sendgrid.
using it I can send mail, but can't track mail states(mail is opened or not, the link is clicked or not).
I tried the below code for sending mail.
function sendMail($toMails, $body, $subject, $ccMails = array(), $bccMails = array()) {
$ci = &get_instance();
if (empty($toName)) {
$toName = $toMails;
}
$sendMail = $ci->config->item('sendMail');
$email = new \SendGrid\Mail\Mail();
$email->setFrom($ci->config->item('from'), "From User name");
$email->setSubject($subject);
$email->addTos($toMails); //for multiple user pass array with emails and names
$email->addCcs($ccMails);
$email->addBccs($bccMails);
$email->addContent("text/html", $body);
$email->setFooter(false, "", "<strong>If you don't want to receive this type of email in the future, please <a href='http://w3schools.com'>Unsubscribe</a>.</strong>");
//$email->setSpamCheck(true, 1, "http://localhost:8081/");
// Tracking Settings
$email->setClickTracking(true, true);
//$email->setOpenTracking(true, true);
$sendgrid = new \SendGrid($ci->config->item('key'));
try {
$response = $sendgrid->send($email);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if ($sendMail) :
if (!$response->statusCode()) :
_pre($response->headers());
return false;
else :
return true;
endif;
endif;
}
which is working fine, except it is going in the spam.
now below code, I am using to get details as per email id.
$sendgrid = new \SendGrid($this->config->item('key'));
$query_params = json_decode('{"start_date": "2019-10-07","end_date": "2019-10-07","to_email": "cadmin1#getnada.com","subject":"This is a subject test"}');
$response = $sendgrid->client->stats()->get(null, $query_params);
_pre($response->body());
exit;
above code only gives me date wise data, but I also want email id wise.
but in spite of adding a parameter for that, still, I am not getting desired output.
https://sendgrid.com/docs/for-developers/sending-email/getting-started-email-activity-api/#filter-by-recipient-email
I have used the above demo, in that demo, they have used curl but I am using CodeIgniter's way.
I am not sure about sendgrid version that's why I added both version tag, I used API one.
anyone having a proper solution regarding it?
I have implemented webhooks to archive my desire output.
for that need to follow steps as per documentation shows
after that need to create a page from where we can get mails status.
on executing that page it returns data as per activity.
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
$data = file_get_contents("php://input");
$events = json_encode($data, true);
$requestData = array('response' => $events);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "<url which we earlier set for webhook as per documentation>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
?>
i have used Curl for getting desire output.

Wordpress "download_url" SSL verify

Right so I've been working with the Facebook API and can confirm that an image is there and I'm trying to import it to Wordpress to attach it to a post.
Here's the code I have that I'm sure the problem is with.
if (!empty($image)){
$fql ="SELECT src_big FROM photo WHERE pid = \"$image\"";
$fql = urlencode($fql);
$feedurl = "https://graph.facebook.com/fql?q=$fql&access_token=$page_at";
$feed=file_get_contents($feedurl);
$feed = json_decode($feed);
$image = $feed->data[0]->src_big;
$tmp = download_url( $image );
$desc = "SocialHub Facebook Image";
$file_array['name'] = 'Facebook Image '.$postid;
$file_array['tmp_name'] = $tmp;
if ( is_wp_error( $tmp ) ) {
#unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
echo $tmp->get_error_message();
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $postid, $desc );
// If error storing permanently, unlink
if ( !is_wp_error($id) ) {
set_post_thumbnail( $postid, $id );
}else{
echo $id->get_error_message().'<br>';
}
}
But when run I get the error message:
SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
If anyone can think of a way to download a facebook image without the SSL certificate error, it would be much appreciated.
Thanks in advance.
Here is a more thorough workaround.
add_filter( 'https_local_ssl_verify', '__return_false' );
add_filter( 'https_ssl_verify', '__return_false' );
See also:
https://wordpress.stackexchange.com/questions/72529/filter-any-http-request-uri
Nevermind, answered my own question; facebook as all the images both with and without SSL so had to simply add:
$image = str_replace('https://','http://',$image);
Before using the download_url() function

Facebook connect to Facebook iframe

I actually tried to find a solution but nothing and I hope I will find a solution here !
I use facebook connect in my website, everything works fine
when I am logged on facebook, I am automatically logged into my site through facebook connect, and vice versa.
Now i tried to make it a facebook application but I have the following problem:
I try to run inside the facebook iframe but unfortunately I'm not automatically logged in. sometimes it works, sometimes nothing happens , Sometimes I get this message: (Could not get the Facebook session. Your server may not Be Able Securely Facebook to connect to the user to retrieve information.)
some code im using :
include 'includes/facebook.php';
$facebook = new Facebook(array(
'appId' => $setting['facebook_appid'],
'secret' => $setting['facebook_secret'],
'cookie' => true, // enable optional cookie support
));
if ($facebook->getUser()) {
$facebook_session = 1;
try {
$fb_user = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
function get_facebook_cookie($app_id, $application_secret) {
$args = array();
parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
ksort($args);
$payload = '';
foreach ($args as $key => $value) {
if ($key != 'sig') {
$payload .= $key . '=' . $value;
}
}
if (md5($payload . $application_secret) != $args['sig']) {
return null;
}
return $args;
}
$cookie = get_facebook_cookie($setting['facebook_appid'], $setting['facebook_secret']);
$open = #file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']);
if ($open != FALSE) {
$fbdata = json_decode($open);
$fb_user = array();
foreach($fbdata as $key => $fbdata2) {
$fb_user[$key] = $fbdata2;
}
}
}
else {
$facebook_session = 0;
}
ps: im using of course a Secure Canvas URL
Please help !
Thanks in advance
First, are you using Firefox, Chrome or Internet Explorer? I had some Problems with FB-connect using it with IE. To solve it you need to add this:
header('P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
to your header, so internet explorer can use the sessions in your IFrame.

Read Facebook page post and token expiration

I need to read, from a server, the stream of a specific fan page.
I tried to read the graph api
https://graph.facebook.com//feed?access_token=&limit=100
and it works.
What I need is to understand if the token will expire and how to renew it programmatically.
Now I generate my token through the http://developers.facebook.com/tools/explorer/ app.
Can you please help me?
I'm using the PHP sdk
thanks,
a.
You can read the facebook page using below codes and you can also get the specified fields
https://graph.facebook.com/$page_id/?fields=link,etc&access_token=page_access_token
or
$response = $fb->api($page_id . '/?fields=link,etc&'. $access_token, 'GET')
Below is the solution for four scenarios
1.The token expires after expires time (2 hours is the default).
2.The user changes her password which invalidates the access token.
3.The user de-authorizes your app.
4.The user logs out of Facebook.
To ensure the best experience for your users, your app needs to be prepared to catch errors for the above scenarios. The following PHP code shows you how to handle these errors and retrieve a new access token.
When you redirect the user to the auth dialog, the user is not prompted for permissions if the user has already authorized your application. Facebook will return you a valid access token without any user facing dialog. However if the user has de-authorized your application then the user will need to re-authorize your application for you to get the access_token.
<?php
$app_id = "YOUR_APP_ID";
$app_secret = "YOUR_APP_SECRET";
$my_url = "YOUR_POST_LOGIN_URL";
// known valid access token stored in a database
$access_token = "YOUR_STORED_ACCESS_TOKEN";
$code = $_REQUEST["code"];
// If we get a code, it means that we have re-authed the user
//and can get a valid access_token.
if (isset($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 . "&display=popup";
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
$access_token = $params['access_token'];
}
// Attempt to query the graph:
$graph_url = "https://graph.facebook.com/me?"
. "access_token=" . $access_token;
$response = curl_get_file_contents($graph_url);
$decoded_response = json_decode($response);
//Check for errors
if ($decoded_response->error) {
// check to see if this is an oAuth error:
if ($decoded_response->error->type== "OAuthException") {
// Retrieving a valid access token.
$dialog_url= "https://www.facebook.com/dialog/oauth?"
. "client_id=" . $app_id
. "&redirect_uri=" . urlencode($my_url);
echo("<script> top.location.href='" . $dialog_url
. "'</script>");
}
else {
echo "other error has happened";
}
}
else {
// success
echo("success" . $decoded_response->name);
echo($access_token);
}
// note this wrapper function exists in order to circumvent PHP’s
//strict obeying of HTTP error codes. In this case, Facebook
//returns error code 400 which PHP obeys and wipes out
//the response.
function curl_get_file_contents($URL) {
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_URL, $URL);
$contents = curl_exec($c);
$err = curl_getinfo($c,CURLINFO_HTTP_CODE);
curl_close($c);
if ($contents) return $contents;
else return FALSE;
}
?>
for more details info you can visit this link
Thanks