Exemple #1
2
function facebook()
{
    global $template;
    $facebook = new Facebook(array('appId' => FB_APPID, 'secret' => FB_APPSECRET));
    $user = $facebook->getUser();
    if ($user) {
        try {
            $pages = $facebook->api('/me/accounts');
            $template->set('pages', $pages);
            $permissions = $facebook->api("/me/permissions");
            $publish_actions = 0;
            $manage_pages = 0;
            foreach ($permissions['data'] as $permission) {
                if ($permission['permission'] == 'publish_actions') {
                    $publish_actions = 1;
                }
                if ($permission['permission'] == 'manage_pages') {
                    $manage_pages = 1;
                }
            }
            if ($publish_actions == 0 || $manage_pages == 0) {
                throw new Exception("Oops");
            }
        } catch (Exception $e) {
            $url = $facebook->getLoginUrl(array("scope" => "publish_actions,manage_pages"));
            header("Location: " . $url);
            exit;
        }
    } else {
        $url = $facebook->getLoginUrl(array("scope" => "publish_actions,manage_pages"));
        header("Location: " . $url);
        exit;
    }
}
 public function postar($dados, $usuario)
 {
     require 'complements/facebook/Facebook.php';
     $facebook = new Facebook(array('appId' => '1651517385125370', 'secret' => '84b4334e3cfe153b5a4348407709cbf0'));
     // Get User ID
     $user = $facebook->getUser();
     if ($user) {
         try {
             echo "teste";
             exit;
             $page_id = $usuario;
             $page_info = $facebook->api("/{$page_id}?fields=access_token");
             if (!empty($page_info['access_token'])) {
                 $args = array('access_token' => $page_info['access_token'], 'message' => $dados[texto]);
                 $post_id = $facebook->api("/{$page_id}/feed", "post", $args);
             } else {
                 $permissions = $facebook->api("/me/permissions");
                 if (!array_key_exists('publish_stream', $permissions['data'][0]) || !array_key_exists('manage_pages', $permissions['data'][0])) {
                     // We don't have one of the permissions
                     // Alert the admin or ask for the permission!
                     header("Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages")));
                 }
             }
         } catch (FacebookApiException $e) {
             error_log($e);
             $user = null;
         }
     }
     // Login or logout url will be needed depending on current user state.
     if ($user) {
         $logoutUrl = $facebook->getLogoutUrl();
     } else {
         $loginUrl = $facebook->getLoginUrl(array('scope' => 'manage_pages,publish_stream'));
     }
 }
Exemple #3
0
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 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;
 }
Exemple #5
0
 function try_connect($pubit = 0, $stUrl = '', $PublishMessage = '')
 {
     $myparams =& JComponentHelper::getParams('com_fbjconnect');
     $getappid = $myparams->get('appid');
     $getappsec = $myparams->get('appsecret');
     $access_token = "";
     $uid = "";
     $postresult = false;
     $facebook = new Facebook(array('appId' => $getappid, 'secret' => $getappsec, 'cookie' => true));
     $session = $facebook->getSession();
     $me = null;
     $uid = "";
     if ($session) {
         try {
             $access_token = $facebook->getAccessToken();
             $me = $facebook->api('/me');
             $uid = $facebook->getUser();
             if ($pubit == 1) {
                 $fbpic = JURI::base() . 'modules/mod_jfbgconnect/fgimage.jpg';
                 $postresult = $facebook->api('/me/feed/', 'post', array('access_token' => $access_token, 'picture' => $fbpic, 'link' => $stUrl, 'message' => $PublishMessage));
             }
         } catch (FacebookApiException $e) {
             error_log($e);
         }
     }
     return array($uid, $me, $session, $access_token, $postresult);
 }
 /**
  * @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;
 }
Exemple #7
0
 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;
 }
 /**
  * Returns the api user
  *
  * @return ApiUser|null
  */
 public function getApiUser()
 {
     try {
         $me = $this->facebook->api('/me');
         return new ApiUser($me);
     } catch (\Exception $e) {
         return null;
     }
 }
