3 * StatusNet, the distributed open-source microblogging tool
5 * Plugin to enable Facebook Connect
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 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')) {
34 require_once INSTALLDIR . '/plugins/Facebook/FacebookPlugin.php';
36 class FBConnectauthAction extends Action
39 var $fb_fields = null;
41 function prepare($args) {
42 parent::prepare($args);
44 $this->fbuid = getFacebook()->get_loggedin_user();
46 if ($this->fbuid > 0) {
47 $this->fb_fields = $this->getFacebookFields($this->fbuid,
48 array('first_name', 'last_name', 'name'));
50 list($proxy, $ip) = common_client_ip();
52 common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
53 "Failed auth attempt, proxy = $proxy, ip = $ip.");
55 $this->clientError(_m('You must be logged into Facebook to ' .
56 'use Facebook Connect.'));
62 function handle($args)
64 parent::handle($args);
66 if (common_is_real_login()) {
67 // User is already logged in. Does she already have a linked Facebook acct?
68 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
71 // User already has a linked Facebook account and shouldn't be here
72 common_debug('Facebook Connect Plugin - ' .
73 'There is already a local user (' . $flink->user_id .
74 ') linked with this Facebook (' . $this->fbuid . ').');
76 // We don't want these cookies
77 getFacebook()->clear_cookie_state();
79 $this->clientError(_m('There is already a local user linked with this Facebook account.'));
82 // User came from the Facebook connect settings tab, and
83 // probably just wants to link/relink their Facebook account
87 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
89 $token = $this->trimmed('token');
90 if (!$token || $token != common_session_token()) {
91 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
94 if ($this->arg('create')) {
95 if (!$this->boolean('license')) {
96 $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
97 $this->trimmed('newname'));
100 $this->createNewUser();
101 } else if ($this->arg('connect')) {
102 $this->connectNewUser();
104 common_debug('Facebook Connect Plugin - ' .
105 print_r($this->args, true));
106 $this->showForm(_m('An unknown error has occured.'),
107 $this->trimmed('newname'));
114 function showPageNotice()
117 $this->element('div', array('class' => 'error'), $this->error);
119 $this->element('div', 'instructions',
120 // TRANS: %s is the site name.
121 sprintf(_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 account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
127 // TRANS: Page title.
128 return _m('Facebook Account Setup');
131 function showForm($error=null, $username=null)
133 $this->error = $error;
134 $this->username = $username;
145 * @fixme much of this duplicates core code, which is very fragile.
146 * Should probably be replaced with an extensible mini version of
147 * the core registration form.
149 function showContent()
151 if (!empty($this->message_text)) {
152 $this->element('p', null, $this->message);
156 $this->elementStart('form', array('method' => 'post',
157 'id' => 'form_settings_facebook_connect',
158 'class' => 'form_settings',
159 'action' => common_local_url('FBConnectAuth')));
160 $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
162 $this->element('legend', null, _m('Connection options'));
163 $this->elementStart('ul', 'form_data');
164 $this->elementStart('li');
165 $this->element('input', array('type' => 'checkbox',
167 'class' => 'checkbox',
170 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
171 // TRANS: %s is the name of the license used by the user for their status updates.
172 $message = _m('My text and files are available under %s ' .
173 'except this private data: password, ' .
174 'email address, IM address, and phone number.');
175 $link = '<a href="' .
176 htmlspecialchars(common_config('license', 'url')) .
178 htmlspecialchars(common_config('license', 'title')) .
180 $this->raw(sprintf(htmlspecialchars($message), $link));
181 $this->elementEnd('label');
182 $this->elementEnd('li');
183 $this->elementEnd('ul');
185 $this->elementStart('fieldset');
186 $this->hidden('token', common_session_token());
187 $this->element('legend', null,
189 _m('Create new account'));
190 $this->element('p', null,
191 _m('Create a new user with this nickname.'));
192 $this->elementStart('ul', 'form_data');
193 $this->elementStart('li');
194 // TRANS: Field label.
195 $this->input('newname', _m('New nickname'),
196 ($this->username) ? $this->username : '',
197 _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
198 $this->elementEnd('li');
199 $this->elementEnd('ul');
200 // TRANS: Submit button.
201 $this->submit('create', _m('BUTTON','Create'));
202 $this->elementEnd('fieldset');
204 $this->elementStart('fieldset');
206 $this->element('legend', null,
207 _m('Connect existing account'));
208 $this->element('p', null,
209 _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
210 $this->elementStart('ul', 'form_data');
211 $this->elementStart('li');
212 // TRANS: Field label.
213 $this->input('nickname', _m('Existing nickname'));
214 $this->elementEnd('li');
215 $this->elementStart('li');
216 $this->password('password', _m('Password'));
217 $this->elementEnd('li');
218 $this->elementEnd('ul');
219 // TRANS: Submit button.
220 $this->submit('connect', _m('BUTTON','Connect'));
221 $this->elementEnd('fieldset');
223 $this->elementEnd('fieldset');
224 $this->elementEnd('form');
227 function message($msg)
229 $this->message_text = $msg;
233 function createNewUser()
235 if (common_config('site', 'closed')) {
236 // TRANS: Client error trying to register with registrations not allowed.
237 $this->clientError(_m('Registration not allowed.'));
243 if (common_config('site', 'inviteonly')) {
244 $code = $_SESSION['invitecode'];
246 // TRANS: Client error trying to register with registrations 'invite only'.
247 $this->clientError(_m('Registration not allowed.'));
251 $invite = Invitation::staticGet($code);
253 if (empty($invite)) {
254 // TRANS: Client error trying to register with an invalid invitation code.
255 $this->clientError(_m('Not a valid invitation code.'));
261 $nickname = Nickname::normalize($this->trimmed('newname'));
262 } catch (NicknameException $e) {
263 $this->showForm($e->getMessage());
266 if (!User::allowed_nickname($nickname)) {
267 $this->showForm(_m('Nickname not allowed.'));
271 if (User::staticGet('nickname', $nickname)) {
272 $this->showForm(_m('Nickname already in use. Try another one.'));
276 $fullname = trim($this->fb_fields['firstname'] .
277 ' ' . $this->fb_fields['lastname']);
279 $args = array('nickname' => $nickname, 'fullname' => $fullname);
281 if (!empty($invite)) {
282 $args['code'] = $invite->code;
285 $user = User::register($args);
287 $result = $this->flinkUser($user->id, $this->fbuid);
290 $this->serverError(_m('Error connecting user to Facebook.'));
294 common_set_user($user);
295 common_real_login(true);
297 common_debug('Facebook Connect Plugin - ' .
298 "Registered new user $user->id from Facebook user $this->fbuid");
300 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
304 function connectNewUser()
306 $nickname = $this->trimmed('nickname');
307 $password = $this->trimmed('password');
309 if (!common_check_user($nickname, $password)) {
310 $this->showForm(_m('Invalid username or password.'));
314 $user = User::staticGet('nickname', $nickname);
317 common_debug('Facebook Connect Plugin - ' .
318 "Legit user to connect to Facebook: $nickname");
321 $result = $this->flinkUser($user->id, $this->fbuid);
324 $this->serverError(_m('Error connecting user to Facebook.'));
328 common_debug('Facebook Connnect Plugin - ' .
329 "Connected Facebook user $this->fbuid to local user $user->id");
331 common_set_user($user);
332 common_real_login(true);
334 $this->goHome($user->nickname);
337 function connectUser()
339 $user = common_current_user();
341 $result = $this->flinkUser($user->id, $this->fbuid);
343 if (empty($result)) {
344 $this->serverError(_m('Error connecting user to Facebook.'));
348 common_debug('Facebook Connect Plugin - ' .
349 "Connected Facebook user $this->fbuid to local user $user->id");
351 // Return to Facebook connection settings tab
352 common_redirect(common_local_url('FBConnectSettings'), 303);
357 common_debug('Facebook Connect Plugin - ' .
358 "Trying login for Facebook user $this->fbuid.");
360 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
362 if (!empty($flink)) {
363 $user = $flink->getUser();
367 common_debug('Facebook Connect Plugin - ' .
368 "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
370 common_set_user($user);
371 common_real_login(true);
372 $this->goHome($user->nickname);
377 common_debug('Facebook Connect Plugin - ' .
378 "No flink found for fbuid: $this->fbuid - new user");
380 $this->showForm(null, $this->bestNewNickname());
384 function goHome($nickname)
386 $url = common_get_returnto();
388 // We don't have to return to it again
389 common_set_returnto(null);
391 $url = common_local_url('all',
396 common_redirect($url, 303);
399 function flinkUser($user_id, $fbuid)
401 $flink = new Foreign_link();
402 $flink->user_id = $user_id;
403 $flink->foreign_id = $fbuid;
404 $flink->service = FACEBOOK_CONNECT_SERVICE;
405 $flink->created = common_sql_now();
407 $flink_id = $flink->insert();
412 function bestNewNickname()
414 if (!empty($this->fb_fields['name'])) {
415 $nickname = $this->nicknamize($this->fb_fields['name']);
416 if ($this->isNewNickname($nickname)) {
423 $fullname = trim($this->fb_fields['firstname'] .
424 ' ' . $this->fb_fields['lastname']);
426 if (!empty($fullname)) {
427 $fullname = $this->nicknamize($fullname);
428 if ($this->isNewNickname($fullname)) {
437 * Given a string, try to make it work as a nickname
439 function nicknamize($str)
441 $str = preg_replace('/\W/', '', $str);
442 return strtolower($str);
445 function isNewNickname($str)
447 if (!Nickname::isValid($str)) {
450 if (!User::allowed_nickname($str)) {
453 if (User::staticGet('nickname', $str)) {
459 // XXX: Consider moving this to lib/facebookutil.php
460 function getFacebookFields($fb_uid, $fields) {
463 $facebook = getFacebook();
465 $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
470 return reset($infos);
472 } catch (Exception $e) {
473 common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
474 "Facebook client failure when requesting " .
475 join(",", $fields) . " on uid " . $fb_uid .
476 " : ". $e->getMessage());