3 * StatusNet, the distributed open-source microblogging tool
5 * Class for doing OAuth authentication against Twitter
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.
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.
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/>.
24 * @author Zach Copley <zach@status.net>
25 * @author Julien C <chaumond@gmail.com>
26 * @copyright 2009-2010 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28 * @link http://status.net/
31 if (!defined('STATUSNET') && !defined('LACONICA')) {
35 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
38 * Class for doing OAuth authentication against Twitter
40 * Peforms the OAuth "dance" between StatusNet and Twitter -- requests a token,
41 * authorizes it, and exchanges it for an access token. It also creates a link
42 * (Foreign_link) between the StatusNet user and Twitter user and stores the
43 * access token and secret in the link.
47 * @author Zach Copley <zach@status.net>
48 * @author Julien C <chaumond@gmail.com>
49 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
50 * @link http://laconi.ca/
53 class TwitterauthorizationAction extends Action
56 var $tw_fields = null;
57 var $access_token = null;
61 * Initialize class members. Looks for 'oauth_token' parameter.
63 * @param array $args misc. arguments
65 * @return boolean true
67 function prepare($args)
69 parent::prepare($args);
71 $this->signin = $this->boolean('signin');
72 $this->oauth_token = $this->arg('oauth_token');
80 * @param array $args is ignored since it's now passed in in prepare()
84 function handle($args)
86 parent::handle($args);
88 if (common_logged_in()) {
89 $user = common_current_user();
90 $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
92 // If there's already a foreign link record, it means we already
93 // have an access token, and this is unecessary. So go back.
96 common_redirect(common_local_url('twittersettings'));
100 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
102 // User was not logged in to StatusNet before
104 $this->twuid = $this->trimmed('twuid');
106 $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
107 'fullname' => $this->trimmed('tw_fields_fullname'));
109 $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
111 $token = $this->trimmed('token');
113 if (!$token || $token != common_session_token()) {
114 $this->showForm(_('There was a problem with your session token. Try again, please.'));
118 if ($this->arg('create')) {
119 if (!$this->boolean('license')) {
120 $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
121 $this->trimmed('newname'));
124 $this->createNewUser();
125 } else if ($this->arg('connect')) {
126 $this->connectNewUser();
128 common_debug('Twitter Connect Plugin - ' .
129 print_r($this->args, true));
130 $this->showForm(_('Something weird happened.'),
131 $this->trimmed('newname'));
134 // $this->oauth_token is only populated once Twitter authorizes our
135 // request token. If it's empty we're at the beginning of the auth
138 if (empty($this->oauth_token)) {
139 $this->authorizeRequestToken();
141 $this->saveAccessToken();
147 * Asks Twitter for a request token, and then redirects to Twitter
152 function authorizeRequestToken()
156 // Get a new request token and authorize it
158 $client = new TwitterOAuthClient();
160 $client->getRequestToken(TwitterOAuthClient::$requestTokenURL);
162 // Sock the request token away in the session temporarily
164 $_SESSION['twitter_request_token'] = $req_tok->key;
165 $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
167 $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
169 } catch (OAuthClientException $e) {
170 $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
171 $e->getCode(), $e->getMessage());
172 $this->serverError(_m('Couldn\'t link your Twitter account.'));
175 common_redirect($auth_link);
179 * Called when Twitter returns an authorized request token. Exchanges
180 * it for an access token and stores it.
184 function saveAccessToken()
187 // Check to make sure Twitter returned the same request
188 // token we sent them
190 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
191 $this->serverError(_m('Couldn\'t link your Twitter account.'));
194 $twitter_user = null;
198 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
199 $_SESSION['twitter_request_token_secret']);
201 // Exchange the request token for an access token
203 $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL);
205 // Test the access token and get the user's Twitter info
207 $client = new TwitterOAuthClient($atok->key, $atok->secret);
208 $twitter_user = $client->verifyCredentials();
210 } catch (OAuthClientException $e) {
211 $msg = sprintf('OAuth client error - code: %1$s, msg: %2$s',
212 $e->getCode(), $e->getMessage());
213 $this->serverError(_m('Couldn\'t link your Twitter account.'));
216 if (common_logged_in()) {
218 // Save the access token and Twitter user info
220 $user = common_current_user();
221 $this->saveForeignLink($user->id, $twitter_user->id, $atok);
222 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
226 $this->twuid = $twitter_user->id;
227 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
228 "name" => $twitter_user->name);
229 $this->access_token = $atok;
233 // Clean up the the mess we made in the session
235 unset($_SESSION['twitter_request_token']);
236 unset($_SESSION['twitter_request_token_secret']);
238 if (common_logged_in()) {
239 common_redirect(common_local_url('twittersettings'));
244 * Saves a Foreign_link between Twitter user and local user,
245 * which includes the access token and secret.
247 * @param int $user_id StatusNet user ID
248 * @param int $twuid Twitter user ID
249 * @param OAuthToken $token the access token to save
253 function saveForeignLink($user_id, $twuid, $access_token)
255 $flink = new Foreign_link();
257 $flink->user_id = $user_id;
258 $flink->foreign_id = $twuid;
259 $flink->service = TWITTER_SERVICE;
261 $creds = TwitterOAuthClient::packToken($access_token);
263 $flink->credentials = $creds;
264 $flink->created = common_sql_now();
266 // Defaults: noticesync on, everything else off
268 $flink->set_flags(true, false, false, false);
270 $flink_id = $flink->insert();
272 if (empty($flink_id)) {
273 common_log_db_error($flink, 'INSERT', __FILE__);
274 $this->serverError(_('Couldn\'t link your Twitter account.'));
280 function showPageNotice()
283 $this->element('div', array('class' => 'error'), $this->error);
285 $this->element('div', 'instructions',
286 sprintf(_('This is the first time you\'ve logged into %s so we must connect your Twitter account to a local account. You can either create a new account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
292 return _('Twitter Account Setup');
295 function showForm($error=null, $username=null)
297 $this->error = $error;
298 $this->username = $username;
308 function showContent()
310 if (!empty($this->message_text)) {
311 $this->element('p', null, $this->message);
315 $this->elementStart('form', array('method' => 'post',
316 'id' => 'form_settings_twitter_connect',
317 'class' => 'form_settings',
318 'action' => common_local_url('twitterauthorization')));
319 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
320 $this->element('legend', null, _('Connection options'));
321 $this->elementStart('ul', 'form_data');
322 $this->elementStart('li');
323 $this->element('input', array('type' => 'checkbox',
325 'class' => 'checkbox',
328 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
329 $this->text(_('My text and files are available under '));
330 $this->element('a', array('href' => common_config('license', 'url')),
331 common_config('license', 'title'));
332 $this->text(_(' except this private data: password, email address, IM address, phone number.'));
333 $this->elementEnd('label');
334 $this->elementEnd('li');
335 $this->elementEnd('ul');
336 $this->hidden('access_token_key', $this->access_token->key);
337 $this->hidden('access_token_secret', $this->access_token->secret);
338 $this->hidden('twuid', $this->twuid);
339 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
340 $this->hidden('tw_fields_name', $this->tw_fields['name']);
342 $this->elementStart('fieldset');
343 $this->hidden('token', common_session_token());
344 $this->element('legend', null,
345 _('Create new account'));
346 $this->element('p', null,
347 _('Create a new user with this nickname.'));
348 $this->elementStart('ul', 'form_data');
349 $this->elementStart('li');
350 $this->input('newname', _('New nickname'),
351 ($this->username) ? $this->username : '',
352 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
353 $this->elementEnd('li');
354 $this->elementEnd('ul');
355 $this->submit('create', _('Create'));
356 $this->elementEnd('fieldset');
358 $this->elementStart('fieldset');
359 $this->element('legend', null,
360 _('Connect existing account'));
361 $this->element('p', null,
362 _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
363 $this->elementStart('ul', 'form_data');
364 $this->elementStart('li');
365 $this->input('nickname', _('Existing nickname'));
366 $this->elementEnd('li');
367 $this->elementStart('li');
368 $this->password('password', _('Password'));
369 $this->elementEnd('li');
370 $this->elementEnd('ul');
371 $this->submit('connect', _('Connect'));
372 $this->elementEnd('fieldset');
374 $this->elementEnd('fieldset');
375 $this->elementEnd('form');
378 function message($msg)
380 $this->message_text = $msg;
384 function createNewUser()
386 if (common_config('site', 'closed')) {
387 $this->clientError(_('Registration not allowed.'));
393 if (common_config('site', 'inviteonly')) {
394 $code = $_SESSION['invitecode'];
396 $this->clientError(_('Registration not allowed.'));
400 $invite = Invitation::staticGet($code);
402 if (empty($invite)) {
403 $this->clientError(_('Not a valid invitation code.'));
408 $nickname = $this->trimmed('newname');
410 if (!Validate::string($nickname, array('min_length' => 1,
412 'format' => NICKNAME_FMT))) {
413 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
417 if (!User::allowed_nickname($nickname)) {
418 $this->showForm(_('Nickname not allowed.'));
422 if (User::staticGet('nickname', $nickname)) {
423 $this->showForm(_('Nickname already in use. Try another one.'));
427 $fullname = trim($this->tw_fields['name']);
429 $args = array('nickname' => $nickname, 'fullname' => $fullname);
431 if (!empty($invite)) {
432 $args['code'] = $invite->code;
435 $user = User::register($args);
437 $result = $this->saveForeignLink($user->id,
439 $this->access_token);
441 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
444 $this->serverError(_('Error connecting user to Twitter.'));
448 common_set_user($user);
449 common_real_login(true);
451 common_debug('TwitterBridge Plugin - ' .
452 "Registered new user $user->id from Twitter user $this->twuid");
454 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
458 function connectNewUser()
460 $nickname = $this->trimmed('nickname');
461 $password = $this->trimmed('password');
463 if (!common_check_user($nickname, $password)) {
464 $this->showForm(_('Invalid username or password.'));
468 $user = User::staticGet('nickname', $nickname);
471 common_debug('TwitterBridge Plugin - ' .
472 "Legit user to connect to Twitter: $nickname");
475 $result = $this->saveForeignLink($user->id,
477 $this->access_token);
479 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
482 $this->serverError(_('Error connecting user to Twitter.'));
486 common_debug('TwitterBridge Plugin - ' .
487 "Connected Twitter user $this->twuid to local user $user->id");
489 common_set_user($user);
490 common_real_login(true);
492 $this->goHome($user->nickname);
495 function connectUser()
497 $user = common_current_user();
499 $result = $this->flinkUser($user->id, $this->twuid);
501 if (empty($result)) {
502 $this->serverError(_('Error connecting user to Twitter.'));
506 common_debug('TwitterBridge Plugin - ' .
507 "Connected Twitter user $this->twuid to local user $user->id");
509 // Return to Twitter connection settings tab
510 common_redirect(common_local_url('twittersettings'), 303);
515 common_debug('TwitterBridge Plugin - ' .
516 "Trying login for Twitter user $this->twuid.");
518 $flink = Foreign_link::getByForeignID($this->twuid,
521 if (!empty($flink)) {
522 $user = $flink->getUser();
526 common_debug('TwitterBridge Plugin - ' .
527 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
529 common_set_user($user);
530 common_real_login(true);
531 $this->goHome($user->nickname);
536 common_debug('TwitterBridge Plugin - ' .
537 "No flink found for twuid: $this->twuid - new user");
539 $this->showForm(null, $this->bestNewNickname());
543 function goHome($nickname)
545 $url = common_get_returnto();
547 // We don't have to return to it again
548 common_set_returnto(null);
550 $url = common_local_url('all',
555 common_redirect($url, 303);
558 function bestNewNickname()
560 if (!empty($this->tw_fields['name'])) {
561 $nickname = $this->nicknamize($this->tw_fields['name']);
562 if ($this->isNewNickname($nickname)) {
570 // Given a string, try to make it work as a nickname
572 function nicknamize($str)
574 $str = preg_replace('/\W/', '', $str);
575 $str = str_replace(array('-', '_'), '', $str);
576 return strtolower($str);
579 function isNewNickname($str)
581 if (!Validate::string($str, array('min_length' => 1,
583 'format' => NICKNAME_FMT))) {
586 if (!User::allowed_nickname($str)) {
589 if (User::staticGet('nickname', $str)) {