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()) {
63 // User is already logged in. Does she already have a linked Facebook acct?
64 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
67 // User already has a linked Facebook account and shouldn't be here
68 common_debug('Facebook Connect Plugin - ' .
69 'There is already a local user (' . $flink->user_id .
70 ') linked with this Facebook (' . $this->fbuid . ').');
72 // We don't want these cookies
73 getFacebook()->clear_cookie_state();
75 $this->clientError(_m('There is already a local user linked with this Facebook account.'));
78 // User came from the Facebook connect settings tab, and
79 // probably just wants to link/relink their Facebook account
83 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
85 $token = $this->trimmed('token');
86 if (!$token || $token != common_session_token()) {
87 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
90 if ($this->arg('create')) {
91 if (!$this->boolean('license')) {
92 $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
93 $this->trimmed('newname'));
96 $this->createNewUser();
97 } else if ($this->arg('connect')) {
98 $this->connectNewUser();
100 common_debug('Facebook Connect Plugin - ' .
101 print_r($this->args, true));
102 $this->showForm(_m('An unknown error has occured.'),
103 $this->trimmed('newname'));
110 function showPageNotice()
113 $this->element('div', array('class' => 'error'), $this->error);
115 $this->element('div', 'instructions',
116 // TRANS: %s is the site name.
117 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')));
123 // TRANS: Page title.
124 return _m('Facebook Account Setup');
127 function showForm($error=null, $username=null)
129 $this->error = $error;
130 $this->username = $username;
141 * @fixme much of this duplicates core code, which is very fragile.
142 * Should probably be replaced with an extensible mini version of
143 * the core registration form.
145 function showContent()
147 if (!empty($this->message_text)) {
148 $this->element('p', null, $this->message);
152 $this->elementStart('form', array('method' => 'post',
153 'id' => 'form_settings_facebook_connect',
154 'class' => 'form_settings',
155 'action' => common_local_url('FBConnectAuth')));
156 $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 // TRANS: %s is the name of the license used by the user for their status updates.
168 $message = _m('My text and files are available under %s ' .
169 'except this private data: password, ' .
170 'email address, IM address, and phone number.');
171 $link = '<a href="' .
172 htmlspecialchars(common_config('license', 'url')) .
174 htmlspecialchars(common_config('license', 'title')) .
176 $this->raw(sprintf(htmlspecialchars($message), $link));
177 $this->elementEnd('label');
178 $this->elementEnd('li');
179 $this->elementEnd('ul');
181 $this->elementStart('fieldset');
182 $this->hidden('token', common_session_token());
183 $this->element('legend', null,
185 _m('Create new account'));
186 $this->element('p', null,
187 _m('Create a new user with this nickname.'));
188 $this->elementStart('ul', 'form_data');
189 $this->elementStart('li');
190 // TRANS: Field label.
191 $this->input('newname', _m('New nickname'),
192 ($this->username) ? $this->username : '',
193 _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
194 $this->elementEnd('li');
195 $this->elementEnd('ul');
196 // TRANS: Submit button.
197 $this->submit('create', _m('BUTTON','Create'));
198 $this->elementEnd('fieldset');
200 $this->elementStart('fieldset');
202 $this->element('legend', null,
203 _m('Connect existing account'));
204 $this->element('p', null,
205 _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
206 $this->elementStart('ul', 'form_data');
207 $this->elementStart('li');
208 // TRANS: Field label.
209 $this->input('nickname', _m('Existing nickname'));
210 $this->elementEnd('li');
211 $this->elementStart('li');
212 $this->password('password', _m('Password'));
213 $this->elementEnd('li');
214 $this->elementEnd('ul');
215 // TRANS: Submit button.
216 $this->submit('connect', _m('BUTTON','Connect'));
217 $this->elementEnd('fieldset');
219 $this->elementEnd('fieldset');
220 $this->elementEnd('form');
223 function message($msg)
225 $this->message_text = $msg;
229 function createNewUser()
231 if (common_config('site', 'closed')) {
232 // TRANS: Client error trying to register with registrations not allowed.
233 $this->clientError(_m('Registration not allowed.'));
239 if (common_config('site', 'inviteonly')) {
240 $code = $_SESSION['invitecode'];
242 // TRANS: Client error trying to register with registrations 'invite only'.
243 $this->clientError(_m('Registration not allowed.'));
247 $invite = Invitation::staticGet($code);
249 if (empty($invite)) {
250 // TRANS: Client error trying to register with an invalid invitation code.
251 $this->clientError(_m('Not a valid invitation code.'));
256 $nickname = $this->trimmed('newname');
258 if (!Validate::string($nickname, array('min_length' => 1,
260 'format' => NICKNAME_FMT))) {
261 $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
265 if (!User::allowed_nickname($nickname)) {
266 $this->showForm(_m('Nickname not allowed.'));
270 if (User::staticGet('nickname', $nickname)) {
271 $this->showForm(_m('Nickname already in use. Try another one.'));
275 $fullname = trim($this->fb_fields['firstname'] .
276 ' ' . $this->fb_fields['lastname']);
278 $args = array('nickname' => $nickname, 'fullname' => $fullname);
280 if (!empty($invite)) {
281 $args['code'] = $invite->code;
284 $user = User::register($args);
286 $result = $this->flinkUser($user->id, $this->fbuid);
289 $this->serverError(_m('Error connecting user to Facebook.'));
293 common_set_user($user);
294 common_real_login(true);
296 common_debug('Facebook Connect Plugin - ' .
297 "Registered new user $user->id from Facebook user $this->fbuid");
299 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
303 function connectNewUser()
305 $nickname = $this->trimmed('nickname');
306 $password = $this->trimmed('password');
308 if (!common_check_user($nickname, $password)) {
309 $this->showForm(_m('Invalid username or password.'));
313 $user = User::staticGet('nickname', $nickname);
316 common_debug('Facebook Connect Plugin - ' .
317 "Legit user to connect to Facebook: $nickname");
320 $result = $this->flinkUser($user->id, $this->fbuid);
323 $this->serverError(_m('Error connecting user to Facebook.'));
327 common_debug('Facebook Connnect Plugin - ' .
328 "Connected Facebook user $this->fbuid to local user $user->id");
330 common_set_user($user);
331 common_real_login(true);
333 $this->goHome($user->nickname);
336 function connectUser()
338 $user = common_current_user();
340 $result = $this->flinkUser($user->id, $this->fbuid);
342 if (empty($result)) {
343 $this->serverError(_m('Error connecting user to Facebook.'));
347 common_debug('Facebook Connect Plugin - ' .
348 "Connected Facebook user $this->fbuid to local user $user->id");
350 // Return to Facebook connection settings tab
351 common_redirect(common_local_url('FBConnectSettings'), 303);
356 common_debug('Facebook Connect Plugin - ' .
357 "Trying login for Facebook user $this->fbuid.");
359 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
361 if (!empty($flink)) {
362 $user = $flink->getUser();
366 common_debug('Facebook Connect Plugin - ' .
367 "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
369 common_set_user($user);
370 common_real_login(true);
371 $this->goHome($user->nickname);
376 common_debug('Facebook Connect Plugin - ' .
377 "No flink found for fbuid: $this->fbuid - new user");
379 $this->showForm(null, $this->bestNewNickname());
383 function goHome($nickname)
385 $url = common_get_returnto();
387 // We don't have to return to it again
388 common_set_returnto(null);
390 $url = common_local_url('all',
395 common_redirect($url, 303);
398 function flinkUser($user_id, $fbuid)
400 $flink = new Foreign_link();
401 $flink->user_id = $user_id;
402 $flink->foreign_id = $fbuid;
403 $flink->service = FACEBOOK_CONNECT_SERVICE;
404 $flink->created = common_sql_now();
406 $flink_id = $flink->insert();
411 function bestNewNickname()
413 if (!empty($this->fb_fields['name'])) {
414 $nickname = $this->nicknamize($this->fb_fields['name']);
415 if ($this->isNewNickname($nickname)) {
422 $fullname = trim($this->fb_fields['firstname'] .
423 ' ' . $this->fb_fields['lastname']);
425 if (!empty($fullname)) {
426 $fullname = $this->nicknamize($fullname);
427 if ($this->isNewNickname($fullname)) {
436 * Given a string, try to make it work as a nickname
438 function nicknamize($str)
440 $str = preg_replace('/\W/', '', $str);
441 return strtolower($str);
444 function isNewNickname($str)
446 if (!Validate::string($str, array('min_length' => 1,
448 'format' => NICKNAME_FMT))) {
451 if (!User::allowed_nickname($str)) {
454 if (User::staticGet('nickname', $str)) {
460 // XXX: Consider moving this to lib/facebookutil.php
461 function getFacebookFields($fb_uid, $fields) {
464 $facebook = getFacebook();
466 $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
471 return reset($infos);
473 } catch (Exception $e) {
474 common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
475 "Facebook client failure when requesting " .
476 join(",", $fields) . " on uid " . $fb_uid .
477 " : ". $e->getMessage());