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 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
124 if ($this->arg('create')) {
125 if (!$this->boolean('license')) {
126 $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
127 $this->trimmed('newname'));
130 $this->createNewUser();
131 } else if ($this->arg('connect')) {
132 $this->connectNewUser();
134 common_debug('Twitter bridge - ' . print_r($this->args, true));
135 $this->showForm(_m('Something weird happened.'),
136 $this->trimmed('newname'));
139 // $this->oauth_token is only populated once Twitter authorizes our
140 // request token. If it's empty we're at the beginning of the auth
143 if (empty($this->oauth_token)) {
144 $this->authorizeRequestToken();
146 $this->saveAccessToken();
152 * Asks Twitter for a request token, and then redirects to Twitter
157 function authorizeRequestToken()
161 // Get a new request token and authorize it
163 $client = new TwitterOAuthClient();
164 $req_tok = $client->getRequestToken();
166 // Sock the request token away in the session temporarily
168 $_SESSION['twitter_request_token'] = $req_tok->key;
169 $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
171 $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
173 } catch (OAuthClientException $e) {
175 'OAuth client error - code: %1s, msg: %2s',
179 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
181 _m('Couldn\'t link your Twitter account.')
185 common_redirect($auth_link);
189 * Called when Twitter returns an authorized request token. Exchanges
190 * it for an access token and stores it.
194 function saveAccessToken()
196 // Check to make sure Twitter returned the same request
197 // token we sent them
199 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
201 _m('Couldn\'t link your Twitter account: oauth_token mismatch.')
205 $twitter_user = null;
209 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
210 $_SESSION['twitter_request_token_secret']);
212 // Exchange the request token for an access token
214 $atok = $client->getAccessToken($this->verifier);
216 // Test the access token and get the user's Twitter info
218 $client = new TwitterOAuthClient($atok->key, $atok->secret);
219 $twitter_user = $client->verifyCredentials();
221 } catch (OAuthClientException $e) {
223 'OAuth client error - code: %1$s, msg: %2$s',
227 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
229 _m('Couldn\'t link your Twitter account.')
233 if (common_logged_in()) {
234 // Save the access token and Twitter user info
236 $user = common_current_user();
237 $this->saveForeignLink($user->id, $twitter_user->id, $atok);
238 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
242 $this->twuid = $twitter_user->id;
243 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
244 "fullname" => $twitter_user->name);
245 $this->access_token = $atok;
249 // Clean up the the mess we made in the session
251 unset($_SESSION['twitter_request_token']);
252 unset($_SESSION['twitter_request_token_secret']);
254 if (common_logged_in()) {
255 common_redirect(common_local_url('twittersettings'));
260 * Saves a Foreign_link between Twitter user and local user,
261 * which includes the access token and secret.
263 * @param int $user_id StatusNet user ID
264 * @param int $twuid Twitter user ID
265 * @param OAuthToken $token the access token to save
269 function saveForeignLink($user_id, $twuid, $access_token)
271 $flink = new Foreign_link();
273 $flink->user_id = $user_id;
274 $flink->service = TWITTER_SERVICE;
276 // delete stale flink, if any
277 $result = $flink->find(true);
279 if (!empty($result)) {
280 $flink->safeDelete();
283 $flink->user_id = $user_id;
284 $flink->foreign_id = $twuid;
285 $flink->service = TWITTER_SERVICE;
287 $creds = TwitterOAuthClient::packToken($access_token);
289 $flink->credentials = $creds;
290 $flink->created = common_sql_now();
292 // Defaults: noticesync on, everything else off
294 $flink->set_flags(true, false, false, false);
296 $flink_id = $flink->insert();
298 if (empty($flink_id)) {
299 common_log_db_error($flink, 'INSERT', __FILE__);
300 $this->serverError(_m('Couldn\'t link your Twitter account.'));
306 function showPageNotice()
309 $this->element('div', array('class' => 'error'), $this->error);
311 $this->element('div', 'instructions',
312 sprintf(_m('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')));
318 return _m('Twitter Account Setup');
321 function showForm($error=null, $username=null)
323 $this->error = $error;
324 $this->username = $username;
335 * @fixme much of this duplicates core code, which is very fragile.
336 * Should probably be replaced with an extensible mini version of
337 * the core registration form.
339 function showContent()
341 if (!empty($this->message_text)) {
342 $this->element('p', null, $this->message);
346 $this->elementStart('form', array('method' => 'post',
347 'id' => 'form_settings_twitter_connect',
348 'class' => 'form_settings',
349 'action' => common_local_url('twitterauthorization')));
350 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
351 $this->element('legend', null, _m('Connection options'));
352 $this->elementStart('ul', 'form_data');
353 $this->elementStart('li');
354 $this->element('input', array('type' => 'checkbox',
356 'class' => 'checkbox',
359 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
360 $message = _m('My text and files are available under %s ' .
361 'except this private data: password, ' .
362 'email address, IM address, and phone number.');
363 $link = '<a href="' .
364 htmlspecialchars(common_config('license', 'url')) .
366 htmlspecialchars(common_config('license', 'title')) .
368 $this->raw(sprintf(htmlspecialchars($message), $link));
369 $this->elementEnd('label');
370 $this->elementEnd('li');
371 $this->elementEnd('ul');
372 $this->hidden('access_token_key', $this->access_token->key);
373 $this->hidden('access_token_secret', $this->access_token->secret);
374 $this->hidden('twuid', $this->twuid);
375 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
376 $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
378 $this->elementStart('fieldset');
379 $this->hidden('token', common_session_token());
380 $this->element('legend', null,
381 _m('Create new account'));
382 $this->element('p', null,
383 _m('Create a new user with this nickname.'));
384 $this->elementStart('ul', 'form_data');
386 // Hook point for captcha etc
387 Event::handle('StartRegistrationFormData', array($this));
389 $this->elementStart('li');
390 $this->input('newname', _m('New nickname'),
391 ($this->username) ? $this->username : '',
392 _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
393 $this->elementEnd('li');
395 // Hook point for captcha etc
396 Event::handle('EndRegistrationFormData', array($this));
398 $this->elementEnd('ul');
399 $this->submit('create', _m('Create'));
400 $this->elementEnd('fieldset');
402 $this->elementStart('fieldset');
403 $this->element('legend', null,
404 _m('Connect existing account'));
405 $this->element('p', null,
406 _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
407 $this->elementStart('ul', 'form_data');
408 $this->elementStart('li');
409 $this->input('nickname', _m('Existing nickname'));
410 $this->elementEnd('li');
411 $this->elementStart('li');
412 $this->password('password', _m('Password'));
413 $this->elementEnd('li');
414 $this->elementEnd('ul');
415 $this->submit('connect', _m('Connect'));
416 $this->elementEnd('fieldset');
418 $this->elementEnd('fieldset');
419 $this->elementEnd('form');
422 function message($msg)
424 $this->message_text = $msg;
428 function createNewUser()
430 if (!Event::handle('StartRegistrationTry', array($this))) {
434 if (common_config('site', 'closed')) {
435 $this->clientError(_m('Registration not allowed.'));
441 if (common_config('site', 'inviteonly')) {
442 $code = $_SESSION['invitecode'];
444 $this->clientError(_m('Registration not allowed.'));
448 $invite = Invitation::staticGet($code);
450 if (empty($invite)) {
451 $this->clientError(_m('Not a valid invitation code.'));
457 $nickname = Nickname::normalize($this->trimmed('newname'));
458 } catch (NicknameException $e) {
459 $this->showForm($e->getMessage());
463 if (!User::allowed_nickname($nickname)) {
464 $this->showForm(_m('Nickname not allowed.'));
468 if (User::staticGet('nickname', $nickname)) {
469 $this->showForm(_m('Nickname already in use. Try another one.'));
473 $fullname = trim($this->tw_fields['fullname']);
475 $args = array('nickname' => $nickname, 'fullname' => $fullname);
477 if (!empty($invite)) {
478 $args['code'] = $invite->code;
481 $user = User::register($args);
484 $this->serverError(_m('Error registering user.'));
488 $result = $this->saveForeignLink($user->id,
490 $this->access_token);
492 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
495 $this->serverError(_m('Error connecting user to Twitter.'));
499 common_set_user($user);
500 common_real_login(true);
502 common_debug('TwitterBridge Plugin - ' .
503 "Registered new user $user->id from Twitter user $this->twuid");
505 Event::handle('EndRegistrationTry', array($this));
507 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
511 function connectNewUser()
513 $nickname = $this->trimmed('nickname');
514 $password = $this->trimmed('password');
516 if (!common_check_user($nickname, $password)) {
517 $this->showForm(_m('Invalid username or password.'));
521 $user = User::staticGet('nickname', $nickname);
524 common_debug('TwitterBridge Plugin - ' .
525 "Legit user to connect to Twitter: $nickname");
528 $result = $this->saveForeignLink($user->id,
530 $this->access_token);
532 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
535 $this->serverError(_m('Error connecting user to Twitter.'));
539 common_debug('TwitterBridge Plugin - ' .
540 "Connected Twitter user $this->twuid to local user $user->id");
542 common_set_user($user);
543 common_real_login(true);
545 $this->goHome($user->nickname);
548 function connectUser()
550 $user = common_current_user();
552 $result = $this->flinkUser($user->id, $this->twuid);
554 if (empty($result)) {
555 $this->serverError(_m('Error connecting user to Twitter.'));
559 common_debug('TwitterBridge Plugin - ' .
560 "Connected Twitter user $this->twuid to local user $user->id");
562 // Return to Twitter connection settings tab
563 common_redirect(common_local_url('twittersettings'), 303);
568 common_debug('TwitterBridge Plugin - ' .
569 "Trying login for Twitter user $this->twuid.");
571 $flink = Foreign_link::getByForeignID($this->twuid,
574 if (!empty($flink)) {
575 $user = $flink->getUser();
579 common_debug('TwitterBridge Plugin - ' .
580 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
582 common_set_user($user);
583 common_real_login(true);
584 $this->goHome($user->nickname);
589 common_debug('TwitterBridge Plugin - ' .
590 "No flink found for twuid: $this->twuid - new user");
592 $this->showForm(null, $this->bestNewNickname());
596 function goHome($nickname)
598 $url = common_get_returnto();
600 // We don't have to return to it again
601 common_set_returnto(null);
603 $url = common_local_url('all',
608 common_redirect($url, 303);
611 function bestNewNickname()
613 if (!empty($this->tw_fields['fullname'])) {
614 $nickname = $this->nicknamize($this->tw_fields['fullname']);
615 if ($this->isNewNickname($nickname)) {
623 // Given a string, try to make it work as a nickname
625 function nicknamize($str)
627 $str = preg_replace('/\W/', '', $str);
628 $str = str_replace(array('-', '_'), '', $str);
629 return strtolower($str);
632 function isNewNickname($str)
634 if (!Nickname::isValid($str)) {
637 if (!User::allowed_nickname($str)) {
640 if (User::staticGet('nickname', $str)) {