open_basedir restriction in effect. File() is not within the allowed path(s) and Uncaught CurlException: 3: No URL set! thrown in base_facebook.php - facebook

protected function makeRequest($url, $params, $ch=null) {
if (!$ch) {
$ch = curl_init();
}
$opts = self::$CURL_OPTS;
if ($this->useFileUploadSupport()) {
$opts[CURLOPT_POSTFIELDS] = $params;
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
}
$opts[CURLOPT_URL] = $url;
// disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
// for 2 seconds if the server does not support this header.
if (isset($opts[CURLOPT_HTTPHEADER])) {
$existing_headers = $opts[CURLOPT_HTTPHEADER];
$existing_headers[] = 'Expect:';
$opts[CURLOPT_HTTPHEADER] = $existing_headers;
} else {
$opts[CURLOPT_HTTPHEADER] = array('Expect:');
}
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
self::errorLog('Invalid or no certificate authority found, '.
'using bundled information');
curl_setopt($ch, CURLOPT_CAINFO,
dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
$result = curl_exec($ch);
}
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
I have built a facebook app, but something went wrong in this piece of code of base_facebook.php.
Whole code is here. All i get everytime are this 2 errors -
1.Warning: curl_setopt_array() [function.curl-setopt-array]: open_basedir restriction in effect. File() is not within the allowed path(s): (/home/:/usr/lib/php:/tmp) in /home/a2424901/public_html/base_facebook.php on line 802
2.Uncaught CurlException: 3: No URL set! thrown in /home/a2424901/public_html/base_facebook.php on line 814
Here is the code of my facebook app i.e.(index.php)

Yeap, non-obvious error message.
But it means, that realpath() returns empty value:
File() is not within the allowed path(s)...
Make sure, that the file passed to realpath() function really exists in the specified path.
Other exceptions in your example were caused by this problem.
By the way, it's good practice to wrap all weak spots (in your example - Facebook API calls) in try-catch blocks.

Related

Facebook Graph Api error "An unexpected error has occurred. Please retry your request later"

I'm trying to retrieve all members in a Facebook group getting this error:
array(5) {
["message"]=>
string(66) "An unexpected error has occurred. Please retry your request later."
["type"]=>
string(14) "OAuthException"
["is_transient"]=>
bool(true)
["code"]=>
int(2)
["fbtrace_id"]=>
string(11) "AnfsXcdgM"
}
Here is my code:
$this->_facebook = new Facebook\Facebook(array('app_id' => "$app_id",'app_secret' => "$secret",'default_graph_version' => 'v2.10'));
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name";
try{
$response = $this->_facebook->get($query);
while($pagesEdge)
{
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
$id = $member->id;
}
}
}catch (Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); }
It works for groups with few hundreads of people (even once for a group with 10.000 members) but randomly I'm occurring to this.
This might be caused by a server side timeout. I get this error every now and then when I request a huge amount of data. Maybe you should try to limit your request by using the limit parameter (default should be 25).
I solved this by doing a cron that takes 100 data at the time and putting into a file text the value of the token for the next call.
I add this string on the query and when the fields inside $url are empty I quit my execution
<?php
public function updateGroupMembers($groupID)
{
$tempNext = file_get_contents($this->dirM); //check if the next string token is in the file
if (!empty($tempNext))
{
$queryUntil = $tempNext;
}
// Sets the default fallback access token so we don't have to pass it to each request
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
// Create table name
$tableName = $groupID . "_Members";
// Query the Graph API to get all current member's ID and name
try
{
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name".$queryUntil; //add the next string to my query
$response = $this->_facebook->get($query);
$pagesEdge = $response->getGraphEdge();
// Index for the elements fetched from the API below
$i = 0;
// Get current time
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
/* ...get data and process them... */
}
$temp = $pagesEdge->getMetaData();
$next = parse_url($temp['paging']['next']);
parse_str($next['query'], $url);
$access_token = '&access_token='.$url['access_token'];
$fields = '&fields='.$url['fields'];
$limit = '&limit=100';
$after = '&after='.$url['after'];
$res['until'] = $access_token.$fields.$limit.$after;
file_put_contents($this->dirM, $res['until'], LOCK_EX);
if ( empty($url['access_token']) || empty($url['fields']) || empty($url['limit']) || empty($url['after']) )
{
file_put_contents($this->dirM, '', LOCK_EX); //clean my txt file that contains my next string
die('FINE');
}
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'm2Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'm2Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}

Catching syntax error and custom error reporting

I am using slim framework 3 . I am new to this framework. I am working on catching the errors and returning the custom JSON error and message.
I used this code to catch notFoundHandler error :
$container['notFoundHandler'] = function ($c) {
return function ($request, $response) use ($c) {
return $c['response']
->withStatus(404)
->withHeader('Content-Type', 'application/json')
->write('Page not found');
};
};
But I am able to catch the normal syntax error.
It is showing Warning: fwrite() expects parameter 2 to be string, array given in X-api\controllers\Products.php on line 42
Instead of this message, I want my custom error to handle syntax error reporting.
I used this also,
$container['phpErrorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
//Format of exception to return
$data = [
'message' => "hello"
];
return $container->get('response')->withStatus($response->getStatus())
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
But not working for me.
The default error handler can also include detailed error diagnostic information. To enable this you need to set the displayErrorDetails setting to true:
$configuration = [
'settings' => [
'displayErrorDetails' => true,
],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);
Note this is not appropriate for production applications, since it may reveal some details you would want not to reveal. You can find more in Slim docs.
EDIT
If you need to handle parseErrors, then you need to define phpErrorHandler in your container, just like you did define notFoundHandler.
$container['phpErrorHandler'] = function ($container) {
return function ($request, $response, $error) use ($container) {
return $container['response']
->withStatus(500)
->withHeader('Content-Type', 'text/html')
->write('Something went wrong!');
};
};
Note: this will work with PHP7+ only, because in older versions parseErrors cannot be catched.
I have used this short of code in my dependencies.php
$container['errorHandler'] = function ($c) {
return function ($request, $response) use ($c) {
$data = [
'message' => "Syntex error"
];
return $c['response']
->withStatus(200)
->withHeader('Content-Type', 'application/json')
->write(json_encode($data));
};
};
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
// This error code is not included in error_reporting, so ignore it
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
});
Now its working for me.

ZF2 application - Dispatch error event triggered every time

I'am working on a Zend Framework 2 application and have a strange behavior concerning error handling. My code in Module.php:
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_ROUTE, [$this, 'onPreRoute'], 100);
$eventManager->attach(\Zend\Mvc\MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'handleError']);
}
public function onPreRoute(MvcEvent $e)
{
$serviceManager = $e->getTarget()->getServiceManager();
$router = $serviceManager->get('router');
$router->setTranslator($serviceManager->get('translator'));
}
public function handleError(MvcEvent $e)
{
$error = $e->getParam('error');
file_put_contents('error.log', $error . PHP_EOL, FILE_APPEND);
switch($error) {
case 'error-router-no-match':
$router = $e->getRouter();
$url = $router->assemble([], ['name' => 'home']);
header('Location: ' . $url);
exit;
}
}
As you can see I'am translating the routes. This works fine. But on every request the dispatch error event is triggered too. The error.log file will be created every time. But the redirect will be only performed if the route doesn't really exist. I think it depends on the translator or is my code in Module.php not correct?
Resolved!
The reason was that the browser automatically requests /favicon.ico and that was not available :-)

Zend Framework: Paypal

I have been attempting to implement a paypal functionality into my application by following the example here: http://www.alexventure.com/2011/04/02/zend-framework-and-paypal-api-part-2-of-2/
This is my paymentAction in my controller.
public function paymentAction()
{
$auth= Zend_Auth::getInstance();
$user= $auth->getIdentity();
$username = $user->username;
$cart = new Application_Model_DbTable_Cart();
$select = $cart->select()
->from(array('c' => 'cart'))
->join(array('p' => 'product'), 'p.productid = c.productid')
->where('username = ?', $username)
->setIntegrityCheck(false);
$fetch = $cart->fetchAll($select)->toArray();
$paypal = new My_Paypal_Client;
$amount = 0.0;
foreach($fetch as $item) {
$amount = $amount + ($item['price']*$item['quantity']);
}
$returnURL = 'http://www.google.com';
$cancelURL = 'http://www.yahoo.com';
$currency_code = 'USD';
$reply = $paypal->ecSetExpressCheckout(
$amount,
$returnURL,
$cancelURL,
$currency_code
);
if ($reply->isSuccessfull())
{
$replyData = $paypal->parse($reply->getBody());
if ($replyData->ACK == 'SUCCESS' || $replyData->ACK == 'SUCCESSWITHWARNING')
{
$token = $replyData->TOKEN;
$_SESSION['CHECKOUT_AMOUNT'] = $amount;
header(
'Location: ' .
$paypal->api_expresscheckout_uri .
'?&cmd=_express-checkout&token=' . $token
);
}
}
else
{
throw new Exception('ECSetExpressCheckout: We failed to get a successfull response from PayPal.');
}
}
However, this is the error that returns.
Message: No valid URI has been passed to the client
Where did i go wrong? I would be happy to provide code from other areas of my application if needed. Thanks.
Zend_Http_Client::request() has not received a valid instance of Zend_Uri_Http.
Here's where the error occurs:
/**
* Send the HTTP request and return an HTTP response object
*
* #param string $method
* #return Zend_Http_Response
* #throws Zend_Http_Client_Exception
*/
public function request($method = null)
{
if (! $this->uri instanceof Zend_Uri_Http) {
/** #see Zend_Http_Client_Exception */
require_once 'Zend/Http/Client/Exception.php';
throw new Zend_Http_Client_Exception('No valid URI has been passed to the client');//Note the exact message.
}//Truncated
The only obvious error I see in the code you provided is :
$paypal = new My_Paypal_Client;//no () at end of declaration
I hope you implemented part one of the tutorial where the constructor is built. Otherwise you may just need to pass a better uri.
[EDIT]
I think your problem is here:
//needs a uri value for Zend_Http_Client to construct
$paypal = new My_Paypal_Client($url);
ecSetExpressCheckout does not construct the http client so it has no idea of where it's requesting the token from.
Alternatively you could just add this line below $paypal and above $reply:
//pass the uri required to construct Zend_Http_Client
$paypal->setUri($url);
I just hope you know what the url shouild be.
Good Luck.

Graph API: How to grab current user's information?

I'm trying to get some basic information about a user in a PHP script (id and name).
I have tried the following methods:
$retrieve = curl_init("https://graph.facebook.com/me?access_token=$accesstoken");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($retrieve, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($retrieve);
curl_close($retrieve);
and
$user = json_decode(file_get_contents(
"https://graph.facebook.com/me?access_token=$accesstoken"))->me;
The cURL method (former) just times out. The file_get_contents (latter) method just doesn't return anything at all...
What could be causing this? Am I using cURL correctly?
for graph api you can use graph api methods rahter than curl
the following code grabs information of current user
define('FACEBOOK_APP_ID', 'Your API ID');
define('FACEBOOK_SECRET', 'YOUR SECRET');
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(FACEBOOK_APP_ID, FACEBOOK_SECRET);
$user=json_decode(file_get_contents('https://graph.facebook.com/me?access_token='.$cookie['access_token']));
its prettey easy
Facebook will not let you use curl. They have the api for that.
copy your link and paste it to browser. It will work. In Mozilla you will see the result in browser, IE will save the result as a file. So it is not about invalid access token etc. It is just because Facebook does not respond to your query when it does not come 1-from a web browser, 2-from Facebook APIs.
here is the relevant PHP call to Facebook.
$attachment = array('access_token' => $access_token);
$result=$facebook->api('/me', 'GET', $attachment);
$id = $result['id'];
$name=$result['name'];