Exemple #9
0
 public function getFeed($options)
 {
     if (empty($options['sa_fb_app_id']) && empty($options['sa_fb_app_secret'])) {
         return array('error' => 2, 'message' => 'Facebook App ID and/or secret not set. Please set this in the settings page.');
     }
     $facebook = new Facebook(array('appId' => $options['sa_fb_app_id'], 'secret' => $options['sa_fb_app_secret']));
     if (empty($options['sa_fb_page_id'])) {
         return array('error' => 2, 'message' => 'Facebook Page ID not set.');
     }
     $since_time = empty($options['sa_since_time']) ? 1 : $options['sa_since_time'];
     try {
         // $user_profile = $facebook->api('/me');
         // $this->log($user_profile);
         $response = $facebook->api($options['sa_fb_page_id'] . '/feed/?fields=id,type,caption,picture,message,link,object_id&limit=25&since=' . $since_time);
     } catch (FacebookApiException $e) {
         // $loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_stream', 'redirect_uri' => 'http://freefly.ryan.invokedev.com/'));
         $result = $e->getResult();
         return array('error' => 4, 'message' => 'Error fetching Facebook feed: <span class="social-feed-error">' . $result['error']['message'] . '</span>');
         // $loginUrl = $facebook->getLoginUrl();
         // $user = null;
         // echo "<script>top.location.href = '$loginUrl'</script>";
         // exit;
     }
     // return an array with success = false if $response is empty..
     if (count($response['data']) == 0) {
         return array('error' => 1, 'message' => 'No Facebook items found.');
     }
     $data = array();
     $date_added = time();
     $created_times = array(0);
     foreach ($response['data'] as $post) {
         if ($post['type'] == 'photo') {
             // get images..
             $images = $facebook->api($post['object_id'] . '?fields=images');
             $p = array();
             foreach ($images['images'] as $item) {
                 if ($item['height'] >= 480) {
                     $p['picture'] = $item['source'];
                     break;
                 }
             }
             $p['id'] = $post['id'];
             $p['message'] = empty($post['message']) ? '' : $post['message'];
             $p['link'] = empty($post['link']) ? '' : $post['link'];
             $p['date_added'] = $date_added;
             $created_time = new DateTime($post['created_time']);
             $p['date_created'] = $created_time->format('U');
             $created_times[] = $created_time->format('U');
             array_push($data, $p);
         }
     }
     if (count($data) == 0) {
         return array('error' => 3, 'message' => 'No new Facebook items found.');
     }
     $res = array('data' => $data, 'since_time' => max($created_times));
     return $res;
 }
function update_facebook_wall($text)
{
    $appId = '101183239949229';
    $appSecret = 'fd040afd3af84cc13b6a70ea602b4ca6';
    $srcPageId = '116587918401126';
    //Use Evan Hsu's access token because he is one of the Page Admins
    //**** The access Token will need to be updated whenever Evan changes his Facebook password
    $accessToken = 'AAABcBo8TC60BAOJGsdKapdUYfvbBOJm9jc9EHZBZBpD45mAN2poo9t7nfxtII3I7XZAxH9RMuI1AOD2BjWUEyso17nTkNVR2aEGaZC287Vqe8932fjQ9';
    $config = array('appId' => $appId, 'secret' => $appSecret);
    $facebook = new Facebook($config);
    $args = array('access_token' => $accessToken, 'message' => $text);
    try {
        $post_id = $facebook->api("/{$srcPageId}/feed", "post", $args);
    } catch (FacebookApiException $e) {
        //If post failed, do nothing. Permission check happens below.
    }
    if (!$post_id) {
        // If the accessToken is no longer valid (Evan changed his password or revoked permissions),
        // then someone with admin access to the Siskiyou facebook page will need to be logged in.
        $user = $facebook->getUser();
        if ($user) {
            try {
                $page_info = $facebook->api("/{$srcPageId}?fields=access_token");
                if (!empty($page_info['access_token'])) {
                    $args = array('access_token' => $page_info['access_token'], 'message' => $text);
                    $post_id = $facebook->api("/{$srcPageId}/feed", "post", $args);
                    //echo "Access Token: ".$page_info['access_token'];
                } else {
                    $permissions = $facebook->api("/me/permissions");
                    if (!array_key_exists('publish_stream', $permissions['data'][0]) || !array_key_exists('manage_pages', $permissions['data'][0])) {
                        // We don't have one of the permissions
                        // Alert the admin or ask for the permission!
                        header("Location: " . $facebook->getLoginUrl(array("scope" => "publish_stream, manage_pages, offline_access")));
                    }
                }
            } catch (FacebookApiException $e) {
                //error_log($e);
                $user = null;
            }
        }
        // Login or logout url will be needed depending on current user state.
        if ($user) {
            $logoutUrl = $facebook->getLogoutUrl();
        } else {
            $loginUrl = $facebook->getLoginUrl(array('scope' => 'manage_pages,publish_stream,offline_access'));
            header("Location: " . $loginUrl);
        }
    }
    // END if(!$post_id)
    if ($post_id != "") {
        header('location: http://www.siskiyourappellers.com/current.php');
    }
}
 public function getInput()
 {
     if ($this->fb->getUser()) {
         $user = $this->fb->getUser();
         $profile = $this->fb->api("/me?fields=id,name,picture");
         $label = "<img src='" . $profile['picture']['data']['url'] . "' />" . $profile['name'];
         $logout = $this->fb->getLogoutUrl(array('next' => JURI::base()));
         return $label . "<br /><a href='" . $logout . "'>Log out of Facebook</a>";
     } else {
         // Not logged in - display a login link
         $uri = JURI::current();
         $loginUrl = $this->fb->getLoginUrl(array('redirect_uri' => "http://aquinas.dphin.co.uk/login/profile?layout=edit"));
         return "<a href='" . $loginUrl . "'>Connect your Facebook account</a>";
     }
 }
 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);
     }
 }
function fbes_get_events($fbes_api_key, $fbes_api_secret, $fbes_access_token, $fbes_api_uids)
{
    require_once 'facebook-php-sdk/facebook.php';
    //modified
    $facebook = new Facebook(array('appId' => $fbes_api_key, 'secret' => $fbes_api_secret, 'cookie' => true));
    $facebook->setAccessToken($fbes_access_token);
    $ret = array();
    foreach ($fbes_api_uids as $key => $value) {
        if ($value != '') {
            $result = $facebook->api('/' . $value . '/events', 'GET', array('fields' => 'name,start_time,end_time,place,description,timezone', 'date_format' => 'U'));
            $result = $result['data'];
            foreach ($result as $k => $v) {
                $result[$k]['uid'] = $value;
                $result[$k]['start_time'] = strtotime($result[$k]['start_time']);
                $result[$k]['end_time'] = strtotime($result[$k]['end_time']);
                if ($result[$k]['place']) {
                    if ($result[$k]['place']['name']) {
                        $result[$k]['location'] = $result[$k]['place']['name'];
                    } else {
                        $result[$k]['location'] = $result[$k]['place'];
                    }
                }
            }
            $ret = array_merge($ret, $result);
        }
    }
    return $ret;
}
 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));
 }
Exemple #15
0
 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 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);
         }
     }
 }
 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;
 }
Exemple #18
0
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;
}
Exemple #19
0
 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;
     }
 }
 private function face($access_token, $dataConfig)
 {
     require_once 'php-sdk/src/facebook.php';
     $facebook = new Facebook($dataConfig);
     $facebook->setAccessToken($access_token);
     Zend_Debug::dump($user = $facebook->getUser());
     if ($user) {
         $this->view->faceUrl = $facebook->getLogoutUrl();
     } else {
         $this->view->faceUrl = $facebook->getLoginUrl();
     }
     Zend_Debug::dump($_REQUEST);
     Zend_Debug::dump($naitik = $facebook->api('/100000874886897'));
     if ($user) {
         try {
             // Proceed knowing you have a logged in user who's authenticated.
             $user_profile = $facebook->api('/me');
             print_r($user_profile);
         } catch (FacebookApiException $e) {
             error_log($e);
             $user = null;
         }
     }
     $this->view->user = $naitik;
 }
