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 and a foreign user
93 // it means the accounts are already linked, and this is unecessary.
97 $fuser = $flink->getForeignUser();
99 common_redirect(common_local_url('twittersettings'));
104 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
106 // User was not logged in to StatusNet before
108 $this->twuid = $this->trimmed('twuid');
110 $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
111 'fullname' => $this->trimmed('tw_fields_fullname'));
113 $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
115 $token = $this->trimmed('token');
117 if (!$token || $token != common_session_token()) {
118 $this->showForm(_('There was a problem with your session token. Try again, please.'));
122 if ($this->arg('create')) {
123 if (!$this->boolean('license')) {
124 $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
125 $this->trimmed('newname'));
128 $this->createNewUser();
129 } else if ($this->arg('connect')) {
130 $this->connectNewUser();
132 common_debug('Twitter Connect Plugin - ' .
133 print_r($this->args, true));
134 $this->showForm(_('Something weird happened.'),
135 $this->trimmed('newname'));
138 // $this->oauth_token is only populated once Twitter authorizes our
139 // request token. If it's empty we're at the beginning of the auth
142 if (empty($this->oauth_token)) {
143 $this->authorizeRequestToken();
145 $this->saveAccessToken();
151 * Asks Twitter for a request token, and then redirects to Twitter
156 function authorizeRequestToken()
160 // Get a new request token and authorize it
162 $client = new TwitterOAuthClient();
164 $client->getRequestToken(TwitterOAuthClient::$requestTokenURL);
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) {
174 $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
175 $e->getCode(), $e->getMessage());
176 $this->serverError(_m('Couldn\'t link your Twitter account.'));
179 common_redirect($auth_link);
183 * Called when Twitter returns an authorized request token. Exchanges
184 * it for an access token and stores it.
188 function saveAccessToken()
191 // Check to make sure Twitter returned the same request
192 // token we sent them
194 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
195 $this->serverError(_m('Couldn\'t link your Twitter account.'));
198 $twitter_user = null;
202 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
203 $_SESSION['twitter_request_token_secret']);
205 // Exchange the request token for an access token
207 $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL);
209 // Test the access token and get the user's Twitter info
211 $client = new TwitterOAuthClient($atok->key, $atok->secret);
212 $twitter_user = $client->verifyCredentials();
214 } catch (OAuthClientException $e) {
215 $msg = sprintf('OAuth client error - code: %1$s, msg: %2$s',
216 $e->getCode(), $e->getMessage());
217 $this->serverError(_m('Couldn\'t link your Twitter account.'));
220 if (common_logged_in()) {
222 // Save the access token and Twitter user info
224 $user = common_current_user();
225 $this->saveForeignLink($user->id, $twitter_user->id, $atok);
226 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
230 $this->twuid = $twitter_user->id;
231 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
232 "name" => $twitter_user->name);
233 $this->access_token = $atok;
237 // Clean up the the mess we made in the session
239 unset($_SESSION['twitter_request_token']);
240 unset($_SESSION['twitter_request_token_secret']);
242 if (common_logged_in()) {
243 common_redirect(common_local_url('twittersettings'));
248 * Saves a Foreign_link between Twitter user and local user,
249 * which includes the access token and secret.
251 * @param int $user_id StatusNet user ID
252 * @param int $twuid Twitter user ID
253 * @param OAuthToken $token the access token to save
257 function saveForeignLink($user_id, $twuid, $access_token)
259 $flink = new Foreign_link();
261 $flink->user_id = $user_id;
262 $flink->service = TWITTER_SERVICE;
263 $flink->delete(); // delete stale flink, if any
265 $flink->user_id = $user_id;
266 $flink->foreign_id = $twuid;
267 $flink->service = TWITTER_SERVICE;
269 $creds = TwitterOAuthClient::packToken($access_token);
271 $flink->credentials = $creds;
272 $flink->created = common_sql_now();
274 // Defaults: noticesync on, everything else off
276 $flink->set_flags(true, false, false, false);
278 $flink_id = $flink->insert();
280 if (empty($flink_id)) {
281 common_log_db_error($flink, 'INSERT', __FILE__);
282 $this->serverError(_('Couldn\'t link your Twitter account.'));
288 function showPageNotice()
291 $this->element('div', array('class' => 'error'), $this->error);
293 $this->element('div', 'instructions',
294 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')));
300 return _('Twitter Account Setup');
303 function showForm($error=null, $username=null)
305 $this->error = $error;
306 $this->username = $username;
316 function showContent()
318 if (!empty($this->message_text)) {
319 $this->element('p', null, $this->message);
323 $this->elementStart('form', array('method' => 'post',
324 'id' => 'form_settings_twitter_connect',
325 'class' => 'form_settings',
326 'action' => common_local_url('twitterauthorization')));
327 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
328 $this->element('legend', null, _('Connection options'));
329 $this->elementStart('ul', 'form_data');
330 $this->elementStart('li');
331 $this->element('input', array('type' => 'checkbox',
333 'class' => 'checkbox',
336 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
337 $this->text(_('My text and files are available under '));
338 $this->element('a', array('href' => common_config('license', 'url')),
339 common_config('license', 'title'));
340 $this->text(_(' except this private data: password, email address, IM address, phone number.'));
341 $this->elementEnd('label');
342 $this->elementEnd('li');
343 $this->elementEnd('ul');
344 $this->hidden('access_token_key', $this->access_token->key);
345 $this->hidden('access_token_secret', $this->access_token->secret);
346 $this->hidden('twuid', $this->twuid);
347 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
348 $this->hidden('tw_fields_name', $this->tw_fields['name']);
350 $this->elementStart('fieldset');
351 $this->hidden('token', common_session_token());
352 $this->element('legend', null,
353 _('Create new account'));
354 $this->element('p', null,
355 _('Create a new user with this nickname.'));
356 $this->elementStart('ul', 'form_data');
357 $this->elementStart('li');
358 $this->input('newname', _('New nickname'),
359 ($this->username) ? $this->username : '',
360 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
361 $this->elementEnd('li');
362 $this->elementEnd('ul');
363 $this->submit('create', _('Create'));
364 $this->elementEnd('fieldset');
366 $this->elementStart('fieldset');
367 $this->element('legend', null,
368 _('Connect existing account'));
369 $this->element('p', null,
370 _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
371 $this->elementStart('ul', 'form_data');
372 $this->elementStart('li');
373 $this->input('nickname', _('Existing nickname'));
374 $this->elementEnd('li');
375 $this->elementStart('li');
376 $this->password('password', _('Password'));
377 $this->elementEnd('li');
378 $this->elementEnd('ul');
379 $this->submit('connect', _('Connect'));
380 $this->elementEnd('fieldset');
382 $this->elementEnd('fieldset');
383 $this->elementEnd('form');
386 function message($msg)
388 $this->message_text = $msg;
392 function createNewUser()
394 if (common_config('site', 'closed')) {
395 $this->clientError(_('Registration not allowed.'));
401 if (common_config('site', 'inviteonly')) {
402 $code = $_SESSION['invitecode'];
404 $this->clientError(_('Registration not allowed.'));
408 $invite = Invitation::staticGet($code);
410 if (empty($invite)) {
411 $this->clientError(_('Not a valid invitation code.'));
416 $nickname = $this->trimmed('newname');
418 if (!Validate::string($nickname, array('min_length' => 1,
420 'format' => NICKNAME_FMT))) {
421 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
425 if (!User::allowed_nickname($nickname)) {
426 $this->showForm(_('Nickname not allowed.'));
430 if (User::staticGet('nickname', $nickname)) {
431 $this->showForm(_('Nickname already in use. Try another one.'));
435 $fullname = trim($this->tw_fields['name']);
437 $args = array('nickname' => $nickname, 'fullname' => $fullname);
439 if (!empty($invite)) {
440 $args['code'] = $invite->code;
443 $user = User::register($args);
445 $result = $this->saveForeignLink($user->id,
447 $this->access_token);
449 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
452 $this->serverError(_('Error connecting user to Twitter.'));
456 common_set_user($user);
457 common_real_login(true);
459 common_debug('TwitterBridge Plugin - ' .
460 "Registered new user $user->id from Twitter user $this->twuid");
462 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
466 function connectNewUser()
468 $nickname = $this->trimmed('nickname');
469 $password = $this->trimmed('password');
471 if (!common_check_user($nickname, $password)) {
472 $this->showForm(_('Invalid username or password.'));
476 $user = User::staticGet('nickname', $nickname);
479 common_debug('TwitterBridge Plugin - ' .
480 "Legit user to connect to Twitter: $nickname");
483 $result = $this->saveForeignLink($user->id,
485 $this->access_token);
487 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
490 $this->serverError(_('Error connecting user to Twitter.'));
494 common_debug('TwitterBridge Plugin - ' .
495 "Connected Twitter user $this->twuid to local user $user->id");
497 common_set_user($user);
498 common_real_login(true);
500 $this->goHome($user->nickname);
503 function connectUser()
505 $user = common_current_user();
507 $result = $this->flinkUser($user->id, $this->twuid);
509 if (empty($result)) {
510 $this->serverError(_('Error connecting user to Twitter.'));
514 common_debug('TwitterBridge Plugin - ' .
515 "Connected Twitter user $this->twuid to local user $user->id");
517 // Return to Twitter connection settings tab
518 common_redirect(common_local_url('twittersettings'), 303);
523 common_debug('TwitterBridge Plugin - ' .
524 "Trying login for Twitter user $this->twuid.");
526 $flink = Foreign_link::getByForeignID($this->twuid,
529 if (!empty($flink)) {
530 $user = $flink->getUser();
534 common_debug('TwitterBridge Plugin - ' .
535 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
537 common_set_user($user);
538 common_real_login(true);
539 $this->goHome($user->nickname);
544 common_debug('TwitterBridge Plugin - ' .
545 "No flink found for twuid: $this->twuid - new user");
547 $this->showForm(null, $this->bestNewNickname());
551 function goHome($nickname)
553 $url = common_get_returnto();
555 // We don't have to return to it again
556 common_set_returnto(null);
558 $url = common_local_url('all',
563 common_redirect($url, 303);
566 function bestNewNickname()
568 if (!empty($this->tw_fields['name'])) {
569 $nickname = $this->nicknamize($this->tw_fields['name']);
570 if ($this->isNewNickname($nickname)) {
578 // Given a string, try to make it work as a nickname
580 function nicknamize($str)
582 $str = preg_replace('/\W/', '', $str);
583 $str = str_replace(array('-', '_'), '', $str);
584 return strtolower($str);
587 function isNewNickname($str)
589 if (!Validate::string($str, array('min_length' => 1,
591 'format' => NICKNAME_FMT))) {
594 if (!User::allowed_nickname($str)) {
597 if (User::staticGet('nickname', $str)) {