Advertisement
Guest User

class.facebook.plugin.php

a guest
Dec 20th, 2014
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 25.54 KB | None | 0 0
  1. <?php if (!defined('APPLICATION')) exit();
  2. /*
  3. Copyright 2008, 2009 Vanilla Forums Inc.
  4. This file is part of Garden.
  5. Garden is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  6. Garden is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  7. You should have received a copy of the GNU General Public License along with Garden.  If not, see <http://www.gnu.org/licenses/>.
  8. Contact Vanilla Forums Inc. at support [at] vanillaforums [dot] com
  9. */
  10.  
  11. // Define the plugin:
  12. $PluginInfo['Facebook'] = array(
  13.     'Name' => 'Facebook Social Connect',
  14.    'Description' => 'Users may sign into your site using their Facebook account.', 
  15.    'Version' => '1.0.9',
  16.    'RequiredApplications' => array('Vanilla' => '2.0.14a'),
  17.    'RequiredTheme' => FALSE,
  18.    'RequiredPlugins' => FALSE,
  19.     'MobileFriendly' => TRUE,
  20.    'SettingsUrl' => '/dashboard/social/facebook',
  21.    'SettingsPermission' => 'Garden.Settings.Manage',
  22.    'HasLocale' => TRUE,
  23.    'RegisterPermissions' => FALSE,
  24.    'Author' => "Todd Burry",
  25.    'AuthorEmail' => 'todd@vanillaforums.com',
  26.    'AuthorUrl' => 'http://www.vanillaforums.org/profile/todd',
  27.    'Hidden' => TRUE,
  28.    'SocialConnect' => TRUE,
  29.    'RequiresRegistration' => TRUE
  30. );
  31.  
  32. class FacebookPlugin extends Gdn_Plugin {
  33.    const ProviderKey = 'Facebook';
  34.    
  35.    protected $_AccessToken = NULL;
  36.    
  37.    public function AccessToken() {
  38.       if (!$this->IsConfigured())
  39.          return FALSE;
  40.      
  41.       if ($this->_AccessToken === NULL) {
  42.          if (Gdn::Session()->IsValid())
  43.             $this->_AccessToken = GetValueR(self::ProviderKey.'.AccessToken', Gdn::Session()->User->Attributes);
  44.          else
  45.             $this->_AccessToken = FALSE;
  46.       }
  47.      
  48.       return $this->_AccessToken;
  49.    }
  50.  
  51.    public function Authorize($Query = FALSE) {
  52.       $Uri = $this->AuthorizeUri($Query);
  53.       Redirect($Uri);
  54.    }
  55.    
  56.    public function API($Path, $Post = FALSE) {
  57.       // Build the url.
  58.       $Url = 'https://graph.facebook.com/'.ltrim($Path, '/');
  59.      
  60.       $AccessToken = $this->AccessToken();
  61.       if (!$AccessToken)
  62.          throw new Gdn_UserException("You don't have a valid Facebook connection.");
  63.      
  64.       if (strpos($Url, '?') === false)
  65.          $Url .= '?';
  66.       else
  67.          $Url .= '&';
  68.       $Url .= 'access_token='.urlencode($AccessToken);
  69.  
  70.       $ch = curl_init();
  71.       curl_setopt($ch, CURLOPT_HEADER, false);
  72.       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  73.       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  74.       curl_setopt($ch, CURLOPT_URL, $Url);
  75.  
  76.       if ($Post !== false) {
  77.          curl_setopt($ch, CURLOPT_POST, true);
  78.          curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
  79.          Trace("  POST $Url");
  80.       } else {
  81.          Trace("  GET  $Url");
  82.       }
  83.  
  84.       $Response = curl_exec($ch);
  85.  
  86.       $HttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  87.       $ContentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  88.       curl_close($ch);
  89.      
  90.       Gdn::Controller()->SetJson('Type', $ContentType);
  91.  
  92.       if (strpos($ContentType, 'javascript') !== FALSE) {
  93.          $Result = json_decode($Response, TRUE);
  94.          
  95.          if (isset($Result['error'])) {
  96.             Gdn::Dispatcher()->PassData('FacebookResponse', $Result);
  97.             throw new Gdn_UserException($Result['error']['message']);
  98.          }
  99.       } else
  100.          $Result = $Response;
  101.  
  102.       return $Result;
  103.    }
  104.  
  105. //   public function AuthenticationController_Render_Before($Sender, $Args) {
  106. //      if (isset($Sender->ChooserList)) {
  107. //         $Sender->ChooserList['facebook'] = 'Facebook';
  108. //      }
  109. //      if (is_array($Sender->Data('AuthenticationConfigureList'))) {
  110. //         $List = $Sender->Data('AuthenticationConfigureList');
  111. //         $List['facebook'] = '/dashboard/settings/facebook';
  112. //         $Sender->SetData('AuthenticationConfigureList', $List);
  113. //      }
  114. //   }
  115.  
  116.    /**
  117.     *
  118.     * @param Gdn_Controller $Sender
  119.     */
  120.    public function EntryController_SignIn_Handler($Sender, $Args) {
  121.       if (!$this->IsConfigured())
  122.          return;
  123.      
  124.       if (isset($Sender->Data['Methods'])) {
  125.          $ImgSrc = Asset('/plugins/Facebook/design/facebook-login.png');
  126.          $ImgAlt = T('Sign In with Facebook');
  127.  
  128. //         if ($AccessToken) {
  129. //            $SigninHref = $this->RedirectUri();
  130. //
  131. //            // We already have an access token so we can just link to the connect page.
  132. //            $FbMethod = array(
  133. //                'Name' => 'Facebook',
  134. //                'SignInHtml' => "<a id=\"FacebookAuth\" href=\"$SigninHref\" class=\"PopLink\" ><img src=\"$ImgSrc\" alt=\"$ImgAlt\" /></a>");
  135. //         } else {
  136.             $SigninHref = $this->AuthorizeUri();
  137.             $PopupSigninHref = $this->AuthorizeUri('display=popup');
  138.  
  139.             // Add the facebook method to the controller.
  140.             $FbMethod = array(
  141.                'Name' => self::ProviderKey,
  142.                'SignInHtml' => "<a id=\"FacebookAuth\" href=\"$SigninHref\" class=\"PopupWindow\" popupHref=\"$PopupSigninHref\" popupHeight=\"326\" popupWidth=\"627\" rel=\"nofollow\" ><img src=\"$ImgSrc\" alt=\"$ImgAlt\" /></a>");
  143. //         }
  144.  
  145.          $Sender->Data['Methods'][] = $FbMethod;
  146.       }
  147.    }
  148.    
  149.    /**
  150.     * Add 'Facebook' option to the row.
  151.     */
  152.    public function Base_AfterReactions_Handler($Sender, $Args) {
  153.       if (!$this->SocialReactions())
  154.          return;
  155.      
  156.       echo Gdn_Theme::BulletItem('Share');
  157.       $this->AddReactButton($Sender, $Args);
  158.    }
  159.    
  160.    public function Base_DiscussionFormOptions_Handler($Sender, $Args) {
  161.       if (!$this->SocialSharing())
  162.          return;
  163.      
  164.       if (!$this->AccessToken())
  165.          return;
  166.      
  167.       $Options =& $Args['Options'];
  168.      
  169.       $Options .= ' <li>'.
  170.          $Sender->Form->CheckBox('ShareFacebook', '@'.Sprite('ReactFacebook', 'ReactSprite'), array('value' => '1', 'title' => sprintf(T('Share to %s.'), 'Facebook'))).
  171.          '</li> ';
  172.    }
  173.    
  174.    public function DiscussionController_AfterBodyField_Handler($Sender, $Args) {
  175.       if (!$this->SocialSharing())
  176.          return;
  177.      
  178.       if (!$this->AccessToken())
  179.          return;
  180.      
  181.       echo ' '.
  182.          $Sender->Form->CheckBox('ShareFacebook', '@'.Sprite('ReactFacebook', 'ReactSprite'), array('value' => '1', 'title' => sprintf(T('Share to %s.'), 'Facebook'))).
  183.          ' ';
  184.    }
  185.    
  186.    public function DiscussionModel_AfterSaveDiscussion_Handler($Sender, $Args) {
  187.       if (!$this->SocialSharing())
  188.          return;
  189.      
  190.       if (!$this->AccessToken())
  191.          return;
  192.      
  193.       $ShareFacebook = GetValueR('FormPostValues.ShareFacebook', $Args);
  194.      
  195.       if ($ShareFacebook) {
  196.          $Url = DiscussionUrl($Args['Fields'], '', TRUE);
  197. //         $Message = SliceParagraph(Gdn_Format::PlainText($Row['Body'], $Row['Format']), 160);
  198.          
  199.          if ($this->AccessToken()) {
  200.             $R = $this->API('/me/feed', array(
  201.                 'link' => $Url
  202.                 ));
  203.          }
  204.       }
  205.    }
  206.    
  207.    public function CommentModel_AfterSaveComment_Handler($Sender, $Args) {
  208.       if (!$this->SocialSharing())
  209.          return;
  210.      
  211.       if (!$this->AccessToken())
  212.          return;
  213.      
  214.       $ShareFacebook = GetValueR('FormPostValues.ShareFacebook', $Args);
  215.      
  216.       if ($ShareFacebook) {
  217.          $Row = $Args['FormPostValues'];
  218.          
  219.          $DiscussionModel = new DiscussionModel();
  220.          $Discussion = $DiscussionModel->GetID(GetValue('DiscussionID', $Row));
  221.          if (!$Discussion)
  222.             die('no discussion');
  223.          
  224.          $Url = DiscussionUrl($Discussion, '', TRUE);
  225.          $Message = SliceParagraph(Gdn_Format::PlainText($Row['Body'], $Row['Format']), 160);
  226.          
  227.          if ($this->AccessToken()) {
  228.             $R = $this->API('/me/feed', array(
  229.                 'link' => $Url,
  230.                 'message' => $Message
  231.                 ));
  232.          }
  233.       }
  234.    }
  235.  
  236.    /**
  237.     * Output Quote link.
  238.     */
  239.    protected function AddReactButton($Sender, $Args) {
  240.       if ($this->AccessToken()) {
  241.          $CssClass = 'ReactButton Hijack';
  242.       } else {
  243.          $CssClass = 'ReactButton PopupWindow';
  244.       }
  245.      
  246.       echo ' '.Anchor(Sprite('ReactFacebook', 'ReactSprite'), Url("post/facebook/{$Args['RecordType']}?id={$Args['RecordID']}", TRUE), $CssClass).' ';
  247.    }
  248.    
  249.    public function Base_SignInIcons_Handler($Sender, $Args) {
  250.       if (!$this->IsConfigured())
  251.          return;
  252.        
  253.         echo "\n".$this->_GetButton();
  254.    }
  255.  
  256.    public function Base_BeforeSignInButton_Handler($Sender, $Args) {
  257.       if (!$this->IsConfigured())
  258.          return;
  259.        
  260.         echo "\n".$this->_GetButton();
  261.     }
  262.    
  263.     public function Base_BeforeSignInLink_Handler($Sender) {
  264.       if (!$this->IsConfigured())
  265.             return;
  266.        
  267.         // if (!IsMobile())
  268.         //  return;
  269.  
  270.         if (!Gdn::Session()->IsValid())
  271.             echo "\n".Wrap($this->_GetButton(), 'li', array('class' => 'Connect FacebookConnect'));
  272.     }
  273.    
  274.    public function Base_GetConnections_Handler($Sender, $Args) {
  275.       $Profile = GetValueR('User.Attributes.'.self::ProviderKey.'.Profile', $Args);
  276.      
  277.       $Sender->Data["Connections"][self::ProviderKey] = array(
  278.          'Icon' => $this->GetWebResource('icon.png', '/'),
  279.          'Name' => 'Facebook',
  280.          'ProviderKey' => self::ProviderKey,
  281.          'ConnectUrl' => $this->AuthorizeUri(FALSE, self::ProfileConnecUrl()),
  282.          'Profile' => array(
  283.             'Name' => GetValue('name', $Profile),
  284.             'Photo' => "//graph.facebook.com/{$Profile['id']}/picture?type=large"
  285.             )
  286.       );
  287.    }
  288.    
  289.    /**
  290.     *
  291.     * @param PostController $Sender
  292.     * @param type $RecordType
  293.     * @param type $ID
  294.     * @throws type
  295.     */
  296.    public function PostController_Facebook_Create($Sender, $RecordType, $ID) {
  297.       if (!$this->SocialReactions())
  298.          throw PermissionException();
  299.            
  300. //      if (!Gdn::Request()->IsPostBack())
  301. //         throw PermissionException('Javascript');
  302.      
  303.       $Row = GetRecord($RecordType, $ID);
  304.       if ($Row) {
  305.          $Message = SliceParagraph(Gdn_Format::PlainText($Row['Body'], $Row['Format']), 160);
  306.          
  307.          if ($this->AccessToken() && $Sender->Request->IsPostBack()) {
  308.             $R = $this->API('/me/feed', array(
  309.                 'link' => $Row['ShareUrl'],
  310.                 'message' => $Message
  311.                 ));
  312.  
  313.             $Sender->SetJson('R', $R);
  314.             $Sender->InformMessage(T('Thanks for sharing!'));
  315.          } else {
  316. //            http://www.facebook.com/dialog/feed?app_id=231546166870342&redirect_uri=http%3A%2F%2Fvanillicon.com%2Fredirect%2Ffacebook%3Fhash%3Daad66afb13105676dffa79bfe2b8595f&link=http%3A%2F%2Fvanillicon.com&picture=http%3A%2F%2Fvanillicon.com%2Faad66afb13105676dffa79bfe2b8595f.png&name=Vanillicon&caption=What%27s+Your+Vanillicon+Look+Like%3F&description=Vanillicons+are+unique+avatars+generated+by+your+name+or+email+that+are+free+to+make+%26+use+around+the+web.+Create+yours+now%21
  317.             $Get = array(
  318.                   'app_id' => C('Plugins.Facebook.ApplicationID'),
  319.                   'link' => $Row['ShareUrl'],
  320.                   'name' => Gdn_Format::PlainText($Row['Name'], 'Text'),
  321. //                  'caption' => 'Foo',
  322.                   'description' => $Message,
  323.                   'redirect_uri' => Url('/post/shared/facebook', TRUE)
  324.                 );
  325.            
  326.             $Url = 'http://www.facebook.com/dialog/feed?'.http_build_query($Get);
  327.             Redirect($Url);
  328.          }
  329.       }
  330.      
  331.       $Sender->Render('Blank', 'Utility', 'Dashboard');
  332.    }
  333.    
  334.    /**
  335.     *
  336.     *
  337.     * @param ProfileController $Sender
  338.     * @param type $UserReference
  339.     * @param type $Username
  340.     * @param type $Code
  341.     */
  342.    public function ProfileController_FacebookConnect_Create($Sender, $UserReference, $Username, $Code = FALSE) {
  343.       $Sender->Permission('Garden.SignIn.Allow');
  344.      
  345.       $Sender->GetUserInfo($UserReference, $Username, '', TRUE);
  346.       $Sender->_SetBreadcrumbs(T('Connections'), '/profile/connections');
  347.      
  348.       // Get the access token.
  349.       $AccessToken = $this->GetAccessToken($Code, self::ProfileConnecUrl());
  350.      
  351.       // Get the profile.
  352.       $Profile = $this->GetProfile($AccessToken);
  353.      
  354.       // Save the authentication.
  355.       Gdn::UserModel()->SaveAuthentication(array(
  356.          'UserID' => $Sender->User->UserID,
  357.          'Provider' => self::ProviderKey,
  358.          'UniqueID' => $Profile['id']));
  359.      
  360.       // Save the information as attributes.
  361.       $Attributes = array(
  362.           'AccessToken' => $AccessToken,
  363.           'Profile' => $Profile
  364.       );
  365.       Gdn::UserModel()->SaveAttribute($Sender->User->UserID, self::ProviderKey, $Attributes);
  366.      
  367.       $this->EventArguments['Provider'] = self::ProviderKey;
  368.       $this->EventArguments['User'] = $Sender->User;
  369.       $this->FireEvent('AfterConnection');
  370.      
  371.       Redirect(UserUrl($Sender->User, '', 'connections'));
  372.    }
  373.    
  374.     private function _GetButton() {
  375.       $ImgSrc = Asset('/plugins/Facebook/design/facebook-icon.png');
  376.       $ImgAlt = T('Sign In with Facebook');
  377.       $SigninHref = $this->AuthorizeUri();
  378.       $PopupSigninHref = $this->AuthorizeUri('display=popup');
  379.       return "<a id=\"FacebookAuth\" href=\"$SigninHref\" class=\"PopupWindow\" title=\"$ImgAlt\" popupHref=\"$PopupSigninHref\" popupHeight=\"326\" popupWidth=\"627\" rel=\"nofollow\" ><img src=\"$ImgSrc\" alt=\"$ImgAlt\" align=\"bottom\" /></a>";
  380.    }
  381.    
  382.    public function SocialController_Facebook_Create($Sender, $Args) {
  383.       $Sender->Permission('Garden.Settings.Manage');
  384.       if ($Sender->Form->AuthenticatedPostBack()) {
  385.          $Settings = array(
  386.              'Plugins.Facebook.ApplicationID' => $Sender->Form->GetFormValue('ApplicationID'),
  387.              'Plugins.Facebook.Secret' => $Sender->Form->GetFormValue('Secret'),
  388.              'Plugins.Facebook.UseFacebookNames' => $Sender->Form->GetFormValue('UseFacebookNames'),
  389.              'Plugins.Facebook.SocialReactions' => $Sender->Form->GetFormValue('SocialReactions'),
  390.              'Plugins.Facebook.SocialSharing' => $Sender->Form->GetFormValue('SocialSharing'),
  391.              'Garden.Registration.SendConnectEmail' => $Sender->Form->GetFormValue('SendConnectEmail'));
  392.  
  393.          SaveToConfig($Settings);
  394.          $Sender->InformMessage(T("Your settings have been saved."));
  395.  
  396.       } else {
  397.          $Sender->Form->SetValue('ApplicationID', C('Plugins.Facebook.ApplicationID'));
  398.          $Sender->Form->SetValue('Secret', C('Plugins.Facebook.Secret'));
  399.          $Sender->Form->SetValue('UseFacebookNames', C('Plugins.Facebook.UseFacebookNames'));
  400.          $Sender->Form->SetValue('SendConnectEmail', C('Garden.Registration.SendConnectEmail', TRUE));
  401.          $Sender->Form->SetValue('SocialReactions', $this->SocialReactions());
  402.          $Sender->Form->SetValue('SocialSharing', $this->SocialSharing());
  403.       }
  404.  
  405.       $Sender->AddSideMenu('dashboard/social');
  406.       $Sender->SetData('Title', T('Facebook Settings'));
  407.       $Sender->Render('Settings', '', 'plugins/Facebook');
  408.    }
  409.  
  410.    /**
  411.     *
  412.     * @param Gdn_Controller $Sender
  413.     * @param array $Args
  414.     */
  415.    public function Base_ConnectData_Handler($Sender, $Args) {
  416.       if (GetValue(0, $Args) != 'facebook')
  417.          return;
  418.  
  419.       if (isset($_GET['error'])) {
  420.          throw new Gdn_UserException(GetValue('error_description', $_GET, T('There was an error connecting to Facebook')));
  421.       }
  422.  
  423.       $AppID = C('Plugins.Facebook.ApplicationID');
  424.       $Secret = C('Plugins.Facebook.Secret');
  425.       $Code = GetValue('code', $_GET);
  426.       $Query = '';
  427.       if ($Sender->Request->Get('display'))
  428.          $Query = 'display='.urlencode($Sender->Request->Get('display'));
  429.  
  430.       $RedirectUri = ConcatSep('&', $this->RedirectUri(), $Query);
  431.      
  432.       $AccessToken = $Sender->Form->GetFormValue('AccessToken');
  433.      
  434.       // Get the access token.
  435.       if (!$AccessToken && $Code) {
  436.          // Exchange the token for an access token.
  437.          $Code = urlencode($Code);
  438.          
  439.          $AccessToken = $this->GetAccessToken($Code, $RedirectUri);
  440.  
  441.          $NewToken = TRUE;
  442.       }
  443.  
  444.       // Get the profile.
  445.       try {
  446.          $Profile = $this->GetProfile($AccessToken);
  447.       } catch (Exception $Ex) {
  448.          if (!isset($NewToken)) {
  449.             // There was an error getting the profile, which probably means the saved access token is no longer valid. Try and reauthorize.
  450.             if ($Sender->DeliveryType() == DELIVERY_TYPE_ALL) {
  451.                Redirect($this->AuthorizeUri());
  452.             } else {
  453.                $Sender->SetHeader('Content-type', 'application/json');
  454.                $Sender->DeliveryMethod(DELIVERY_METHOD_JSON);
  455.                $Sender->RedirectUrl = $this->AuthorizeUri();
  456.             }
  457.          } else {
  458.             $Sender->Form->AddError('There was an error with the Facebook connection.');
  459.          }
  460.       }
  461.  
  462.       $Form = $Sender->Form; //new Gdn_Form();
  463.       $ID = GetValue('id', $Profile);
  464.       $Form->SetFormValue('UniqueID', $ID);
  465.       $Form->SetFormValue('Provider', self::ProviderKey);
  466.       $Form->SetFormValue('ProviderName', 'Facebook');
  467.       $Form->SetFormValue('FullName', GetValue('name', $Profile));
  468.       $Form->SetFormValue('Email', GetValue('email', $Profile));
  469.       $Form->SetFormValue('Photo', "//graph.facebook.com/{$ID}/picture?type=large");
  470.       $Form->AddHidden('AccessToken', $AccessToken);
  471.      
  472.       if (C('Plugins.Facebook.UseFacebookNames')) {
  473.          $Form->SetFormValue('Name', GetValue('name', $Profile));
  474.          SaveToConfig(array(
  475.              'Garden.User.ValidationRegex' => UserModel::USERNAME_REGEX_MIN,
  476.              'Garden.User.ValidationLength' => '{3,50}',
  477.              'Garden.Registration.NameUnique' => FALSE
  478.          ), '', FALSE);
  479.       }
  480.      
  481.       // Save some original data in the attributes of the connection for later API calls.
  482.       $Attributes = array();
  483.       $Attributes[self::ProviderKey] = array(
  484.           'AccessToken' => $AccessToken,
  485.           'Profile' => $Profile
  486.       );
  487.       $Form->SetFormValue('Attributes', $Attributes);
  488.      
  489.       $Sender->SetData('Verified', TRUE);
  490.    }
  491.    
  492.    protected function GetAccessToken($Code, $RedirectUri, $ThrowError = TRUE) {
  493.       $Get = array(
  494.           'client_id' => C('Plugins.Facebook.ApplicationID'),
  495.           'client_secret' => C('Plugins.Facebook.Secret'),
  496.           'code' => $Code,
  497.           'redirect_uri' => $RedirectUri);
  498.      
  499.       $Url = 'https://graph.facebook.com/oauth/access_token?'.http_build_query($Get);
  500.      
  501.       // Get the redirect URI.
  502.       $C = curl_init();
  503.       curl_setopt($C, CURLOPT_RETURNTRANSFER, TRUE);
  504.       curl_setopt($C, CURLOPT_SSL_VERIFYPEER, FALSE);
  505.       curl_setopt($C, CURLOPT_URL, $Url);
  506.       $Contents = curl_exec($C);
  507.  
  508.       $Info = curl_getinfo($C);
  509.       if (strpos(GetValue('content_type', $Info, ''), '/javascript') !== FALSE) {
  510.          $Tokens = json_decode($Contents, TRUE);
  511.       } else {
  512.          parse_str($Contents, $Tokens);
  513.       }
  514.  
  515.       if (GetValue('error', $Tokens)) {
  516.          throw new Gdn_UserException('Facebook returned the following error: '.GetValueR('error.message', $Tokens, 'Unknown error.'), 400);
  517.       }
  518.  
  519.       $AccessToken = GetValue('access_token', $Tokens);
  520. //      $Expires = GetValue('expires', $Tokens, NULL);
  521.      
  522.       return $AccessToken;
  523.    }
  524.  
  525.    public function GetProfile($AccessToken) {
  526.       $Url = "https://graph.facebook.com/me?access_token=$AccessToken";
  527. //      $C = curl_init();
  528. //      curl_setopt($C, CURLOPT_RETURNTRANSFER, TRUE);
  529. //      curl_setopt($C, CURLOPT_SSL_VERIFYPEER, FALSE);
  530. //      curl_setopt($C, CURLOPT_URL, $Url);
  531. //      $Contents = curl_exec($C);
  532. //      $Contents = ProxyRequest($Url);
  533.       $Contents = file_get_contents($Url);
  534.       $Profile = json_decode($Contents, TRUE);
  535.       return $Profile;
  536.    }
  537.  
  538.    public function AuthorizeUri($Query = FALSE, $RedirectUri = FALSE) {
  539.       $AppID = C('Plugins.Facebook.ApplicationID');
  540.       $FBScope = C('Plugins.Facebook.Scope', Array('email','publish_stream'));
  541.  
  542.       if (!$RedirectUri)
  543.          $RedirectUri = $this->RedirectUri();
  544.       if ($Query)
  545.          $RedirectUri .= '&'.$Query;
  546.       $RedirectUri = urlencode($RedirectUri);
  547.  
  548.       $Scopes = implode(',', $FBScope);
  549.       $SigninHref = "https://graph.facebook.com/oauth/authorize?client_id=$AppID&redirect_uri=$RedirectUri&scope=$Scopes";
  550.       if ($Query)
  551.          $SigninHref .= '&'.$Query;
  552.       return $SigninHref;
  553.    }
  554.  
  555.    protected $_RedirectUri = NULL;
  556.  
  557.    public function RedirectUri($NewValue = NULL) {
  558.       if ($NewValue !== NULL)
  559.          $this->_RedirectUri = $NewValue;
  560.       elseif ($this->_RedirectUri === NULL) {
  561.          $RedirectUri = Url('/entry/connect/facebook', TRUE);
  562.          if (strpos($RedirectUri, '=') !== FALSE) {
  563.             $p = strrchr($RedirectUri, '=');
  564.             $Uri = substr($RedirectUri, 0, -strlen($p));
  565.             $p = urlencode(ltrim($p, '='));
  566.             $RedirectUri = $Uri.'='.$p;
  567.          }
  568.  
  569.          $Path = Gdn::Request()->Path();
  570.  
  571.          $Target = GetValue('Target', $_GET, $Path ? $Path : '/');
  572.          if (ltrim($Target, '/') == 'entry/signin' || empty($Target))
  573.             $Target = '/';
  574.          $Args = array('Target' => $Target);
  575.  
  576.  
  577.          $RedirectUri .= strpos($RedirectUri, '?') === FALSE ? '?' : '&';
  578.          $RedirectUri .= http_build_query($Args);
  579.          $this->_RedirectUri = $RedirectUri;
  580.       }
  581.      
  582.       return $this->_RedirectUri;
  583.    }
  584.    
  585.    public static function ProfileConnecUrl() {
  586.       return Url(UserUrl(Gdn::Session()->User, FALSE, 'facebookconnect'), TRUE);
  587.    }
  588.  
  589.    public function IsConfigured() {
  590.       $AppID = C('Plugins.Facebook.ApplicationID');
  591.       $Secret = C('Plugins.Facebook.Secret');
  592.       if (!$AppID || !$Secret)
  593.          return FALSE;
  594.       return TRUE;
  595.    }
  596.    
  597.    public function SocialSharing() {
  598.       return C('Plugins.Facebook.SocialSharing', TRUE) && $this->IsConfigured();
  599.    }
  600.    
  601.    public function SocialReactions() {
  602.       return C('Plugins.Facebook.SocialReactions', TRUE) && $this->IsConfigured();
  603.    }
  604.    
  605.    public function Setup() {
  606.       $Error = '';
  607.       if (!function_exists('curl_init'))
  608.          $Error = ConcatSep("\n", $Error, 'This plugin requires curl.');
  609.       if ($Error)
  610.          throw new Gdn_UserException($Error, 400);
  611.  
  612.       $this->Structure();
  613.    }
  614.  
  615.    public function Structure() {
  616.       // Save the facebook provider type.
  617.       Gdn::SQL()->Replace('UserAuthenticationProvider',
  618.          array('AuthenticationSchemeAlias' => 'facebook', 'URL' => '...', 'AssociationSecret' => '...', 'AssociationHashMethod' => '...'),
  619.          array('AuthenticationKey' => self::ProviderKey), TRUE);
  620.    }
  621.  
  622.    public function OnDisable() {
  623.    }
  624.  
  625. //   public function OnDisable() {
  626. //      $this->_Disable();
  627. //   }
  628.  
  629. //   protected function _CreateProviderModel() {
  630. //      $Key = 'k'.sha1(implode('.',array(
  631. //         'vanillaconnect',
  632. //         'key',
  633. //         microtime(true),
  634. //         RandomString(16),
  635. //         Gdn::Session()->User->Name
  636. //      )));
  637. //
  638. //      $Secret = 's'.sha1(implode('.',array(
  639. //         'vanillaconnect',
  640. //         'secret',
  641. //         md5(microtime(true)),
  642. //         RandomString(16),
  643. //         Gdn::Session()->User->Name
  644. //      )));
  645. //
  646. //      $ProviderModel = new Gdn_AuthenticationProviderModel();
  647. //      $ProviderModel->Insert($Provider = array(
  648. //         'AuthenticationKey'           => $Key,
  649. //         'AuthenticationSchemeAlias'   => 'handshake',
  650. //         'URL'                         => 'Enter your site url',
  651. //         'AssociationSecret'           => $Secret,
  652. //         'AssociationHashMethod'       => 'HMAC-SHA1'
  653. //      ));
  654. //
  655. //      return $Provider;
  656. //   }
  657. //
  658. //   public function AuthenticationController_DisableAuthenticatorHandshake_Handler(&$Sender) {
  659. //      $this->_Disable();
  660. //   }
  661. //
  662. //   private function _Disable() {
  663. //      RemoveFromConfig('Plugins.VanillaConnect.Enabled');
  664. //      RemoveFromConfig('Garden.SignIn.Popup');
  665. //      RemoveFromConfig('Garden.Authenticator.DefaultScheme');
  666. //      RemoveFromConfig('Garden.Authenticators.handshake.Name');
  667. //      RemoveFromConfig('Garden.Authenticators.handshake.CookieName');
  668. //      RemoveFromConfig('Garden.Authenticators.handshake.TokenLifetime');
  669. //   }
  670. //
  671. //   public function AuthenticationController_EnableAuthenticatorHandshake_Handler(&$Sender) {
  672. //      $this->_Enable();
  673. //   }
  674. //
  675. //  private function _Enable($FullEnable = TRUE) {
  676. //      SaveToConfig('Garden.SignIn.Popup', FALSE);
  677. //      SaveToConfig('Garden.Authenticators.handshake.Name', 'VanillaConnect');
  678. //      SaveToConfig('Garden.Authenticators.handshake.CookieName', 'VanillaHandshake');
  679. //      SaveToConfig('Garden.Authenticators.handshake.TokenLifetime', 0);
  680. //
  681. //      if ($FullEnable) {
  682. //         SaveToConfig('Garden.Authenticator.DefaultScheme', 'handshake');
  683. //         SaveToConfig('Plugins.VanillaConnect.Enabled', TRUE);
  684. //      }
  685. //
  686. //      // Create a provider key/secret pair if needed
  687. //      $SQL = Gdn::Database()->SQL();
  688. //      $Provider = $SQL->Select('uap.*')
  689. //         ->From('UserAuthenticationProvider uap')
  690. //         ->Where('uap.AuthenticationSchemeAlias', 'handshake')
  691. //         ->Get()
  692. //         ->FirstRow(DATASET_TYPE_ARRAY);
  693. //
  694. //      if (!$Provider)
  695. //         $this->_CreateProviderModel();
  696. //  }
  697. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement