Пример #1
0
 private function get_facebook_credentials($fbToken)
 {
     $settings = array('app_id' => APP_ID_FOR_ADS_MANAGER, 'app_secret' => APP_SECRET_FOR_ADS_MANAGER, 'default_graph_version' => 'v2.5');
     $fb = new Facebook\Facebook($settings);
     $fb->setDefaultAccessToken($fbToken);
     return $fb;
 }
Пример #2
0
 /**
  * Create an instance of Facebook session
  */
 private function set_fb_request_session()
 {
     $settings = array('app_id' => APP_ID_FOR_ADS_MANAGER, 'app_secret' => APP_SECRET_FOR_ADS_MANAGER, 'default_graph_version' => 'v2.5');
     $fb = new Facebook\Facebook($settings);
     $fb->setDefaultAccessToken(self::$fbToken);
     self::$fbSession = $fb;
     Api::init(APP_ID_FOR_ADS_MANAGER, APP_SECRET_FOR_ADS_MANAGER, self::$fbToken);
 }
Пример #3
0
 public function login()
 {
     $client = new Facebook\Facebook(['app_id' => '558049591013252', 'app_secret' => '6678bbf4ef0bfad674601faee955a507', 'default_graph_version' => 'v2.5']);
     if (!isset($_GET['code'])) {
         $helper = $client->getRedirectLoginHelper();
         $permissions = ['email', 'user_likes', 'manage_pages', 'publish_pages', 'read_insights'];
         // optional
         $loginUrl = $helper->getLoginUrl(base_url() . 'index.php/facebook/login', $permissions);
         $data['redirect_uri'] = $loginUrl;
         $this->load->view('youtube/oauth', $data);
     } else {
         $helper = $client->getRedirectLoginHelper();
         try {
             $fb_access_token = $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($fb_access_token)) {
             // Logged in!
             // Now you can redirect to another page and use the
             // access token from $_SESSION['facebook_access_token']
             // OAuth 2.0 client handler
             $oAuth2Client = $client->getOAuth2Client();
             // Exchanges a short-lived access token for a long-lived one
             $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($fb_access_token);
             $client->setDefaultAccessToken($longLivedAccessToken);
             $data['redirect_uri'] = base_url() . 'index.php/facebook/analytics';
             $_SESSION['fb_access_token'] = (string) $longLivedAccessToken;
             $_SESSION['fb_client'] = $client;
             echo "token found";
         }
     }
     $this->load->view('youtube/oauth', $data);
 }
Пример #4
0
 public function index()
 {
     $this->load->helper('url');
     $fb = new Facebook\Facebook(['app_id' => $this->config->item('fb_app_id'), 'app_secret' => $this->config->item('fb_secret'), 'default_graph_version' => $this->config->item('default_graph_version')]);
     $helper = $fb->getRedirectLoginHelper();
     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)) {
         // Logged in!
         $_SESSION['facebook_access_token'] = (string) $accessToken;
         // Sets the default fallback access token so we don't have to pass it to each request
         $fb->setDefaultAccessToken($accessToken);
         try {
             $response = $fb->get('/me?fields=id,email,first_name,last_name,location,picture');
             // $userNode = $response->getGraphUser();
         } 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;
         }
         $this->saveFbData($response);
     }
     redirect('http://' . $_SERVER['HTTP_HOST'] . '/survey');
     return;
 }
Пример #5
0
   public function afterImport() {
      if (!function_exists('PHPMailerAutoload'))
         require __DIR__ . DIRECTORY_SEPARATOR . 'phpmailer' . DIRECTORY_SEPARATOR . 'PHPMailerAutoload.php';
      $config = array();
      foreach ($this->selectAll(
              'SELECT `path`,`value` FROM `core_config_data`
                     WHERE `scope` = "default" AND ( `path` LIKE "%/lesti_smtp/%" OR `path` LIKE "%/ident_general/%" OR `path` = "web/unsecure/base_url")') as $value) {
         $config [$value['path']] = $value['value'];
      }
      $secondPath = $this->selectone('SELECT `value` FROM `core_config_data` WHERE `scope_id` = 2 AND `path` = "web/unsecure/base_url"',null,'value');
      $imageDir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR .
              '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR .
              'media' . DIRECTORY_SEPARATOR . 'catalog' . DIRECTORY_SEPARATOR . 'product' . DIRECTORY_SEPARATOR;

      $imageDir = realpath($imageDir);
      $name_id = $this->selectone('
         SELECT `attribute_id` FROM `eav_attribute` WHERE
         `attribute_code`="name" AND `entity_type_id`= 
             (SELECT `entity_type_id` FROM  `eav_entity_type` WHERE
             `entity_type_code`="catalog_product"
             )
      ',null,'attribute_id');
      //$name = 71;
      $description_id = $this->selectone('
         SELECT `attribute_id` FROM `eav_attribute` WHERE
         `attribute_code`="description" AND `entity_type_id`= 
             (SELECT `entity_type_id` FROM  `eav_entity_type` WHERE
             `entity_type_code`="catalog_product"
             )
      ',null,'attribute_id');
      //$description = 72;
      $url_key_id = $this->selectone('
      SELECT `attribute_id` FROM `eav_attribute` WHERE
         `attribute_code`="url_key" AND `entity_type_id`= 
             (SELECT `entity_type_id` FROM  `eav_entity_type` WHERE
             `entity_type_code`="catalog_product"
             )
      ',null,'attribute_id');
      //$url_key = 97;
      $image_id = $this->selectone('
      SELECT `attribute_id` FROM `eav_attribute` WHERE
      `attribute_code`="image" AND `entity_type_id`= 
          (SELECT `entity_type_id` FROM  `eav_entity_type` WHERE
          `entity_type_code`="catalog_product"
          )
      ',null,'attribute_id');
      //$image = 85;
      $catalog_category_id = $this->selectone('
      SELECT `attribute_id` FROM `eav_attribute` WHERE
      `attribute_code`="name" AND `entity_type_id`= 
      (SELECT `entity_type_id` FROM  `eav_entity_type` WHERE
         `entity_type_code`="catalog_category"
      )
      ',null,'attribute_id');
      //$catalog_category = 41;
      $shared_on_social_networks_id = $this->selectone('
            SELECT `attribute_id` FROM `eav_attribute` WHERE
            `attribute_code`="shared_on_social_networks"
      ',null,'attribute_id');
      //$shared_on_social_networks = 143;
      $news_from_date = $this->selectone('
            SELECT `attribute_id` FROM `eav_attribute` WHERE
            `attribute_code`="news_from_date"
      ',null,'attribute_id');
      //$shared_on_social_networks = 93;
      $product_stmt = $this->exec_stmt('
         SELECT
         `catalog_product_entity`.`entity_id` ,
         `catalog_product_entity`.`sku`
         FROM `catalog_product_entity` 
         LEFT JOIN `catalog_product_entity_int` ON 
         `catalog_product_entity_int`.`entity_id`=`catalog_product_entity`.`entity_id` AND 
         `catalog_product_entity_int`.`attribute_id`= '.$shared_on_social_networks_id.'
         LEFT JOIN `catalog_product_entity_datetime` ON 
         `catalog_product_entity_datetime`.`entity_id`=`catalog_product_entity`.`entity_id` AND 
         `catalog_product_entity_datetime`.`attribute_id`= '.$news_from_date.'
         WHERE 
           ( `catalog_product_entity_int`.`value` IS NULL OR `catalog_product_entity_int`.`value` != 1 ) AND  
           ( `catalog_product_entity_datetime`.`value` IS NOT NULL OR `catalog_product_entity_datetime`.`value` != "" )
         GROUP BY `catalog_product_entity`.`entity_id`
         ORDER BY `catalog_product_entity_datetime`.`value` DESC
         ',null,false);
      // Full path to twitterOAuth.php (change OAuth to your own path)
      // create new instance
      $tweet = new TwitterOAuth(
              $this->getParam("SOCIAL:twitterkey", ""), $this->getParam("SOCIAL:twittersecret", ""), $this->getParam("SOCIAL:twitterotoken", ""), $this->getParam("SOCIAL:twitterosecret", "")
      );
      $productCount = 0;
      $facebookPages = explode(':',$this->getParam("SOCIAL:facebook", ""));
      $gogglePages = explode(':',$this->getParam("SOCIAL:gpage", ""));
      while ($productCount < $this->getParam("SOCIAL:topost", "10") && $product = $product_stmt->fetch(PDO::FETCH_ASSOC) ) {
         $product['image']= $this->selectone('
               SELECT `value` FROM `catalog_product_entity_varchar` WHERE
                  `catalog_product_entity_varchar`.`entity_id`='.$product['entity_id'].' AND
                  `catalog_product_entity_varchar`.`attribute_id`= '.$image_id.'
               LIMIT 1
         ',null,'value');
         $product['url_path'] = $this->selectone('
               SELECT `request_path` FROM `core_url_rewrite`
               WHERE `id_path` LIKE "product/%" AND `product_id` ='.$product['entity_id'].'
               ORDER BY `category_id` ASC LIMIT 1
         ',null,'request_path');
         if (
                 $product['url_path'] == '' ||
                 !is_file($imageDir . $product['image'])
            ) {
            continue;
         }
         $product['name']= $this->selectone('
               SELECT `value` FROM `catalog_product_entity_varchar` WHERE
                     `catalog_product_entity_varchar`.`entity_id`='.$product['entity_id'].' AND
                     `catalog_product_entity_varchar`.`attribute_id`= '.$name_id.'  
               LIMIT 1
         ',null,'value');
         $product['description']= $this->selectone('
               SELECT `value` FROM `catalog_product_entity_text` WHERE
                     `catalog_product_entity_text`.`entity_id`='.$product['entity_id'].' AND
                     `catalog_product_entity_text`.`attribute_id`= '.$description_id.'
               LIMIT 1
         ',null,'value');
         $product['url_key']= $this->selectone('
               SELECT `value` FROM `catalog_product_entity_varchar` WHERE
                     `catalog_product_entity_varchar`.`entity_id`='.$product['entity_id'].' AND
                     `catalog_product_entity_varchar`.`attribute_id`= '.$url_key_id.'
               LIMIT 1
         ',null,'value');
         $product['category_names'] = $this->selectone('
               SELECT GROUP_CONCAT( DISTINCT `value` SEPARATOR ", ") as value
               FROM `catalog_category_entity_varchar` WHERE
               `entity_id` IN (SELECT `category_id` FROM `catalog_category_product` WHERE `product_id` = '.$product['entity_id'].')
               AND `catalog_category_entity_varchar`.`attribute_id`= '.$catalog_category_id.'                       
         ',null,'value');
         
         $productCount ++;
         $tags = preg_replace('/^[^,]*, /', '', $product['category_names']);
         $tags = strtolower(', '.$tags);
         $tags = str_replace(' ','_',$tags);
         $tags = trim(str_replace(',_',' #',$tags));
         if (
                 $this->getParam("SOCIAL:gemail", "") != '' &&
                 $this->getParam("SOCIAL:gpassword", "") != '' &&
                 $this->getParam("SOCIAL:gpage", "") != ''
         ) {
            foreach($gogglePages as $key=>$gogglePage) {
	       $baseUrl = $config['web/unsecure/base_url'];
	       if ($key>0 && $secondPath != '')
		   $baseUrl = $secondPath;
               $nt = new nxsAPI_GP();
               $loginError = $nt->connect($this->getParam("SOCIAL:gemail", ""), $this->getParam("SOCIAL:gpassword", ""));
               // Image URL
               $lnk = array('img'=>$baseUrl. '/media/catalog/product/' . $product['image']);
               $nt->postGP($product['name'] .' '. $tags . ' ' . $baseUrl . 'index.php/' . $product['url_path'], $lnk, $gogglePage);
               if ($loginError === false)
                  $this->log($baseUrl . 'index.php/' . $product['url_path'] . " not sent succesfully " . $loginError, "info");
            }
         }
         // Your Message
         $message = substr($product['name'], 0, 100) . ' ' . $config['web/unsecure/base_url'] . 'index.php/' . $product['url_path']. ' ' . $tags;

         if (
                 $this->getParam("SOCIAL:twitterkey", "") != '' &&
                 $this->getParam("SOCIAL:twittersecret", "") != '' &&
                 $this->getParam("SOCIAL:twitterotoken", "") != '' &&
                 $this->getParam("SOCIAL:twitterosecret", "") != ''
         ) {
            // Send tweet 
            $tweet->post('statuses/update', array('status' => $message));
         }
         if (
                 $this->getParam("SOCIAL:wpurl", "") != '' &&
                 $this->getParam("SOCIAL:wpusername") != '' &&
                 $this->getParam("SOCIAL:wppassword", "") != ''
         ) {
            $client = new IXR_Client($this->getParam("SOCIAL:wpurl", ""));
	    $description = substr($product['description'],0,100);
	    $description .= '<!--more-->';
            $description .= substr($product['description'],100);
            $description .= '<br/><a href="' . $config['web/unsecure/base_url'] . 'index.php/' . $product['url_path'] . '">' . $product['name'] . '</a>';
            $content = array(
                'post_status' => 'draft',
                'post_type' => 'post',
                'post_title' => $product['name'],
                'post_content' => $description,
                'terms' => array('category' => array($this->getParam("SOCIAL:wpcategory_id", "")))
            );
            $params = array(0, $this->getParam("SOCIAL:wpusername", ""), $this->getParam("SOCIAL:wppassword", ""), $content);
            $client->query('wp.newPost', $params);
            $post_id = $client->getResponse();
            
            $command = 'convert "' .$imageDir . $product['image']. '" -resize 604x270\\>  -resample 72 /tmp/storebaby.jpg 2>&1 ';
            exec($command);
            
            $content = array(
                'name' => basename($product['image']),
                'type' => mime_content_type(basename($product['image'])),
                'bits' => new IXR_Base64(file_get_contents('/tmp/storebaby.jpg')),
                true
            );
            $client->query('metaWeblog.newMediaObject', 1, $this->getParam("SOCIAL:wpusername"), $this->getParam("SOCIAL:wppassword"), $content);
            $media = $client->getResponse();
            $content = array(
                'post_status' => 'publish',
                'mt_keywords' => preg_replace('/^[^,]*, /', '', $product['category_names']),
                'wp_post_thumbnail' => $media['id']
            );
            $client->query('metaWeblog.editPost', $post_id, $this->getParam("SOCIAL:wpusername"), $this->getParam("SOCIAL:wppassword"), $content, true);
         }
         $fbConfigFile = __DIR__.'/fbConf.php';
         if (is_file($fbConfigFile)) {
             require $fbConfigFile;
             $baseUrl = $config['web/unsecure/base_url'];
             $fb = new Facebook\Facebook(array(
                        'app_id' => $fbConfig['appId'],
                        'app_secret' => $fbConfig['appSecret'],
                        'default_graph_version' => 'v2.3'
             ));
             foreach($fbConfig['pages'] as $pageId=>$pageToken) {
                   $fb->setDefaultAccessToken($pageToken);
               $linkData = [
		  'link' =>  $baseUrl . 'index.php/' . $product['url_path'],
                  'name' =>  $product['name'] .' ' . $tags,
 		  'message' =>  $product['name'] .' ' . $tags,
                  'picture' => $baseUrl. '/media/catalog/product/' . $product['image']
		  ];
		  try {
		  // Returns a `Facebook\FacebookResponse` object
                  $fb->post('/'. substr($pageId,1,99) .'/feed', $linkData,$pageToken);
                  } catch(Facebook\Exceptions\FacebookResponseException $e) {
                    echo 'Graph returned an error: ' . $e->getMessage();
                  } catch(Facebook\Exceptions\FacebookSDKException $e) {
                    echo 'Facebook SDK returned an error: ' . $e->getMessage();
                  }
            }
	    $this->exec_stmt('REPLACE INTO `catalog_product_entity_int` SET `value`=1 ,
            	`catalog_product_entity_int`.`attribute_id`= '.$shared_on_social_networks_id.',
                `catalog_product_entity_int`.`entity_id` = ' . $product['entity_id'] . '
            ');
         }
         unlink('/tmp/storebaby.jpg');
      }
      $product_stmt->closeCursor();
   }
Пример #6
0
var_dump($accessToken->getValue());
// 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(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;
    }
    echo '<h3>Long-lived</h3>';
    var_dump($accessToken->getValue());
}
// Logged in!
$_SESSION['fb_access_token'] = (string) $accessToken;
// Sets the default fallback access token so we don't have to pass it to each request
$fb->setDefaultAccessToken((string) $accessToken);
getPosts($fb);
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header(REDIRECT_MEMBERS_URL);
 function facebookLogin()
 {
     $request = $_REQUEST;
     $site = $this->siteUrl();
     $callBackUrl = $this->callBackUrl();
     $response = new stdClass();
     $return_user_details = new stdClass();
     $exploder = explode('_', $_GET['apsl_login_id']);
     $action = $exploder[1];
     $options = get_option(APSL_SETTINGS);
     $config = array('app_id' => $options['apsl_facebook_settings']['apsl_facebook_app_id'], 'app_secret' => $options['apsl_facebook_settings']['apsl_facebook_app_secret'], 'default_graph_version' => 'v2.4');
     include APSL_PLUGIN_DIR . 'facebook/autoload.php';
     $fb = new Facebook\Facebook($config);
     $encoded_url = isset($_GET['redirect_to']) ? $_GET['redirect_to'] : '';
     if (isset($encoded_url) && $encoded_url != '') {
         $callback = $callBackUrl . 'apsl_login_id' . '=facebook_check&redirect_to=' . $encoded_url;
     } else {
         $callback = $callBackUrl . 'apsl_login_id' . '=facebook_check';
     }
     if ($action == 'login') {
         // Well looks like we are a fresh dude, login to Facebook!
         $helper = $fb->getRedirectLoginHelper();
         $permissions = array('email', 'public_profile');
         // optional
         $loginUrl = $helper->getLoginUrl($callback, $permissions);
         $this->redirect($loginUrl);
     } else {
         if (isset($_REQUEST['error'])) {
             $response->status = 'ERROR';
             $response->error_code = 2;
             $response->error_message = 'INVALID AUTHORIZATION';
             return $response;
             die;
         }
         if (isset($_REQUEST['code'])) {
             $helper = $fb->getRedirectLoginHelper();
             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)) {
                 // Logged in!
                 $_SESSION['facebook_access_token'] = (string) $accessToken;
                 $fb->setDefaultAccessToken($accessToken);
                 try {
                     $response = $fb->get('/me?fields=email,name, first_name, last_name, gender, link, about, address, bio, birthday, education, hometown, is_verified, languages, location, website');
                     $userNode = $response->getGraphUser();
                 } 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;
                 }
                 $user_profile = $this->accessProtected($userNode, 'items');
                 if ($user_profile != null) {
                     $return_user_details->status = 'SUCCESS';
                     $return_user_details->deuid = $user_profile['id'];
                     $return_user_details->deutype = 'facebook';
                     $return_user_details->first_name = $user_profile['first_name'];
                     $return_user_details->last_name = $user_profile['last_name'];
                     $return_user_details->email = $user_profile['email'];
                     $return_user_details->username = $user_profile['email'];
                     $return_user_details->gender = $user_profile['gender'];
                     $return_user_details->url = $user_profile['link'];
                     $return_user_details->about = '';
                     //facebook doesn't return user about details.
                     $headers = get_headers('https://graph.facebook.com/' . $user_profile['id'] . '/picture', 1);
                     // just a precaution, check whether the header isset...
                     if (isset($headers['Location'])) {
                         $return_user_details->deuimage = $headers['Location'];
                         // string
                     } else {
                         $return_user_details->deuimage = false;
                         // nothing there? .. weird, but okay!
                     }
                     $return_user_details->error_message = '';
                 } else {
                     $return_user_details->status = 'ERROR';
                     $return_user_details->error_code = 2;
                     $return_user_details->error_message = 'INVALID AUTHORIZATION';
                 }
             }
         } else {
             // Well looks like we are a fresh dude, login to Facebook!
             $helper = $fb->getRedirectLoginHelper();
             $permissions = array('email', 'public_profile');
             // optional
             $loginUrl = $helper->getLoginUrl($callback, $permissions);
             $this->redirect($loginUrl);
         }
     }
     return $return_user_details;
 }
        $accessToken = $_SESSION['localhost_app_token'];
    } else {
        $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)) {
    if (isset($_SESSION['localhost_app_token'])) {
        $fb->setDefaultAccessToken($_SESSION['localhost_app_token']);
    } else {
        // getting short-lived access token
        $_SESSION['localhost_app_token'] = (string) $accessToken;
        // OAuth 2.0 client handler
        $oAuth2Client = $fb->getOAuth2Client();
        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['localhost_app_token']);
        $_SESSION['localhost_app_token'] = (string) $longLivedAccessToken;
        // setting default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['localhost_app_token']);
    }
    // redirect the user back to the same page if it has "code" GET variable
    if (isset($_GET['code'])) {
        header('Location: ./');
    }
Пример #9
0
 /**
  * Connection to facebook application
  *
  * @return \Facebook\Facebook
  */
 private function connectApps()
 {
     $fb = new \Facebook\Facebook(['app_id' => $this->appID, 'app_secret' => $this->appSecret, 'default_graph_version' => $this->defaultGraphVersion]);
     try {
         $token = $fb->getCanvasHelper()->getAccessToken();
     } catch (FacebookSDKException $e) {
         throw new HttpException(500, 'Facebook Access Token returned an error: ' . $e->getMessage());
     }
     if ($token == null) {
         $helper = $fb->getRedirectLoginHelper();
         $scope = ['email', 'user_likes', 'publish_actions'];
         $loginUrl = $helper->getLoginUrl('https://apps.facebook.com/' . $this->appID, $scope);
         echo '<script>window.top.location.href = "' . $loginUrl . '"</script>';
     } else {
         $fb->setDefaultAccessToken($token);
     }
     $this->session->set('access_token', $token);
     $this->session->set('fb', $fb);
     return $fb;
 }
 function getSourceBannerLogo($albumId)
 {
     $fb = new Facebook\Facebook(['app_id' => '959119600818575', 'app_secret' => '9f0062f110ea6d3589e7debcb04c2268', 'default_graph_version' => 'v2.5']);
     //Récupère token Admin
     $fb->setDefaultAccessToken($_SESSION['token']);
     try {
         $response = $fb->get('/196951203980314?fields=access_token');
         $token = $response->getGraphNode()->asArray();
         $tokenId = $token['access_token'];
     } catch (Facebook\Exceptions\FacebookResponseException $e) {
         // After you're done debugging, comment out the below lines
         $result = $e->getMessage();
         echo "<pre>";
         print_r($result);
         echo "</pre>";
     }
     $fb->setDefaultAccessToken($tokenId);
     try {
         $response = $fb->get('/' . $albumId . '?fields=name,photos{name,source}');
         $items = $response->getGraphNode()->asArray();
         foreach ($items['photos'] as $item) {
             $bannerlogo[] = $item['source'];
         }
     } catch (Facebook\Exceptions\FacebookResponseException $e) {
         // After you're done debugging, comment out the below lines
         $result = $e->getMessage();
         echo "<pre>";
         print_r($result);
         echo "</pre>";
     }
     return $bannerlogo;
 }
Пример #11
0
 public static function LoginFacebook()
 {
     $fb = new Facebook\Facebook(['app_id' => '1068588159868715', 'app_secret' => 'd3790d1f47df4805b47976f16199fd89', 'default_gra]ph_version' => 'v2.6']);
     $helper = $fb->getRedirectLoginHelper();
     $permissions = ['email'];
     // optional
     if (isset($_SESSION['facebook_access_token'])) {
         $accessToken = $_SESSION['facebook_access_token'];
     } else {
         $accessToken = $helper->getAccessToken();
     }
     if (isset($_SESSION['facebook_access_token'])) {
         $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
     } else {
         // getting short-lived access token
         $_SESSION['facebook_access_token'] = (string) $accessToken;
         // OAuth 2.0 client handler
         $oAuth2Client = $fb->getOAuth2Client();
         // Exchanges a short-lived access token for a long-lived one
         $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
         $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
         // setting default access token to be used in script
         $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
     }
     $profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
     $profile = $profile_request->getGraphNode()->asArray();
     return $profile;
 }
Пример #12
0
 function getPage($user_model)
 {
     if (!$user_model instanceof \xepan\marketing\Model_SocialPosters_Base_SocialUsers) {
         throw new \Exception("must pass instance of social user");
     }
     // get Facebook Config
     $config_model = $user_model->appConfig();
     $config = array('app_id' => $config_model['appId'], 'app_secret' => $config_model['secret'], 'default_graph_version' => $this->default_graph_version);
     $this->fb = $facebook = $fb = new \Facebook\Facebook($config);
     if (!$this->fb) {
         return "Configuration Problem";
     }
     $fb->setDefaultAccessToken($user_model['access_token']);
     // get all  pages
     // https://graph.facebook.com/$user_id_returned/accounts/?access_token=$access_token
     $requests = [$facebook->request('GET', '/' . $user_model['userid_returned'] . '/accounts')];
     try {
         $responses = $fb->sendBatchRequest($requests);
     } catch (Facebook\Exceptions\FacebookResponseException $e) {
         echo 'Graph returned an error: ' . $e->getMessage();
         exit;
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         echo 'Facebook SDK returned an error: ' . $e->getMessage();
         exit;
     }
     // decode all the data
     $response_data = $responses->getDecodedBody();
     if ($response_data[0]['code'] === 200) {
         return $response_data[0]['body'];
     } else {
         throw new \Exception("some thing wrong return code = " . $response_data[0]['code']);
     }
 }
Пример #13
0
    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)) {
    // Logged in!
    $_SESSION['facebook_access_token'] = (string) $accessToken;
    $short_access_token = (string) $accessToken;
    // OAuth 2.0 client handler
    $oAuth2Client = $fb->getOAuth2Client();
    // Exchanges a short-lived access token for a long-lived one
    $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($short_access_token);
    // Sets the default fallback access token so we don't have to pass it to each request
    $fb->setDefaultAccessToken($longLivedAccessToken);
    try {
        $response = $fb->get('/me');
        $userNode = $response->getGraphUser();
        // Add to header of your file
        // Add after echo "You are logged in "
        // Initialize a new Session and instantiate an Api object
        Api::init($CLIENT_ID, $APP_SECRET, $longLivedAccessToken);
        // Add after Api::init()
        $me = new AdUser('me');
        $my_adaccount = $me->getAdAccounts()->current();
        print_r($my_adaccount->getData());
        // $page_token = $fb -> get("/$PAGE_ID") ->getAccessToken() ;
        // $albums = $fb -> get("/$PAGE_ID/albums") -> getGraphEdge();
        // $photo = $fb -> post("$ALBUM_ID/photos", array( 'source' => $fb ->fileToUpload("Monkey.D..Luffy.full.476449.jpg"), "message" => 'New photo hello' ), $page_token);
        // $total_post = $fb -> get("/$PAGE_ID/feed") -> getGraphEdge() ->asJson();
Пример #14
0
    try {
        $helper = $fb->getRedirectLoginHelper();
        $scope = ["email", "user_likes", "user_photos", "publish_actions"];
        $loginUrl = $helper->getLoginUrl('participate/login', $scope);
    } 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;
    }
} else {
    try {
        $fb->setDefaultAccessToken($_SESSION['token']);
    } 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;
    }
}
function verifyAccessToken()
{
    $graph_url = "https://graph.facebook.com/me?access_token=" . $_SESSION['token'];
    $ch = curl_init($graph_url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Пример #15
0
 /**
  * 透過token 取得 fb 的 uid 驗證登入。
  * 1. 如果 email 存在資料庫,則表示登入成功。
  * 2. 如果 email 不存在,則導入註冊頁。
  *
  * @Route("fblogin", name="front_custom_verifyFblogin", options={"expose"=true})
  * @Method("GET")
  */
 public function verifyFbloginAction(Request $request)
 {
     $session = $this->get('session');
     $redirectUrlList = $this->getRedirectUrlList();
     $fbParam = $this->container->getParameter('fb');
     $fb = new \Facebook\Facebook(['app_id' => $fbParam['app_id'], 'app_secret' => $fbParam['app_secret'], 'default_graph_version' => $fbParam['api_version']]);
     $helper = $fb->getRedirectLoginHelper();
     try {
         $accessToken = $helper->getAccessToken();
     } catch (\Facebook\Exceptions\FacebookResponseException $e) {
         // add flash messages
         $session->getFlashBag()->add('error', 'Facebook 驗證發生錯誤' . $e->getMessage());
         return $this->redirect($redirectUrlList['fail'], 302);
     } catch (\Facebook\Exceptions\FacebookSDKException $e) {
         // add flash messages
         $session->getFlashBag()->add('error', 'Facebook 驗證發生錯誤' . $e->getMessage());
         return $this->redirect($redirectUrlList['fail'], 302);
     }
     if (isset($accessToken)) {
         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;
             }
         }
         // Logged in
         $fb->setDefaultAccessToken($accessToken);
         try {
             $response = $fb->get('/me', $accessToken);
             $userNode = $response->getGraphUser();
         } catch (\Facebook\Exceptions\FacebookResponseException $e) {
             // When Graph returns an error
             $session->getFlashBag()->add('error', 'Graph returned an error: ' . $e->getMessage());
             return $this->redirect($this->get('router')->generate('front_custom_create'));
         } catch (\Facebook\Exceptions\FacebookSDKException $e) {
             // When validation fails or other local issues
             $session->getFlashBag()->add('error', 'Facebook SDK returned an error: ' . $e->getMessage());
             return $this->redirect($this->get('router')->generate('front_custom_create'));
         }
     }
     $em = $this->getDoctrine()->getManager();
     //$custom = $em->getRepository('WoojinOrderBundle:Custom')->findByEmailFromWebsite($userNode['email']);
     $custom = $em->getRepository('WoojinOrderBundle:Custom')->findByFaceBookUserNode($userNode);
     if ($custom && NULL === $custom->getFbToken()) {
         $custom->setFbToken($userNode['id']);
         $em->persist($custom);
         $em->flush();
     }
     if (!$custom) {
         // 這邊應該是導向一個輸入email的 Form 頁面
         if (!isset($userNode['email'])) {
             $session->set('userNode', $userNode);
             return $this->redirect($this->get('router')->generate('front_custom_light_simple'));
         }
         $custom = new Custom();
         $custom->setStore($em->find('WoojinStoreBundle:Store', Avenue::STORE_WEBSITE));
         $custom->handleFbResponse($userNode);
         $em->persist($custom);
         $em->flush();
         $this->get('avenue.notifier')->register($custom);
     }
     // 客戶若原本就存在則進行登入成功流程
     // 若客戶不存在則導向註冊頁
     return $this->loginSuccessCallback($session, $custom, $em)->redirect($redirectUrlList['success']);
 }
Пример #16
0
function fbPost($code)
{
    require realpath(dirname(__FILE__) . "/../config.php");
    $servername = $config["db"]["fanbot"]["host"];
    $username = $config["db"]["fanbot"]["username"];
    $password = $config["db"]["fanbot"]["password"];
    $dbname = $config["db"]["fanbot"]["dbname"];
    $fb = new Facebook\Facebook(['app_id' => $config["fbApp"]["appId"], 'app_secret' => $config["fbApp"]["appSecret"], 'default_graph_version' => 'v2.6']);
    $token = fbCode2token($code);
    $fb->setDefaultAccessToken($token);
    $pageJson = file_get_contents('https://graph.facebook.com/' . $_SESSION['fnbt']['config']['link'] . '?fields=location&access_token=1498446833779418|6Uo2HajAgYUiIE0x8DR1AXuhxbw');
    $pageArray = json_decode($pageJson, true);
    // Get fbPageId for facebook post
    $pageId = $pageArray["id"];
    // fbPost array wiht the post info
    if ($_SESSION['fnbt']['name'] == 'futy') {
        $linkData = ['link' => 'https://www.facebook.com/277802179240254'];
    } else {
        if (isset($pageArray['location']['latitude'])) {
            $linkData = ['place' => $pageId];
        } else {
            $linkData = ['link' => 'https://www.facebook.com/' . $_SESSION['fnbt']['config']['link']];
        }
    }
    $post = $fb->post('/me/feed', $linkData);
}
Пример #17
0
<?php

include_once '../../../MasterPages/overhead.php';
$accessTokens = array("short" => $_SESSION['facebook_access_token'], "long" => $_SESSION['facebook_access_token_long_term']);
require_once 'src/autoload.php';
$fb = new Facebook\Facebook(['app_id' => FACEBOOK_APPID, 'app_secret' => FACEBOOK_SECRET, 'default_graph_version' => 'v2.5', 'cookie' => true]);
// Sets the default fallback access token so we don't have to pass it to each request
$fb->setDefaultAccessToken($accessTokens['short']);
try {
    $response = $fb->get('/me?fields=id,name,first_name,last_name,age_range,link,gender,locale,picture.width(500).height(500),timezone,updated_time,verified,email', $accessTokens['short']);
    $user = $response->getGraphUser();
    $today = date("m/d/y");
    if ($user) {
        $user_id = pb_db("SELECT user_id FROM pb_users WHERE user_id = '{$user['id']}'", true);
        //Create User
        if (empty($user_id)) {
            $user_id = $user['id'];
            $username = pb_new_row('pb_users', 'username', $user['first_name'] . $user['last_name']);
            $contact_info = '[{"resident":"true","building":"","room":"","phone":"","email":"' . $user['email'] . '","notify_d":"true","notify_m":"true"}]';
            $user_data = '[{"ID":"' . $user_id . '","username":"******","name":"' . $user['first_name'] . ' ' . $user['last_name'] . '","avatar":"' . $user['picture']['url'] . '","registered":"' . $today . '","permissions":"25","theme":"darkblue","interest":""}]';
            $sql = pb_db("INSERT INTO pb_users (user_id, username, num_of_ratings, total_ratings, permissions, id_card_key, contact_info, user_data, steps)\n\t\t\tVALUES ('{$user_id}', '{$username}', '0', '0', '25', '', '{$contact_info}', '{$user_data}', '')");
            if ($sql) {
                $_SESSION['user_id'] = $user_id;
                header('Location: ' . $_GET['redirect_on_login']);
            } else {
                print 'No sql';
            }
        } else {
            $_SESSION['user_id'] = $user_id->user_id;
            $user_id = $user_id->user_id;
            $contact_info = array();
Пример #18
0
<?php

require_once __DIR__ . '/vendor/autoload.php';
$assetsFolder = __DIR__ . '/downloaded-assets';
$nodes = array();
$fb = new Facebook\Facebook(['app_id' => '1671486879750098', 'app_secret' => '34571d3ffa4960308192d362dc4d0711', 'default_graph_version' => 'v2.4']);
$fb->setDefaultAccessToken('1671486879750098|34571d3ffa4960308192d362dc4d0711');
$request = $fb->request('GET', '/1410974149199136/posts', ['fields' => 'full_picture,link,source,properties,type,created_time,updated_time,to,message,message_tags,story,story_tags', 'limit' => 100]);
try {
    $response = $fb->getClient()->sendRequest($request);
} 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;
}
$edge = $response->getGraphEdge();
do {
    foreach ($edge as $post) {
        $nodes[$post->getField('id')] = $post->asArray();
    }
} while ($edge = $fb->next($edge));
if (!empty($nodes)) {
    $filename = 'data-' . time() . '.json';
    file_put_contents($assetsFolder . "/{$filename}", json_encode($nodes));
    print "Saved " . count($nodes) . " nodes to {$filename}\n";
} else {
    echo "Something went wrong!\n";
Пример #19
0
 private function initApi($accessToken = null)
 {
     $facebookApi = new Facebook\Facebook(['app_id' => $this->_appid, 'app_secret' => $this->_appkey, 'default_graph_version' => 'v2.5']);
     if (!$accessToken) {
         try {
             $jsHelper = $facebookApi->getJavaScriptHelper();
             $accessToken = $jsHelper->getAccessToken();
         } catch (Facebook\Exceptions\FacebookResponseException $e) {
             // When Graph returns an error
             FSLTools::returnError(sprintf(Tools::displayError('Facebook Graph returned an error: %s'), $e->getMessage()));
         } catch (Facebook\Exceptions\FacebookSDKException $e) {
             // When validation fails or other local issues
             FSLTools::returnError(sprintf(Tools::displayError('Facebook SDK returned an error: %s'), $e->getMessage()));
         }
     }
     $facebookApi->setDefaultAccessToken($accessToken);
     return $facebookApi;
 }
//$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;
    }
    #echo '<h3>Long-lived</h3>';
    #var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
// Sets the default fallback access token so we don't have to pass it to each request
$fb->setDefaultAccessToken($_SESSION['fb_access_token']);
/* Changed this to the actual fb_access token*/
try {
    $response = $fb->get('/me');
    $userNode = $response->getGraphUser();
} 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 the token is set redirect user to .... index.php
Пример #21
0
 public function logincallback()
 {
     $fb = new Facebook\Facebook(['app_id' => '1509104876060790', 'app_secret' => '977e891176e8e1e9e6b626323f01d8bb', 'default_graph_version' => 'v2.5']);
     //$fbApp = new Facebook\FacebookApp('1509104876060790','977e891176e8e1e9e6b626323f01d8bb');
     $helper = $fb->getRedirectLoginHelper();
     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 error1 : ' . $e->getMessage();
         exit;
     }
     if (isset($accessToken)) {
         // Logged in!
         $_SESSION['facebook_access_token'] = (string) $accessToken;
         // Sets the default fallback access token so we don't have to pass it to each request
         $fb->setDefaultAccessToken($accessToken);
         // Now you can redirect to another page and use the
         // access token from $_SESSION['facebook_access_token']
         try {
             //Get pages
             $request = $fb->request('GET', '/me/accounts');
             $response = $fb->getClient()->sendRequest($request);
             $graphEdge = $response->getGraphEdge();
             // Iterate over all the GraphNode's returned from the edge
             $json = "";
             foreach ($graphEdge as $key => $value) {
                 $json .= $value['id'] . ":" . $value['name'] . ",";
             }
             //Get name and email
             $request = $fb->request('GET', '/me?fields=name,email');
             $response = $fb->getClient()->sendRequest($request);
             $graphNode = $response->getGraphNode();
             $name = $graphNode['name'];
             $id = $graphNode['id'];
             $email = isset($graphNode['email']) ? $graphNode['email'] : '';
             //Get long token
             // OAuth 2.0 client handler
             $oAuth2Client = $fb->getOAuth2Client();
             // Exchanges a short-lived access token for a long-lived one
             $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
             $loginData = array();
             $loginData['pages'] = $json;
             $loginData['name'] = $name;
             $loginData['email'] = $email;
             $loginData['id'] = $id;
             $loginData['facebook_token'] = $longLivedAccessToken;
             $loginData['login_provider'] = 'facebook';
             $this->save_and_login($loginData);
             //$this->index($loginData);
         } 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 error1 : ' . $e->getMessage();
             exit;
         }
         //echo 'Logged in as ' . $userNode->getName();
     }
 }
Пример #22
0
    // get new access token if we've been redirected from login page
    try {
        // get access token
        $access_token = $helper->getAccessToken();
        // save access token to persistent data store
        $helper->getPersistentDataHandler()->set('access_token', $access_token);
    } catch (Exception $e) {
        // error occured
    }
}
// get stored access token
$access_token = $helper->getPersistentDataHandler()->get('access_token');
// check if we have an access_token, and that it's valid
if ($access_token && !$access_token->isExpired()) {
    // set default access_token so we can use it in any requests
    $fb->setDefaultAccessToken($access_token);
    try {
        // If you provided a 'default_access_token', second parameter '{access-token}' is optional.
        $response = $fb->get('/me');
        // use $fb->post() to make a POST API call
    } catch (Exception $e) {
        // catch any errors and halt script
        echo $e->getMessage();
        exit;
    }
    $me = $response->getGraphUser();
    echo '<p>Logged in as ' . $me->getName() . '</p>';
    echo '<pre>' . print_r($me, 1) . '</pre>';
    echo '<p><a href="' . $helper->getLogoutUrl($access_token, 'http://fbappapp.herokuapp.com/logout.php') . '">Logout of Facebook</a></p>';
} else {
    // show login link
function rgt_fb_email_button_shortcode()
{
    $options = get_option('rgt_fb_email_button_settings');
    $app_id = $options['rgt_fb_email_button_app_id'];
    $app_secret = $options['rgt_fb_email_button_app_secret'];
    $current_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    wp_register_style('rgt_fb_email_button_css', plugins_url('fb_email_button_style.css', __FILE__));
    wp_enqueue_style('rgt_fb_email_button_css');
    if (!($app_id and $app_secret)) {
        $error = rgt_fb_email_button_error_wrapper('Facebook App ID and App Secret must be set in the Settings before using this plugin.');
        return $error;
    } else {
        require_once __DIR__ . '/Facebook_SDK/autoload.php';
        $fb = new Facebook\Facebook(['app_id' => $app_id, 'app_secret' => $app_secret, 'default_graph_version' => 'v2.5', 'default_access_token' => $app_id . '|' . $app_secret]);
        $helper = $fb->getRedirectLoginHelper();
        if (isset($_GET['code'])) {
            // API Callback
            try {
                $accessToken = $helper->getAccessToken();
            } catch (Facebook\Exceptions\FacebookResponseException $e) {
                $error = rgt_fb_email_button_error_wrapper('Invalid Facebook App Info.');
                return $error;
            } catch (Facebook\Exceptions\FacebookSDKException $e) {
                $error = rgt_fb_email_button_error_wrapper('Invalid Facebook App Info.');
                return $error;
            }
            if (isset($accessToken)) {
                $oAuth2Client = $fb->getOAuth2Client();
                $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
                $_SESSION['rgt_fb_email_button_facebook_access_token'] = (string) $longLivedAccessToken;
                // Get data
                $fb->setDefaultAccessToken($longLivedAccessToken);
                try {
                    $response = $fb->get('/me?fields=id,name,email');
                } catch (Facebook\Exceptions\FacebookResponseException $e) {
                    $error = rgt_fb_email_button_error_wrapper('Graph returned an error: ' . $e->getMessage());
                    return $error;
                } catch (Facebook\Exceptions\FacebookSDKException $e) {
                    $error = rgt_fb_email_button_error_wrapper('Facebook SDK returned an error: ' . $e->getMessage());
                    return $error;
                }
                $graphObject = $response->getGraphObject();
                $fb_id = $graphObject->getProperty('id');
                $name = $graphObject->getProperty('name');
                $email = $graphObject->getProperty('email');
                if (!isset($_GET['unsubscribe'])) {
                    rgt_fb_email_button_add_subscriber($fb_id, $name, $email);
                } elseif (wp_verify_nonce($_GET['unsubscribe'], 'fb_email_unsubscribe')) {
                    rgt_fb_email_button_remove_subscriber($fb_id);
                    unset($_SESSION['rgt_fb_email_button_facebook_access_token']);
                }
                $js_redirect = "<script>window.location = '" . remove_query_arg(array('code', 'unsubscribe', 'state')) . "'</script>";
                return $js_redirect;
            }
        }
        $permissions = array('public_profile', 'email');
        if (!isset($_SESSION['rgt_fb_email_button_facebook_access_token']) or !$_SESSION['rgt_fb_email_button_facebook_access_token']) {
            $login_url = $helper->getLoginUrl($current_url, $permissions);
            $button = "<a class=\"btn_fb_subscribe\" onclick=\"location.href='{$login_url}'\"></a>";
        } else {
            $nonce_unsubscribe = wp_nonce_url($current_url, 'fb_email_unsubscribe', 'unsubscribe');
            $unsubscribe_url = $helper->getLoginUrl($nonce_unsubscribe, $permissions);
            $button = "<a class=\"btn_fb_subscribed\" onclick=\"location.href='{$unsubscribe_url}'\"></a>";
        }
        return $button;
    }
}
Пример #24
0
<?php

session_start();
require_once __DIR__ . '/facebook-php-sdk-v4-5.0.0/src/Facebook/autoload.php';
require_once __DIR__ . '/facebook-php-sdk-v4-5.0.0/src/Facebook/Facebook.php';
$fb = new Facebook\Facebook(['app_id' => '1023466864382694', 'app_secret' => '814079f172a9399b12177a08a9cbbc42', 'default_graph_version' => 'v2.4']);
$token = 'CAAOi1nLkEuYBAAb450P075eXAo7scVnZAl1GXPwffgIbJqfO0AZC54bZA7T4ehfLdo574gdBiC1Wfw1CwZBdviCrLNywe2MDlK3cXdu5XqCWmtFn2s5LmGuZAsJeC5rLvZB2O4arqDdnEf6sIn98vu4lnwZA4qhypQnIbRI05Y0vvBGg9w3zj9jdVadMdzMIh13f0xtZCnEyNAZDZD';
$fb->setDefaultAccessToken($token);
$requestFriends = $fb->get('/me/taggable_friends?fields=name&limit=100');
$friends = $requestFriends->getGraphEdge();
if ($fb->next($friends)) {
    $allFriends = array();
    $friendsArray = $friends->asArray();
    $allFriends = array_merge($friendsArray, $allFriends);
    while ($friends = $fb->next($friends)) {
        $friendsArray = $friends->asArray();
        $allFriends = array_merge($friendsArray, $allFriends);
    }
    foreach ($allFriends as $key) {
        echo $key['name'] . "<br>";
    }
    echo count($allfriends);
} else {
    $allFriends = $friends->asArray();
    $totalFriends = count($allFriends);
    foreach ($allFriends as $key) {
        echo $key['name'] . "<br>";
    }
}
 public function uploadAction()
 {
     session_start();
     include "../include/connexion.php";
     require_once APPLICATION_PATH . '/public/facebook-php-sdk-v4-5.0.0/src/Facebook/autoload.php';
     $fb = new Facebook\Facebook(['app_id' => '959119600818575', 'app_secret' => '9f0062f110ea6d3589e7debcb04c2268', 'default_graph_version' => 'v2.5']);
     if (!isset($_SESSION['token'])) {
         header("Location: /participate");
     } else {
         $fb->setDefaultAccessToken($_SESSION['token']);
     }
     $target_dir = "images/";
     $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
     $uploadOk = 1;
     $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
     $error = 0;
     $error_msg = "";
     if (isset($_POST["submit"])) {
         $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
         if ($check === false) {
             $error_msg = "File is not an image.";
             $error = 1;
         }
     }
     if ($_FILES["fileToUpload"]["size"] > 500000) {
         $error_msg = "Sorry, your file is too large.";
         $error = 1;
     }
     if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
         $error_msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
         $error = 1;
     }
     //Vérification de l'existance de l'album
     $_POST["name_album"] = trim($_POST["name_album"]);
     if (empty($_POST["name_album"])) {
         $response = $fb->get('/me/albums?fields=id,can_upload');
         $albums = $response->getGraphEdge()->asArray();
         $albumFacebook = false;
         foreach ($albums as $album) {
             if ($album["id"] == $_POST['album']) {
                 $albumFacebook = true;
                 break;
             }
         }
         if (!$albumFacebook) {
             $error_msg = "L'upload is not allowed in this album.";
             $error = 1;
         }
     } else {
         $data = ["name" => $_POST["name_album"]];
         try {
             $response = $fb->post('/me/albums', $data);
             $graphNode = $response->getGraphNode();
             $_POST['album'] = $graphNode['id'];
         } 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 ($error == 0) {
         $data = ['message' => "Photo chargé depuis l'application Hakoopix ", 'source' => $fb->fileToUpload($_FILES["fileToUpload"]["tmp_name"])];
         try {
             $response = $fb->post('/' . $_POST['album'] . '/photos', $data);
             header("Location: /participate");
         } catch (Facebook\Exceptions\FacebookResponseException $e) {
             $error_msg = 'Error: ' . $e->getMessage();
         }
     }
     header("Location: /participate");
 }
Пример #26
0
<?php

session_start();
require_once __DIR__ . '/src/Facebook/autoload.php';
$fb = new Facebook\Facebook(['app_id' => '184276038596359', 'app_secret' => '4e91c5099b09034802b8b2ab8ef1a662', 'default_graph_version' => 'v2.4']);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
// optional
if (isset($_SESSION['facebook_access_token'])) {
    $accessToken = $_SESSION['facebook_access_token'];
} else {
    $accessToken = $helper->getAccessToken();
}
if (isset($accessToken)) {
    if (isset($_SESSION['facebook_access_token'])) {
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    } else {
        // getting short-lived access token
        $_SESSION['facebook_access_token'] = (string) $accessToken;
        // OAuth 2.0 client handler
        $oAuth2Client = $fb->getOAuth2Client();
        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
        // setting default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }
    $profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
    $profile = $profile_request->getGraphNode()->asArray();
    $linkData = ['message' => 'User provided message'];
    $response = $fb->post("/me/feed", $linkData, $accessToken);
Пример #27
0
 public function facebook_oauth()
 {
     $this->load->library("FacebookAuth");
     $fb = new Facebook\Facebook(['app_id' => '400987613433600', 'app_secret' => '2e4c483ea56dd2b9be87242321ec32cb', 'default_graph_version' => 'v2.2']);
     $helper = $fb->getRedirectLoginHelper();
     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)) {
         if ($helper->getError()) {
             header('HTTP/1.0 401 Unauthorized');
             echo "Error: " . $helper->getError() . "\n";
             echo "Error Code: " . $helper->getErrorCode() . "\n";
             echo "Error Reason: " . $helper->getErrorReason() . "\n";
             echo "Error Description: " . $helper->getErrorDescription() . "\n";
         } else {
             header('HTTP/1.0 400 Bad Request');
             echo 'Bad request';
         }
         exit;
     }
     // 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);
     // Validation (these will throw FacebookSDKException's when they fail)
     $tokenMetadata->validateAppId("400987613433600");
     // 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;
         }
     }
     $this->session->set_userdata('fb_access_token', (string) $accessToken);
     try {
         // Returns a `Facebook\FacebookResponse` object
         $fb->setDefaultAccessToken($this->session->userdata('fb_access_token'));
         $response = $fb->get('/me?fields=name,email,bio,birthday,gender,picture');
     } catch (Facebook\Exceptions\FacebookResponseException $e) {
         echo 'Graph returned an error: ' . $e->getMessage();
         exit;
     } catch (Facebook\Exceptions\FacebookSDKException $e) {
         echo 'Facebook SDK returned an error: ' . $e->getMessage();
         exit;
     }
     $user = $response->getGraphUser();
     $this->load->model("UserModel", "user_model");
     $this->user_model->register_via_facebook($user);
     redirect("dashboard");
 }