3 * Laconica, 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@controlyourself.ca>
25 * @copyright 2009 Control Yourself, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://laconi.ca/
30 require_once INSTALLDIR . '/plugins/FBConnect/FBConnectPlugin.php';
32 class FBConnectauthAction extends Action
36 var $fb_fields = null;
38 function prepare($args) {
39 parent::prepare($args);
41 $this->fbuid = getFacebook()->get_loggedin_user();
43 if ($this->fbuid > 0) {
44 $this->fb_fields = $this->getFacebookFields($this->fbuid,
45 array('first_name', 'last_name', 'name'));
47 $this->clientError(_('You must be logged into Facebook to ' .
48 'use Facebook Connect.'));
54 function handle($args)
56 parent::handle($args);
58 if (common_is_real_login()) {
60 // User is already logged in. Does she already have a linked Facebook acct?
61 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
65 // User already has a linked Facebook account and shouldn't be here
66 common_debug('There is already a local user (' . $flink->user_id .
67 ') linked with this Facebook (' . $this->fbuid . ').');
69 // We don't want these cookies
70 getFacebook()->clear_cookie_state();
72 $this->clientError(_('There is already a local user linked with this Facebook.'));
76 // User came from the Facebook connect settings tab, and
77 // probably just wants to link/relink their Facebook account
81 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
83 $token = $this->trimmed('token');
84 if (!$token || $token != common_session_token()) {
85 $this->showForm(_('There was a problem with your session token. Try again, please.'));
88 if ($this->arg('create')) {
89 if (!$this->boolean('license')) {
90 $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
91 $this->trimmed('newname'));
94 $this->createNewUser();
95 } else if ($this->arg('connect')) {
96 $this->connectNewUser();
98 common_debug(print_r($this->args, true), __FILE__);
99 $this->showForm(_('Something weird happened.'),
100 $this->trimmed('newname'));
107 function showPageNotice()
110 $this->element('div', array('class' => 'error'), $this->error);
112 $this->element('div', 'instructions',
113 sprintf(_('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')));
119 return _('Facebook Account Setup');
122 function showForm($error=null, $username=null)
124 $this->error = $error;
125 $this->username = $username;
135 function showContent()
137 if (!empty($this->message_text)) {
138 $this->element('p', null, $this->message);
142 $this->elementStart('form', array('method' => 'post',
143 'id' => 'form_settings_facebook_connect',
144 'class' => 'form_settings',
145 'action' => common_local_url('FBConnectAuth')));
146 $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
147 $this->element('legend', null, _('Connection options'));
148 $this->elementStart('ul', 'form_data');
149 $this->elementStart('li');
150 $this->element('input', array('type' => 'checkbox',
152 'class' => 'checkbox',
155 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
156 $this->text(_('My text and files are available under '));
157 $this->element('a', array('href' => common_config('license', 'url')),
158 common_config('license', 'title'));
159 $this->text(_(' except this private data: password, email address, IM address, phone number.'));
160 $this->elementEnd('label');
161 $this->elementEnd('li');
162 $this->elementEnd('ul');
164 $this->elementStart('fieldset');
165 $this->hidden('token', common_session_token());
166 $this->element('legend', null,
167 _('Create new account'));
168 $this->element('p', null,
169 _('Create a new user with this nickname.'));
170 $this->elementStart('ul', 'form_data');
171 $this->elementStart('li');
172 $this->input('newname', _('New nickname'),
173 ($this->username) ? $this->username : '',
174 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
175 $this->elementEnd('li');
176 $this->elementEnd('ul');
177 $this->submit('create', _('Create'));
178 $this->elementEnd('fieldset');
180 $this->elementStart('fieldset');
181 $this->element('legend', null,
182 _('Connect existing account'));
183 $this->element('p', null,
184 _('If you already have an account, login with your username and password to connect it to your Facebook.'));
185 $this->elementStart('ul', 'form_data');
186 $this->elementStart('li');
187 $this->input('nickname', _('Existing nickname'));
188 $this->elementEnd('li');
189 $this->elementStart('li');
190 $this->password('password', _('Password'));
191 $this->elementEnd('li');
192 $this->elementEnd('ul');
193 $this->submit('connect', _('Connect'));
194 $this->elementEnd('fieldset');
196 $this->elementEnd('fieldset');
197 $this->elementEnd('form');
200 function message($msg)
202 $this->message_text = $msg;
206 function createNewUser()
209 if (common_config('site', 'closed')) {
210 $this->clientError(_('Registration not allowed.'));
216 if (common_config('site', 'inviteonly')) {
217 $code = $_SESSION['invitecode'];
219 $this->clientError(_('Registration not allowed.'));
223 $invite = Invitation::staticGet($code);
225 if (empty($invite)) {
226 $this->clientError(_('Not a valid invitation code.'));
231 $nickname = $this->trimmed('newname');
233 if (!Validate::string($nickname, array('min_length' => 1,
235 'format' => NICKNAME_FMT))) {
236 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
240 if (!User::allowed_nickname($nickname)) {
241 $this->showForm(_('Nickname not allowed.'));
245 if (User::staticGet('nickname', $nickname)) {
246 $this->showForm(_('Nickname already in use. Try another one.'));
250 $fullname = trim($this->fb_fields['firstname'] .
251 ' ' . $this->fb_fields['lastname']);
253 $args = array('nickname' => $nickname, 'fullname' => $fullname);
255 if (!empty($invite)) {
256 $args['code'] = $invite->code;
259 $user = User::register($args);
261 $result = $this->flinkUser($user->id, $this->fbuid);
264 $this->serverError(_('Error connecting user to Facebook.'));
268 common_set_user($user);
269 common_real_login(true);
271 common_debug("Registered new user $user->id from Facebook user $this->fbuid");
273 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
277 function connectNewUser()
279 $nickname = $this->trimmed('nickname');
280 $password = $this->trimmed('password');
282 if (!common_check_user($nickname, $password)) {
283 $this->showForm(_('Invalid username or password.'));
287 $user = User::staticGet('nickname', $nickname);
290 common_debug("Legit user to connect to Facebook: $nickname");
293 $result = $this->flinkUser($user->id, $this->fbuid);
296 $this->serverError(_('Error connecting user to Facebook.'));
300 common_debug("Connected Facebook user $this->fbuid to local user $user->id");
302 common_set_user($user);
303 common_real_login(true);
305 $this->goHome($user->nickname);
308 function connectUser()
310 $user = common_current_user();
312 $result = $this->flinkUser($user->id, $this->fbuid);
315 $this->serverError(_('Error connecting user to Facebook.'));
319 common_debug("Connected Facebook user $this->fbuid to local user $user->id");
321 // Return to Facebook connection settings tab
322 common_redirect(common_local_url('FBConnectSettings'), 303);
327 common_debug("Trying Facebook Login...");
329 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
332 $user = $flink->getUser();
336 common_debug("Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
338 common_set_user($user);
339 common_real_login(true);
340 $this->goHome($user->nickname);
345 common_debug("No flink found for fbuid: $this->fbuid");
347 $this->showForm(null, $this->bestNewNickname());
351 function goHome($nickname)
353 $url = common_get_returnto();
355 // We don't have to return to it again
356 common_set_returnto(null);
358 $url = common_local_url('all',
363 common_redirect($url, 303);
366 function flinkUser($user_id, $fbuid)
368 $flink = new Foreign_link();
369 $flink->user_id = $user_id;
370 $flink->foreign_id = $fbuid;
371 $flink->service = FACEBOOK_CONNECT_SERVICE;
372 $flink->created = common_sql_now();
374 $flink_id = $flink->insert();
379 function bestNewNickname()
381 if (!empty($this->fb_fields['name'])) {
382 $nickname = $this->nicknamize($this->fb_fields['name']);
383 if ($this->isNewNickname($nickname)) {
390 $fullname = trim($this->fb_fields['firstname'] .
391 ' ' . $this->fb_fields['lastname']);
393 if (!empty($fullname)) {
394 $fullname = $this->nicknamize($fullname);
395 if ($this->isNewNickname($fullname)) {
403 // Given a string, try to make it work as a nickname
405 function nicknamize($str)
407 $str = preg_replace('/\W/', '', $str);
408 return strtolower($str);
411 function isNewNickname($str)
413 if (!Validate::string($str, array('min_length' => 1,
415 'format' => NICKNAME_FMT))) {
418 if (!User::allowed_nickname($str)) {
421 if (User::staticGet('nickname', $str)) {
427 // XXX: Consider moving this to lib/facebookutil.php
428 function getFacebookFields($fb_uid, $fields) {
431 $facebook = getFacebook();
433 $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
438 return reset($infos);
440 } catch (Exception $e) {
441 common_log(LOG_WARNING, "Facebook client failure when requesting " .
442 join(",", $fields) . " on uid " . $fb_uid .
443 " : ". $e->getMessage());