Exemple #21
0
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);
}
 /**
  * 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);
 }
 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!
     }
 }
 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');
 }
Exemple #25
0
 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');
     }
 }
 /**
  * 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
 }
Exemple #27
0
 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);
         }
     }
 }
 /**
  *
  * @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;
 }
Exemple #29
0
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;
    }
}
Exemple #30
-1
 /**
  * Fetch the HTML for the button
  *
  * @param   string   $type  Unused string.
  * @param   string   $name  The name of the button icon class.
  * @param   string   $text  Button text.
  * @param   string   $task  Task associated with the button.
  * @param   boolean  $list  True to allow lists
  *
  * @return  string  HTML string for the button
  *
  * @since   3.0
  */
 public function fetchButton($type = 'J2FBPost', $name = '', $text = '', $task = '', $list = false)
 {
     $class = $this->fetchIconClass($name);
     if ($name == "apply" || $name == "new") {
         $btnClass = "btn btn-small btn-success";
         $iconWhite = "icon-white";
     } else {
         $btnClass = "btn btn-small";
         $iconWhite = "";
     }
     JFactory::getDocument()->addStyleDeclaration('div#toolbar div#toolbar-' . $name . ' button.btn i.icon-' . $name . '-login::before {color: #2F96B4;content: "\\"";}');
     JFactory::getDocument()->addStyleDeclaration('div#toolbar div#toolbar-' . $name . ' button.btn i.icon-' . $name . '::before {color: #2F96B4;content: "&";}');
     JFactory::getDocument()->addStyleDeclaration('div#toolbar div#toolbar-' . $name . ' button.btn i.icon-' . $name . '-waiting::before {color: #2F96B4;content: "j";}');
     // Create our Application instance
     $facebook = new Facebook(array('appId' => self::$appid, 'secret' => self::$secret, 'cookie' => true));
     if ($fbuser = $facebook->getUser()) {
         try {
             $user_profile = $facebook->api('/me');
             //Get user pages details using Facebook Query Language (FQL)
             $fql_query = 'SELECT page_id, name, page_url FROM page WHERE page_id IN (SELECT page_id FROM page_admin WHERE uid=' . $fbuser . ')';
             $postResults = $facebook->api(array('method' => 'fql.query', 'query' => $fql_query));
         } catch (FacebookApiException $e) {
             JError::raiseWarning(1, $e->getMessage());
             return null;
         }
     } else {
         //Show login button for guest users
         $i18n_text = JText::_('Login');
         $doTask = $facebook->getLoginUrl(array('redirect_uri' => JURI::current(), 'scope' => 'publish_stream,read_stream,offline_access,manage_pages'));
         /* 
          * publish_stream – allows the application to publish updates to Facebook on the user’s behalf
          * read_stream – allows the application to read from the user’s News Feed
          * offline_access – converts the access_token to one that doesn’t expire, thus letting the application make API calls anytime. Without this, the application’s access_token will expire after a few minutes, which isn’t ideal in this case
          * manage_pages – lets the application access the user’s Facebook Pages. Since the application we’re building deals with Facebook Pages, we’ll need this as well.
          */
         $html = "<button class=\"btn btn-small\" onclick=\"location.href='{$doTask}';\">\n";
         $html .= "<i class=\"{$class}-login\">\n";
         $html .= "</i>\n";
         $html .= "{$i18n_text}\n";
         $html .= "</button>\n";
     }
     if ($fbuser && $postResults) {
         $i18n_text = JText::_($text);
         $doTask = $this->_getCommand($name, $task, $list);
         $doc = JFactory::getDocument();
         $doc->addScript("../media/lib_eshiol_core/js/encryption.js");
         $doc->addScript("../media/lib_eshiol_core/js/core.js");
         foreach ($postResults as $item) {
             $options[] = array('text' => $item['name'], 'value' => $item['page_id']);
         }
         array_unshift($options, JHTML::_('select.option', 0, '- Select a page -'));
         $html = "<button data-toggle=\"modal\" data-target=\"#collapseModal{$name}\" class=\"" . $btnClass . "\">\n";
         $html .= "<i class=\"{$class} {$iconWhite}\">\n";
         $html .= "</i>\n";
         $html .= "{$i18n_text}\n";
         $html .= "</button>\n";
         $html .= "\r\n<div class=\"modal hide fade\" id=\"collapseModal{$name}\">\r\n\t<div class=\"modal-header\">\r\n\t\t<button type=\"button\" class=\"close\" data-dismiss=\"modal\">x</button>\r\n\t\t<h3>Post to Facebook</h3>\r\n\t</div>\r\n\t<div class=\"modal-body\" style=\"min-height:250px\">\r\n\t\t<p>Post to facebook using www.eshiol.it app</p>\r\n\t\t<div class=\"control-group\">\r\n\t\t\t<div class=\"controls\">" . JHtml::_('select.genericlist', $options, 'fbpage', array('list.attr' => 'class="inputbox" size="1"', 'list.select' => 0)) . "\r\n\t\t\t</div>\r\n\t\t</div>\r\n\t</div>\r\n\t<div class=\"modal-footer\">\r\n\t\t<button class=\"btn\" type=\"button\" onclick=\"document.id('fbpage').value=''\" data-dismiss=\"modal\">\r\n\t\t\t" . JText::_('JCANCEL') . "\r\n\t\t</button>\r\n\t\t<button class=\"btn btn-primary\" type=\"button\" onclick=\"{$doTask}\">\r\n\t\t\t{$i18n_text}\r\n\t\t</button>\r\n\t</div>\r\n</div>\r\n\t\t\t";
     }
     return $html;
 }