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';
36 * Class for doing OAuth authentication against Twitter
38 * Peforms the OAuth "dance" between StatusNet and Twitter -- requests a token,
39 * authorizes it, and exchanges it for an access token. It also creates a link
40 * (Foreign_link) between the StatusNet user and Twitter user and stores the
41 * access token and secret in the link.
45 * @author Zach Copley <zach@status.net>
46 * @author Julien C <chaumond@gmail.com>
47 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
48 * @link http://status.net/
51 class TwitterauthorizationAction extends FormAction
54 var $tw_fields = null;
55 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->signin = $this->boolean('signin');
64 $this->oauth_token = $this->arg('oauth_token');
65 $this->verifier = $this->arg('oauth_verifier');
67 if ($this->scoped instanceof Profile) {
68 $flink = Foreign_link::getByUserID($this->scoped->getID(), TWITTER_SERVICE);
70 // If there's already a foreign link record and a foreign user
71 // it means the accounts are already linked, and this is unecessary.
74 if ($flink instanceof Foreign_link) {
76 $fuser = $flink->getForeignUser();
77 common_redirect(common_local_url('twittersettings'));
78 } catch (NoResultException $e) {
79 // ok, so no foreign user but there's a foreign link??
80 // this logic is left since the StatusNet days
85 // $this->oauth_token is only populated once Twitter authorizes our
86 // request token. If it's empty we're at the beginning of the auth
88 if (empty($this->oauth_token)) {
89 // authorizeRequestToken either throws an exception or redirects
90 $this->authorizeRequestToken();
92 $this->saveAccessToken();
96 protected function doPost()
98 // User was not logged in to StatusNet before
100 $this->twuid = $this->trimmed('twuid');
102 $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_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 if ($this->arg('create')) {
108 if (!$this->boolean('license')) {
109 // TRANS: Form validation error displayed when the checkbox to agree to the license has not been checked.
110 throw new ClientException(_m('You cannot register if you do not agree to the license.'));
112 return $this->createNewUser();
113 } else if ($this->arg('connect')) {
114 return $this->connectNewUser();
117 common_debug('Twitter bridge - ' . print_r($this->args, true));
118 // TRANS: Form validation error displayed when an unhandled error occurs.
119 throw new ClientException(_m('No known action for POST.'));
123 * Asks Twitter for a request token, and then redirects to Twitter
126 protected function authorizeRequestToken()
129 // Get a new request token and authorize it
131 $client = new TwitterOAuthClient();
132 $req_tok = $client->getTwitterRequestToken();
134 // Sock the request token away in the session temporarily
136 $_SESSION['twitter_request_token'] = $req_tok->key;
137 $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
139 $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
140 } catch (OAuthClientException $e) {
142 'OAuth client error - code: %1s, msg: %2s',
146 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
147 // TRANS: Server error displayed when linking to a Twitter account fails.
148 throw new ServerException(_m('Could not link your Twitter account.'));
151 common_redirect($auth_link);
155 * Called when Twitter returns an authorized request token. Exchanges
156 * it for an access token and stores it.
160 function saveAccessToken()
162 // Check to make sure Twitter returned the same request
163 // token we sent them
165 if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
166 // TRANS: Server error displayed when linking to a Twitter account fails because of an incorrect oauth_token.
167 throw new ServerException(_m('Could not link your Twitter account: oauth_token mismatch.'));
170 $twitter_user = null;
174 $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
175 $_SESSION['twitter_request_token_secret']);
177 // Exchange the request token for an access token
179 $atok = $client->getTwitterAccessToken($this->verifier);
181 // Test the access token and get the user's Twitter info
183 $client = new TwitterOAuthClient($atok->key, $atok->secret);
184 $twitter_user = $client->verifyCredentials();
186 } catch (OAuthClientException $e) {
188 'OAuth client error - code: %1$s, msg: %2$s',
192 common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
194 // TRANS: Server error displayed when linking to a Twitter account fails.
195 _m('Could not link your Twitter account.')
199 if (common_logged_in()) {
200 // Save the access token and Twitter user info
202 $this->saveForeignLink($this->scoped->getID(), $twitter_user->id, $atok);
203 save_twitter_user($twitter_user->id, $twitter_user->screen_name);
207 $this->twuid = $twitter_user->id;
208 $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
209 "fullname" => $twitter_user->name);
210 $this->access_token = $atok;
214 // Clean up the the mess we made in the session
216 unset($_SESSION['twitter_request_token']);
217 unset($_SESSION['twitter_request_token_secret']);
219 if (common_logged_in()) {
220 common_redirect(common_local_url('twittersettings'));
225 * Saves a Foreign_link between Twitter user and local user,
226 * which includes the access token and secret.
228 * @param int $user_id StatusNet user ID
229 * @param int $twuid Twitter user ID
230 * @param OAuthToken $token the access token to save
234 function saveForeignLink($user_id, $twuid, $access_token)
236 $flink = new Foreign_link();
238 $flink->user_id = $user_id;
239 $flink->service = TWITTER_SERVICE;
241 // delete stale flink, if any
242 $result = $flink->find(true);
244 if (!empty($result)) {
245 $flink->safeDelete();
248 $flink->user_id = $user_id;
249 $flink->foreign_id = $twuid;
250 $flink->service = TWITTER_SERVICE;
252 $creds = TwitterOAuthClient::packToken($access_token);
254 $flink->credentials = $creds;
255 $flink->created = common_sql_now();
257 // Defaults: noticesync on, everything else off
259 $flink->set_flags(true, false, false, false);
261 $flink_id = $flink->insert();
263 // We want to make sure we got a numerical >0 value, not just failed the insert (which would be === false)
264 if (empty($flink_id)) {
265 common_log_db_error($flink, 'INSERT', __FILE__);
266 // TRANS: Server error displayed when linking to a Twitter account fails.
267 throw new ServerException(_m('Could not link your Twitter account.'));
273 function getInstructions()
275 // TRANS: Page instruction. %s is the StatusNet sitename.
276 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'));
281 // TRANS: Page title.
282 return _m('Twitter Account Setup');
286 * @fixme much of this duplicates core code, which is very fragile.
287 * Should probably be replaced with an extensible mini version of
288 * the core registration form.
290 function showContent()
292 if (!empty($this->message_text)) {
293 $this->element('p', null, $this->message);
297 $this->elementStart('form', array('method' => 'post',
298 'id' => 'form_settings_twitter_connect',
299 'class' => 'form_settings',
300 'action' => common_local_url('twitterauthorization')));
301 $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
302 // TRANS: Fieldset legend.
303 $this->element('legend', null, _m('Connection options'));
305 $this->hidden('access_token_key', $this->access_token->key);
306 $this->hidden('access_token_secret', $this->access_token->secret);
307 $this->hidden('twuid', $this->twuid);
308 $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
309 $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
310 $this->hidden('token', common_session_token());
312 // Don't allow new account creation if site is flagged as invite only
313 if (common_config('site', 'inviteonly') == false) {
314 $this->elementStart('fieldset');
315 $this->element('legend', null,
316 // TRANS: Fieldset legend.
317 _m('Create new account'));
318 $this->element('p', null,
319 // TRANS: Sub form introduction text.
320 _m('Create a new user with this nickname.'));
321 $this->elementStart('ul', 'form_data');
323 // Hook point for captcha etc
324 Event::handle('StartRegistrationFormData', array($this));
326 $this->elementStart('li');
327 // TRANS: Field label.
328 $this->input('newname', _m('New nickname'),
329 $this->username ?: '',
330 // TRANS: Field title for nickname field.
331 _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
332 $this->elementEnd('li');
333 $this->elementStart('li');
334 // TRANS: Field label.
335 $this->input('email', _m('LABEL','Email'), $this->getEmail(),
336 // TRANS: Field title for e-mail address field.
337 _m('Used only for updates, announcements, '.
338 'and password recovery'));
339 $this->elementEnd('li');
341 // Hook point for captcha etc
342 Event::handle('EndRegistrationFormData', array($this));
344 $this->elementEnd('ul');
345 // TRANS: Button text for creating a new StatusNet account in the Twitter connect page.
346 $this->submit('create', _m('BUTTON','Create'));
347 $this->elementEnd('fieldset');
350 $this->elementStart('fieldset');
351 $this->element('legend', null,
352 // TRANS: Fieldset legend.
353 _m('Connect existing account'));
354 $this->element('p', null,
355 // TRANS: Sub form introduction text.
356 _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
357 $this->elementStart('ul', 'form_data');
358 $this->elementStart('li');
359 // TRANS: Field label.
360 $this->input('nickname', _m('Existing nickname'));
361 $this->elementEnd('li');
362 $this->elementStart('li');
363 // TRANS: Field label.
364 $this->password('password', _m('Password'));
365 $this->elementEnd('li');
366 $this->elementEnd('ul');
367 $this->elementEnd('fieldset');
369 $this->elementStart('fieldset');
370 $this->element('legend', null,
371 // TRANS: Fieldset legend.
373 $this->elementStart('ul', 'form_data');
374 $this->elementStart('li');
375 $this->element('input', array('type' => 'checkbox',
377 'class' => 'checkbox',
380 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
381 // TRANS: Text for license agreement checkbox.
382 // TRANS: %s is the license as configured for the StatusNet site.
383 $message = _m('My text and files are available under %s ' .
384 'except this private data: password, ' .
385 'email address, IM address, and phone number.');
386 $link = '<a href="' .
387 htmlspecialchars(common_config('license', 'url')) .
389 htmlspecialchars(common_config('license', 'title')) .
391 $this->raw(sprintf(htmlspecialchars($message), $link));
392 $this->elementEnd('label');
393 $this->elementEnd('li');
394 $this->elementEnd('ul');
395 $this->elementEnd('fieldset');
396 // TRANS: Button text for connecting an existing StatusNet account in the Twitter connect page..
397 $this->submit('connect', _m('BUTTON','Connect'));
398 $this->elementEnd('fieldset');
399 $this->elementEnd('form');
403 * Get specified e-mail from the form, or the invite code.
409 $email = $this->trimmed('email');
410 if (!empty($email)) {
414 // Terrible hack for invites...
415 if (common_config('site', 'inviteonly')) {
416 $code = $_SESSION['invitecode'];
418 $invite = Invitation::getKV($code);
420 if ($invite && $invite->address_type == 'email') {
421 return $invite->address;
428 function message($msg)
430 $this->message_text = $msg;
434 function createNewUser()
436 if (!Event::handle('StartRegistrationTry', array($this))) {
437 // TRANS: Client error displayed when trying to create a new user but a plugin aborted the process.
438 throw new ClientException(_m('Registration of new user was aborted, maybe you failed a captcha?'));
441 if (common_config('site', 'closed')) {
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.'));
448 if (common_config('site', 'inviteonly')) {
449 $code = $_SESSION['invitecode'];
451 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
452 throw new ClientException(_m('Registration not allowed.'));
455 $invite = Invitation::getKV('code', $code);
457 if (!$invite instanceof Invite) {
458 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
459 throw new ClientException(_m('Not a valid invitation code.'));
463 // Nickname::normalize throws exception if the nickname is taken
464 $nickname = Nickname::normalize($this->trimmed('newname'), true);
466 $fullname = trim($this->tw_fields['fullname']);
468 $args = array('nickname' => $nickname, 'fullname' => $fullname);
470 if (!empty($invite)) {
471 $args['code'] = $invite->code;
474 $email = $this->getEmail();
475 if (!empty($email)) {
476 $args['email'] = $email;
479 $user = User::register($args);
481 $this->saveForeignLink($user->id,
483 $this->access_token);
485 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
487 common_set_user($user);
488 common_real_login(true);
490 common_debug('TwitterBridge Plugin - ' .
491 "Registered new user $user->id from Twitter user $this->twuid");
493 Event::handle('EndRegistrationTry', array($this));
495 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)), 303);
498 function connectNewUser()
500 $nickname = $this->trimmed('nickname');
501 $password = $this->trimmed('password');
503 if (!common_check_user($nickname, $password)) {
504 // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
505 // TRANS: the provided username and/or password are incorrect.
506 throw new ClientException(_m('Invalid username or password.'));
509 $user = User::getKV('nickname', $nickname);
511 if ($user instanceof User) {
512 common_debug('TwitterBridge Plugin - ' .
513 "Legit user to connect to Twitter: $nickname");
516 // throws exception on failure
517 $this->saveForeignLink($user->id,
519 $this->access_token);
521 save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
523 common_debug('TwitterBridge Plugin - ' .
524 "Connected Twitter user $this->twuid to local user $user->id");
526 common_set_user($user);
527 common_real_login(true);
529 $this->goHome($user->nickname);
532 function connectUser()
534 $user = common_current_user();
536 $result = $this->flinkUser($user->id, $this->twuid);
538 if (empty($result)) {
539 // TRANS: Server error displayed connecting a user to a Twitter user has failed.
540 $this->serverError(_m('Error connecting user to Twitter.'));
543 common_debug('TwitterBridge Plugin - ' .
544 "Connected Twitter user $this->twuid to local user $user->id");
546 // Return to Twitter connection settings tab
547 common_redirect(common_local_url('twittersettings'), 303);
552 common_debug('TwitterBridge Plugin - ' .
553 "Trying login for Twitter user $this->twuid.");
555 $flink = Foreign_link::getByForeignID($this->twuid,
558 if (!empty($flink)) {
559 $user = $flink->getUser();
563 common_debug('TwitterBridge Plugin - ' .
564 "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
566 common_set_user($user);
567 common_real_login(true);
568 $this->goHome($user->nickname);
573 common_debug('TwitterBridge Plugin - ' .
574 "No flink found for twuid: $this->twuid - new user");
576 $this->showForm(null, $this->bestNewNickname());
580 function goHome($nickname)
582 $url = common_get_returnto();
584 // We don't have to return to it again
585 common_set_returnto(null);
587 $url = common_local_url('all',
592 common_redirect($url, 303);
595 function bestNewNickname()
598 return Nickname::normalize($this->tw_fields['fullname'], true);
599 } catch (NicknameException $e) {