3 * StatusNet, the distributed open-source microblogging tool
5 * Register a local user and connect it to a Facebook account
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 * @copyright 2010 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')) {
34 class FacebookregisterAction extends Action
37 private $facebook = null; // Facebook client
38 private $fbuid = null; // Facebook user ID
39 private $fbuser = null; // Facebook user object (JSON)
41 function prepare($args) {
43 parent::prepare($args);
45 $this->facebook = new Facebook(
47 'appId' => common_config('facebook', 'appid'),
48 'secret' => common_config('facebook', 'secret'),
53 // Check for a Facebook user session
55 $session = $this->facebook->getSession();
60 $this->fbuid = $this->facebook->getUser();
61 $this->fbuser = $this->facebook->api('/me');
62 } catch (FacebookApiException $e) {
63 common_log(LOG_ERROR, $e, __FILE__);
67 if (!empty($this->fbuser)) {
69 // OKAY, all is well... proceed to register
71 common_debug("Found a valid Facebook user.", __FILE__);
74 // This shouldn't happen in the regular course of things
76 list($proxy, $ip) = common_client_ip();
81 'Failed Facebook authentication attempt, proxy = %s, ip = %s.',
89 _m('You must be logged into Facebook to register a local account using Facebook.')
96 function handle($args)
98 parent::handle($args);
100 if (common_is_real_login()) {
102 // User is already logged in, are her accounts already linked?
104 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_SERVICE);
106 if (!empty($flink)) {
108 // User already has a linked Facebook account and shouldn't be here!
112 'There\'s already a local user %d linked with Facebook user %s.',
119 _m('There is already a local account linked with that Facebook account.')
124 // Possibly reconnect an existing account
126 $this->connectUser();
129 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
131 $token = $this->trimmed('token');
133 if (!$token || $token != common_session_token()) {
135 _m('There was a problem with your session token. Try again, please.'));
139 if ($this->arg('create')) {
141 if (!$this->boolean('license')) {
143 _m('You can\'t register if you don\'t agree to the license.'),
144 $this->trimmed('newname')
149 // We has a valid Facebook session and the Facebook user has
150 // agreed to the SN license, so create a new user
151 $this->createNewUser();
153 } else if ($this->arg('connect')) {
155 $this->connectNewUser();
160 _m('An unknown error has occured.'),
161 $this->trimmed('newname')
170 function showPageNotice()
174 $this->element('div', array('class' => 'error'), $this->error);
179 'div', 'instructions',
180 // TRANS: %s is the site name.
182 _m('This is the first time you\'ve logged into %s so we must connect your Facebook to a local account. You can either create a new local account, or connect with an existing local account.'),
183 common_config('site', 'name')
191 // TRANS: Page title.
192 return _m('Facebook Setup');
195 function showForm($error=null, $username=null)
197 $this->error = $error;
198 $this->username = $username;
209 * @fixme much of this duplicates core code, which is very fragile.
210 * Should probably be replaced with an extensible mini version of
211 * the core registration form.
213 function showContent()
215 if (!empty($this->message_text)) {
216 $this->element('p', null, $this->message);
220 $this->elementStart('form', array('method' => 'post',
221 'id' => 'form_settings_facebook_connect',
222 'class' => 'form_settings',
223 'action' => common_local_url('facebookregister')));
224 $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
226 $this->element('legend', null, _m('Connection options'));
227 $this->elementStart('ul', 'form_data');
228 $this->elementStart('li');
229 $this->element('input', array('type' => 'checkbox',
231 'class' => 'checkbox',
234 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
235 // TRANS: %s is the name of the license used by the user for their status updates.
236 $message = _m('My text and files are available under %s ' .
237 'except this private data: password, ' .
238 'email address, IM address, and phone number.');
239 $link = '<a href="' .
240 htmlspecialchars(common_config('license', 'url')) .
242 htmlspecialchars(common_config('license', 'title')) .
244 $this->raw(sprintf(htmlspecialchars($message), $link));
245 $this->elementEnd('label');
246 $this->elementEnd('li');
247 $this->elementEnd('ul');
249 $this->elementStart('fieldset');
250 $this->hidden('token', common_session_token());
251 $this->element('legend', null,
253 _m('Create new account'));
254 $this->element('p', null,
255 _m('Create a new user with this nickname.'));
256 $this->elementStart('ul', 'form_data');
257 $this->elementStart('li');
258 // TRANS: Field label.
259 $this->input('newname', _m('New nickname'),
260 ($this->username) ? $this->username : '',
261 _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
262 $this->elementEnd('li');
263 $this->elementEnd('ul');
264 // TRANS: Submit button.
265 $this->submit('create', _m('BUTTON','Create'));
266 $this->elementEnd('fieldset');
268 $this->elementStart('fieldset');
270 $this->element('legend', null,
271 _m('Connect existing account'));
272 $this->element('p', null,
273 _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
274 $this->elementStart('ul', 'form_data');
275 $this->elementStart('li');
276 // TRANS: Field label.
277 $this->input('nickname', _m('Existing nickname'));
278 $this->elementEnd('li');
279 $this->elementStart('li');
280 $this->password('password', _m('Password'));
281 $this->elementEnd('li');
282 $this->elementEnd('ul');
283 // TRANS: Submit button.
284 $this->submit('connect', _m('BUTTON','Connect'));
285 $this->elementEnd('fieldset');
287 $this->elementEnd('fieldset');
288 $this->elementEnd('form');
291 function message($msg)
293 $this->message_text = $msg;
297 function createNewUser()
299 if (common_config('site', 'closed')) {
300 // TRANS: Client error trying to register with registrations not allowed.
301 $this->clientError(_m('Registration not allowed.'));
307 if (common_config('site', 'inviteonly')) {
308 $code = $_SESSION['invitecode'];
310 // TRANS: Client error trying to register with registrations 'invite only'.
311 $this->clientError(_m('Registration not allowed.'));
315 $invite = Invitation::staticGet($code);
317 if (empty($invite)) {
318 // TRANS: Client error trying to register with an invalid invitation code.
319 $this->clientError(_m('Not a valid invitation code.'));
324 $nickname = $this->trimmed('newname');
326 if (!Validate::string($nickname, array('min_length' => 1,
328 'format' => NICKNAME_FMT))) {
329 $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
333 if (!User::allowed_nickname($nickname)) {
334 $this->showForm(_m('Nickname not allowed.'));
338 if (User::staticGet('nickname', $nickname)) {
339 $this->showForm(_m('Nickname already in use. Try another one.'));
344 'nickname' => $nickname,
345 'fullname' => $this->fbuser['firstname'] . ' ' . $this->fbuser['lastname'],
346 // XXX: Figure out how to get email
347 'homepage' => $this->fbuser['link'],
348 'bio' => $this->fbuser['about'],
349 'location' => $this->fbuser['location']['name']
352 if (!empty($invite)) {
353 $args['code'] = $invite->code;
356 $user = User::register($args);
358 $result = $this->flinkUser($user->id, $this->fbuid);
361 $this->serverError(_m('Error connecting user to Facebook.'));
365 common_set_user($user);
366 common_real_login(true);
371 'Registered new user %d from Facebook user %s',
381 array('nickname' => $user->nickname)
387 function connectNewUser()
389 $nickname = $this->trimmed('nickname');
390 $password = $this->trimmed('password');
392 if (!common_check_user($nickname, $password)) {
393 $this->showForm(_m('Invalid username or password.'));
397 $user = User::staticGet('nickname', $nickname);
400 common_debug('Facebook Connect Plugin - ' .
401 "Legit user to connect to Facebook: $nickname");
404 $result = $this->flinkUser($user->id, $this->fbuid);
407 $this->serverError(_m('Error connecting user to Facebook.'));
411 common_debug('Facebook Connnect Plugin - ' .
412 "Connected Facebook user $this->fbuid to local user $user->id");
414 common_set_user($user);
415 common_real_login(true);
417 $this->goHome($user->nickname);
420 function connectUser()
422 $user = common_current_user();
424 $result = $this->flinkUser($user->id, $this->fbuid);
426 if (empty($result)) {
427 $this->serverError(_m('Error connecting user to Facebook.'));
431 common_debug('Facebook Connect Plugin - ' .
432 "Connected Facebook user $this->fbuid to local user $user->id");
434 // Return to Facebook connection settings tab
435 common_redirect(common_local_url('FBConnectSettings'), 303);
440 common_debug('Facebook Connect Plugin - ' .
441 "Trying login for Facebook user $this->fbuid.");
443 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
445 if (!empty($flink)) {
446 $user = $flink->getUser();
450 common_debug('Facebook Connect Plugin - ' .
451 "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
453 common_set_user($user);
454 common_real_login(true);
455 $this->goHome($user->nickname);
460 common_debug('Facebook Connect Plugin - ' .
461 "No flink found for fbuid: $this->fbuid - new user");
463 $this->showForm(null, $this->bestNewNickname());
467 function goHome($nickname)
469 $url = common_get_returnto();
471 // We don't have to return to it again
472 common_set_returnto(null);
474 $url = common_local_url('all',
479 common_redirect($url, 303);
482 function flinkUser($user_id, $fbuid)
484 $flink = new Foreign_link();
485 $flink->user_id = $user_id;
486 $flink->foreign_id = $fbuid;
487 $flink->service = FACEBOOK_SERVICE;
489 // Pull the access token from the Facebook cookies
490 $flink->credentials = $this->facebook->getAccessToken();
492 $flink->created = common_sql_now();
494 $flink_id = $flink->insert();
499 function bestNewNickname()
501 if (!empty($this->fbuser['name'])) {
502 $nickname = $this->nicknamize($this->fbuser['name']);
503 if ($this->isNewNickname($nickname)) {
510 $fullname = trim($this->fbuser['firstname'] .
511 ' ' . $this->fbuser['lastname']);
513 if (!empty($fullname)) {
514 $fullname = $this->nicknamize($fullname);
515 if ($this->isNewNickname($fullname)) {
524 * Given a string, try to make it work as a nickname
526 function nicknamize($str)
528 $str = preg_replace('/\W/', '', $str);
529 return strtolower($str);
532 function isNewNickname($str)
534 if (!Validate::string($str, array('min_length' => 1,
536 'format' => NICKNAME_FMT))) {
539 if (!User::allowed_nickname($str)) {
542 if (User::staticGet('nickname', $str)) {