]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterauthorization.php
Merge branch '0.9.x' into pluginize-twitter-bridge
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitterauthorization.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Class for doing OAuth authentication against Twitter
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  TwitterauthorizationAction
23  * @package   StatusNet
24  * @author    Zach Copely <zach@status.net>
25  * @copyright 2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
31     exit(1);
32 }
33
34 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
35
36 /**
37  * Class for doing OAuth authentication against Twitter
38  *
39  * Peforms the OAuth "dance" between StatusNet and Twitter -- requests a token,
40  * authorizes it, and exchanges it for an access token.  It also creates a link
41  * (Foreign_link) between the StatusNet user and Twitter user and stores the
42  * access token and secret in the link.
43  *
44  * @category Twitter
45  * @package  StatusNet
46  * @author   Zach Copley <zach@status.net>
47  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
48  * @link     http://laconi.ca/
49  *
50  */
51 class TwitterauthorizationAction extends Action
52 {
53     /**
54      * Initialize class members. Looks for 'oauth_token' parameter.
55      *
56      * @param array $args misc. arguments
57      *
58      * @return boolean true
59      */
60     function prepare($args)
61     {
62         parent::prepare($args);
63
64         $this->oauth_token = $this->arg('oauth_token');
65
66         return true;
67     }
68
69     /**
70      * Handler method
71      *
72      * @param array $args is ignored since it's now passed in in prepare()
73      *
74      * @return nothing
75      */
76     function handle($args)
77     {
78         parent::handle($args);
79
80         if (!common_logged_in()) {
81             $this->clientError(_('Not logged in.'), 403);
82         }
83
84         $user  = common_current_user();
85         $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
86
87         // If there's already a foreign link record, it means we already
88         // have an access token, and this is unecessary. So go back.
89
90         if (isset($flink)) {
91             common_redirect(common_local_url('twittersettings'));
92         }
93
94         // $this->oauth_token is only populated once Twitter authorizes our
95         // request token. If it's empty we're at the beginning of the auth
96         // process
97
98         if (empty($this->oauth_token)) {
99             $this->authorizeRequestToken();
100         } else {
101             $this->saveAccessToken();
102         }
103     }
104
105     /**
106      * Asks Twitter for a request token, and then redirects to Twitter
107      * to authorize it.
108      *
109      * @return nothing
110      */
111     function authorizeRequestToken()
112     {
113         try {
114
115             // Get a new request token and authorize it
116
117             $client  = new TwitterOAuthClient();
118             $req_tok =
119               $client->getRequestToken(TwitterOAuthClient::$requestTokenURL);
120
121             // Sock the request token away in the session temporarily
122
123             $_SESSION['twitter_request_token']        = $req_tok->key;
124             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
125
126             $auth_link = $client->getAuthorizeLink($req_tok);
127
128         } catch (TwitterOAuthClientException $e) {
129             $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
130                            $e->getCode(), $e->getMessage());
131             $this->serverError(_('Couldn\'t link your Twitter account.'));
132         }
133
134         common_redirect($auth_link);
135     }
136
137     /**
138      * Called when Twitter returns an authorized request token. Exchanges
139      * it for an access token and stores it.
140      *
141      * @return nothing
142      */
143     function saveAccessToken()
144     {
145
146         // Check to make sure Twitter returned the same request
147         // token we sent them
148
149         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
150             $this->serverError(_('Couldn\'t link your Twitter account.'));
151         }
152
153         try {
154
155             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
156                 $_SESSION['twitter_request_token_secret']);
157
158             // Exchange the request token for an access token
159
160             $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL);
161
162             // Test the access token and get the user's Twitter info
163
164             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
165             $twitter_user = $client->verifyCredentials();
166
167         } catch (OAuthClientException $e) {
168             $msg = sprintf('OAuth client cURL error - code: %1$s, msg: %2$s',
169                            $e->getCode(), $e->getMessage());
170             $this->serverError(_('Couldn\'t link your Twitter account.'));
171         }
172
173         // Save the access token and Twitter user info
174
175         $this->saveForeignLink($atok, $twitter_user);
176
177         // Clean up the the mess we made in the session
178
179         unset($_SESSION['twitter_request_token']);
180         unset($_SESSION['twitter_request_token_secret']);
181
182         common_redirect(common_local_url('twittersettings'));
183     }
184
185     /**
186      * Saves a Foreign_link between Twitter user and local user,
187      * which includes the access token and secret.
188      *
189      * @param OAuthToken $access_token the access token to save
190      * @param mixed      $twitter_user twitter API user object
191      *
192      * @return nothing
193      */
194     function saveForeignLink($access_token, $twitter_user)
195     {
196         $user = common_current_user();
197
198         $flink = new Foreign_link();
199
200         $flink->user_id     = $user->id;
201         $flink->foreign_id  = $twitter_user->id;
202         $flink->service     = TWITTER_SERVICE;
203
204         $creds = TwitterOAuthClient::packToken($access_token);
205
206         $flink->credentials = $creds;
207         $flink->created     = common_sql_now();
208
209         // Defaults: noticesync on, everything else off
210
211         $flink->set_flags(true, false, false, false);
212
213         $flink_id = $flink->insert();
214
215         if (empty($flink_id)) {
216             common_log_db_error($flink, 'INSERT', __FILE__);
217                 $this->serverError(_('Couldn\'t link your Twitter account.'));
218         }
219
220         save_twitter_user($twitter_user->id, $twitter_user->screen_name);
221     }
222
223 }
224