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 dirname(__DIR__) . '/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://status.net/
53 class TwitterauthorizationAction extends Action
56 var $tw_fields = null;
57 var $access_token = null;
62 * Initialize class members. Looks for 'oauth_token' parameter.
64 * @param array $args misc. arguments
66 * @return boolean true
68 function prepare(array $args=array())
70 parent::prepare($args);
72 $this->signin = $this->boolean('signin');
73 $this->oauth_token = $this->arg('oauth_token');
74 $this->verifier = $this->arg('oauth_verifier');
82 * @param array $args is ignored since it's now passed in in prepare()
86 function handle(array $args=array())
88 parent::handle($args);
90 if (common_logged_in()) {
91 $user = common_current_user();
92 $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
94 // If there's already a foreign link record and a foreign user
95 // it means the accounts are already linked, and this is unecessary.
99 $fuser = $flink->getForeignUser();
100 if (!empty($fuser)) {
101 common_redirect(common_local_url('twittersettings'));
106 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
108 // User was not logged in to StatusNet before
110 $this->twuid = $this->trimmed('twuid');
112 $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
113 'fullname' => $this->trimmed('tw_fields_fullname'));
115 $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
117 $token = $this->trimmed('token');
119 if (!$token || $token != common_session_token()) {
120 // TRANS: Client error displayed when the session token does not match or is not given.
121 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
125 if ($this->arg('create')) {
126 if (!$this->boolean('license')) {
127 // TRANS: Form validation error displayed when the checkbox to agree to the license has not been checked.
128 $this->showForm(_m('You cannot register if you do not agree to the license.'),
129 $this->trimmed('newname'));
132 $this->createNewUser();
133 } else if ($this->arg('connect')) {
134 $this->connectNewUser();
136 common_debug('Twitter bridge - ' . print_r($this->args, true));
137 // TRANS: Form validation error displayed when an unhandled error occurs.
138 $this->showForm(_m('Something weird happened.'),
139 $this->trimmed('newname'));
142 // $this->oauth_token is only populated once Twitter authorizes our
143 // request token. If it's empty we're at the beginning of the auth
146 if (empty($this->oauth_token)) {
147 $this->authorizeRequestToken();
149 $this->saveAccessToken();
155 * Asks Twitter for a request token, and then redirects to Twitter
160 function authorizeRequestToken()
163 // Get a new request token and authorize it
165 $client = new TwitterOAuthClient();
166 $req_tok = $client->getRequestToken();
168 // Sock the request token away in the session temporarily
170 $_SESSION['twitter_request_token'] = $req_tok->key;
171 $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
173 $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
174 } catch (OAuthClientException $e) {
176 'OAuth client error - code: %1s, msg: %2s',
180 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
182 // TRANS: Server error displayed when linking to a Twitter account fails.
183 _m('Could not link your Twitter account.')
187 common_redirect($auth_link);
191 * Called when Twitter returns an authorized request token. Exchanges
192 * it for an access token and stores it.
196 function saveAccessToken()
198 // Check to make sure Twitter returned the same request
199 // token we sent them
201 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
203 // TRANS: Server error displayed when linking to a Twitter account fails because of an incorrect oauth_token.
204 _m('Could not link your Twitter account: oauth_token mismatch.')
208 $twitter_user = null;
212 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
213 $_SESSION['twitter_request_token_secret']);
215 // Exchange the request token for an access token
217 $atok = $client->getAccessToken($this->verifier);
219 // Test the access token and get the user's Twitter info
221 $client = new TwitterOAuthClient($atok->key, $atok->secret);
222 $twitter_user = $client->verifyCredentials();
224 } catch (OAuthClientException $e) {
226 'OAuth client error - code: %1$s, msg: %2$s',
230 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
232 // TRANS: Server error displayed when linking to a Twitter account fails.
233 _m('Could not link your Twitter account.')
237 if (common_logged_in()) {
238 // Save the access token and Twitter user info
240 $user = common_current_user();
241 $this->saveForeignLink($user->id, $twitter_user->id, $atok);
242 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
246 $this->twuid = $twitter_user->id;
247 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
248 "fullname" => $twitter_user->name);
249 $this->access_token = $atok;
253 // Clean up the the mess we made in the session
255 unset($_SESSION['twitter_request_token']);
256 unset($_SESSION['twitter_request_token_secret']);
258 if (common_logged_in()) {
259 common_redirect(common_local_url('twittersettings'));
264 * Saves a Foreign_link between Twitter user and local user,
265 * which includes the access token and secret.
267 * @param int $user_id StatusNet user ID
268 * @param int $twuid Twitter user ID
269 * @param OAuthToken $token the access token to save
273 function saveForeignLink($user_id, $twuid, $access_token)
275 $flink = new Foreign_link();
277 $flink->user_id = $user_id;
278 $flink->service = TWITTER_SERVICE;
280 // delete stale flink, if any
281 $result = $flink->find(true);
283 if (!empty($result)) {
284 $flink->safeDelete();
287 $flink->user_id = $user_id;
288 $flink->foreign_id = $twuid;
289 $flink->service = TWITTER_SERVICE;
291 $creds = TwitterOAuthClient::packToken($access_token);
293 $flink->credentials = $creds;
294 $flink->created = common_sql_now();
296 // Defaults: noticesync on, everything else off
298 $flink->set_flags(true, false, false, false);
300 $flink_id = $flink->insert();
302 if (empty($flink_id)) {
303 common_log_db_error($flink, 'INSERT', __FILE__);
304 // TRANS: Server error displayed when linking to a Twitter account fails.
305 $this->serverError(_m('Could not link your Twitter account.'));
311 function showPageNotice()
314 $this->element('div', array('class' => 'error'), $this->error);
316 $this->element('div', 'instructions',
317 // TRANS: Page instruction. %s is the StatusNet sitename.
318 sprintf(_m('This is the first time you have 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')));
324 // TRANS: Page title.
325 return _m('Twitter Account Setup');
328 function showForm($error=null, $username=null)
330 $this->error = $error;
331 $this->username = $username;
342 * @fixme much of this duplicates core code, which is very fragile.
343 * Should probably be replaced with an extensible mini version of
344 * the core registration form.
346 function showContent()
348 if (!empty($this->message_text)) {
349 $this->element('p', null, $this->message);
353 $this->elementStart('form', array('method' => 'post',
354 'id' => 'form_settings_twitter_connect',
355 'class' => 'form_settings',
356 'action' => common_local_url('twitterauthorization')));
357 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
358 // TRANS: Fieldset legend.
359 $this->element('legend', null, _m('Connection options'));
361 $this->hidden('access_token_key', $this->access_token->key);
362 $this->hidden('access_token_secret', $this->access_token->secret);
363 $this->hidden('twuid', $this->twuid);
364 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
365 $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
366 $this->hidden('token', common_session_token());
368 // Don't allow new account creation if site is flagged as invite only
369 if (common_config('site', 'inviteonly') == false) {
370 $this->elementStart('fieldset');
371 $this->element('legend', null,
372 // TRANS: Fieldset legend.
373 _m('Create new account'));
374 $this->element('p', null,
375 // TRANS: Sub form introduction text.
376 _m('Create a new user with this nickname.'));
377 $this->elementStart('ul', 'form_data');
379 // Hook point for captcha etc
380 Event::handle('StartRegistrationFormData', array($this));
382 $this->elementStart('li');
383 // TRANS: Field label.
384 $this->input('newname', _m('New nickname'),
385 ($this->username) ? $this->username : '',
386 // TRANS: Field title for nickname field.
387 _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
388 $this->elementEnd('li');
389 $this->elementStart('li');
390 // TRANS: Field label.
391 $this->input('email', _m('LABEL','Email'), $this->getEmail(),
392 // TRANS: Field title for e-mail address field.
393 _m('Used only for updates, announcements, '.
394 'and password recovery'));
395 $this->elementEnd('li');
397 // Hook point for captcha etc
398 Event::handle('EndRegistrationFormData', array($this));
400 $this->elementEnd('ul');
401 // TRANS: Button text for creating a new StatusNet account in the Twitter connect page.
402 $this->submit('create', _m('BUTTON','Create'));
403 $this->elementEnd('fieldset');
406 $this->elementStart('fieldset');
407 $this->element('legend', null,
408 // TRANS: Fieldset legend.
409 _m('Connect existing account'));
410 $this->element('p', null,
411 // TRANS: Sub form introduction text.
412 _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
413 $this->elementStart('ul', 'form_data');
414 $this->elementStart('li');
415 // TRANS: Field label.
416 $this->input('nickname', _m('Existing nickname'));
417 $this->elementEnd('li');
418 $this->elementStart('li');
419 // TRANS: Field label.
420 $this->password('password', _m('Password'));
421 $this->elementEnd('li');
422 $this->elementEnd('ul');
423 $this->elementEnd('fieldset');
425 $this->elementStart('fieldset');
426 $this->element('legend', null,
427 // TRANS: Fieldset legend.
429 $this->elementStart('ul', 'form_data');
430 $this->elementStart('li');
431 $this->element('input', array('type' => 'checkbox',
433 'class' => 'checkbox',
436 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
437 // TRANS: Text for license agreement checkbox.
438 // TRANS: %s is the license as configured for the StatusNet site.
439 $message = _m('My text and files are available under %s ' .
440 'except this private data: password, ' .
441 'email address, IM address, and phone number.');
442 $link = '<a href="' .
443 htmlspecialchars(common_config('license', 'url')) .
445 htmlspecialchars(common_config('license', 'title')) .
447 $this->raw(sprintf(htmlspecialchars($message), $link));
448 $this->elementEnd('label');
449 $this->elementEnd('li');
450 $this->elementEnd('ul');
451 $this->elementEnd('fieldset');
452 // TRANS: Button text for connecting an existing StatusNet account in the Twitter connect page..
453 $this->submit('connect', _m('BUTTON','Connect'));
454 $this->elementEnd('fieldset');
455 $this->elementEnd('form');
459 * Get specified e-mail from the form, or the invite code.
465 $email = $this->trimmed('email');
466 if (!empty($email)) {
470 // Terrible hack for invites...
471 if (common_config('site', 'inviteonly')) {
472 $code = $_SESSION['invitecode'];
474 $invite = Invitation::getKV($code);
476 if ($invite && $invite->address_type == 'email') {
477 return $invite->address;
484 function message($msg)
486 $this->message_text = $msg;
490 function createNewUser()
492 if (!Event::handle('StartRegistrationTry', array($this))) {
496 if (common_config('site', 'closed')) {
497 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
498 $this->clientError(_m('Registration not allowed.'));
503 if (common_config('site', 'inviteonly')) {
504 $code = $_SESSION['invitecode'];
506 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
507 $this->clientError(_m('Registration not allowed.'));
510 $invite = Invitation::getKV($code);
512 if (empty($invite)) {
513 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
514 $this->clientError(_m('Not a valid invitation code.'));
519 $nickname = Nickname::normalize($this->trimmed('newname'), true);
520 } catch (NicknameException $e) {
521 $this->showForm($e->getMessage());
525 $fullname = trim($this->tw_fields['fullname']);
527 $args = array('nickname' => $nickname, 'fullname' => $fullname);
529 if (!empty($invite)) {
530 $args['code'] = $invite->code;
533 $email = $this->getEmail();
534 if (!empty($email)) {
535 $args['email'] = $email;
538 $user = User::register($args);
541 // TRANS: Server error displayed when creating a new user has failed.
542 $this->serverError(_m('Error registering user.'));
545 $result = $this->saveForeignLink($user->id,
547 $this->access_token);
549 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
552 // TRANS: Server error displayed when connecting a user to a Twitter user has failed.
553 $this->serverError(_m('Error connecting user to Twitter.'));
556 common_set_user($user);
557 common_real_login(true);
559 common_debug('TwitterBridge Plugin - ' .
560 "Registered new user $user->id from Twitter user $this->twuid");
562 Event::handle('EndRegistrationTry', array($this));
564 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)), 303);
567 function connectNewUser()
569 $nickname = $this->trimmed('nickname');
570 $password = $this->trimmed('password');
572 if (!common_check_user($nickname, $password)) {
573 // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
574 // TRANS: the provided username and/or password are incorrect.
575 $this->showForm(_m('Invalid username or password.'));
579 $user = User::getKV('nickname', $nickname);
582 common_debug('TwitterBridge Plugin - ' .
583 "Legit user to connect to Twitter: $nickname");
586 $result = $this->saveForeignLink($user->id,
588 $this->access_token);
590 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
593 // TRANS: Server error displayed connecting a user to a Twitter user has failed.
594 $this->serverError(_m('Error connecting user to Twitter.'));
597 common_debug('TwitterBridge Plugin - ' .
598 "Connected Twitter user $this->twuid to local user $user->id");
600 common_set_user($user);
601 common_real_login(true);
603 $this->goHome($user->nickname);
606 function connectUser()
608 $user = common_current_user();
610 $result = $this->flinkUser($user->id, $this->twuid);
612 if (empty($result)) {
613 // TRANS: Server error displayed connecting a user to a Twitter user has failed.
614 $this->serverError(_m('Error connecting user to Twitter.'));
617 common_debug('TwitterBridge Plugin - ' .
618 "Connected Twitter user $this->twuid to local user $user->id");
620 // Return to Twitter connection settings tab
621 common_redirect(common_local_url('twittersettings'), 303);
626 common_debug('TwitterBridge Plugin - ' .
627 "Trying login for Twitter user $this->twuid.");
629 $flink = Foreign_link::getByForeignID($this->twuid,
632 if (!empty($flink)) {
633 $user = $flink->getUser();
637 common_debug('TwitterBridge Plugin - ' .
638 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
640 common_set_user($user);
641 common_real_login(true);
642 $this->goHome($user->nickname);
647 common_debug('TwitterBridge Plugin - ' .
648 "No flink found for twuid: $this->twuid - new user");
650 $this->showForm(null, $this->bestNewNickname());
654 function goHome($nickname)
656 $url = common_get_returnto();
658 // We don't have to return to it again
659 common_set_returnto(null);
661 $url = common_local_url('all',
666 common_redirect($url, 303);
669 function bestNewNickname()
672 return Nickname::normalize($this->tw_fields['fullname'], true);
673 } catch (NicknameException $e) {