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(_('There was a problem with your session token. Try again, please.'));
124 if ($this->arg('create')) {
125 if (!$this->boolean('license')) {
126 $this->showForm(_('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(_('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()) {
235 // Save the access token and Twitter user info
237 $user = common_current_user();
238 $this->saveForeignLink($user->id, $twitter_user->id, $atok);
239 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
243 $this->twuid = $twitter_user->id;
244 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
245 "name" => $twitter_user->name);
246 $this->access_token = $atok;
250 // Clean up the the mess we made in the session
252 unset($_SESSION['twitter_request_token']);
253 unset($_SESSION['twitter_request_token_secret']);
255 if (common_logged_in()) {
256 common_redirect(common_local_url('twittersettings'));
261 * Saves a Foreign_link between Twitter user and local user,
262 * which includes the access token and secret.
264 * @param int $user_id StatusNet user ID
265 * @param int $twuid Twitter user ID
266 * @param OAuthToken $token the access token to save
270 function saveForeignLink($user_id, $twuid, $access_token)
272 $flink = new Foreign_link();
274 $flink->user_id = $user_id;
275 $flink->service = TWITTER_SERVICE;
277 // delete stale flink, if any
278 $result = $flink->find(true);
280 if (!empty($result)) {
281 $flink->safeDelete();
284 $flink->user_id = $user_id;
285 $flink->foreign_id = $twuid;
286 $flink->service = TWITTER_SERVICE;
288 $creds = TwitterOAuthClient::packToken($access_token);
290 $flink->credentials = $creds;
291 $flink->created = common_sql_now();
293 // Defaults: noticesync on, everything else off
295 $flink->set_flags(true, false, false, false);
297 $flink_id = $flink->insert();
299 if (empty($flink_id)) {
300 common_log_db_error($flink, 'INSERT', __FILE__);
301 $this->serverError(_('Couldn\'t link your Twitter account.'));
307 function showPageNotice()
310 $this->element('div', array('class' => 'error'), $this->error);
312 $this->element('div', 'instructions',
313 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')));
319 return _('Twitter Account Setup');
322 function showForm($error=null, $username=null)
324 $this->error = $error;
325 $this->username = $username;
336 * @fixme much of this duplicates core code, which is very fragile.
337 * Should probably be replaced with an extensible mini version of
338 * the core registration form.
340 function showContent()
342 if (!empty($this->message_text)) {
343 $this->element('p', null, $this->message);
347 $this->elementStart('form', array('method' => 'post',
348 'id' => 'form_settings_twitter_connect',
349 'class' => 'form_settings',
350 'action' => common_local_url('twitterauthorization')));
351 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
352 $this->element('legend', null, _('Connection options'));
353 $this->elementStart('ul', 'form_data');
354 $this->elementStart('li');
355 $this->element('input', array('type' => 'checkbox',
357 'class' => 'checkbox',
360 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
361 $message = _('My text and files are available under %s ' .
362 'except this private data: password, ' .
363 'email address, IM address, and phone number.');
364 $link = '<a href="' .
365 htmlspecialchars(common_config('license', 'url')) .
367 htmlspecialchars(common_config('license', 'title')) .
369 $this->raw(sprintf(htmlspecialchars($message), $link));
370 $this->elementEnd('label');
371 $this->elementEnd('li');
372 $this->elementEnd('ul');
373 $this->hidden('access_token_key', $this->access_token->key);
374 $this->hidden('access_token_secret', $this->access_token->secret);
375 $this->hidden('twuid', $this->twuid);
376 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
377 $this->hidden('tw_fields_name', $this->tw_fields['name']);
379 $this->elementStart('fieldset');
380 $this->hidden('token', common_session_token());
381 $this->element('legend', null,
382 _('Create new account'));
383 $this->element('p', null,
384 _('Create a new user with this nickname.'));
385 $this->elementStart('ul', 'form_data');
386 $this->elementStart('li');
387 $this->input('newname', _('New nickname'),
388 ($this->username) ? $this->username : '',
389 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
390 $this->elementEnd('li');
391 $this->elementEnd('ul');
392 $this->submit('create', _('Create'));
393 $this->elementEnd('fieldset');
395 $this->elementStart('fieldset');
396 $this->element('legend', null,
397 _('Connect existing account'));
398 $this->element('p', null,
399 _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
400 $this->elementStart('ul', 'form_data');
401 $this->elementStart('li');
402 $this->input('nickname', _('Existing nickname'));
403 $this->elementEnd('li');
404 $this->elementStart('li');
405 $this->password('password', _('Password'));
406 $this->elementEnd('li');
407 $this->elementEnd('ul');
408 $this->submit('connect', _('Connect'));
409 $this->elementEnd('fieldset');
411 $this->elementEnd('fieldset');
412 $this->elementEnd('form');
415 function message($msg)
417 $this->message_text = $msg;
421 function createNewUser()
423 if (common_config('site', 'closed')) {
424 $this->clientError(_('Registration not allowed.'));
430 if (common_config('site', 'inviteonly')) {
431 $code = $_SESSION['invitecode'];
433 $this->clientError(_('Registration not allowed.'));
437 $invite = Invitation::staticGet($code);
439 if (empty($invite)) {
440 $this->clientError(_('Not a valid invitation code.'));
445 $nickname = $this->trimmed('newname');
447 if (!Validate::string($nickname, array('min_length' => 1,
449 'format' => NICKNAME_FMT))) {
450 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
454 if (!User::allowed_nickname($nickname)) {
455 $this->showForm(_('Nickname not allowed.'));
459 if (User::staticGet('nickname', $nickname)) {
460 $this->showForm(_('Nickname already in use. Try another one.'));
464 $fullname = trim($this->tw_fields['name']);
466 $args = array('nickname' => $nickname, 'fullname' => $fullname);
468 if (!empty($invite)) {
469 $args['code'] = $invite->code;
472 $user = User::register($args);
475 $this->serverError(_('Error registering user.'));
479 $result = $this->saveForeignLink($user->id,
481 $this->access_token);
483 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
486 $this->serverError(_('Error connecting user to Twitter.'));
490 common_set_user($user);
491 common_real_login(true);
493 common_debug('TwitterBridge Plugin - ' .
494 "Registered new user $user->id from Twitter user $this->twuid");
496 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
500 function connectNewUser()
502 $nickname = $this->trimmed('nickname');
503 $password = $this->trimmed('password');
505 if (!common_check_user($nickname, $password)) {
506 $this->showForm(_('Invalid username or password.'));
510 $user = User::staticGet('nickname', $nickname);
513 common_debug('TwitterBridge Plugin - ' .
514 "Legit user to connect to Twitter: $nickname");
517 $result = $this->saveForeignLink($user->id,
519 $this->access_token);
521 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
524 $this->serverError(_('Error connecting user to Twitter.'));
528 common_debug('TwitterBridge Plugin - ' .
529 "Connected Twitter user $this->twuid to local user $user->id");
531 common_set_user($user);
532 common_real_login(true);
534 $this->goHome($user->nickname);
537 function connectUser()
539 $user = common_current_user();
541 $result = $this->flinkUser($user->id, $this->twuid);
543 if (empty($result)) {
544 $this->serverError(_('Error connecting user to Twitter.'));
548 common_debug('TwitterBridge Plugin - ' .
549 "Connected Twitter user $this->twuid to local user $user->id");
551 // Return to Twitter connection settings tab
552 common_redirect(common_local_url('twittersettings'), 303);
557 common_debug('TwitterBridge Plugin - ' .
558 "Trying login for Twitter user $this->twuid.");
560 $flink = Foreign_link::getByForeignID($this->twuid,
563 if (!empty($flink)) {
564 $user = $flink->getUser();
568 common_debug('TwitterBridge Plugin - ' .
569 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
571 common_set_user($user);
572 common_real_login(true);
573 $this->goHome($user->nickname);
578 common_debug('TwitterBridge Plugin - ' .
579 "No flink found for twuid: $this->twuid - new user");
581 $this->showForm(null, $this->bestNewNickname());
585 function goHome($nickname)
587 $url = common_get_returnto();
589 // We don't have to return to it again
590 common_set_returnto(null);
592 $url = common_local_url('all',
597 common_redirect($url, 303);
600 function bestNewNickname()
602 if (!empty($this->tw_fields['name'])) {
603 $nickname = $this->nicknamize($this->tw_fields['name']);
604 if ($this->isNewNickname($nickname)) {
612 // Given a string, try to make it work as a nickname
614 function nicknamize($str)
616 $str = preg_replace('/\W/', '', $str);
617 $str = str_replace(array('-', '_'), '', $str);
618 return strtolower($str);
621 function isNewNickname($str)
623 if (!Validate::string($str, array('min_length' => 1,
625 'format' => NICKNAME_FMT))) {
628 if (!User::allowed_nickname($str)) {
631 if (User::staticGet('nickname', $str)) {