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/>.
22 * @category TwitterauthorizationAction
24 * @author Zach Copley <zach@status.net>
25 * @copyright 2009 StatusNet, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
34 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
37 * Class for doing OAuth authentication against Twitter
39 * Peforms the OAuth "dance" between StatusNet and Twitter -- requests a token,
40 * authorizes it, and exchanges it for an access token. It also creates a link
41 * (Foreign_link) between the StatusNet user and Twitter user and stores the
42 * access token and secret in the link.
46 * @author Zach Copley <zach@status.net>
47 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
48 * @link http://laconi.ca/
51 class TwitterauthorizationAction extends Action
54 var $tw_fields = null;
55 var $access_token = null;
58 * Initialize class members. Looks for 'oauth_token' parameter.
60 * @param array $args misc. arguments
62 * @return boolean true
64 function prepare($args)
66 parent::prepare($args);
68 $this->oauth_token = $this->arg('oauth_token');
76 * @param array $args is ignored since it's now passed in in prepare()
80 function handle($args)
82 parent::handle($args);
84 if (common_logged_in()) {
85 $user = common_current_user();
86 $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
88 // If there's already a foreign link record, it means we already
89 // have an access token, and this is unecessary. So go back.
92 common_redirect(common_local_url('twittersettings'));
96 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
98 // User was not logged in to StatusNet before
100 $this->twuid = $this->trimmed('twuid');
102 $this->tw_fields = array('name' => $this->trimmed('tw_fields_name'),
103 'fullname' => $this->trimmed('tw_fields_fullname'));
105 $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
107 $token = $this->trimmed('token');
109 if (!$token || $token != common_session_token()) {
110 $this->showForm(_('There was a problem with your session token. Try again, please.'));
114 if ($this->arg('create')) {
115 if (!$this->boolean('license')) {
116 $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
117 $this->trimmed('newname'));
120 $this->createNewUser();
121 } else if ($this->arg('connect')) {
122 $this->connectNewUser();
124 common_debug('Twitter Connect Plugin - ' .
125 print_r($this->args, true));
126 $this->showForm(_('Something weird happened.'),
127 $this->trimmed('newname'));
130 // $this->oauth_token is only populated once Twitter authorizes our
131 // request token. If it's empty we're at the beginning of the auth
134 if (empty($this->oauth_token)) {
135 $this->authorizeRequestToken();
137 $this->saveAccessToken();
143 * Asks Twitter for a request token, and then redirects to Twitter
148 function authorizeRequestToken()
152 // Get a new request token and authorize it
154 $client = new TwitterOAuthClient();
156 $client->getRequestToken(TwitterOAuthClient::$requestTokenURL);
158 // Sock the request token away in the session temporarily
160 $_SESSION['twitter_request_token'] = $req_tok->key;
161 $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
163 $auth_link = $client->getAuthorizeLink($req_tok);
165 } catch (OAuthClientException $e) {
166 $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
167 $e->getCode(), $e->getMessage());
168 $this->serverError(_m('Couldn\'t link your Twitter account.'));
171 common_redirect($auth_link);
175 * Called when Twitter returns an authorized request token. Exchanges
176 * it for an access token and stores it.
180 function saveAccessToken()
183 // Check to make sure Twitter returned the same request
184 // token we sent them
186 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
187 $this->serverError(_m('Couldn\'t link your Twitter account.'));
190 $twitter_user = null;
194 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
195 $_SESSION['twitter_request_token_secret']);
197 // Exchange the request token for an access token
199 $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL);
201 // Test the access token and get the user's Twitter info
203 $client = new TwitterOAuthClient($atok->key, $atok->secret);
204 $twitter_user = $client->verifyCredentials();
206 } catch (OAuthClientException $e) {
207 $msg = sprintf('OAuth client error - code: %1$s, msg: %2$s',
208 $e->getCode(), $e->getMessage());
209 $this->serverError(_m('Couldn\'t link your Twitter account.'));
212 if (common_logged_in()) {
214 // Save the access token and Twitter user info
216 $this->saveForeignLink($atok, $twitter_user);
220 $this->twuid = $twitter_user->id;
221 $this->tw_fields = array("name" => $twitter_user->screen_name, "fullname" => $twitter_user->name);
222 $this->access_token = $atok;
226 // Clean up the the mess we made in the session
228 unset($_SESSION['twitter_request_token']);
229 unset($_SESSION['twitter_request_token_secret']);
231 if (common_logged_in()) {
232 common_redirect(common_local_url('twittersettings'));
237 * Saves a Foreign_link between Twitter user and local user,
238 * which includes the access token and secret.
240 * @param OAuthToken $access_token the access token to save
241 * @param mixed $twitter_user twitter API user object
245 function saveForeignLink($access_token, $twitter_user)
247 $user = common_current_user();
249 $flink = new Foreign_link();
251 $flink->user_id = $user->id;
252 $flink->foreign_id = $twitter_user->id;
253 $flink->service = TWITTER_SERVICE;
255 $creds = TwitterOAuthClient::packToken($access_token);
257 $flink->credentials = $creds;
258 $flink->created = common_sql_now();
260 // Defaults: noticesync on, everything else off
262 $flink->set_flags(true, false, false, false);
264 $flink_id = $flink->insert();
266 if (empty($flink_id)) {
267 common_log_db_error($flink, 'INSERT', __FILE__);
268 $this->serverError(_m('Couldn\'t link your Twitter account.'));
271 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
274 function flinkUser($user_id, $twuid)
276 $flink = new Foreign_link();
278 $flink->user_id = $user_id;
279 $flink->foreign_id = $twuid;
280 $flink->service = TWITTER_SERVICE;
282 $creds = TwitterOAuthClient::packToken($this->access_token);
284 $flink->credentials = $creds;
285 $flink->created = common_sql_now();
287 // Defaults: noticesync on, everything else off
289 $flink->set_flags(true, false, false, false);
291 $flink_id = $flink->insert();
293 if (empty($flink_id)) {
294 common_log_db_error($flink, 'INSERT', __FILE__);
295 $this->serverError(_('Couldn\'t link your Twitter account.'));
298 save_twitter_user($twuid, $this->tw_fields['name']);
303 function showPageNotice()
306 $this->element('div', array('class' => 'error'), $this->error);
308 $this->element('div', 'instructions',
309 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')));
315 return _('Twitter Account Setup');
318 function showForm($error=null, $username=null)
320 $this->error = $error;
321 $this->username = $username;
331 function showContent()
333 if (!empty($this->message_text)) {
334 $this->element('p', null, $this->message);
338 $this->elementStart('form', array('method' => 'post',
339 'id' => 'form_settings_twitter_connect',
340 'class' => 'form_settings',
341 'action' => common_local_url('twitterauthorization')));
342 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
343 $this->element('legend', null, _('Connection options'));
344 $this->elementStart('ul', 'form_data');
345 $this->elementStart('li');
346 $this->element('input', array('type' => 'checkbox',
348 'class' => 'checkbox',
351 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
352 $this->text(_('My text and files are available under '));
353 $this->element('a', array('href' => common_config('license', 'url')),
354 common_config('license', 'title'));
355 $this->text(_(' except this private data: password, email address, IM address, phone number.'));
356 $this->elementEnd('label');
357 $this->elementEnd('li');
358 $this->elementEnd('ul');
359 $this->hidden('access_token_key', $this->access_token->key);
360 $this->hidden('access_token_secret', $this->access_token->secret);
361 $this->hidden('twuid', $this->twuid);
362 $this->hidden('tw_fields_name', $this->tw_fields['name']);
363 $this->hidden('tw_fields_fullname', $this->tw_fields['fullname']);
365 $this->elementStart('fieldset');
366 $this->hidden('token', common_session_token());
367 $this->element('legend', null,
368 _('Create new account'));
369 $this->element('p', null,
370 _('Create a new user with this nickname.'));
371 $this->elementStart('ul', 'form_data');
372 $this->elementStart('li');
373 $this->input('newname', _('New nickname'),
374 ($this->username) ? $this->username : '',
375 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
376 $this->elementEnd('li');
377 $this->elementEnd('ul');
378 $this->submit('create', _('Create'));
379 $this->elementEnd('fieldset');
381 $this->elementStart('fieldset');
382 $this->element('legend', null,
383 _('Connect existing account'));
384 $this->element('p', null,
385 _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
386 $this->elementStart('ul', 'form_data');
387 $this->elementStart('li');
388 $this->input('nickname', _('Existing nickname'));
389 $this->elementEnd('li');
390 $this->elementStart('li');
391 $this->password('password', _('Password'));
392 $this->elementEnd('li');
393 $this->elementEnd('ul');
394 $this->submit('connect', _('Connect'));
395 $this->elementEnd('fieldset');
397 $this->elementEnd('fieldset');
398 $this->elementEnd('form');
401 function message($msg)
403 $this->message_text = $msg;
407 function createNewUser()
409 if (common_config('site', 'closed')) {
410 $this->clientError(_('Registration not allowed.'));
416 if (common_config('site', 'inviteonly')) {
417 $code = $_SESSION['invitecode'];
419 $this->clientError(_('Registration not allowed.'));
423 $invite = Invitation::staticGet($code);
425 if (empty($invite)) {
426 $this->clientError(_('Not a valid invitation code.'));
431 $nickname = $this->trimmed('newname');
433 if (!Validate::string($nickname, array('min_length' => 1,
435 'format' => NICKNAME_FMT))) {
436 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
440 if (!User::allowed_nickname($nickname)) {
441 $this->showForm(_('Nickname not allowed.'));
445 if (User::staticGet('nickname', $nickname)) {
446 $this->showForm(_('Nickname already in use. Try another one.'));
450 $fullname = trim($this->tw_fields['fullname']);
452 $args = array('nickname' => $nickname, 'fullname' => $fullname);
454 if (!empty($invite)) {
455 $args['code'] = $invite->code;
458 $user = User::register($args);
460 $result = $this->flinkUser($user->id, $this->twuid);
463 $this->serverError(_('Error connecting user to Twitter.'));
467 common_set_user($user);
468 common_real_login(true);
470 common_debug('TwitterBridge Plugin - ' .
471 "Registered new user $user->id from Twitter user $this->fbuid");
473 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
477 function connectNewUser()
479 $nickname = $this->trimmed('nickname');
480 $password = $this->trimmed('password');
482 if (!common_check_user($nickname, $password)) {
483 $this->showForm(_('Invalid username or password.'));
487 $user = User::staticGet('nickname', $nickname);
490 common_debug('TwitterBridge Plugin - ' .
491 "Legit user to connect to Twitter: $nickname");
494 $result = $this->flinkUser($user->id, $this->twuid);
497 $this->serverError(_('Error connecting user to Twitter.'));
501 common_debug('TwitterBridge Plugin - ' .
502 "Connected Twitter user $this->fbuid to local user $user->id");
504 common_set_user($user);
505 common_real_login(true);
507 $this->goHome($user->nickname);
510 function connectUser()
512 $user = common_current_user();
514 $result = $this->flinkUser($user->id, $this->twuid);
516 if (empty($result)) {
517 $this->serverError(_('Error connecting user to Twitter.'));
521 common_debug('TwitterBridge Plugin - ' .
522 "Connected Twitter user $this->fbuid to local user $user->id");
524 // Return to Twitter connection settings tab
525 common_redirect(common_local_url('twittersettings'), 303);
530 common_debug('TwitterBridge Plugin - ' .
531 "Trying login for Twitter user $this->twuid.");
533 $flink = Foreign_link::getByForeignID($this->twuid, TWITTER_SERVICE);
535 if (!empty($flink)) {
536 $user = $flink->getUser();
540 common_debug('TwitterBridge Plugin - ' .
541 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
543 common_set_user($user);
544 common_real_login(true);
545 $this->goHome($user->nickname);
550 common_debug('TwitterBridge Plugin - ' .
551 "No flink found for twuid: $this->twuid - new user");
553 $this->showForm(null, $this->bestNewNickname());
557 function goHome($nickname)
559 $url = common_get_returnto();
561 // We don't have to return to it again
562 common_set_returnto(null);
564 $url = common_local_url('all',
569 common_redirect($url, 303);
572 function bestNewNickname()
574 if (!empty($this->tw_fields['name'])) {
575 $nickname = $this->nicknamize($this->tw_fields['name']);
576 if ($this->isNewNickname($nickname)) {
584 // Given a string, try to make it work as a nickname
586 function nicknamize($str)
588 $str = preg_replace('/\W/', '', $str);
589 $str = str_replace(array('-', '_'), '', $str);
590 return strtolower($str);
593 function isNewNickname($str)
595 if (!Validate::string($str, array('min_length' => 1,
597 'format' => NICKNAME_FMT))) {
600 if (!User::allowed_nickname($str)) {
603 if (User::staticGet('nickname', $str)) {