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 require_once INSTALLDIR . '/plugins/Facebook/FacebookPlugin.php';
32 class FBConnectauthAction extends Action
35 var $fb_fields = null;
37 function prepare($args) {
38 parent::prepare($args);
40 $this->fbuid = getFacebook()->get_loggedin_user();
42 if ($this->fbuid > 0) {
43 $this->fb_fields = $this->getFacebookFields($this->fbuid,
44 array('first_name', 'last_name', 'name'));
46 list($proxy, $ip) = common_client_ip();
48 common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
49 "Failed auth attempt, proxy = $proxy, ip = $ip.");
51 $this->clientError(_m('You must be logged into Facebook to ' .
52 'use Facebook Connect.'));
58 function handle($args)
60 parent::handle($args);
62 if (common_is_real_login()) {
64 // User is already logged in. Does she already have a linked Facebook acct?
65 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
69 // User already has a linked Facebook account and shouldn't be here
70 common_debug('Facebook Connect Plugin - ' .
71 'There is already a local user (' . $flink->user_id .
72 ') linked with this Facebook (' . $this->fbuid . ').');
74 // We don't want these cookies
75 getFacebook()->clear_cookie_state();
77 $this->clientError(_m('There is already a local user linked with this Facebook.'));
81 // User came from the Facebook connect settings tab, and
82 // probably just wants to link/relink their Facebook account
86 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
88 $token = $this->trimmed('token');
89 if (!$token || $token != common_session_token()) {
90 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
93 if ($this->arg('create')) {
94 if (!$this->boolean('license')) {
95 $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
96 $this->trimmed('newname'));
99 $this->createNewUser();
100 } else if ($this->arg('connect')) {
101 $this->connectNewUser();
103 common_debug('Facebook Connect Plugin - ' .
104 print_r($this->args, true));
105 $this->showForm(_m('Something weird happened.'),
106 $this->trimmed('newname'));
113 function showPageNotice()
116 $this->element('div', array('class' => 'error'), $this->error);
118 $this->element('div', 'instructions',
119 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')));
125 return _m('Facebook Account Setup');
128 function showForm($error=null, $username=null)
130 $this->error = $error;
131 $this->username = $username;
142 * @fixme much of this duplicates core code, which is very fragile.
143 * Should probably be replaced with an extensible mini version of
144 * the core registration form.
146 function showContent()
148 if (!empty($this->message_text)) {
149 $this->element('p', null, $this->message);
153 $this->elementStart('form', array('method' => 'post',
154 'id' => 'form_settings_facebook_connect',
155 'class' => 'form_settings',
156 'action' => common_local_url('FBConnectAuth')));
157 $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
158 $this->element('legend', null, _m('Connection options'));
159 $this->elementStart('ul', 'form_data');
160 $this->elementStart('li');
161 $this->element('input', array('type' => 'checkbox',
163 'class' => 'checkbox',
166 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
167 $message = _('My text and files are available under %s ' .
168 'except this private data: password, ' .
169 'email address, IM address, and phone number.');
170 $link = '<a href="' .
171 htmlspecialchars(common_config('license', 'url')) .
173 htmlspecialchars(common_config('license', 'title')) .
175 $this->raw(sprintf(htmlspecialchars($message), $link));
176 $this->elementEnd('label');
177 $this->elementEnd('li');
178 $this->elementEnd('ul');
180 $this->elementStart('fieldset');
181 $this->hidden('token', common_session_token());
182 $this->element('legend', null,
183 _m('Create new account'));
184 $this->element('p', null,
185 _m('Create a new user with this nickname.'));
186 $this->elementStart('ul', 'form_data');
187 $this->elementStart('li');
188 $this->input('newname', _m('New nickname'),
189 ($this->username) ? $this->username : '',
190 _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
191 $this->elementEnd('li');
192 $this->elementEnd('ul');
193 $this->submit('create', _m('Create'));
194 $this->elementEnd('fieldset');
196 $this->elementStart('fieldset');
197 $this->element('legend', null,
198 _m('Connect existing account'));
199 $this->element('p', null,
200 _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
201 $this->elementStart('ul', 'form_data');
202 $this->elementStart('li');
203 $this->input('nickname', _m('Existing nickname'));
204 $this->elementEnd('li');
205 $this->elementStart('li');
206 $this->password('password', _m('Password'));
207 $this->elementEnd('li');
208 $this->elementEnd('ul');
209 $this->submit('connect', _m('Connect'));
210 $this->elementEnd('fieldset');
212 $this->elementEnd('fieldset');
213 $this->elementEnd('form');
216 function message($msg)
218 $this->message_text = $msg;
222 function createNewUser()
224 if (common_config('site', 'closed')) {
225 $this->clientError(_m('Registration not allowed.'));
231 if (common_config('site', 'inviteonly')) {
232 $code = $_SESSION['invitecode'];
234 $this->clientError(_m('Registration not allowed.'));
238 $invite = Invitation::staticGet($code);
240 if (empty($invite)) {
241 $this->clientError(_m('Not a valid invitation code.'));
246 $nickname = $this->trimmed('newname');
248 if (!Validate::string($nickname, array('min_length' => 1,
250 'format' => NICKNAME_FMT))) {
251 $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
255 if (!User::allowed_nickname($nickname)) {
256 $this->showForm(_m('Nickname not allowed.'));
260 if (User::staticGet('nickname', $nickname)) {
261 $this->showForm(_m('Nickname already in use. Try another one.'));
265 $fullname = trim($this->fb_fields['firstname'] .
266 ' ' . $this->fb_fields['lastname']);
268 $args = array('nickname' => $nickname, 'fullname' => $fullname);
270 if (!empty($invite)) {
271 $args['code'] = $invite->code;
274 $user = User::register($args);
276 $result = $this->flinkUser($user->id, $this->fbuid);
279 $this->serverError(_m('Error connecting user to Facebook.'));
283 common_set_user($user);
284 common_real_login(true);
286 common_debug('Facebook Connect Plugin - ' .
287 "Registered new user $user->id from Facebook user $this->fbuid");
289 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
293 function connectNewUser()
295 $nickname = $this->trimmed('nickname');
296 $password = $this->trimmed('password');
298 if (!common_check_user($nickname, $password)) {
299 $this->showForm(_m('Invalid username or password.'));
303 $user = User::staticGet('nickname', $nickname);
306 common_debug('Facebook Connect Plugin - ' .
307 "Legit user to connect to Facebook: $nickname");
310 $result = $this->flinkUser($user->id, $this->fbuid);
313 $this->serverError(_m('Error connecting user to Facebook.'));
317 common_debug('Facebook Connnect Plugin - ' .
318 "Connected Facebook user $this->fbuid to local user $user->id");
320 common_set_user($user);
321 common_real_login(true);
323 $this->goHome($user->nickname);
326 function connectUser()
328 $user = common_current_user();
330 $result = $this->flinkUser($user->id, $this->fbuid);
332 if (empty($result)) {
333 $this->serverError(_m('Error connecting user to Facebook.'));
337 common_debug('Facebook Connect Plugin - ' .
338 "Connected Facebook user $this->fbuid to local user $user->id");
340 // Return to Facebook connection settings tab
341 common_redirect(common_local_url('FBConnectSettings'), 303);
346 common_debug('Facebook Connect Plugin - ' .
347 "Trying login for Facebook user $this->fbuid.");
349 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
351 if (!empty($flink)) {
352 $user = $flink->getUser();
356 common_debug('Facebook Connect Plugin - ' .
357 "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
359 common_set_user($user);
360 common_real_login(true);
361 $this->goHome($user->nickname);
366 common_debug('Facebook Connect Plugin - ' .
367 "No flink found for fbuid: $this->fbuid - new user");
369 $this->showForm(null, $this->bestNewNickname());
373 function goHome($nickname)
375 $url = common_get_returnto();
377 // We don't have to return to it again
378 common_set_returnto(null);
380 $url = common_local_url('all',
385 common_redirect($url, 303);
388 function flinkUser($user_id, $fbuid)
390 $flink = new Foreign_link();
391 $flink->user_id = $user_id;
392 $flink->foreign_id = $fbuid;
393 $flink->service = FACEBOOK_CONNECT_SERVICE;
394 $flink->created = common_sql_now();
396 $flink_id = $flink->insert();
401 function bestNewNickname()
403 if (!empty($this->fb_fields['name'])) {
404 $nickname = $this->nicknamize($this->fb_fields['name']);
405 if ($this->isNewNickname($nickname)) {
412 $fullname = trim($this->fb_fields['firstname'] .
413 ' ' . $this->fb_fields['lastname']);
415 if (!empty($fullname)) {
416 $fullname = $this->nicknamize($fullname);
417 if ($this->isNewNickname($fullname)) {
425 // Given a string, try to make it work as a nickname
427 function nicknamize($str)
429 $str = preg_replace('/\W/', '', $str);
430 return strtolower($str);
433 function isNewNickname($str)
435 if (!Validate::string($str, array('min_length' => 1,
437 'format' => NICKNAME_FMT))) {
440 if (!User::allowed_nickname($str)) {
443 if (User::staticGet('nickname', $str)) {
449 // XXX: Consider moving this to lib/facebookutil.php
450 function getFacebookFields($fb_uid, $fields) {
453 $facebook = getFacebook();
455 $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
460 return reset($infos);
462 } catch (Exception $e) {
463 common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
464 "Facebook client failure when requesting " .
465 join(",", $fields) . " on uid " . $fb_uid .
466 " : ". $e->getMessage());