]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/twitterauthorization.php
change Laconica and Control Yourself to StatusNet in PHP files
[quix0rs-gnu-social.git] / actions / 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@controlyourself.ca>
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://laconi.ca/
28  */
29
30 if (!defined('LACONICA')) {
31     exit(1);
32 }
33
34 class TwitterauthorizationAction extends Action
35 {
36
37     function prepare($args)
38     {
39         parent::prepare($args);
40
41         $this->oauth_token = $this->arg('oauth_token');
42
43         return true;
44     }
45
46     /**
47      * Handler method
48      *
49      * @param array $args is ignored since it's now passed in in prepare()
50      *
51      * @return nothing
52      */
53     function handle($args)
54     {
55         parent::handle($args);
56
57         if (!common_logged_in()) {
58             $this->clientError(_('Not logged in.'), 403);
59         }
60
61         $user  = common_current_user();
62         $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
63
64         // If there's already a foreign link record, it means we already
65         // have an access token, and this is unecessary. So go back.
66
67         if (isset($flink)) {
68             common_redirect(common_local_url('twittersettings'));
69         }
70
71         // $this->oauth_token is only populated once Twitter authorizes our
72         // request token. If it's empty we're at the beginning of the auth
73         // process
74
75         if (empty($this->oauth_token)) {
76             $this->authorizeRequestToken();
77         } else {
78             $this->saveAccessToken();
79         }
80     }
81
82     /**
83      * Asks Twitter for a request token, and then redirects to Twitter
84      * to authorize it.
85      *
86      * @return nothing
87      */
88     function authorizeRequestToken()
89     {
90         try {
91
92             // Get a new request token and authorize it
93
94             $client  = new TwitterOAuthClient();
95             $req_tok =
96               $client->getRequestToken(TwitterOAuthClient::$requestTokenURL);
97
98             // Sock the request token away in the session temporarily
99
100             $_SESSION['twitter_request_token']        = $req_tok->key;
101             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
102
103             $auth_link = $client->getAuthorizeLink($req_tok);
104
105         } catch (TwitterOAuthClientException $e) {
106             $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
107                            $e->getCode(), $e->getMessage());
108             $this->serverError(_('Couldn\'t link your Twitter account.'));
109         }
110
111         common_redirect($auth_link);
112     }
113
114     /**
115      * Called when Twitter returns an authorized request token. Exchanges
116      * it for an access token and stores it.
117      *
118      * @return nothing
119      */
120     function saveAccessToken()
121     {
122
123         // Check to make sure Twitter returned the same request
124         // token we sent them
125
126         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
127             $this->serverError(_('Couldn\'t link your Twitter account.'));
128         }
129
130         try {
131
132             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
133                 $_SESSION['twitter_request_token_secret']);
134
135             // Exchange the request token for an access token
136
137             $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL);
138
139             // Test the access token and get the user's Twitter info
140
141             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
142             $twitter_user = $client->verifyCredentials();
143
144         } catch (OAuthClientException $e) {
145             $msg = sprintf('OAuth client cURL error - code: %1$s, msg: %2$s',
146                            $e->getCode(), $e->getMessage());
147             $this->serverError(_('Couldn\'t link your Twitter account.'));
148         }
149
150         // Save the access token and Twitter user info
151
152         $this->saveForeignLink($atok, $twitter_user);
153
154         // Clean up the the mess we made in the session
155
156         unset($_SESSION['twitter_request_token']);
157         unset($_SESSION['twitter_request_token_secret']);
158
159         common_redirect(common_local_url('twittersettings'));
160     }
161
162     /**
163      * Saves a Foreign_link between Twitter user and local user,
164      * which includes the access token and secret.
165      *
166      * @param OAuthToken $access_token the access token to save
167      * @param mixed      $twitter_user twitter API user object
168      *
169      * @return nothing
170      */
171     function saveForeignLink($access_token, $twitter_user)
172     {
173         $user = common_current_user();
174
175         $flink = new Foreign_link();
176
177         $flink->user_id     = $user->id;
178         $flink->foreign_id  = $twitter_user->id;
179         $flink->service     = TWITTER_SERVICE;
180
181         $creds = TwitterOAuthClient::packToken($access_token);
182
183         $flink->credentials = $creds;
184         $flink->created     = common_sql_now();
185
186         // Defaults: noticesync on, everything else off
187
188         $flink->set_flags(true, false, false, false);
189
190         $flink_id = $flink->insert();
191
192         if (empty($flink_id)) {
193             common_log_db_error($flink, 'INSERT', __FILE__);
194                 $this->serverError(_('Couldn\'t link your Twitter account.'));
195         }
196
197         save_twitter_user($twitter_user->id, $twitter_user->screen_name);
198     }
199
200 }
201