new Facebook SDK 4 throw exception about PHP_SESSION_ACTIVE in laravel - facebook

I wanted implement the new facebook API v 4.0.0 on my project laravel.
Setting all the necessary informations and credentials for access to my app, when is time to call the function for the login:
$helper = new FacebookRedirectLoginHelper('http://mywebsite.dev');
$loginUrl = $helper->getLoginUrl();
It throw me an exception
FacebookSDKException 'Session not active, could not store state.'
So I dig in to the SDK class of facebook on that line and there is a check about session precisely this one:
if (session_status() !== PHP_SESSION_ACTIVE) {
throw new FacebookSDKException(
'Session not active, could not store state.'
);
}
Then I didn't know why this happen so i tried to put the same check on a clean route and see the result
Route::get('test',function() {
if (session_status() !== PHP_SESSION_ACTIVE)
{
return "is not active";
}
return "is active";
});
And it return is not active why this happen? in this way I cannot use the new facebook API with laravel?

Sharing how I implemented Facebook SDK V4 on Laravel 4.
Here's what I added on default composer.json
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
],
"psr-4" : {
"Facebook\\":"vendor/facebook/php-sdk-v4/src/Facebook/"
}
},
Added Facebook initialization on my index.php, like this :
/*
|--------------------------------------------------------------------------
| Initialized Facebook PHP SDK V4
|--------------------------------------------------------------------------
|
*/
//Initialize
use Facebook\FacebookSession;
FacebookSession::setDefaultApplication(Config::get('facebook.AppId'),Config::get('facebook.AppSecret'));
And for the Session, Laravel doesn't use $_SESSION so you don't need to do session_start at all. For you to be able to use Laravel session on Facebook PHP SDK V4, you need to extend Facebook's FacebookRedirectLoginHelper class.
Here's how how to subclass FacebookRedirectLoginHelper and overwrite Session handling.
class LaravelFacebookRedirectLoginHelper extends \Facebook\FacebookRedirectLoginHelper
{
protected function storeState($state)
{
Session::put('state', $state);
}
protected function loadState()
{
$this->state = Session::get('state');
return $this->state;
}
protected function isValidRedirect()
{
return $this->getCode() && Input::has('state')
&& Input::get('state') == $this->state;
}
protected function getCode()
{
return Input::has('code') ? Input::get('code') : null;
}
//Fix for state value from Auth redirect not equal to session stored state value
//Get FacebookSession via User access token from code
public function getAccessTokenDetails($app_id,$app_secret,$redirect_url,$code)
{
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . $redirect_url
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
return $params;
}
}
And one more step, you need to do a composer command to regenerate autoload files :
composer dump-autoload -o
Ok, if all goes right, you are now ready to start using the SDK, here's a sample
Here's an excerpt from one of my project classes :
namespace Fb\Insights;
//Facebook Classes
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookSDKException;
//Our Facebook Controller
use FbController;
class PagePosts extends \Facebook\GraphObject {
/*
Get Page Posts Impression
https://developers.facebook.com/docs/graph-api/reference/v2.0/insights#post_impressions
*/
public static function getPagePostsImpressions($postid = null) {
$fbctrl = new FbController();
$metricNames = array(
'post_impressions',
'post_impressions_unique',
'post_impressions_paid',
'post_impressions_paid_unique',
'post_impressions_fan',
'post_impressions_fan_unique',
'post_impressions_fan_paid',
'post_impressions_fan_paid_unique',
'post_impressions_organic',
'post_impressions_organic_unique',
'post_impressions_viral',
'post_impressions_viral_unique',
'post_impressions_by_story_type',
'post_impressions_by_story_type_unique',
'post_impressions_by_paid_non_paid',
'post_impressions_by_paid_non_paid_unique'
);
$postsInsights = array();
$batch = array();
$limit = $fbctrl->FacebookGraphDateLimit();
//craft our batch API call
for($i=0; $i<count($metricNames); $i++) {
$batch[] = json_encode(array('method' => 'GET','relative_url' => $postid . '/insights/' . $metricNames[$i] . '?since=' . $limit['since'] . '&until=' . $limit['until'] ));
}
$params = array( 'batch' => '[' . implode(',',$batch ) . ']' );
$session = new FacebookSession($fbctrl->userAccessToken);
try {
$res = (new FacebookRequest($session,'POST','/',$params))
->execute()
->getGraphObject();
} catch(FacebookRequestException $ex) {
//log this error
echo $ex->getMessage();
} catch(\Exception $ex) {
//log this error
echo $ex->getMessage();
}
//Collect data
for($i=0; $i<count($batch); $i++) {
$resdata = json_decode(json_encode($res->asArray()[$i]),true);
$fbctrl->batchErrorDataChecker($resdata,$postsInsights,$metricNames[$i]);
}
return $postsInsights;
}
Feel free comment or suggest so I can also improve my code.
Happy coding.

I solve extending that class and overwriting the following 2 methods that require native sessions.
protected function storeState($state)
{
Session::put('facebook.state', $state);
}
protected function loadState()
{
return $this->state = Session::get('facebook.state');
}

I used follow steps using Composer and had problem "Session not active, could not store state" so session_start() fixed my issue.
require_once './vendor/autoload.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
session_start();
FacebookSession::setDefaultApplication('apid', 'appscret');
$helper = new FacebookRedirectLoginHelper("callbackurl", $apiVersion = NULL);
try {
$session = $helper->getSessionFromRedirect();
} catch (FacebookRequestException $ex) {
// When Facebook returns an error
} catch (\Exception $ex) {
// When validation fails or other local issues
}
if (isset($session)) {
$request = new FacebookRequest($session, 'GET', '/me');
$response = $request->execute();
$graphObject = $response->getGraphObject();
var_dump($graphObject);
} else {
echo 'Login with Facebook';
}

To solve problem call session_start php function after to inizialize FacebookRedirectLoginHelper somthing like this:
session_start();
$helper = new FacebookRedirectLoginHelper('http://mywebsite.dev');
$loginUrl = $helper->getLoginUrl();

kaixersoft's answer really saved my bacon a little while ago, and I got everything to work by following his instructions using the custom LaravelFacebookRedirectLoginHelper class. But today I went to do a 'composer update' and for some reason, it broke everything. I've modified kaixersoft's LaravelFacebookRedirectLoginHelper class so that it works now, specifically the isValidRedirect method. Here is the updated class:
class LaravelFacebookRedirectLoginHelper extends \Facebook\FacebookRedirectLoginHelper
{
protected function storeState($state)
{
Session::put('state', $state);
}
protected function loadState()
{
$this->state = Session::get('state');
return $this->state;
}
protected function isValidRedirect()
{
$savedState = $this->loadState();
if (!$this->getCode() || !isset($_GET['state'])) {
return false;
}
$givenState = $_GET['state'];
$savedLen = mb_strlen($savedState);
$givenLen = mb_strlen($givenState);
if ($savedLen !== $givenLen) {
return false;
}
$result = 0;
for ($i = 0; $i < $savedLen; $i++) {
$result |= ord($savedState[$i]) ^ ord($givenState[$i]);
}
return $result === 0;
}
protected function getCode()
{
return Input::has('code') ? Input::get('code') : null;
}
//Fix for state value from Auth redirect not equal to session stored state value
//Get FacebookSession via User access token from code
public function getAccessTokenDetails($app_id,$app_secret,$redirect_url,$code)
{
$token_url = "https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . $redirect_url
. "&client_secret=" . $app_secret . "&code=" . $code;
$response = file_get_contents($token_url);
$params = null;
parse_str($response, $params);
return $params;
}
}

session_status function is available on (PHP >=5.4.0) version. So if you are using older version of PHP then Please update it Or Just
// change this
if (session_status() !== PHP_SESSION_ACTIVE) {
throw new FacebookSDKException(
'Session not active, could not store state.'
);
}
//into this
if(session_id() === "") {
throw new FacebookSDKException(
'Session not active, could not load state.'
);
}

Related

Magento 2: change order status programmatically

I need to set in "canceled" all orders stucks in "pending" status.
The code that I used return this exception error:
[2022-12-03 08:00:53] main.CRITICAL: Please provide payment for the order.
Here the code:
use Magento\Sales\Model\Order;
protected $order;
public function __construct(Order $order)
{
$this->order = $order;
}
public function orderStatusChange()
{
$orderId = 9999;
$order = $this->order->load($orderId);
$order->setStatus("canceled");
$order->save();
}
Please create a new file on the magento2 root and add below code:
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$orderId = '12345';
$order = $obj->create('\Magento\Sales\Model\OrderRepository')->get($orderId);
$order->setStatus("canceled");
$order->setState("canceled");
$order->save();
echo "Order updated";

How to get database stuff by using customized connection

I want to auto save the sql query every time, I found this article, if I do everything by the page it will work, but the problem is, I have master and slave database, therefore I have to connect to database like:
model/Users.php
<?php
class Users extends CI_Model
{
protected $table = 'users';
public $master;
public $slave;
public function __construct()
{
$this->master = $this->load->database('master', true);
$this->slave = $this->load->database('slave', true);
}
public function save($datas)
{
$this->master->insert($this->table, $datas);
return $this->master;
}
}
Then I adjust demo code like:
<?php
class Query_log
{
public function log_query()
{
$ci =& get_instance();
$filepath = APPPATH . 'logs/Query-log-' . date('Y-m-d') . '.php';
$handle = fopen($filepath, "a+");
$times = $ci->master->query_times;
foreach ($ci->master->queries as $key => $query) {
$sql = $query . " \n Execution Time:" . $times[$key];
fwrite($handle, $sql . "\n\n");
}
fclose($handle);
}
}
Of course I got error message
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Users::$master
Filename: hooks/query_log.php
How to make it right?

Symfony log into by using FosRestBundle

I'm working on a API. To give User Access - for example by smartphone - I need to login users by rest.
Is there an existing module available? Actually, I'm using fosUserBundle. Maybe there is a possibility to get those two bundle work together?
The Users which will login by rest are already existing as "normal" fos users.
It would be grest if you could gomme some links, tips or hints cause I'm searching and searching and searching and for the reason that I am new in symfony it's not that easy :):)
rgrds
I use FOSUserBundle for login since a smartphone by the API.
APIBundle/Controller/UserController.php (the default route is /api)
/**
* #Post("/user/login")
* #Template(engine="serializer")
*/
public function loginAction()
{
$request = $this->get('request');
$username = $request->request->get('username');
$password = $request->request->get('password');
return $this->container->get('myproject_user.user_service')
->login($username, $password);
}
in this method, I call a personal service who manage the user's functions. (UserHandler.php)
UserBundle/Handler/UserHandler.php
class UserHandler implements UserHandlerInterface
{
private $om;
private $entityClass;
private $repository;
private $container;
private $manager;
public function __construct(ObjectManager $om, Container $container, $entityClass)
{
$this->om = $om;
$this->entityClass = $entityClass;
$this->repository = $this->om->getRepository($this->entityClass);
$this->container = $container;
$this->manager = $this->container->get('fos_user.user_manager');
}
public function login($username, $password)
{
$jsonErrorCreator = $this->container->get('myproject_api.create_error_json');
$code = 0;
// check the arguments here.
$user = $this->manager->findUserByUsername($username);
if($user === null) $user = $this->manager->findUserByEmail($username);
if($user === null)
{
$code = 224;
return ($jsonErrorCreator->createErrorJson($code, $username));
}
// check the user password
if($this->checkUserPassword($user, $password) === false)
{
$code = 225;
return ($jsonErrorCreator->createErrorJson($code, null));
}
// log the user
$this->loginUser($user);
$jsonCreator = $this->container->get('myproject_api.create_json');
$response = $jsonCreator->createJson(array('success'=>true, 'user'=>$user));
return $response;
}
protected function loginUser(User $user)
{
$security = $this->container->get('security.context');
$providerKey = $this->container->getParameter('fos_user.firewall_name');
$roles = $user->getRoles();
$token = new UsernamePasswordToken($user, null, $providerKey, $roles);
$security->setToken($token);
}
protected function checkUserPassword(User $user, $password)
{
$factory = $this->container->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
if(!$encoder)
return false;
return $encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt());
}
}
UserBundle/Handler/UserHandlerInterface.php
Interface UserHandlerInterface
{
public function login($username, $password);
}
Don't forget to declare your service !
UserBundle/Resources/config/services.yml
myproject_user.user_service:
class: %myproject_user.user_handler.class%
arguments: [ #doctrine.orm.entity_manager, #service_container, %fos_user.model.user.class%]
You can now login with your smartphone at the adresse api/user/login
I think I got the solution:
http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html
This seems pretty nice to me and paired with Guras inputit should work as well.

Symfony Integrate Zend Lucene Search

I've been following the Jobeet tutorial in order to integrate the Zend Lucene search into my Symfony project and I can't seem to get it to work. I have added the following code to my config/ProjectConfiguration.class.php
class ProjectConfiguration extends sfProjectConfiguration
{
static protected $zendLoaded = false;
static public function registerZend()
{
if (self::$zendLoaded)
{
return;
}
set_include_path(sfConfig::get('sf_lib_dir').'/vendor'.PATH_SEPARATOR.get_include_path());
require_once sfConfig::get('sf_lib_dir').'/vendor/Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
self::$zendLoaded = true;
}
I have also added this code to my CarTable.class.php
static public function getLuceneIndex()
{
ProjectConfiguration::registerZend();
if (file_exists($index = self::getLuceneIndexFile()))
{
return Zend_Search_Lucene::open($index);
}
return Zend_Search_Lucene::create($index);
}
static public function getLuceneIndexFile()
{
return sfConfig::get('sf_data_dir').'/car.'.sfConfig::get('sf_environment').'.index';
}
And lastly I have added the following code to my Car.class.php
public function updateLuceneIndex()
{
$index = CarTable::getLuceneIndex();
foreach ($index->find('pk:'.$this->getIditem()) as $hit)
{
$index->delete($hit->id);
}
if (!$this->getActivated())
{
return;
}
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::Keyword('pk', $this->getIditem()));
$doc->addField(Zend_Search_Lucene_Field::UnStored('title', $this->getTitle(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('features', $this->getFeatures(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('location_city', $this->getLocation_city(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('location_state', $this->getLocation_state(), 'utf-8'));
$index->addDocument($doc);
$index->commit();
}
public function delete(Doctrine_Connection $conn = null)
{
$index = CarTable::getLuceneIndex();
foreach ($index->find('pk:'.$this->getIditem()) as $hit)
{
$index->delete($hit->id);
}
return parent::delete($conn);
}
And of course I added these few lines to the save function:
$conn = $conn ? $conn : $this->getTable()->getConnection();
$conn->beginTransaction();
try
{
$ret = parent::save($conn);
$this->updateLuceneIndex();
$conn->commit();
return $ret;
}
catch (Exception $e)
{
$conn->rollBack();
throw $e;
}
I have extracted the contents of the "library" folder of the Zend Framework into my lib/vendor/Zend folder.
But every time I run the command
php symfony doctrine:data-load
It runs all the way through and loads all of my fixtures but it doesn't create the folder with the index files in my data folder. I'm not sure what I'm doing wrong.
Here is my reference (Jobeet Tutorial) http://www.symfony-project.org/jobeet/1_4/Doctrine/en/17
By the way I'm using Symfony 1.4 (Doctrine).

Zend Paginator with Gdata Youtube

How Zend_Paginator can work according to the exchange of the variable query?
In line 8 performs a single fetch and does not change even by changing the query variable.
How to do paging function in accordance with the start-index from gdata feed?
The code: http://pastebin.com/rmxSP1Us
$yt = new Zend_Gdata_YouTube();
$limit = 12;
$offset = ($page - 1) * $limit + 1;
$query = "http://gdata.youtube.com/feeds/api/users/aculinario/favorites?start-index=$offset";
$paginator = Zend_Paginator::factory($yt->getVideoFeed($query));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage($limit);
$paginator->setPageRange(6);
$this->view->paginator = $paginator;
echo $query // query changes but paginator no, every time Zend_Paginator factory should check the returned array of getVideoFeed, but not this checking
Sry, my poor english, i'm Trying
I got something similar working using a quick & dirty paginator adapter.
It's worth noting there's probably nicer, more generic ways to achieve this. But this will get you going if you're in a hurry.
<?php
class Lib_Paginator_Adapter_YoutubeUser implements Zend_Paginator_Adapter_Interface
{
protected $_username;
protected $_results;
public function __construct($username)
{
$this->_username = $username;
}
public function getItems($offset, $itemCountPerPage)
{
$url = sprintf(
'%s/%s/%s',
Zend_Gdata_YouTube::USER_URI,
$this->_username,
Zend_Gdata_YouTube::UPLOADS_URI_SUFFIX
);
try
{
$query = new Zend_Gdata_Query($url);
$query->setMaxResults($itemCountPerPage)
->setStartIndex($offset);
$youtube = new Zend_Gdata_YouTube();
$this->_results = $youtube->getUserUploads(null, $query);
return $this->_results;
}
catch (Exception $ex)
{
echo $ex->getMessage();
exit;
}
}
public function count()
{
try
{
$youtube = new Zend_Gdata_YouTube();
return $youtube->getUserUploads($this->_username)->getTotalResults()->getText();
}
catch (Exception $ex)
{
echo $ex->getMessage();
exit;
}
}
}
Then in your controller
$page = $this->getRequest()->getParam("page");
$limit = 10;
$username = 'aculinario';
$paginator = new Zend_Paginator(new Lib_Paginator_Adapter_YoutubeUser($username));
$paginator->setItemCountPerPage($limit);
$paginator->setPageRange(10);
$paginator->setCurrentPageNumber($page);
$this->view->youtubeFeed = $paginator;