graph api v2.7 update, get profile picture master
graph api v2.7 update, get profile picture

file:a/.gitignore -> file:b/.gitignore
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,5 @@
 /theme/tpl_c/*.php
 /vendor
-/upload/*
 /app/Config/app.php
 composer.lock
 /bower_components

--- a/app/Config/bootstrap.php
+++ b/app/Config/bootstrap.php
@@ -76,7 +76,7 @@
 $fb = new Facebook\Facebook([
     'app_id' => Configure::getFacebookAppConfig()['app_id'],
     'app_secret' => Configure::getFacebookAppConfig()['app_secret'],
-    'default_graph_version' => 'v2.4',
+    'default_graph_version' => 'v2.7',
     'persistent_data_handler' => 'session'
 ]);
 
@@ -85,19 +85,7 @@
 $user = $sr ? $sr->getUserId() : null;
 
 $accessToken = null;
-try {
-    $accessToken = $helper->getAccessToken();
-} catch(Facebook\Exceptions\FacebookResponseException $e) {
-    // When Graph returns an error
-    //echo 'Graph returned an error: ' . $e->getMessage();
-    //exit;
-} catch(Facebook\Exceptions\FacebookSDKException $e) {
-    // When validation fails or other local issues
-    //echo 'Facebook SDK returned an error: ' . $e->getMessage();
-    //exit;
-}
-if (!isset($accessToken) || $accessToken == null) {
-    $helper = $fb->getCanvasHelper();
+if (empty($_SESSION['FBAPP_access_token'])) {
     try {
         $accessToken = $helper->getAccessToken();
     } catch(Facebook\Exceptions\FacebookResponseException $e) {
@@ -109,10 +97,50 @@
         //echo 'Facebook SDK returned an error: ' . $e->getMessage();
         //exit;
     }
+    if (!isset($accessToken) || $accessToken == null) {
+        $helper = $fb->getCanvasHelper();
+        try {
+            $accessToken = $helper->getAccessToken();
+        } catch(Facebook\Exceptions\FacebookResponseException $e) {
+            // When Graph returns an error
+            //echo 'Graph returned an error: ' . $e->getMessage();
+            //exit;
+        } catch(Facebook\Exceptions\FacebookSDKException $e) {
+            // When validation fails or other local issues
+            //echo 'Facebook SDK returned an error: ' . $e->getMessage();
+            //exit;
+        }
+    }
+
+    if ($accessToken) {
+        // The OAuth 2.0 client handler helps us manage access tokens
+        $oAuth2Client = $fb->getOAuth2Client();
+
+        // Get the access token metadata from /debug_token
+        $tokenMetadata = $oAuth2Client->debugToken($accessToken);
+        //echo '<h3>Metadata</h3>';
+        //var_dump($tokenMetadata);
+
+        // Validation (these will throw FacebookSDKException's when they fail)
+        $tokenMetadata->validateAppId(Configure::getFacebookAppConfig()['app_id']); // Replace {app-id} with your app id
+        // If you know the user ID this access token belongs to, you can validate it here
+        //$tokenMetadata->validateUserId('123');
+        $tokenMetadata->validateExpiration();
+
+        if (!$accessToken->isLongLived()) {
+            // Exchanges a short-lived access token for a long-lived one
+            try {
+                $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
+            } catch (Facebook\Exceptions\FacebookSDKException $e) {
+                //echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
+                //exit;
+            }
+        }
+    }
 }
 
 if ($accessToken != null) {
-    $_SESSION['FBAPP_access_token'] = $accessToken->getValue();
+    $_SESSION['FBAPP_access_token'] = (string) $accessToken;
 }
 $fb->setDefaultAccessToken((string) $_SESSION['FBAPP_access_token']);
 

--- a/app/Controller/AppController.php
+++ b/app/Controller/AppController.php
@@ -9,6 +9,7 @@
     public $smarty;
     public $fb;
     public $fb_id;
+    public $fb_user;
 
     public function __construct()
     {
@@ -31,7 +32,9 @@
         $sr = $helper->getSignedRequest();
         $this->fb_id = $sr ? $sr->getUserId() : null;
 
-        $this->registerUser();
+        if ($this->fb_id) {
+            $this->registerUser();
+        }
     }
 
     protected function registerUser()
@@ -40,6 +43,7 @@
             $res = $this->fb->get('/me?fields=first_name,last_name,email,gender,hometown');
             $profile = $res->getGraphObject();
             $uD = [];
+            $uD['fb_id'] = $this->fb_id;
             $uD['first_name'] = $this->DB->real_escape_string($profile->getProperty('first_name'));
             $uD['last_name'] = $this->DB->real_escape_string($profile->getProperty('last_name'));
             $uD['email'] = $this->DB->real_escape_string($profile->getProperty('email'));
@@ -53,6 +57,21 @@
                 $row = $this->DB->query("INSERT INTO `users` (`id`, `fb_id`, `first_name`, `last_name`, `email`, `gender`, `hometown`, `date`, `ip`, `active`) VALUES
                     (NULL, '".$this->fb_id."', '".$uD['first_name']."', '".$uD['last_name']."', '".$uD['email']."', '".$uD['gender']."', '".$uD['hometown']."', '".date("Y-m-d H:i:s")."', '".Request::clientIp()."', 1);");
             }
+            $this->fb_user = $uD;
+        } catch (\Exception $e) {
+            //die($e->getMessage() . "\n");
+        }
+
+        try {
+            if ($this->fb_id) {
+                $res = $this->fb->get('/' . $this->fb_id . '/picture?redirect=false&type=large');
+                $photo = $res->getGraphObject();
+                if ($photo['url'] != "") {
+                    $photo['url'] = str_replace('https', 'http', $photo['url']);
+                    $photo = file_get_contents($photo['url']);
+                    file_put_contents(ROOT . "upload/profile-pics/" . $this->fb_id . ".jpg", $photo);
+                }
+            }
         } catch (\Exception $e) {
             //die($e->getMessage() . "\n");
         }

--- a/app/Controller/DefaultController.php
+++ b/app/Controller/DefaultController.php
@@ -17,5 +17,16 @@
         $this->smarty->assign("page", "default/test");
         $this->smarty->display("layout/index.tpl");
     }
+
+    public function user()
+    {
+        if ($this->fb_id) {
+            echo json_encode($this->fb_user);
+        } else {
+            echo json_encode([]);
+        }
+        exit();
+    }
+
 }
 

--- a/composer.json
+++ b/composer.json
@@ -7,8 +7,8 @@
     "require": {
         "php": ">=5.4.16",
         "smarty/smarty": "^3.1@dev",
-        "facebook/php-sdk-v4": "^5.0@dev",
-        "cakephp/core": "dev-master"
+        "cakephp/core": "dev-master",
+        "facebook/graph-sdk": "^5.3"
     },
     "require-dev": {
     },

--- a/theme/js/fb.js
+++ b/theme/js/fb.js
@@ -1,16 +1,10 @@
-(function(){
-    // If we've already installed the SDK, we're done
-    if (document.getElementById('facebook-jssdk')) {return;}
-    // Get the first script element, which we'll use to find the parent node
-    var firstScriptElement = document.getElementsByTagName('script')[0];
-    // Create a new script element and set its id
-    var facebookJS = document.createElement('script');
-    facebookJS.id = 'facebook-jssdk';
-    // Set the new script's source to the source of the Facebook JS SDK
-    facebookJS.src = '//connect.facebook.net/en_US/all.js';
-    // Insert the Facebook JS SDK into the DOM
-    firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
-}());
+(function(d, s, id){
+    var js, fjs = d.getElementsByTagName(s)[0];
+    if (d.getElementById(id)) {return;}
+    js = d.createElement(s); js.id = id;
+    js.src = "https://connect.facebook.net/en_US/sdk.js";
+    fjs.parentNode.insertBefore(js, fjs);
+}(document, 'script', 'facebook-jssdk'));
 
 window.fbAsyncInit = function()
 {
@@ -19,16 +13,16 @@
         status      : true,
         cookie      : true,
         xfbml       : true,
-        version     : 'v2.4'
+        version     : 'v2.7'
     });
     FB.Canvas.setSize({ width: 800, height: 640 });
 
     FB.getLoginStatus(function(response) {
-        if ( response.status == "connected" ) {
+        if (response.status == "connected") {
         }
     });
 
-    FB.Event.subscribe('auth.login', function(response) {
+    FB.Event.subscribe('auth.statusChange', function(response) {
         onFacebookLogin();
         ga('send', 'event', 'Facebook', 'Logged in', '');
     });
@@ -131,14 +125,16 @@
 /**
 * Custom for each app
 */
-var loginFrom = null;
 function onFacebookLogin()
 {
-    if (loginFrom == 'start') {
-        window.location = FBAPP.path;
-    } else {
-        window.location = FBAPP.path;
-    }
+    $.get(FBAPP.path + 'index/user', function(user){
+        if (user.fb_id) {
+            $('.fblogin').hide();
+            // user is logged in, do something
+            console.log (user);
+            $('.container').html('Hello ' + user.first_name + ' ' + user.last_name);
+        }
+    }, 'json');
 }
 
 $(document).ready(function(){
@@ -154,4 +150,8 @@
         };
         postToFeed(obj);
     });
+    $(".fblogin").click(function(e){
+        e.preventDefault();
+        loginButton();
+    });
 });

--- a/theme/tpl/content/default/index.tpl
+++ b/theme/tpl/content/default/index.tpl
@@ -1,7 +1,8 @@
-
 <div class="main">
 	<div class="container">
-
+        {if $APP.logged_in == false}
+        <a href="#" class="fblogin">facebook login</a>
+        {/if}
 	</div>
 </div>
 

--- /dev/null
+++ b/upload/profile-pics/.keep

comments