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('GNUSOCIAL')) { exit(1); }
33 require_once dirname(__DIR__) . '/twitter.php';
34 require_once INSTALLDIR . '/lib/oauthclient.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 * @author Julien C <chaumond@gmail.com>
48 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
49 * @link http://status.net/
52 class TwitterauthorizationAction extends FormAction
55 var $tw_fields = null;
56 var $access_token = null;
59 protected $needLogin = false; // authorization page can also be used to create a new user
61 protected function doPreparation()
63 $this->oauth_token = $this->arg('oauth_token');
64 $this->verifier = $this->arg('oauth_verifier');
66 if ($this->scoped instanceof Profile) {
68 $flink = Foreign_link::getByUserID($this->scoped->getID(), TWITTER_SERVICE);
69 $fuser = $flink->getForeignUser();
71 // If there's already a foreign link record and a foreign user
72 // (no exceptions were thrown when fetching either of them...)
73 // it means the accounts are already linked, and this is unecessary.
76 common_redirect(common_local_url('twittersettings'));
77 } catch (NoResultException $e) {
78 // but if we don't have a foreign user linked, let's continue authorization procedure.
83 protected function doPost()
85 // User was not logged in to StatusNet before
87 $this->twuid = $this->trimmed('twuid');
89 $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
90 'fullname' => $this->trimmed('tw_fields_fullname'));
92 $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
94 if ($this->arg('create')) {
95 common_debug('TwitterBridgeDebug - POST with create');
96 if (!$this->boolean('license')) {
97 // TRANS: Form validation error displayed when the checkbox to agree to the license has not been checked.
98 throw new ClientException(_m('You cannot register if you do not agree to the license.'));
100 return $this->createNewUser();
101 } elseif ($this->arg('connect')) {
102 common_debug('TwitterBridgeDebug - POST with connect');
103 return $this->connectNewUser();
106 common_debug('TwitterBridgeDebug - ' . print_r($this->args, true));
107 // TRANS: Form validation error displayed when an unhandled error occurs.
108 throw new ClientException(_m('No known action for POST.'));
112 * Asks Twitter for a request token, and then redirects to Twitter
115 protected function authorizeRequestToken()
118 // Get a new request token and authorize it
119 $client = new TwitterOAuthClient();
120 $req_tok = $client->getTwitterRequestToken();
122 // Sock the request token away in the session temporarily
123 $_SESSION['twitter_request_token'] = $req_tok->key;
124 $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
126 $auth_link = $client->getTwitterAuthorizeLink($req_tok, $this->boolean('signin'));
127 } catch (OAuthClientException $e) {
129 'OAuth client error - code: %1s, msg: %2s',
133 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
134 // TRANS: Server error displayed when linking to a Twitter account fails.
135 throw new ServerException(_m('Could not link your Twitter account.'));
138 common_redirect($auth_link);
142 * Called when Twitter returns an authorized request token. Exchanges
143 * it for an access token and stores it.
147 function saveAccessToken()
149 // Check to make sure Twitter returned the same request
150 // token we sent them
152 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
153 // TRANS: Server error displayed when linking to a Twitter account fails because of an incorrect oauth_token.
154 throw new ServerException(_m('Could not link your Twitter account: oauth_token mismatch.'));
157 $twitter_user = null;
160 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], $_SESSION['twitter_request_token_secret']);
162 // Exchange the request token for an access token
163 $atok = $client->getTwitterAccessToken($this->verifier);
165 // Test the access token and get the user's Twitter info
166 $client = new TwitterOAuthClient($atok->key, $atok->secret);
167 $twitter_user = $client->verifyCredentials();
169 } catch (OAuthClientException $e) {
171 'OAuth client error - code: %1$s, msg: %2$s',
175 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
176 // TRANS: Server error displayed when linking to a Twitter account fails.
177 throw new ServerException(_m('Could not link your Twitter account.'));
180 if ($this->scoped instanceof Profile) {
181 // Save the access token and Twitter user info
183 $this->saveForeignLink($this->scoped->getID(), $twitter_user->id, $atok);
184 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
188 $this->twuid = $twitter_user->id;
189 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
190 "fullname" => $twitter_user->name);
191 $this->access_token = $atok;
192 return $this->tryLogin();
195 // Clean up the the mess we made in the session
197 unset($_SESSION['twitter_request_token']);
198 unset($_SESSION['twitter_request_token_secret']);
200 if (common_logged_in()) {
201 common_redirect(common_local_url('twittersettings'));
206 * Saves a Foreign_link between Twitter user and local user,
207 * which includes the access token and secret.
209 * @param int $user_id StatusNet user ID
210 * @param int $twuid Twitter user ID
211 * @param OAuthToken $token the access token to save
215 function saveForeignLink($user_id, $twuid, $access_token)
217 $flink = new Foreign_link();
219 $flink->user_id = $user_id;
220 $flink->service = TWITTER_SERVICE;
222 // delete stale flink, if any
223 $result = $flink->find(true);
225 if (!empty($result)) {
226 $flink->safeDelete();
229 $flink->user_id = $user_id;
230 $flink->foreign_id = $twuid;
231 $flink->service = TWITTER_SERVICE;
233 $creds = TwitterOAuthClient::packToken($access_token);
235 $flink->credentials = $creds;
236 $flink->created = common_sql_now();
238 // Defaults: noticesync on, everything else off
240 $flink->set_flags(true, false, false, false);
242 $flink_id = $flink->insert();
244 // We want to make sure we got a numerical >0 value, not just failed the insert (which would be === false)
245 if (empty($flink_id)) {
246 common_log_db_error($flink, 'INSERT', __FILE__);
247 // TRANS: Server error displayed when linking to a Twitter account fails.
248 throw new ServerException(_m('Could not link your Twitter account.'));
254 function getInstructions()
256 // TRANS: Page instruction. %s is the StatusNet sitename.
257 return 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'));
262 // TRANS: Page title.
263 return _m('Twitter Account Setup');
266 public function showPage()
268 // $this->oauth_token is only populated once Twitter authorizes our
269 // request token. If it's empty we're at the beginning of the auth
271 if (empty($this->error)) {
272 if (empty($this->oauth_token)) {
273 // authorizeRequestToken either throws an exception or redirects
274 $this->authorizeRequestToken();
276 $this->saveAccessToken();
284 * @fixme much of this duplicates core code, which is very fragile.
285 * Should probably be replaced with an extensible mini version of
286 * the core registration form.
288 function showContent()
290 $this->elementStart('form', array('method' => 'post',
291 'id' => 'form_settings_twitter_connect',
292 'class' => 'form_settings',
293 'action' => common_local_url('twitterauthorization')));
294 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
295 // TRANS: Fieldset legend.
296 $this->element('legend', null, _m('Connection options'));
298 $this->hidden('access_token_key', $this->access_token->key);
299 $this->hidden('access_token_secret', $this->access_token->secret);
300 $this->hidden('twuid', $this->twuid);
301 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
302 $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
303 $this->hidden('token', common_session_token());
305 // Only allow new account creation if site is not flagged invite-only
306 if (!common_config('site', 'inviteonly')) {
307 $this->elementStart('fieldset');
308 $this->element('legend', null,
309 // TRANS: Fieldset legend.
310 _m('Create new account'));
311 $this->element('p', null,
312 // TRANS: Sub form introduction text.
313 _m('Create a new user with this nickname.'));
314 $this->elementStart('ul', 'form_data');
316 // Hook point for captcha etc
317 Event::handle('StartRegistrationFormData', array($this));
319 $this->elementStart('li');
320 // TRANS: Field label.
321 $this->input('newname', _m('New nickname'),
322 $this->username ?: '',
323 // TRANS: Field title for nickname field.
324 _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
325 $this->elementEnd('li');
326 $this->elementStart('li');
327 // TRANS: Field label.
328 $this->input('email', _m('LABEL','Email'), $this->getEmail(),
329 // TRANS: Field title for e-mail address field.
330 _m('Used only for updates, announcements, '.
331 'and password recovery'));
332 $this->elementEnd('li');
334 // Hook point for captcha etc
335 Event::handle('EndRegistrationFormData', array($this));
337 $this->elementEnd('ul');
338 // TRANS: Button text for creating a new StatusNet account in the Twitter connect page.
339 $this->submit('create', _m('BUTTON','Create'));
340 $this->elementEnd('fieldset');
343 $this->elementStart('fieldset');
344 $this->element('legend', null,
345 // TRANS: Fieldset legend.
346 _m('Connect existing account'));
347 $this->element('p', null,
348 // TRANS: Sub form introduction text.
349 _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
350 $this->elementStart('ul', 'form_data');
351 $this->elementStart('li');
352 // TRANS: Field label.
353 $this->input('nickname', _m('Existing nickname'));
354 $this->elementEnd('li');
355 $this->elementStart('li');
356 // TRANS: Field label.
357 $this->password('password', _m('Password'));
358 $this->elementEnd('li');
359 $this->elementEnd('ul');
360 $this->elementEnd('fieldset');
362 $this->elementStart('fieldset');
363 $this->element('legend', null,
364 // TRANS: Fieldset legend.
366 $this->elementStart('ul', 'form_data');
367 $this->elementStart('li');
368 $this->element('input', array('type' => 'checkbox',
370 'class' => 'checkbox',
373 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
374 // TRANS: Text for license agreement checkbox.
375 // TRANS: %s is the license as configured for the StatusNet site.
376 $message = _m('My text and files are available under %s ' .
377 'except this private data: password, ' .
378 'email address, IM address, and phone number.');
379 $link = '<a href="' .
380 htmlspecialchars(common_config('license', 'url')) .
382 htmlspecialchars(common_config('license', 'title')) .
384 $this->raw(sprintf(htmlspecialchars($message), $link));
385 $this->elementEnd('label');
386 $this->elementEnd('li');
387 $this->elementEnd('ul');
388 $this->elementEnd('fieldset');
389 // TRANS: Button text for connecting an existing StatusNet account in the Twitter connect page..
390 $this->submit('connect', _m('BUTTON','Connect'));
391 $this->elementEnd('fieldset');
392 $this->elementEnd('form');
396 * Get specified e-mail from the form, or the invite code.
402 $email = $this->trimmed('email');
403 if (!empty($email)) {
407 // Terrible hack for invites...
408 if (common_config('site', 'inviteonly')) {
409 $code = $_SESSION['invitecode'];
411 $invite = Invitation::getKV($code);
413 if ($invite && $invite->address_type == 'email') {
414 return $invite->address;
421 protected function createNewUser()
423 common_debug('TwitterBridgeDebug - createNewUser');
424 if (!Event::handle('StartRegistrationTry', array($this))) {
425 common_debug('TwitterBridgeDebug - StartRegistrationTry failed');
426 // TRANS: Client error displayed when trying to create a new user but a plugin aborted the process.
427 throw new ClientException(_m('Registration of new user was aborted, maybe you failed a captcha?'));
430 if (common_config('site', 'closed')) {
431 common_debug('TwitterBridgeDebug - site is closed for registrations');
432 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
433 throw new ClientException(_m('Registration not allowed.'));
438 if (common_config('site', 'inviteonly')) {
439 common_debug('TwitterBridgeDebug - site is inviteonly');
440 $code = $_SESSION['invitecode'];
442 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
443 throw new ClientException(_m('Registration not allowed.'));
446 $invite = Invitation::getKV('code', $code);
448 if (!$invite instanceof Invite) {
449 common_debug('TwitterBridgeDebug - and we failed the invite code test');
450 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
451 throw new ClientException(_m('Not a valid invitation code.'));
455 common_debug('TwitterBridgeDebug - trying our nickname: '.$this->trimmed('newname'));
456 // Nickname::normalize throws exception if the nickname is taken
457 $nickname = Nickname::normalize($this->trimmed('newname'), true);
459 $fullname = trim($this->tw_fields['fullname']);
461 $args = array('nickname' => $nickname, 'fullname' => $fullname);
463 if (!empty($invite)) {
464 $args['code'] = $invite->code;
467 $email = $this->getEmail();
468 if (!empty($email)) {
469 $args['email'] = $email;
472 common_debug('TwitterBridgeDebug - registering user with args:'.var_export($args,true));
473 $user = User::register($args);
475 common_debug('TwitterBridgeDebug - registered the user and saving foreign link for '.$user->id);
477 $this->saveForeignLink($user->id,
479 $this->access_token);
481 common_debug('TwitterBridgeDebug - saving twitter user after creating new local user '.$user->id);
482 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
484 common_set_user($user);
485 common_real_login(true);
487 common_debug('TwitterBridge Plugin - ' .
488 "Registered new user $user->id from Twitter user $this->twuid");
490 Event::handle('EndRegistrationTry', array($this));
492 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)), 303);
495 function connectNewUser()
497 $nickname = $this->trimmed('nickname');
498 $password = $this->trimmed('password');
500 if (!common_check_user($nickname, $password)) {
501 // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
502 // TRANS: the provided username and/or password are incorrect.
503 throw new ClientException(_m('Invalid username or password.'));
506 $user = User::getKV('nickname', $nickname);
508 if ($user instanceof User) {
509 common_debug('TwitterBridge Plugin - ' .
510 "Legit user to connect to Twitter: $nickname");
513 // throws exception on failure
514 $this->saveForeignLink($user->id,
516 $this->access_token);
518 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
520 common_debug('TwitterBridge Plugin - ' .
521 "Connected Twitter user $this->twuid to local user $user->id");
523 common_set_user($user);
524 common_real_login(true);
526 $this->goHome($user->nickname);
529 function connectUser()
531 $user = common_current_user();
533 $result = $this->flinkUser($user->id, $this->twuid);
535 if (empty($result)) {
536 // TRANS: Server error displayed connecting a user to a Twitter user has failed.
537 $this->serverError(_m('Error connecting user to Twitter.'));
540 common_debug('TwitterBridge Plugin - ' .
541 "Connected Twitter user $this->twuid to local user $user->id");
543 // Return to Twitter connection settings tab
544 common_redirect(common_local_url('twittersettings'), 303);
547 protected function tryLogin()
549 common_debug('TwitterBridge Plugin - ' .
550 "Trying login for Twitter user $this->twuid.");
553 $flink = Foreign_link::getByForeignID($this->twuid, TWITTER_SERVICE);
554 $user = $flink->getUser();
556 common_debug('TwitterBridge Plugin - ' .
557 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
559 common_set_user($user);
560 common_real_login(true);
561 $this->goHome($user->nickname);
562 } catch (NoResultException $e) {
563 // Either no Foreign_link was found or not the user connected to it.
564 // Let's just continue to allow creating or logging in as a new user.
566 common_debug("TwitterBridge Plugin - No flink found for twuid: {$this->twuid} - new user");
568 // FIXME: what do we want to do here? I forgot
570 throw new ServerException(_m('No foreign link found for Twitter user'));
573 function goHome($nickname)
575 $url = common_get_returnto();
577 // We don't have to return to it again
578 common_set_returnto(null);
580 $url = common_local_url('all',
585 common_redirect($url, 303);
588 function bestNewNickname()
591 return Nickname::normalize($this->tw_fields['fullname'], true);
592 } catch (NicknameException $e) {