public function requestToken($Account) { $NGPushIni = eZINI::instance('ngpush.ini'); $SiteIni = eZINI::instance('site.ini'); $AccessToken = $NGPushIni->variable($Account, 'AccessToken'); // If access tokens are given if ($AccessToken) { //Save request signing tokens to cache ngPushBase::save_token($Account, $AccessToken, 'main_token'); } else { $AdministrationUrl = '/'; eZURI::transformURI($AdministrationUrl, false, 'full'); $AdministrationUrl = base64_encode($AdministrationUrl); $SettingsBlock = base64_encode($Account); $redirectUrl = 'http://' . $NGPushIni->variable('PushNodeSettings', 'ConnectURL') . '/redirect.php/' . $AdministrationUrl . '/' . $SettingsBlock . '?case=facebook'; $Facebook = new Facebook(array('appId' => $NGPushIni->variable($Account, 'AppAPIKey'), 'secret' => $NGPushIni->variable($Account, 'AppSecret'))); $Permissions = array('publish_actions', 'user_posts'); if ($NGPushIni->variable($Account, 'EntityType') == 'page') { $Permissions[] = 'manage_pages'; } $state = md5(uniqid(rand(), true)); $http = eZHTTPTool::instance(); $http->setSessionVariable('ngpush_state', $state); $LoginUrl = $Facebook->getLoginUrl(array('redirect_uri' => $redirectUrl, 'scope' => implode($Permissions, ','), 'state' => $state)); self::$response['RequestPermissionsUrl'] = $LoginUrl; } }
public function authenticateFacebook() { $fbconfig = Yum::module()->facebookConfig; if (!$fbconfig || $fbconfig && !is_array($fbconfig)) throw new Exception('actionLogout for Facebook was called, but is not activated in application configuration'); Yii::import('application.modules.user.vendors.facebook.*'); require_once('Facebook.php'); $facebook = new Facebook($fbconfig); $fb_uid = $facebook->getUser(); $profile = YumProfile::model()->findByAttributes(array('facebook_id'=>$fb_uid)); $user = ($profile) ? YumUser::model()->findByPk($profile->user_id) : null; if ($user === null) $this->errorCode = self::ERROR_USERNAME_INVALID; else if($user->status == YumUser::STATUS_INACTIVE) $this->errorCode = self::ERROR_STATUS_INACTIVE; else if($user->status == YumUser::STATUS_BANNED) $this->errorCode = self::ERROR_STATUS_BANNED; else { $this->id = $user->id; $this->username = '******'; $this->facebook_id = $fb_uid; //$this->facebook_user = $facebook->api('/me'); $this->errorCode = self::ERROR_NONE; } }
function getFacebookUserDetails($params) { //$graph_url = "https://graph.facebook.com/me?access_token=$access_token"; // // $ch = curl_init(); // curl_setopt($ch, CURLOPT_URL, $graph_url); // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // $user = @json_decode(curl_exec($ch)); // curl_close($ch); // return $user; //die(print_r(realpath(dirname(__FILE__)))); //echo '8888'; //$CI =& get_instance(); //echo '7777'; //$CI->load->library('facebook'); //die( base_url() ); //echo 'base...'.$params->base_dir; require_once $params->base_dir . '/server/facebook.php'; $facebook = new Facebook(array('appId' => $params->app_id, 'secret' => $params->app_secret)); $user = $facebook->getUser(); if ($user) { try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } return $user_profile; } }
protected function test_fb_connection($debug = false) { if ($this->configured) { $stime = microtime(true); // is configured, so lets make sure the App ID and Secret are valid include_once 'libs/facebook.php'; $fb = new Facebook(array('appId' => $this->app_id, 'secret' => $this->app_secret)); $error = false; try { $resp = $fb->api(array('method' => 'admin.getAppProperties', 'properties' => 'connect_url')); } catch (Exception $e) { $error = true; echo $debug ? '<p class="error">There is an error with your Facebook settings: "' : ''; echo $debug ? "Error #{$e->getCode()}: {$e->getMessage()}\"." : ''; switch ($e->getCode()) { case 104: echo $debug ? ' This probably means your <strong>Application ID</strong> is incorrect.' : ''; break; case 190: echo $debug ? ' This probably means your <strong>Application Secret</strong> is incorrect.' : ''; break; } echo $debug ? '</p>' : ''; } $etime = microtime(true); $time = $etime - $stime; # echo "Facebook check took $time seconds\n"; $this->connected = !$error; return !$error; } else { return false; # not configured, so let's not even try to connect! } }
function fb() { $this->load->config('facebook'); include_once APPPATH . 'third_party/facebook.php'; $facebook = new Facebook(array('appId' => $this->config->item('facebook_app_id'), 'secret' => $this->config->item('facebook_api_secret'), 'cookie' => true)); $session = $facebook->getSession(); if (isset($session['uid'])) { $me = $facebook->api('/me'); // kalo login fb apakah ada user ini $rows = $this->db->get_where('meta', array('fb_id' => $session['uid']))->row(); if ($rows) { $row = $this->ion_auth->get_user_by_email($me['email']); $this->ion_auth_model->update_last_login($row->id); $session_data = array('email' => $row->email, 'id' => $row->id, 'user_id' => $row->id, 'group_id' => $row->group_id, 'group' => $row->group); $this->session->set_userdata($session_data); redirect($this->url_if_login); } else { $this->session->set_flashdata('message', 'Can\'t Find Your FB accounts mapping to our database member'); redirect('member/registration/'); } } else { $this->session->set_flashdata('message', 'Please Login To Your Facebook First'); redirect('member/login', 'refresh'); } }
public function loadUserByUsername($username) { $user = $this->findUserByFbId($username); try { $fbdata = $this->facebook->api('/me'); } catch (FacebookApiException $e) { $fbdata = null; } if (!empty($fbdata)) { if (empty($user)) { if (!isset($fbdata['email']) || $fbdata['email'] == '') { // TODO: the user was found obviously, but doesnt match our expectations, do something smart throw new UsernameNotFoundException('Une erreur est survenue lors de votre connexion...'); } $user = $this->userManager->createUser(); $user->setEnabled(true); $user->setPassword(''); } if ($user->getUsername() == '' || $user->getUsername() == null) { $user->setUsername($username . '@facebook.com'); } $user->setFBData($fbdata); if (count($this->validator->validate($user, 'Facebook'))) { // TODO: the user was found obviously, but doesnt match our expectations, do something smart throw new UsernameNotFoundException('Une erreur est survenue lors de votre connexion...'); } $this->userManager->updateUser($user); } if (empty($user)) { // TODO: the user was found obviously, but doesnt match our expectations, do something smart throw new UsernameNotFoundException('Une erreur est survenue lors de votre connexion...'); } return $user; }
function post_facebook_link_to_post(array $post) { $post_text = construct_post_text($post); $facebook = new Facebook(array('appId' => FacebookCredentials::$app_id, 'secret' => FacebookCredentials::$app_secret, 'cookie' => true)); $req = array('access_token' => FacebookCredentials::$access_token, 'message' => $post_text); $res = $facebook->api('/me/feed', 'POST', $req); }
static function requireAuthenticate($is_ajax = true, $extra_secure = true, &$realUser = null) { global $api_key, $api_key_secret, $adminUserIDs; $u = MyAuth::checkAuthentication($extra_secure); if (!$u) { if ($is_ajax) { return 0; } $facebook = new Facebook($api_key, $api_key_secret); $user = $facebook->require_login(); if ($user) { MyAuth::setLoginAuthenticate($user); } $u = $user; } if (isset($realUser)) { $realUser = $u; } //Return the mock_user if the real user is an administrator and mockuser is set $mu = GetAdminDebug('mock_user'); if ($mu != 'NONE' && in_array(intval($u), $adminUserIDs)) { return $mu; } else { return $u; } }
function fbpromo_clientarea($vars) { global $_LANG; require dirname(__FILE__) . "/src/facebook.php"; $app_id = fbpromo_get_addon('appid'); $application_secret = fbpromo_get_addon('appsecret'); $facebook = new Facebook(array('appId' => $app_id, 'secret' => $application_secret)); // Get User ID $user = $facebook->getUser(); // We may or may not have this data based on whether the user is logged in. // // If we have a $user id here, it means we know the user is logged into // Facebook, but we don't know if the access token is valid. An access // token is invalid if the user logged out of Facebook. if ($user) { try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $user = null; } } require dirname(__FILE__) . '/clientarea.php'; die; }
function fb() { $this->load->config('facebook'); include_once APPPATH . 'third_party/facebook.php'; $facebook = new Facebook(array('appId' => $this->config->item('facebook_app_id'), 'secret' => $this->config->item('facebook_api_secret'), 'cookie' => true)); $signed = $facebook->getSignedRequest(); if (isset($signed['registration'])) { $username = $signed['registration']['name']; $password = $signed['registration']['password']; $email = $signed['registration']['email']; $additional_data = array('fullname' => $username, 'fb_id' => $signed['user_id'], 'fb_oauth_token' => $signed['oauth_token'], 'avatar' => 'http://graph.facebook.com/' . $signed['user_id'] . '/picture'); $registration = $this->ion_auth->register($username, $password, $email, $additional_data); if ($registration) { //langsung auto login lah if ($this->ion_auth->login($email, $password)) { redirect('/member/'); return; } else { echo 'successfully registered but no login'; return; } } else { $this->tpl['error'] = $this->ion_auth->errors(); } } $this->tpl['content'] = $this->load->view('registration_fb', $this->tpl, true); $this->load->view('member/body', $this->tpl); }
public function call() { //echo $this->_fbLoginRedirectUrl;exit; // Create our Application instance (replace this with your appId and secret). $facebook = new Facebook(array('appId' => $this->_fbAppId, 'secret' => $this->_fbAppSecret, 'cookie' => false)); // Get User ID $this->_fbUser = $facebook->getUser(); // We may or may not have this data based on whether the user is logged in. // If we have a $user id here, it means we know the user is logged into // Facebook, but we don't know if the access token is valid. An access // token is invalid if the user logged out of Facebook. if ($this->_fbUser) { try { // Proceed knowing you have a logged in user who's authenticated. $this->_fbUserProfile = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); $this->_fbUser = null; } } // Login or logout url will be needed depending on current user state. if ($this->_fbUser) { $this->_fbLogoutUrl = $facebook->getLogoutUrl(array("next" => $this->_fbLogoutRedirectUrl)); } else { $this->_fbLoginUrl = $facebook->getLoginUrl(array('redirect_uri' => $this->_fbLoginRedirectUrl)); //echo $this->_fbLoginUrl;exit; } }
function facebook_init() { require 'src/facebook.php'; global $facebook; $facebook = new Facebook(array('appId' => FB_KEY, 'secret' => FB_SECRET)); if (!empty($_SESSION) && !empty($_SESSION['fb_code'])) { $url = "https://graph.facebook.com/oauth/access_token?"; $params = array(); $params[] = 'client_id=' . $facebook->getAppId(); $params[] = 'redirect_uri=' . 'http://' . HOST . get_url('/facebook/auth/'); $params[] = 'client_secret=' . $facebook->getApiSecret(); $params[] = 'code=' . $_SESSION['fb_code']; $url .= implode('&', $params); $data = explode('&', get_data($url)); foreach ($data as &$d) { $d = explode('=', $d); if ($d[0] == 'access_token') { $_SESSION['fb_access_token'] = $d[1]; } elseif ($d[0] == 'expires') { $_SESSION['fb_at_expires'] = time() + $d[1]; } } } if (array_key_exists('fb_access_token', $_SESSION)) { if ($_SESSION['fb_at_expires'] > time()) { $facebook->setAccessToken($_SESSION['fb_access_token']); unset($_SESSION['fb_code']); } } }
public function doLogin() { $code = Input::get('code'); if (strlen($code) == 0) { return Redirect::to('/')->with('message', 'There was an error communicating with Facebook'); } $facebook = new Facebook(Config::get('facebook')); $uid = $facebook->getUser(); if ($uid == 0) { return Redirect::to('/')->with('message', 'There was an error'); } $me = $facebook->api('/me', ['fields' => ['id', 'first_name', 'last_name', 'picture', 'email', 'gender']]); $profile = Profile::whereUid($uid)->first(); if (empty($profile)) { $user = new User(); $user->name = $me['first_name'] . ' ' . $me['last_name']; $user->email = $me['email']; $user->photo = 'https://graph.facebook.com/' . $me['id'] . '/picture?type=large'; $user->save(); $profile = new Profile(); $profile->uid = $uid; $profile->username = $me['id']; $profile->gender = $me['gender']; $profile = $user->profiles()->save($profile); } $profile->access_token = $facebook->getAccessToken(); $profile->save(); $user = $profile->user; Auth::login($user); return Redirect::to('/')->with('message', 'Logged in with Facebook'); }
function connectFacebook() { $this->autoRender = false; $facebook = new Facebook(array('appId' => $this->facebookAppId, 'secret' => $this->facebookSecret)); $user = $facebook->getUser(); if ($user) { try { $user_profile = $facebook->api('/me'); $userinfo = $this->User->find('first', array('conditions' => array('User.username' => isset($user_profile['id']) ? $user_profile['id'] : $user_profile['email'], 'User.social_connect' => 'facebook'))); if (empty($userinfo)) { $data['User']['username'] = isset($user_profile['id']) ? $user_profile['id'] : $user_profile['email']; $data['User']['password'] = $user_profile['id']; $data['User']['group_id'] = $this->socialLoginGroupId; $data['User']['social_connect'] = 'facebook'; $data['User']['social_info'] = json_encode($user_profile); $this->User->create(); $this->User->save($data); $userinfo = $this->User->find('first', array('conditions' => array('User.id' => $this->User->id))); $this->makeUserLogin($userinfo); } else { $this->makeUserLogin($userinfo); } } catch (Exception $e) { error_log($e->getMessage()); $this->Session->setFlash($e->getMessage()); $user = NULL; } } else { $this->Session->setFlash('Sorry.Please try again'); } $this->render('Social/close_window'); }
public function process_request($request) { if ($request == 'facebook-login') { $app_id = qa_opt('facebook_app_id'); $app_secret = qa_opt('facebook_app_secret'); $tourl = qa_get('to'); if (!strlen($tourl)) { $tourl = qa_path_absolute(''); } if (strlen($app_id) && strlen($app_secret)) { require_once $this->directory . 'facebook.php'; $facebook = new Facebook(array('appId' => $app_id, 'secret' => $app_secret, 'cookie' => true)); $fb_userid = $facebook->getUser(); if ($fb_userid) { try { $user = $facebook->api('/me?fields=email,name,verified,location,website,about,picture.width(250)'); if (is_array($user)) { qa_log_in_external_user('facebook', $fb_userid, array('email' => @$user['email'], 'handle' => @$user['name'], 'confirmed' => @$user['verified'], 'name' => @$user['name'], 'location' => @$user['location']['name'], 'website' => @$user['website'], 'about' => @$user['bio'], 'avatar' => strlen(@$user['picture']['data']['url']) ? qa_retrieve_url($user['picture']['data']['url']) : null)); } } catch (FacebookApiException $e) { } } else { qa_redirect_raw($facebook->getLoginUrl(array('redirect_uri' => $tourl))); } } qa_redirect_raw($tourl); } }
public function authenticate() { $session = Yii::app()->session; $facebook = new Facebook(array('appId' => $this->key, 'secret' => $this->secret)); $here = Yii::app()->request->hostInfo . Yii::app()->request->url; // Get User ID $user = $facebook->getUser(); // already logged in if (isset($user)) { try { // Proceed knowing you have a logged in user who's authenticated. $user_profile = $facebook->api('/me'); $session['facebook_user'] = $user_profile; $this->_authenticated = true; } catch (FacebookApiException $e) { $user = null; $params = array("scope" => "user_birthday,email,read_stream"); $loginUrl = $facebook->getLoginUrl($params); Yii::app()->request->redirect($loginUrl); } // Log in! } else { $params = array("scope" => "user_birthday,email,read_stream"); $loginUrl = $facebook->getLoginUrl($params); Yii::app()->request->redirect($loginUrl); } return $this->_authenticated; }
/** * Renders the bookmarklet when it is opened. Gets the URL of the item being ingested through the Request container, * sends it to the parser and renders the result on the bookmarklet if it can be ingested or an error otherwise. * * @return Response * */ public function openAction() { $request = $this->getRequest(); $session = $request->getSession(); // get logged user $user = $this->get('security.context')->getToken()->getUser(); $widgetId = $request->query->get('widget-id'); $itemUrl = $request->query->get('url'); $parserResponse = $this->forward('ZeegaApiBundle:Items:getItemsParser', array(), array("url" => $itemUrl))->getContent(); $parserResponse = json_decode($parserResponse, true); $message = "SORRY! We can't add this item."; if (isset($parserResponse)) { //var_dump($parserResponse); $isUrlValid = $parserResponse["request"]["parser"]["success"]; $isUrlCollection = $parserResponse["request"]["parser"]["is_set"]; $message = $parserResponse["request"]["parser"]["message"]; $items = $parserResponse["items"]; if ($isUrlValid && count($items) > 0) { $parsedItem = $items[0]; // check if the item exists on the database $item = $this->getDoctrine()->getRepository('ZeegaDataBundle:Item')->findOneBy(array("user" => $user->getId(), "attributionUri" => $parsedItem["attribution_uri"], "enabled" => 1)); if (isset($item)) { $update = 1; $parsedItem["id"] = $item->getId(); } else { $update = 0; } if ($parsedItem["archive"] == "Dropbox") { if (!$update && $parsedItem["child_items_count"] == 0) { // Dropbox - welcome screen for the initial connection with dropbox return $this->render('ZeegaBookmarkletBundle:Bookmarklet:dropboxwelcome.widget.html.twig', array('displayname' => $user->getDisplayname(), 'widget_id' => $widgetId, 'item' => json_encode($parsedItem), 'update' => $update, 'child_items_count' => $parsedItem["child_items_count"], 'archive' => $parsedItem["archive"])); } } else { if ($parsedItem["archive"] == "Facebook") { // Facebook - needs to be loaded in a pop-up if ($parsedItem["child_items_count"] == -1) { // no access token. overloading child_items_count is a hack. Find cleaner way soon. //header('X-Frame-Options: Allow'); $requirePath = __DIR__ . '/../../../../vendor/facebook/facebook.php'; require_once $requirePath; $facebook = new \Facebook(array('appId' => '459848834048078', 'secret' => 'f5b344b91bff03ace4df454e35fca4e4')); $loginUrlParams = array('scope' => 'user_photos,friends_photos', 'display' => 'popup'); $loginUrl = $facebook->getLoginUrl($loginUrlParams); return $this->render('ZeegaBookmarkletBundle:Bookmarklet:facebookWelcome.widget.html.twig', array('displayname' => $user->getDisplayname(), 'widget_id' => $widgetId, 'item' => json_encode($parsedItem), 'update' => $update, 'archive' => $parsedItem["archive"], 'child_items_count' => $parsedItem["child_items_count"], 'login_url' => $loginUrl)); } else { // access token return $this->render('ZeegaBookmarkletBundle:Bookmarklet:widget.html.twig', array('displayname' => $user->getDisplayname(), 'widget_id' => $widgetId, 'item' => json_encode($parsedItem), 'update' => $update, 'archive' => $parsedItem["archive"], 'thumbnail_url' => $parsedItem["thumbnail_url"], 'child_items_count' => $parsedItem["child_items_count"])); } } else { if ($update) { return $this->render('ZeegaBookmarkletBundle:Bookmarklet:duplicate.widget.html.twig', array('displayname' => $user->getDisplayname(), 'widget_id' => $widgetId, 'item' => $item, 'update' => $update, 'archive' => $parsedItem["archive"])); } } } // for all other cases return $this->render('ZeegaBookmarkletBundle:Bookmarklet:widget.html.twig', array('displayname' => $user->getDisplayname(), 'widget_id' => $widgetId, 'item' => json_encode($parsedItem), 'update' => $update, 'archive' => $parsedItem["archive"], 'thumbnail_url' => $parsedItem["thumbnail_url"], 'child_items_count' => $parsedItem["child_items_count"])); } } return $this->render('ZeegaBookmarkletBundle:Bookmarklet:fail.widget.html.twig', array('displayname' => $user->getDisplayname(), 'widget_id' => $widgetId, 'item' => json_encode(array()), 'urlmessage' => $message, 'url' => $itemUrl, 'archive' => "")); }
function mx_mntestusers($page, $option, $action) { global $facebook; echo 'Disabled.'; return; $fbapp = new Facebook(array('appId' => FACEBOOK_APP_ID, 'secret' => FACEBOOK_SECRET, 'grant_type' => 'client_credentials')); $acctok = $fbapp->getAccessToken(); if ($_REQUEST['createuser']) { $newuser = $fbapp->api('/' . FACEBOOK_APP_ID . '/accounts/test-users?installed=true&permissions=&access_token=' . $acctok, 'POST'); } else { if ($_REQUEST['deleteuser']) { foreach ($_REQUEST['selected'] as $user) { $testusers = $fbapp->api('/' . $user . '?access_token=' . $acctok, 'DELETE'); mx_deleteuser($user); // delete should only be possible for test users!! } } } $testusers = $fbapp->api('/' . FACEBOOK_APP_ID . '/accounts/test-users&access_token=' . $acctok, 'GET'); echo '<form action="' . mx_optionurl($page, $option) . '" method=POST>'; echo '<table border=1 width=100%><tr><th>Sel</th><th>ID</th><!-- <th>access_token</th> --><th>login_url</th></tr>'; foreach ($testusers['data'] as $testuser) { echo '<tr><td><input type=checkbox name="selected[]" value="' . $testuser['id'] . '"></td>' . '<td>' . $testuser['id'] . '</td>'; //$user=$facebook->api('/'.$testuser['id']); //die(print_r($user)); //echo '<td>'.$user['name'].'</td>'; echo '<!-- <td>' . $testuser['access_token'] . '</td> --><td>' . '<a href="' . $testuser['login_url'] . '">' . $testuser['login_url'] . '</a></td></tr>'; } echo '<tr><td colspan=3 align=center><input type=submit name="createuser" value="Create User">' . ' <input type=submit name="deleteuser" value="Delete User(s)"></td></tr>'; echo '</table></form>'; }
public function actionFacebook() { require_once 'facebook/facebook.php'; $facebook = new Facebook(array('appId' => Yii::app()->params['facebookAppId'], 'secret' => Yii::app()->params['facebookSecretCode'], 'cookie' => true)); $user = $facebook->getUser(); if (isset($_POST['Member']['memberid'])) { $memberdata = Member::model()->getMemberById($_POST['Member']['memberid']); $this->actMemberinfo($memberdata, '', '', '', 'facebook', ''); } else { if (!empty($user)) { //Active session, let's try getting the user id (getUser()) and user info (api->('/me')) try { //$facebookuserid = $facebook->getUser(); $facebookuser = $facebook->api('/me'); //print_r($facebookuser); } catch (FacebookApiException $e) { error_log($e); } if (!empty($facebookuser)) { $memberdata = Member::model()->getMemberByOauth($facebookuser['id']); $this->actMemberinfo($memberdata, '', '', $facebookuser, 'facebook', ''); } else { //For testing purposes, if there was an error, let's kill the script die("There was an error."); } } else { //There's no active session, let's generate one $login_url = $facebook->getLoginUrl(array('scope' => 'email')); // echo $login_url; header("Location: " . $login_url); } } }
/** * Function for check login * */ public function login() { // Setting the page title $this->set("title_for_layout", "User Login"); if ($this->Auth->login()) { $this->redirect($this->Auth->redirect()); } else { if ($this->request->is('post')) { $this->Session->setFlash(__('Invalid username or password, try again')); } } $facebooksecretkey = '4753a9042404a78aaff1069f73aa8994'; $facebookapikey = '203755806382341'; App::import('Vendor', 'facebook', array('file' => 'facebook/src/facebook.php')); $facebook = new Facebook(array('appId' => "{$facebookapikey}", 'secret' => "{$facebooksecretkey}")); $user = $facebook->getUser(); $facebookLoginUrl = $facebook->getLoginUrl(); $this->set('facebookLoginUrl', $facebookLoginUrl); if ($user) { $faceBookUserProfile = $facebook->api('/me'); if (isset($faceBookUserProfile) && !empty($faceBookUserProfile)) { $this->facebook($faceBookUserProfile); } } //ends here }
public function loadUserByUsername($username) { $user = $this->findUserByFbId($username); try { $fbdata = $this->facebook->api('/me'); } catch (FacebookApiException $e) { $fbdata = null; } if (!empty($fbdata)) { if (empty($user)) { $user = $this->userManager->createUser(); $user->setEnabled(true); $user->setPassword(''); } // TODO use http://developers.facebook.com/docs/api/realtime $user->setFBData($fbdata); if (count($this->validator->validate($user, 'Facebook'))) { // TODO: the user was found obviously, but doesnt match our expectations, do something smart throw new UsernameNotFoundException('The facebook user could not be stored'); } $this->userManager->updateUser($user); } if (empty($user)) { throw new UsernameNotFoundException('The user is not authenticated on facebook'); } return $user; }
/** * * @param array $data * @param array $services */ public function sendToSocialMedia(array $data, array $services = array('facebook', 'twitter')) { // init output $ids = array('facebook' => null, 'twitter' => null); // Facebook if (in_array('facebook', $services) && $this->confirmFacebookAccess()) { $facebook = new Facebook(array('appId' => static::$conf->FacebookAppId, 'secret' => static::$conf->FacebookAppSecret)); $facebook->setAccessToken(static::$conf->FacebookPageAccessToken); try { $post_id = $facebook->api("/" . static::$conf->FacebookPageId . "/feed", "post", $data); $ids['facebook'] = $post_id['id']; } catch (FacebookApiException $e) { SS_Log::log('Error ' . $e->getCode() . ' : ' . $e->getFile() . ' Line ' . $e->getLine() . ' : ' . $e->getMessage() . "\n" . 'BackTrace: ' . "\n" . $e->getTraceAsString(), SS_Log::ERR); } } // Twitter if (in_array('twitter', $services) && $this->confirmTwitterAccess()) { $connection = new tmhOAuth(array('consumer_key' => static::$conf->TwitterConsumerKey, 'consumer_secret' => static::$conf->TwitterConsumerSecret, 'user_token' => static::$conf->TwitterOAuthToken, 'user_secret' => static::$conf->TwitterOAuthSecret)); $tweet = $data['name'] . ": " . $data['link']; $code = $connection->request('POST', $connection->url('1.1/statuses/update'), array('status' => $tweet)); if ($code == 200) { $data = json_decode($connection->response['response']); $ids['twitter'] = $data->id_str; } } return $ids; }
/** * Try to login with Facebook and return true on success * @return boolean */ protected function loginWithFacebook() { $objFacebook = new Facebook(array('appId' => $this->fblogin_appId, 'secret' => $this->fblogin_appKey)); $arrProfile = false; if ($objFacebook->getUser() > 0) { try { $arrProfile = $objFacebook->api('/me?fields=id,name,first_name,last_name,email,gender'); } catch (FacebookApiException $e) { $arrProfile = false; $this->log('Could not fetch the Facebook data: ' . $e->getMessage(), 'ModuleFacebookLogin loginWithFacebook()', TL_ERROR); } } // Log the error message if (!$arrProfile) { $this->log('Could not fetch the Facebook user.', 'ModuleFacebookLogin loginWithFacebook()', TL_ERROR); return false; } $time = time(); $objUser = $this->Database->prepare("SELECT id FROM tl_member WHERE fblogin=? AND login=1 AND (start='' OR start<{$time}) AND (stop='' OR stop>{$time}) AND disable=''")->limit(1)->execute($arrProfile['id']); // Create a new user if none found if (!$objUser->numRows) { $objUser = $this->createNewUser($arrProfile); if ($objUser === false) { return false; } } $this->import('FrontendUser', 'User'); return $this->User->login($arrProfile); }
/** * Render method * @return void */ public function render() { $config = array('appId' => $this->arguments['id'], 'secret' => $this->arguments['secret'], 'allowSignedRequest' => false); $facebook = new Facebook($config); $user_id = $facebook->getUser(); $this->renderChildren(); }
public function fbc_friend() { global $context, $fbuser, $Url, $FacebookId, $fb_hook_object, $friends, $scripturl, $fb_object, $curOffset; $context['sub_template'] = 'fbc_friends'; $context['fb_do'] = 'friends'; SAFacebookhooks::face_init(); $facebook = new Facebook(array('appId' => $fb_hook_object->modSettings['fb_app_id'], 'secret' => $fb_hook_object->modSettings['fb_app_secret'])); $Url = $facebook->getLoginUrl(array('redirect_uri' => $scripturl . '?action=facebook', 'scope' => 'email,publish_actions')); $fb_object->fbc_cons_pages('friends', 32); if (!$fb_hook_object->modSettings['fb_mode2']) { redirectexit(); } $fbuser = $FacebookId; if ($fbuser) { //Try it!!!!! try { //These api calls can be slow so were only do it if needed if (empty($_SESSION['safbfriends'][$curOffset])) { $_SESSION['safbfriends'][$curOffset] = $facebook->api('/me/friends?offset=' . $curOffset . '&limit=32'); } $friends = $_SESSION['safbfriends'][$curOffset]; } catch (FacebookApiException $e) { //Throw it!!!!! fatal_error($e, false); } } }
public function indexAction() { // connect to app $config = array(); $config['appId'] = '1017499418312477'; $config['secret'] = 'b8887afcd0172d566b624ae920065234'; $config['fileUpload'] = false; // optional // instantiate $facebook = new \Facebook($config); //call the API to retrieve data from facebook $array = $facebook->api("/feed?ids=lilotregal,649823778452363"); //build a pattern to use it in regex in order to retrieve only menus from the posts $pattern = '/(repas du|menu du|repas du jour|menu du jour).*(lundi|mardi|mercredi|jeudi|vendredi|samedi|dimanche).*(\\d).*(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i'; //make a counter to take just the three last menus $i = 0; //build an array to store data of the first page $data = array(); //build an array to retrieve menu's titles to display them in the panel heading $menuOfdays = array(); foreach ($array["lilotregal"] as $pagefeed) { foreach ($pagefeed as $page) { if (isset($page['message']) && isset($page['created_time']) && preg_match($pattern, $page['message'], $matches)) { $dates = date("Y/m/d", strtotime($page['created_time'] . "+1 day")); $menuOfdays[$dates] = $matches['0']; if ($dates == date("Y/m/d")) { $menuOfdays[$dates] = "Menu d'aujourd'hui"; } $data[] = $page['message']; //take only the three last menus if (++$i === 3) { break; } } } } $menuOfday = array_values($menuOfdays); $i = 0; //store the data of the second page $refine = array(); //build an array to retrieve meal's titles to display them in the panel heading $mealOfdays = array(); foreach ($array["649823778452363"] as $menus) { foreach ($menus as $menu) { if (isset($menu['message']) && isset($menu['created_time']) && preg_match($pattern, $menu['message'], $matches)) { $dates2 = date("Y/m/d", strtotime($menu['created_time'] . "+1 day")); $mealOfdays[] = $matches['0']; if ($dates2 == date("Y/m/d")) { $mealOfdays['0'] = "Repas d'aujourd'hui"; } $refine[] = $menu['message']; //take only the three last meals if (++$i === 3) { break; } } } } return $this->render('ApplicationApplicationBundle:Default:index.html.twig', array('data' => $data, 'refine' => $refine, 'menuOfday' => $menuOfday, 'mealOfday' => $mealOfdays)); }
/** * @todo fix this BIG mess. */ public static function postFacebook($message, $link = null, $impression = null) { $member = Member::currentUser(); $postresult = false; $SiteConfig = SiteConfig::current_site_config(); if ($member && $SiteConfig->FBAppID && $SiteConfig->FBSecret) { if ($link == null) { $link = Director::absoluteBaseURL(); } $page = '/' . $SiteConfig->FBPageID . '/feed'; $facebook = new Facebook(array('appId' => $SiteConfig->FBAppID, 'secret' => $SiteConfig->FBSecret)); $token = $facebook->api('/me/accounts'); foreach ($token['data'] as $pages) { if ($pages['id'] == $SiteConfig->FBPageID) { $facebook->setAccessToken($pages['access_token']); $verified = true; break; } } if ($verified) { $data = array('message' => $message, 'link' => $link, 'picture' => $impression); $postresult = $facebook->api($page, 'post', $data); } } return $postresult; }
/** * Log-in using Facebook cronus * * @param array &$state Information about the current authentication. */ public function authenticate(&$state) { assert('is_array($state)'); /* We are going to need the authId in order to retrieve this authentication source later. */ $state[self::AUTHID] = $this->authId; $stateID = SimpleSAML_Auth_State::saveState($state, self::STAGE_INIT); SimpleSAML_Logger::debug('facebook auth state id = ' . $stateID); $facebook = new Facebook($this->api_key, $this->secret); $u = $facebook->require_login(SimpleSAML_Module::getModuleUrl('authfacebook') . '/linkback.php?next=' . $stateID); # http://developers.facebook.com/documentation.php?v=1.0&method=users.getInfo /* Causes an notice / warning... if ($facebook->api_client->error_code) { throw new Exception('Unable to load profile from facebook'); } */ // http://developers.facebook.com/docs/reference/rest/users.getInfo $info = $facebook->api_client->users_getInfo($u, array('uid', 'first_name', 'middle_name', 'last_name', 'name', 'locale', 'current_location', 'affiliations', 'pic_square', 'profile_url', 'sex', 'email', 'pic', 'username', 'about_me', 'status', 'profile_blurb')); $attributes = array(); foreach ($info[0] as $key => $value) { if (is_string($value) && !empty($value)) { $attributes['facebook.' . $key] = array((string) $value); } } if (array_key_exists('username', $info[0])) { $attributes['facebook_user'] = array($info[0]['username'] . '@facebook.com'); } else { $attributes['facebook_user'] = array($u . '@facebook.com'); } $attributes['facebook_targetedID'] = array('http://facebook.com!' . $u); $attributes['facebook_cn'] = array($info[0]['name']); SimpleSAML_Logger::debug('Facebook Returned Attributes: ' . implode(", ", array_keys($attributes))); $state['Attributes'] = $attributes; }
public function authenticate(CakeRequest $request, CakeResponse $response) { $user = $this->_Collection->Auth->user(); $service = strtolower($request->params['pass'][0]); if ($service !== $this->service) { return false; } try { $facebook = new Facebook(array('appId' => $this->myConsumerKey, 'secret' => $this->myConsumerSec, 'cookie' => true)); $action = $request->params['action']; if ($action === 'login') { $url = $facebook->getLoginUrl(array('redirect_uri' => Router::url('callback/facebook/', true), 'scope' => 'email,publish_stream')); if ($url !== null) { $response->header('Location', $url); $response->send(); } } elseif ($action === 'callback') { preg_match('/state=(.*)/', $_REQUEST['url'], $state); $_REQUEST['state'] = $state[1]; $accessToken = $facebook->getAccessToken(); if ($accessToken != '') { $this->_fetch($facebook, $accessToken, $response); } else { //you should throw exception } } } catch (OAuthException $E) { //you can catch OAuth exception } }
function authorize() { global $globals, $db; $fb = new Facebook($globals['facebook_key'], $globals['facebook_secret']); $fb->require_login(); $fb_user = $fb->get_loggedin_user(); if ($_GET['op'] != 'ok' || !$fb_user) { $this->user_return(); } $user_details = $fb->api_client->users_getInfo($fb_user, array('uid', 'name', 'profile_url', 'pic_square')); $this->token = $user_details[0]['uid']; $this->secret = $user_details[0]['uid']; $this->uid = $user_details[0]['uid']; $this->username = preg_replace('/.+?\\/.*?([\\w\\.\\-_]+)$/', '$1', $user_details[0]['profile_url']); // Most Facebook users don't have a name, only profile number if (!$this->username || preg_match('/^\\d+$/', $this->username)) { // Create a name like a uri used in stories if (strlen($user_details[0]['name']) > 2) { $this->username = User::get_valid_username($user_details[0]['name']); } else { $this->username = '******' . $this->username; } } $db->transaction(); if (!$this->user_exists()) { $this->url = $user_details[0]['profile_url']; $this->names = $user_details[0]['name']; $this->avatar = $user_details[0]['pic_square']; $this->store_user(); } $this->store_auth(); $db->commit(); $this->user_login(); }