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.'));
260 $nickname = $this->trimmed('newname');
262 if (!Validate::string($nickname, array('min_length' => 1,
264 'format' => NICKNAME_FMT))) {
265 $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
269 if (!User::allowed_nickname($nickname)) {
270 $this->showForm(_m('Nickname not allowed.'));
274 if (User::staticGet('nickname', $nickname)) {
275 $this->showForm(_m('Nickname already in use. Try another one.'));
279 $fullname = trim($this->fb_fields['firstname'] .
280 ' ' . $this->fb_fields['lastname']);
282 $args = array('nickname' => $nickname, 'fullname' => $fullname);
284 if (!empty($invite)) {
285 $args['code'] = $invite->code;
288 $user = User::register($args);
290 $result = $this->flinkUser($user->id, $this->fbuid);
293 $this->serverError(_m('Error connecting user to Facebook.'));
297 common_set_user($user);
298 common_real_login(true);
300 common_debug('Facebook Connect Plugin - ' .
301 "Registered new user $user->id from Facebook user $this->fbuid");
303 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
307 function connectNewUser()
309 $nickname = $this->trimmed('nickname');
310 $password = $this->trimmed('password');
312 if (!common_check_user($nickname, $password)) {
313 $this->showForm(_m('Invalid username or password.'));
317 $user = User::staticGet('nickname', $nickname);
320 common_debug('Facebook Connect Plugin - ' .
321 "Legit user to connect to Facebook: $nickname");
324 $result = $this->flinkUser($user->id, $this->fbuid);
327 $this->serverError(_m('Error connecting user to Facebook.'));
331 common_debug('Facebook Connnect Plugin - ' .
332 "Connected Facebook user $this->fbuid to local user $user->id");
334 common_set_user($user);
335 common_real_login(true);
337 $this->goHome($user->nickname);
340 function connectUser()
342 $user = common_current_user();
344 $result = $this->flinkUser($user->id, $this->fbuid);
346 if (empty($result)) {
347 $this->serverError(_m('Error connecting user to Facebook.'));
351 common_debug('Facebook Connect Plugin - ' .
352 "Connected Facebook user $this->fbuid to local user $user->id");
354 // Return to Facebook connection settings tab
355 common_redirect(common_local_url('FBConnectSettings'), 303);
360 common_debug('Facebook Connect Plugin - ' .
361 "Trying login for Facebook user $this->fbuid.");
363 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
365 if (!empty($flink)) {
366 $user = $flink->getUser();
370 common_debug('Facebook Connect Plugin - ' .
371 "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
373 common_set_user($user);
374 common_real_login(true);
375 $this->goHome($user->nickname);
380 common_debug('Facebook Connect Plugin - ' .
381 "No flink found for fbuid: $this->fbuid - new user");
383 $this->showForm(null, $this->bestNewNickname());
387 function goHome($nickname)
389 $url = common_get_returnto();
391 // We don't have to return to it again
392 common_set_returnto(null);
394 $url = common_local_url('all',
399 common_redirect($url, 303);
402 function flinkUser($user_id, $fbuid)
404 $flink = new Foreign_link();
405 $flink->user_id = $user_id;
406 $flink->foreign_id = $fbuid;
407 $flink->service = FACEBOOK_CONNECT_SERVICE;
408 $flink->created = common_sql_now();
410 $flink_id = $flink->insert();
415 function bestNewNickname()
417 if (!empty($this->fb_fields['name'])) {
418 $nickname = $this->nicknamize($this->fb_fields['name']);
419 if ($this->isNewNickname($nickname)) {
426 $fullname = trim($this->fb_fields['firstname'] .
427 ' ' . $this->fb_fields['lastname']);
429 if (!empty($fullname)) {
430 $fullname = $this->nicknamize($fullname);
431 if ($this->isNewNickname($fullname)) {
440 * Given a string, try to make it work as a nickname
442 function nicknamize($str)
444 $str = preg_replace('/\W/', '', $str);
445 return strtolower($str);
448 function isNewNickname($str)
450 if (!Validate::string($str, array('min_length' => 1,
452 'format' => NICKNAME_FMT))) {
455 if (!User::allowed_nickname($str)) {
458 if (User::staticGet('nickname', $str)) {
464 // XXX: Consider moving this to lib/facebookutil.php
465 function getFacebookFields($fb_uid, $fields) {
468 $facebook = getFacebook();
470 $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
475 return reset($infos);
477 } catch (Exception $e) {
478 common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
479 "Facebook client failure when requesting " .
480 join(",", $fields) . " on uid " . $fb_uid .
481 " : ". $e->getMessage());