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 <<<<<<< .merge_file_Bq71r4
60 protected $needLogin = false; // authorization page can also be used to create a new user
63 * Initialize class members. Looks for 'oauth_token' parameter.
65 * @param array $args misc. arguments
67 * @return boolean true
69 function prepare(array $args=array())
71 parent::prepare($args);
72 >>>>>>> .merge_file_Ad5nH4
74 protected function doPreparation()
76 $this->oauth_token = $this->arg('oauth_token');
77 $this->verifier = $this->arg('oauth_verifier');
79 <<<<<<< .merge_file_Bq71r4
80 if ($this->scoped instanceof Profile) {
82 $flink = Foreign_link::getByUserID($this->scoped->getID(), TWITTER_SERVICE);
83 $fuser = $flink->getForeignUser();
91 * @param array $args is ignored since it's now passed in in prepare()
95 function handle(array $args=array())
97 parent::handle($args);
99 if (common_logged_in()) {
100 $user = common_current_user();
101 $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
102 >>>>>>> .merge_file_Ad5nH4
104 // If there's already a foreign link record and a foreign user
105 // (no exceptions were thrown when fetching either of them...)
106 // it means the accounts are already linked, and this is unecessary.
109 common_redirect(common_local_url('twittersettings'));
110 } catch (NoResultException $e) {
111 // but if we don't have a foreign user linked, let's continue authorization procedure.
116 protected function doPost()
118 // User was not logged in to StatusNet before
120 $this->twuid = $this->trimmed('twuid');
122 $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
123 'fullname' => $this->trimmed('tw_fields_fullname'));
125 $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
127 if ($this->arg('create')) {
128 common_debug('TwitterBridgeDebug - POST with create');
129 if (!$this->boolean('license')) {
130 // TRANS: Form validation error displayed when the checkbox to agree to the license has not been checked.
131 throw new ClientException(_m('You cannot register if you do not agree to the license.'));
133 return $this->createNewUser();
134 } elseif ($this->arg('connect')) {
135 common_debug('TwitterBridgeDebug - POST with connect');
136 return $this->connectNewUser();
139 common_debug('TwitterBridgeDebug - ' . print_r($this->args, true));
140 // TRANS: Form validation error displayed when an unhandled error occurs.
141 throw new ClientException(_m('No known action for POST.'));
145 * Asks Twitter for a request token, and then redirects to Twitter
148 protected function authorizeRequestToken()
151 // Get a new request token and authorize it
152 $client = new TwitterOAuthClient();
153 $req_tok = $client->getTwitterRequestToken();
155 // Sock the request token away in the session temporarily
156 $_SESSION['twitter_request_token'] = $req_tok->key;
157 $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
159 $auth_link = $client->getTwitterAuthorizeLink($req_tok, $this->boolean('signin'));
160 } catch (OAuthClientException $e) {
162 'OAuth client error - code: %1s, msg: %2s',
166 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
167 // TRANS: Server error displayed when linking to a Twitter account fails.
168 throw new ServerException(_m('Could not 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()
182 // Check to make sure Twitter returned the same request
183 // token we sent them
185 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
186 // TRANS: Server error displayed when linking to a Twitter account fails because of an incorrect oauth_token.
187 throw new ServerException(_m('Could not link your Twitter account: oauth_token mismatch.'));
190 $twitter_user = null;
193 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], $_SESSION['twitter_request_token_secret']);
195 // Exchange the request token for an access token
196 $atok = $client->getTwitterAccessToken($this->verifier);
198 // Test the access token and get the user's Twitter info
199 $client = new TwitterOAuthClient($atok->key, $atok->secret);
200 $twitter_user = $client->verifyCredentials();
202 } catch (OAuthClientException $e) {
204 'OAuth client error - code: %1$s, msg: %2$s',
208 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
209 // TRANS: Server error displayed when linking to a Twitter account fails.
210 throw new ServerException(_m('Could not link your Twitter account.'));
213 if ($this->scoped instanceof Profile) {
214 // Save the access token and Twitter user info
216 $this->saveForeignLink($this->scoped->getID(), $twitter_user->id, $atok);
217 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
221 $this->twuid = $twitter_user->id;
222 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
223 "fullname" => $twitter_user->name);
224 $this->access_token = $atok;
225 return $this->tryLogin();
228 // Clean up the the mess we made in the session
230 unset($_SESSION['twitter_request_token']);
231 unset($_SESSION['twitter_request_token_secret']);
233 if (common_logged_in()) {
234 common_redirect(common_local_url('twittersettings'));
239 * Saves a Foreign_link between Twitter user and local user,
240 * which includes the access token and secret.
242 * @param int $user_id StatusNet user ID
243 * @param int $twuid Twitter user ID
244 * @param OAuthToken $token the access token to save
248 function saveForeignLink($user_id, $twuid, $access_token)
250 $flink = new Foreign_link();
252 $flink->user_id = $user_id;
253 $flink->service = TWITTER_SERVICE;
255 // delete stale flink, if any
256 $result = $flink->find(true);
258 if (!empty($result)) {
259 $flink->safeDelete();
262 $flink->user_id = $user_id;
263 $flink->foreign_id = $twuid;
264 $flink->service = TWITTER_SERVICE;
266 $creds = TwitterOAuthClient::packToken($access_token);
268 $flink->credentials = $creds;
269 $flink->created = common_sql_now();
271 // Defaults: noticesync on, everything else off
273 $flink->set_flags(true, false, false, false);
275 $flink_id = $flink->insert();
277 // We want to make sure we got a numerical >0 value, not just failed the insert (which would be === false)
278 if (empty($flink_id)) {
279 common_log_db_error($flink, 'INSERT', __FILE__);
280 // TRANS: Server error displayed when linking to a Twitter account fails.
281 throw new ServerException(_m('Could not link your Twitter account.'));
287 function getInstructions()
289 // TRANS: Page instruction. %s is the StatusNet sitename.
290 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'));
295 // TRANS: Page title.
296 return _m('Twitter Account Setup');
299 public function showPage()
301 // $this->oauth_token is only populated once Twitter authorizes our
302 // request token. If it's empty we're at the beginning of the auth
304 if (empty($this->error)) {
305 if (empty($this->oauth_token)) {
306 // authorizeRequestToken either throws an exception or redirects
307 $this->authorizeRequestToken();
309 $this->saveAccessToken();
317 * @fixme much of this duplicates core code, which is very fragile.
318 * Should probably be replaced with an extensible mini version of
319 * the core registration form.
321 function showContent()
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 // TRANS: Fieldset legend.
329 $this->element('legend', null, _m('Connection options'));
331 $this->hidden('access_token_key', $this->access_token->key);
332 $this->hidden('access_token_secret', $this->access_token->secret);
333 $this->hidden('twuid', $this->twuid);
334 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
335 $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
336 $this->hidden('token', common_session_token());
338 // Only allow new account creation if site is not flagged invite-only
339 if (!common_config('site', 'inviteonly')) {
340 $this->elementStart('fieldset');
341 $this->element('legend', null,
342 // TRANS: Fieldset legend.
343 _m('Create new account'));
344 $this->element('p', null,
345 // TRANS: Sub form introduction text.
346 _m('Create a new user with this nickname.'));
347 $this->elementStart('ul', 'form_data');
349 // Hook point for captcha etc
350 Event::handle('StartRegistrationFormData', array($this));
352 $this->elementStart('li');
353 // TRANS: Field label.
354 $this->input('newname', _m('New nickname'),
355 $this->username ?: '',
356 // TRANS: Field title for nickname field.
357 _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
358 $this->elementEnd('li');
359 $this->elementStart('li');
360 // TRANS: Field label.
361 $this->input('email', _m('LABEL','Email'), $this->getEmail(),
362 // TRANS: Field title for e-mail address field.
363 _m('Used only for updates, announcements, '.
364 'and password recovery'));
365 $this->elementEnd('li');
367 // Hook point for captcha etc
368 Event::handle('EndRegistrationFormData', array($this));
370 $this->elementEnd('ul');
371 // TRANS: Button text for creating a new StatusNet account in the Twitter connect page.
372 $this->submit('create', _m('BUTTON','Create'));
373 $this->elementEnd('fieldset');
376 $this->elementStart('fieldset');
377 $this->element('legend', null,
378 // TRANS: Fieldset legend.
379 _m('Connect existing account'));
380 $this->element('p', null,
381 // TRANS: Sub form introduction text.
382 _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
383 $this->elementStart('ul', 'form_data');
384 $this->elementStart('li');
385 // TRANS: Field label.
386 $this->input('nickname', _m('Existing nickname'));
387 $this->elementEnd('li');
388 $this->elementStart('li');
389 // TRANS: Field label.
390 $this->password('password', _m('Password'));
391 $this->elementEnd('li');
392 $this->elementEnd('ul');
393 $this->elementEnd('fieldset');
395 $this->elementStart('fieldset');
396 $this->element('legend', null,
397 // TRANS: Fieldset legend.
399 $this->elementStart('ul', 'form_data');
400 $this->elementStart('li');
401 $this->element('input', array('type' => 'checkbox',
403 'class' => 'checkbox',
406 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
407 // TRANS: Text for license agreement checkbox.
408 // TRANS: %s is the license as configured for the StatusNet site.
409 $message = _m('My text and files are available under %s ' .
410 'except this private data: password, ' .
411 'email address, IM address, and phone number.');
412 $link = '<a href="' .
413 htmlspecialchars(common_config('license', 'url')) .
415 htmlspecialchars(common_config('license', 'title')) .
417 $this->raw(sprintf(htmlspecialchars($message), $link));
418 $this->elementEnd('label');
419 $this->elementEnd('li');
420 $this->elementEnd('ul');
421 $this->elementEnd('fieldset');
422 // TRANS: Button text for connecting an existing StatusNet account in the Twitter connect page..
423 $this->submit('connect', _m('BUTTON','Connect'));
424 $this->elementEnd('fieldset');
425 $this->elementEnd('form');
429 * Get specified e-mail from the form, or the invite code.
435 $email = $this->trimmed('email');
436 if (!empty($email)) {
440 // Terrible hack for invites...
441 if (common_config('site', 'inviteonly')) {
442 $code = $_SESSION['invitecode'];
444 $invite = Invitation::getKV($code);
446 if ($invite && $invite->address_type == 'email') {
447 return $invite->address;
454 protected function createNewUser()
456 common_debug('TwitterBridgeDebug - createNewUser');
457 if (!Event::handle('StartRegistrationTry', array($this))) {
458 common_debug('TwitterBridgeDebug - StartRegistrationTry failed');
459 // TRANS: Client error displayed when trying to create a new user but a plugin aborted the process.
460 throw new ClientException(_m('Registration of new user was aborted, maybe you failed a captcha?'));
463 if (common_config('site', 'closed')) {
464 common_debug('TwitterBridgeDebug - site is closed for registrations');
465 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
466 throw new ClientException(_m('Registration not allowed.'));
471 if (common_config('site', 'inviteonly')) {
472 common_debug('TwitterBridgeDebug - site is inviteonly');
473 $code = $_SESSION['invitecode'];
475 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
476 throw new ClientException(_m('Registration not allowed.'));
479 $invite = Invitation::getKV('code', $code);
481 if (!$invite instanceof Invite) {
482 common_debug('TwitterBridgeDebug - and we failed the invite code test');
483 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
484 throw new ClientException(_m('Not a valid invitation code.'));
488 common_debug('TwitterBridgeDebug - trying our nickname: '.$this->trimmed('newname'));
489 // Nickname::normalize throws exception if the nickname is taken
490 $nickname = Nickname::normalize($this->trimmed('newname'), true);
492 $fullname = trim($this->tw_fields['fullname']);
494 $args = array('nickname' => $nickname, 'fullname' => $fullname);
496 if (!empty($invite)) {
497 $args['code'] = $invite->code;
500 $email = $this->getEmail();
501 if (!empty($email)) {
502 $args['email'] = $email;
505 common_debug('TwitterBridgeDebug - registering user with args:'.var_export($args,true));
506 $user = User::register($args);
508 common_debug('TwitterBridgeDebug - registered the user and saving foreign link for '.$user->id);
510 $this->saveForeignLink($user->id,
512 $this->access_token);
514 common_debug('TwitterBridgeDebug - saving twitter user after creating new local user '.$user->id);
515 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
517 common_set_user($user);
518 common_real_login(true);
520 common_debug('TwitterBridge Plugin - ' .
521 "Registered new user $user->id from Twitter user $this->twuid");
523 Event::handle('EndRegistrationTry', array($this));
525 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)), 303);
528 function connectNewUser()
530 $nickname = $this->trimmed('nickname');
531 $password = $this->trimmed('password');
533 if (!common_check_user($nickname, $password)) {
534 // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
535 // TRANS: the provided username and/or password are incorrect.
536 throw new ClientException(_m('Invalid username or password.'));
539 $user = User::getKV('nickname', $nickname);
541 if ($user instanceof User) {
542 common_debug('TwitterBridge Plugin - ' .
543 "Legit user to connect to Twitter: $nickname");
546 // throws exception on failure
547 $this->saveForeignLink($user->id,
549 $this->access_token);
551 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
553 common_debug('TwitterBridge Plugin - ' .
554 "Connected Twitter user $this->twuid to local user $user->id");
556 common_set_user($user);
557 common_real_login(true);
559 $this->goHome($user->nickname);
562 function connectUser()
564 $user = common_current_user();
566 $result = $this->flinkUser($user->id, $this->twuid);
568 if (empty($result)) {
569 // TRANS: Server error displayed connecting a user to a Twitter user has failed.
570 $this->serverError(_m('Error connecting user to Twitter.'));
573 common_debug('TwitterBridge Plugin - ' .
574 "Connected Twitter user $this->twuid to local user $user->id");
576 // Return to Twitter connection settings tab
577 common_redirect(common_local_url('twittersettings'), 303);
580 protected function tryLogin()
582 common_debug('TwitterBridge Plugin - ' .
583 "Trying login for Twitter user $this->twuid.");
586 $flink = Foreign_link::getByForeignID($this->twuid, TWITTER_SERVICE);
587 $user = $flink->getUser();
589 common_debug('TwitterBridge Plugin - ' .
590 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
592 common_set_user($user);
593 common_real_login(true);
594 $this->goHome($user->nickname);
595 } catch (NoResultException $e) {
596 // Either no Foreign_link was found or not the user connected to it.
597 // Let's just continue to allow creating or logging in as a new user.
599 common_debug("TwitterBridge Plugin - No flink found for twuid: {$this->twuid} - new user");
601 // FIXME: what do we want to do here? I forgot
603 throw new ServerException(_m('No foreign link found for Twitter user'));
606 function goHome($nickname)
608 $url = common_get_returnto();
610 // We don't have to return to it again
611 common_set_returnto(null);
613 $url = common_local_url('all',
618 common_redirect($url, 303);
621 function bestNewNickname()
624 return Nickname::normalize($this->tw_fields['fullname'], true);
625 } catch (NicknameException $e) {