Advertisement
Guest User

Untitled

a guest
Apr 2nd, 2013
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.55 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',
  14.    'Description' => 'This plugin integrates Vanilla with Facebook. <b>You must register your application with Facebook for this plugin to work.</b>',
  15.    'Version' => '1.0.1',
  16.    'RequiredApplications' => array('Vanilla' => '2.0.14a'),
  17.    'RequiredTheme' => FALSE,
  18.    'RequiredPlugins' => FALSE,
  19.     'MobileFriendly' => TRUE,
  20.    'SettingsUrl' => '/dashboard/settings/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. );
  28.  
  29. class FacebookPlugin extends Gdn_Plugin {
  30.    public function AccessToken() {
  31.       $Token = GetValue('fb_access_token', $_COOKIE);
  32.       return $Token;
  33.    }
  34.  
  35.    public function Authorize($Query = FALSE) {
  36.       $Uri = $this->AuthorizeUri($Query);
  37.       Redirect($Uri);
  38.    }
  39.  
  40.    public function AuthenticationController_Render_Before($Sender, $Args) {
  41.       if (isset($Sender->ChooserList)) {
  42.          $Sender->ChooserList['facebook'] = 'Facebook';
  43.       }
  44.       if (is_array($Sender->Data('AuthenticationConfigureList'))) {
  45.          $List = $Sender->Data('AuthenticationConfigureList');
  46.          $List['facebook'] = '/dashboard/settings/facebook';
  47.          $Sender->SetData('AuthenticationConfigureList', $List);
  48.       }
  49.    }
  50.  
  51.    /**
  52.     *
  53.     * @param Gdn_Controller $Sender
  54.     */
  55.    public function EntryController_SignIn_Handler($Sender, $Args) {
  56.       if (!$this->IsConfigured())
  57.          return;
  58.      
  59.       if (isset($Sender->Data['Methods'])) {
  60.          $AccessToken = $this->AccessToken();
  61.  
  62.          $ImgSrc = Asset('/plugins/Facebook/design/facebook-login.png');
  63.          $ImgAlt = T('Login with Facebook');
  64.  
  65. //         if ($AccessToken) {
  66. //            $SigninHref = $this->RedirectUri();
  67. //
  68. //            // We already have an access token so we can just link to the connect page.
  69. //            $FbMethod = array(
  70. //                'Name' => 'Facebook',
  71. //                'SignInHtml' => "<a id=\"FacebookAuth\" href=\"$SigninHref\" class=\"PopLink\" ><img src=\"$ImgSrc\" alt=\"$ImgAlt\" /></a>");
  72. //         } else {
  73.             $SigninHref = $this->AuthorizeUri();
  74.             $PopupSigninHref = $this->AuthorizeUri('display=popup');
  75.  
  76.             // Add the facebook method to the controller.
  77.             $FbMethod = array(
  78.                'Name' => 'Facebook',
  79.                'SignInHtml' => "<a id=\"FacebookAuth\" href=\"$SigninHref\" class=\"PopupWindow\" popupHref=\"$PopupSigninHref\" popupHeight=\"326\" popupWidth=\"627\" ><img src=\"$ImgSrc\" alt=\"$ImgAlt\" /></a>");
  80. //         }
  81.  
  82.          $Sender->Data['Methods'][] = $FbMethod;
  83.       }
  84.    }
  85.  
  86.    public function Base_BeforeSignInButton_Handler($Sender, $Args) {
  87.       if (!$this->IsConfigured())
  88.          return;
  89.        
  90.         echo "\n".$this->_GetButton();
  91.     }
  92.    
  93.     public function Base_BeforeSignInLink_Handler($Sender) {
  94.       if (!$this->IsConfigured())
  95.             return;
  96.        
  97.         // if (!IsMobile())
  98.         //  return;
  99.  
  100.         if (!Gdn::Session()->IsValid())
  101.             echo "\n".Wrap($this->_GetButton(), 'li', array('class' => 'Connect FacebookConnect'));
  102.     }
  103.    
  104.     private function _GetButton() {
  105.       $ImgSrc = Asset('/plugins/Facebook/design/facebook-icon.png');
  106.       $ImgAlt = T('Login with Facebook');
  107.       $SigninHref = $this->AuthorizeUri();
  108.       $PopupSigninHref = $this->AuthorizeUri('display=popup');
  109.       return "<a id=\"FacebookAuth\" href=\"$SigninHref\" class=\"PopupWindow\" title=\"$ImgAlt\" popupHref=\"$PopupSigninHref\" popupHeight=\"326\" popupWidth=\"627\" ><img src=\"$ImgSrc\" alt=\"$ImgAlt\" align=\"bottom\" /></a>";
  110.    }
  111.    
  112.    public function SettingsController_Facebook_Create($Sender, $Args) {
  113.       $Sender->Permission('Garden.Settings.Manage');
  114.       if ($Sender->Form->IsPostBack()) {
  115.          $Settings = array(
  116.              'Plugins.Facebook.ApplicationID' => $Sender->Form->GetFormValue('ApplicationID'),
  117.              'Plugins.Facebook.Secret' => $Sender->Form->GetFormValue('Secret'));
  118.  
  119.          SaveToConfig($Settings);
  120.          $Sender->InformMessage(T("Your settings have been saved."));
  121.  
  122.       } else {
  123.          $Sender->Form->SetFormValue('ApplicationID', C('Plugins.Facebook.ApplicationID'));
  124.          $Sender->Form->SetFormValue('Secret', C('Plugins.Facebook.Secret'));
  125.       }
  126.  
  127.       $Sender->AddSideMenu();
  128.       $Sender->SetData('Title', T('Facebook Settings'));
  129.       $Sender->Render('Settings', '', 'plugins/Facebook');
  130.    }
  131.  
  132.    /**
  133.     *
  134.     * @param Gdn_Controller $Sender
  135.     * @param array $Args
  136.     */
  137.    public function Base_ConnectData_Handler($Sender, $Args) {
  138.       if (GetValue(0, $Args) != 'facebook')
  139.          return;
  140.  
  141.       if (isset($_GET['error'])) {
  142.          throw new Gdn_UserException(GetValue('error_description', $_GET, T('There was an error connecting to Facebook')));
  143.       }
  144.  
  145.       $AppID = C('Plugins.Facebook.ApplicationID');
  146.       $Secret = C('Plugins.Facebook.Secret');
  147.       $Code = GetValue('code', $_GET);
  148.       $Query = '';
  149.       if ($Sender->Request->Get('display'))
  150.          $Query = 'display='.urlencode($Sender->Request->Get('display'));
  151.  
  152.       $RedirectUri = ConcatSep('&', $this->RedirectUri(), $Query);
  153.       $RedirectUri = urlencode($RedirectUri);
  154.  
  155.       // Get the access token.
  156.       if ($Code || !($AccessToken = $this->AccessToken())) {
  157.          // Exchange the token for an access token.
  158.          $Code = urlencode($Code);
  159.  
  160.          $Url = "https://graph.facebook.com/oauth/access_token?client_id=$AppID&client_secret=$Secret&code=$Code&redirect_uri=$RedirectUri";
  161.  
  162.          // Get the redirect URI.
  163.          $C = curl_init();
  164.          curl_setopt($C, CURLOPT_RETURNTRANSFER, TRUE);
  165.          curl_setopt($C, CURLOPT_SSL_VERIFYPEER, FALSE);
  166.          curl_setopt($C, CURLOPT_URL, $Url);
  167.          $Contents = curl_exec($C);
  168. //         $Contents = ProxyRequest($Url);
  169.          $Info = curl_getinfo($C);
  170.          if (strpos(GetValue('content_type', $Info, ''), '/javascript') !== FALSE) {
  171.             $Tokens = json_decode($Contents, TRUE);
  172.          } else {
  173.             parse_str($Contents, $Tokens);
  174.          }
  175.  
  176.          if (GetValue('error', $Tokens)) {
  177.             throw new Gdn_UserException('Facebook returned the following error: '.GetValueR('error.message', $Tokens, 'Unknown error.'), 400);
  178.          }
  179.  
  180.          $AccessToken = GetValue('access_token', $Tokens);
  181.          $Expires = GetValue('expires', $Tokens, NULL);
  182.  
  183.          setcookie('fb_access_token', $AccessToken, time() + $Expires, C('Garden.Cookie.Path', '/'), C('Garden.Cookie.Domain', ''));
  184.          $NewToken = TRUE;
  185.       }
  186.  
  187.       // Get the profile.
  188.       try {
  189.          $Profile = $this->GetProfile($AccessToken);
  190.       } catch (Exception $Ex) {
  191.          if (!isset($NewToken)) {
  192.             // There was an error getting the profile, which probably means the saved access token is no longer valid. Try and reauthorize.
  193.             if ($Sender->DeliveryType() == DELIVERY_TYPE_ALL) {
  194.                Redirect($this->AuthorizeUri());
  195.             } else {
  196.                $Sender->SetHeader('Content-type', 'application/json');
  197.                $Sender->DeliveryMethod(DELIVERY_METHOD_JSON);
  198.                $Sender->RedirectUrl = $this->AuthorizeUri();
  199.             }
  200.          } else {
  201.             $Sender->Form->AddError('There was an error with the Facebook connection.');
  202.          }
  203.       }
  204.  
  205.       $Form = $Sender->Form; //new Gdn_Form();
  206.       $ID = GetValue('id', $Profile);
  207.       $Form->SetFormValue('UniqueID', $ID);
  208.       $Form->SetFormValue('Provider', 'facebook');
  209.       $Form->SetFormValue('ProviderName', 'Facebook');
  210.       $Form->SetFormValue('FullName', GetValue('name', $Profile));
  211.       $Form->SetFormValue('Email', GetValue('email', $Profile));
  212.       $Form->SetFormValue('Photo', "http://graph.facebook.com/$ID/picture");
  213.       $Sender->SetData('Verified', TRUE);
  214.    }
  215.  
  216.    public function GetProfile($AccessToken) {
  217.       $Url = "http://graph.facebook.com/me?access_token=$AccessToken";
  218. //      $C = curl_init();
  219. //      curl_setopt($C, CURLOPT_RETURNTRANSFER, TRUE);
  220. //      curl_setopt($C, CURLOPT_SSL_VERIFYPEER, FALSE);
  221. //      curl_setopt($C, CURLOPT_URL, $Url);
  222. //      $Contents = curl_exec($C);
  223. //      $Contents = ProxyRequest($Url);
  224.       $Contents = $this->file_get_contents_curl($Url);
  225.       echo $Contents;
  226.       $Profile = json_decode($Contents, TRUE);
  227.       return $Profile;
  228.    }
  229.     function file_get_contents_curl($url) {
  230.         $ch = curl_init($url);
  231.        
  232.         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  233.         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  234.         curl_setopt($ch, CURLOPT_HEADER, 0);
  235.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
  236.         curl_setopt($ch, CURLOPT_URL, $url);
  237.        
  238.         $data = curl_exec($ch);
  239.         curl_close($ch);
  240.        
  241.         return $data;
  242.     }
  243.  
  244.    public function AuthorizeUri($Query = FALSE) {
  245.       $AppID = C('Plugins.Facebook.ApplicationID');
  246.  
  247.       $RedirectUri = $this->RedirectUri();
  248.       if ($Query)
  249.          $RedirectUri .= '&'.$Query;
  250.       $RedirectUri = urlencode($RedirectUri);
  251.  
  252.       $SigninHref = "https://graph.facebook.com/oauth/authorize?client_id=$AppID&redirect_uri=$RedirectUri&scope=email,publish_stream";
  253.       if ($Query)
  254.          $SigninHref .= '&'.$Query;
  255.       return $SigninHref;
  256.    }
  257.  
  258.    protected $_RedirectUri = NULL;
  259.  
  260.    public function RedirectUri($NewValue = NULL) {
  261.       if ($NewValue !== NULL)
  262.          $this->_RedirectUri = $NewValue;
  263.       elseif ($this->_RedirectUri === NULL) {
  264.          $RedirectUri = Url('/entry/connect/facebook', TRUE);
  265.          if (strpos($RedirectUri, '=') !== FALSE) {
  266.             $p = strrchr($RedirectUri, '=');
  267.             $Uri = substr($RedirectUri, 0, -strlen($p));
  268.             $p = urlencode(ltrim($p, '='));
  269.             $RedirectUri = $Uri.'='.$p;
  270.          }
  271.  
  272.          $Path = Gdn::Request()->Path();
  273.  
  274.          $Target = GetValue('Target', $_GET, $Path ? $Path : '/');
  275.          if (ltrim($Target, '/') == 'entry/signin' || empty($Target))
  276.             $Target = '/';
  277.          $Args = array('Target' => $Target);
  278.  
  279.  
  280.          $RedirectUri .= strpos($RedirectUri, '?') === FALSE ? '?' : '&';
  281.          $RedirectUri .= http_build_query($Args);
  282.          $this->_RedirectUri = $RedirectUri;
  283.       }
  284.      
  285.       return $this->_RedirectUri;
  286.    }
  287.  
  288.    public function IsConfigured() {
  289.       $AppID = C('Plugins.Facebook.ApplicationID');
  290.       $Secret = C('Plugins.Facebook.Secret');
  291.       if (!$AppID || !$Secret)
  292.          return FALSE;
  293.       return TRUE;
  294.    }
  295.    
  296.    public function Setup() {
  297.       $Error = '';
  298.       if (!function_exists('curl_init'))
  299.          $Error = ConcatSep("\n", $Error, 'This plugin requires curl.');
  300.       if ($Error)
  301.          throw new Gdn_UserException($Error, 400);
  302.  
  303.       $this->Structure();
  304.    }
  305.  
  306.    public function Structure() {
  307.       // Save the facebook provider type.
  308.       Gdn::SQL()->Replace('UserAuthenticationProvider',
  309.          array('AuthenticationSchemeAlias' => 'facebook', 'URL' => '...', 'AssociationSecret' => '...', 'AssociationHashMethod' => '...'),
  310.          array('AuthenticationKey' => 'Facebook'), TRUE);
  311.    }
  312.  
  313.    public function OnDisable() {
  314.    }
  315.  
  316. //   public function OnDisable() {
  317. //      $this->_Disable();
  318. //   }
  319.  
  320. //   protected function _CreateProviderModel() {
  321. //      $Key = 'k'.sha1(implode('.',array(
  322. //         'vanillaconnect',
  323. //         'key',
  324. //         microtime(true),
  325. //         RandomString(16),
  326. //         Gdn::Session()->User->Name
  327. //      )));
  328. //
  329. //      $Secret = 's'.sha1(implode('.',array(
  330. //         'vanillaconnect',
  331. //         'secret',
  332. //         md5(microtime(true)),
  333. //         RandomString(16),
  334. //         Gdn::Session()->User->Name
  335. //      )));
  336. //
  337. //      $ProviderModel = new Gdn_AuthenticationProviderModel();
  338. //      $ProviderModel->Insert($Provider = array(
  339. //         'AuthenticationKey'           => $Key,
  340. //         'AuthenticationSchemeAlias'   => 'handshake',
  341. //         'URL'                         => 'Enter your site url',
  342. //         'AssociationSecret'           => $Secret,
  343. //         'AssociationHashMethod'       => 'HMAC-SHA1'
  344. //      ));
  345. //
  346. //      return $Provider;
  347. //   }
  348. //
  349. //   public function AuthenticationController_DisableAuthenticatorHandshake_Handler(&$Sender) {
  350. //      $this->_Disable();
  351. //   }
  352. //
  353. //   private function _Disable() {
  354. //      RemoveFromConfig('Plugins.VanillaConnect.Enabled');
  355. //      RemoveFromConfig('Garden.SignIn.Popup');
  356. //      RemoveFromConfig('Garden.Authenticator.DefaultScheme');
  357. //      RemoveFromConfig('Garden.Authenticators.handshake.Name');
  358. //      RemoveFromConfig('Garden.Authenticators.handshake.CookieName');
  359. //      RemoveFromConfig('Garden.Authenticators.handshake.TokenLifetime');
  360. //   }
  361. //
  362. //   public function AuthenticationController_EnableAuthenticatorHandshake_Handler(&$Sender) {
  363. //      $this->_Enable();
  364. //   }
  365. //
  366. //  private function _Enable($FullEnable = TRUE) {
  367. //      SaveToConfig('Garden.SignIn.Popup', FALSE);
  368. //      SaveToConfig('Garden.Authenticators.handshake.Name', 'VanillaConnect');
  369. //      SaveToConfig('Garden.Authenticators.handshake.CookieName', 'VanillaHandshake');
  370. //      SaveToConfig('Garden.Authenticators.handshake.TokenLifetime', 0);
  371. //
  372. //      if ($FullEnable) {
  373. //         SaveToConfig('Garden.Authenticator.DefaultScheme', 'handshake');
  374. //         SaveToConfig('Plugins.VanillaConnect.Enabled', TRUE);
  375. //      }
  376. //
  377. //      // Create a provider key/secret pair if needed
  378. //      $SQL = Gdn::Database()->SQL();
  379. //      $Provider = $SQL->Select('uap.*')
  380. //         ->From('UserAuthenticationProvider uap')
  381. //         ->Where('uap.AuthenticationSchemeAlias', 'handshake')
  382. //         ->Get()
  383. //         ->FirstRow(DATASET_TYPE_ARRAY);
  384. //
  385. //      if (!$Provider)
  386. //         $this->_CreateProviderModel();
  387. //  }
  388. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement