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://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($args)
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($args)
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'));
360 $this->elementStart('ul', 'form_data');
361 $this->elementStart('li');
362 $this->element('input', array('type' => 'checkbox',
364 'class' => 'checkbox',
367 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
368 // TRANS: Text for license agreement checkbox.
369 // TRANS: %s is the license as configured for the StatusNet site.
370 $message = _m('My text and files are available under %s ' .
371 'except this private data: password, ' .
372 'email address, IM address, and phone number.');
373 $link = '<a href="' .
374 htmlspecialchars(common_config('license', 'url')) .
376 htmlspecialchars(common_config('license', 'title')) .
378 $this->raw(sprintf(htmlspecialchars($message), $link));
379 $this->elementEnd('label');
380 $this->elementEnd('li');
381 $this->elementEnd('ul');
382 $this->hidden('access_token_key', $this->access_token->key);
383 $this->hidden('access_token_secret', $this->access_token->secret);
384 $this->hidden('twuid', $this->twuid);
385 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
386 $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
388 $this->elementStart('fieldset');
389 $this->hidden('token', common_session_token());
390 $this->element('legend', null,
391 // TRANS: Fieldset legend.
392 _m('Create new account'));
393 $this->element('p', null,
394 // TRANS: Sub form introduction text.
395 _m('Create a new user with this nickname.'));
396 $this->elementStart('ul', 'form_data');
398 // Hook point for captcha etc
399 Event::handle('StartRegistrationFormData', array($this));
401 $this->elementStart('li');
402 // TRANS: Field label.
403 $this->input('newname', _m('New nickname'),
404 ($this->username) ? $this->username : '',
405 // TRANS: Field title for nickname field.
406 _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
407 $this->elementEnd('li');
408 $this->elementStart('li');
409 // TRANS: Field label.
410 $this->input('email', _m('LABEL','Email'), $this->getEmail(),
411 // TRANS: Field title for e-mail address field.
412 _m('Used only for updates, announcements, '.
413 'and password recovery'));
414 $this->elementEnd('li');
416 // Hook point for captcha etc
417 Event::handle('EndRegistrationFormData', array($this));
419 $this->elementEnd('ul');
420 // TRANS: Button text for creating a new StatusNet account in the Twitter connect page.
421 $this->submit('create', _m('BUTTON','Create'));
422 $this->elementEnd('fieldset');
424 $this->elementStart('fieldset');
425 $this->element('legend', null,
426 // TRANS: Fieldset legend.
427 _m('Connect existing account'));
428 $this->element('p', null,
429 // TRANS: Sub form introduction text.
430 _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
431 $this->elementStart('ul', 'form_data');
432 $this->elementStart('li');
433 // TRANS: Field label.
434 $this->input('nickname', _m('Existing nickname'));
435 $this->elementEnd('li');
436 $this->elementStart('li');
437 // TRANS: Field label.
438 $this->password('password', _m('Password'));
439 $this->elementEnd('li');
440 $this->elementEnd('ul');
441 // TRANS: Button text for connecting an existing StatusNet account in the Twitter connect page..
442 $this->submit('connect', _m('BUTTON','Connect'));
443 $this->elementEnd('fieldset');
445 $this->elementEnd('fieldset');
446 $this->elementEnd('form');
450 * Get specified e-mail from the form, or the invite code.
456 $email = $this->trimmed('email');
457 if (!empty($email)) {
461 // Terrible hack for invites...
462 if (common_config('site', 'inviteonly')) {
463 $code = $_SESSION['invitecode'];
465 $invite = Invitation::staticGet($code);
467 if ($invite && $invite->address_type == 'email') {
468 return $invite->address;
475 function message($msg)
477 $this->message_text = $msg;
481 function createNewUser()
483 if (!Event::handle('StartRegistrationTry', array($this))) {
487 if (common_config('site', 'closed')) {
488 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
489 $this->clientError(_m('Registration not allowed.'));
495 if (common_config('site', 'inviteonly')) {
496 $code = $_SESSION['invitecode'];
498 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
499 $this->clientError(_m('Registration not allowed.'));
503 $invite = Invitation::staticGet($code);
505 if (empty($invite)) {
506 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
507 $this->clientError(_m('Not a valid invitation code.'));
513 $nickname = Nickname::normalize($this->trimmed('newname'));
514 } catch (NicknameException $e) {
515 $this->showForm($e->getMessage());
519 if (!User::allowed_nickname($nickname)) {
520 // TRANS: Client error displayed when trying to create a new user with an invalid username.
521 $this->showForm(_m('Nickname not allowed.'));
525 if (User::staticGet('nickname', $nickname)) {
526 // TRANS: Client error displayed when trying to create a new user with a username that is already in use.
527 $this->showForm(_m('Nickname already in use. Try another one.'));
531 $fullname = trim($this->tw_fields['fullname']);
533 $args = array('nickname' => $nickname, 'fullname' => $fullname);
535 if (!empty($invite)) {
536 $args['code'] = $invite->code;
539 $email = $this->getEmail();
540 if (!empty($email)) {
541 $args['email'] = $email;
544 $user = User::register($args);
547 // TRANS: Server error displayed when creating a new user has failed.
548 $this->serverError(_m('Error registering user.'));
552 $result = $this->saveForeignLink($user->id,
554 $this->access_token);
556 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
559 // TRANS: Server error displayed when connecting a user to a Twitter user has failed.
560 $this->serverError(_m('Error connecting user to Twitter.'));
564 common_set_user($user);
565 common_real_login(true);
567 common_debug('TwitterBridge Plugin - ' .
568 "Registered new user $user->id from Twitter user $this->twuid");
570 Event::handle('EndRegistrationTry', array($this));
572 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
576 function connectNewUser()
578 $nickname = $this->trimmed('nickname');
579 $password = $this->trimmed('password');
581 if (!common_check_user($nickname, $password)) {
582 // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
583 // TRANS: the provided username and/or password are incorrect.
584 $this->showForm(_m('Invalid username or password.'));
588 $user = User::staticGet('nickname', $nickname);
591 common_debug('TwitterBridge Plugin - ' .
592 "Legit user to connect to Twitter: $nickname");
595 $result = $this->saveForeignLink($user->id,
597 $this->access_token);
599 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
602 // TRANS: Server error displayed connecting a user to a Twitter user has failed.
603 $this->serverError(_m('Error connecting user to Twitter.'));
607 common_debug('TwitterBridge Plugin - ' .
608 "Connected Twitter user $this->twuid to local user $user->id");
610 common_set_user($user);
611 common_real_login(true);
613 $this->goHome($user->nickname);
616 function connectUser()
618 $user = common_current_user();
620 $result = $this->flinkUser($user->id, $this->twuid);
622 if (empty($result)) {
623 // TRANS: Server error displayed connecting a user to a Twitter user has failed.
624 $this->serverError(_m('Error connecting user to Twitter.'));
628 common_debug('TwitterBridge Plugin - ' .
629 "Connected Twitter user $this->twuid to local user $user->id");
631 // Return to Twitter connection settings tab
632 common_redirect(common_local_url('twittersettings'), 303);
637 common_debug('TwitterBridge Plugin - ' .
638 "Trying login for Twitter user $this->twuid.");
640 $flink = Foreign_link::getByForeignID($this->twuid,
643 if (!empty($flink)) {
644 $user = $flink->getUser();
648 common_debug('TwitterBridge Plugin - ' .
649 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
651 common_set_user($user);
652 common_real_login(true);
653 $this->goHome($user->nickname);
658 common_debug('TwitterBridge Plugin - ' .
659 "No flink found for twuid: $this->twuid - new user");
661 $this->showForm(null, $this->bestNewNickname());
665 function goHome($nickname)
667 $url = common_get_returnto();
669 // We don't have to return to it again
670 common_set_returnto(null);
672 $url = common_local_url('all',
677 common_redirect($url, 303);
680 function bestNewNickname()
682 if (!empty($this->tw_fields['fullname'])) {
683 $nickname = $this->nicknamize($this->tw_fields['fullname']);
684 if ($this->isNewNickname($nickname)) {
692 // Given a string, try to make it work as a nickname
694 function nicknamize($str)
696 $str = preg_replace('/\W/', '', $str);
697 $str = str_replace(array('-', '_'), '', $str);
698 return strtolower($str);
701 function isNewNickname($str)
703 if (!Nickname::isValid($str)) {
706 if (!User::allowed_nickname($str)) {
709 if (User::staticGet('nickname', $str)) {