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);
43 $this->fbuid = getFacebook()->get_loggedin_user();
45 if ($this->fbuid > 0) {
46 $this->fb_fields = $this->getFacebookFields($this->fbuid,
47 array('first_name', 'last_name', 'name'));
49 common_debug("No Facebook User found.");
52 } catch (Exception $e) {
53 common_log(LOG_WARNING, 'Problem getting Facebook uid: ' .
60 function handle($args)
62 parent::handle($args);
64 if (common_is_real_login()) {
66 // User is already logged in. Does she already have a linked Facebook acct?
67 $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('There is already a local user (' . $flink->user_id .
73 ') linked with this Facebook (' . $this->fbuid . ').');
75 // We don't want these cookies
76 getFacebook()->clear_cookie_state();
78 $this->clientError(_('There is already a local user linked with this Facebook.'));
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(_('There was a problem with your session token. Try again, please.'));
94 if ($this->arg('create')) {
95 if (!$this->boolean('license')) {
96 $this->showForm(_('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(print_r($this->args, true), __FILE__);
105 $this->showForm(_('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(_('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 _('Facebook Account Setup');
128 function showForm($error=null, $username=null)
130 $this->error = $error;
131 $this->username = $username;
141 function showContent()
143 if (!empty($this->message_text)) {
144 $this->element('p', null, $this->message);
148 $this->elementStart('form', array('method' => 'post',
149 'id' => 'form_settings_facebook_connect',
150 'class' => 'form_settings',
151 'action' => common_local_url('FBConnectAuth')));
152 $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
153 $this->element('legend', null, _('Connection options'));
154 $this->elementStart('ul', 'form_data');
155 $this->elementStart('li');
156 $this->element('input', array('type' => 'checkbox',
158 'class' => 'checkbox',
161 $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
162 $this->text(_('My text and files are available under '));
163 $this->element('a', array('href' => common_config('license', 'url')),
164 common_config('license', 'title'));
165 $this->text(_(' except this private data: password, email address, IM address, phone number.'));
166 $this->elementEnd('label');
167 $this->elementEnd('li');
168 $this->elementEnd('ul');
170 $this->elementStart('fieldset');
171 $this->hidden('token', common_session_token());
172 $this->element('legend', null,
173 _('Create new account'));
174 $this->element('p', null,
175 _('Create a new user with this nickname.'));
176 $this->elementStart('ul', 'form_data');
177 $this->elementStart('li');
178 $this->input('newname', _('New nickname'),
179 ($this->username) ? $this->username : '',
180 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
181 $this->elementEnd('li');
182 $this->elementEnd('ul');
183 $this->submit('create', _('Create'));
184 $this->elementEnd('fieldset');
186 $this->elementStart('fieldset');
187 $this->element('legend', null,
188 _('Connect existing account'));
189 $this->element('p', null,
190 _('If you already have an account, login with your username and password to connect it to your Facebook.'));
191 $this->elementStart('ul', 'form_data');
192 $this->elementStart('li');
193 $this->input('nickname', _('Existing nickname'));
194 $this->elementEnd('li');
195 $this->elementStart('li');
196 $this->password('password', _('Password'));
197 $this->elementEnd('li');
198 $this->elementEnd('ul');
199 $this->submit('connect', _('Connect'));
200 $this->elementEnd('fieldset');
202 $this->elementEnd('fieldset');
203 $this->elementEnd('form');
206 function message($msg)
208 $this->message_text = $msg;
212 function createNewUser()
215 if (common_config('site', 'closed')) {
216 $this->clientError(_('Registration not allowed.'));
222 if (common_config('site', 'inviteonly')) {
223 $code = $_SESSION['invitecode'];
225 $this->clientError(_('Registration not allowed.'));
229 $invite = Invitation::staticGet($code);
231 if (empty($invite)) {
232 $this->clientError(_('Not a valid invitation code.'));
237 $nickname = $this->trimmed('newname');
239 if (!Validate::string($nickname, array('min_length' => 1,
241 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
242 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
246 if (!User::allowed_nickname($nickname)) {
247 $this->showForm(_('Nickname not allowed.'));
251 if (User::staticGet('nickname', $nickname)) {
252 $this->showForm(_('Nickname already in use. Try another one.'));
256 $fullname = trim($this->fb_fields['firstname'] .
257 ' ' . $this->fb_fields['lastname']);
259 $args = array('nickname' => $nickname, 'fullname' => $fullname);
261 if (!empty($invite)) {
262 $args['code'] = $invite->code;
265 $user = User::register($args);
267 $result = $this->flinkUser($user->id, $this->fbuid);
270 $this->serverError(_('Error connecting user to Facebook.'));
274 common_set_user($user);
275 common_real_login(true);
277 common_debug("Registered new user $user->id from Facebook user $this->fbuid");
279 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
283 function connectNewUser()
285 $nickname = $this->trimmed('nickname');
286 $password = $this->trimmed('password');
288 if (!common_check_user($nickname, $password)) {
289 $this->showForm(_('Invalid username or password.'));
293 $user = User::staticGet('nickname', $nickname);
296 common_debug("Legit user to connect to Facebook: $nickname");
299 $result = $this->flinkUser($user->id, $this->fbuid);
302 $this->serverError(_('Error connecting user to Facebook.'));
306 common_debug("Connected Facebook user $this->fbuid to local user $user->id");
308 common_set_user($user);
309 common_real_login(true);
311 $this->goHome($user->nickname);
314 function connectUser()
316 $user = common_current_user();
318 $result = $this->flinkUser($user->id, $this->fbuid);
321 $this->serverError(_('Error connecting user to Facebook.'));
325 common_debug("Connected Facebook user $this->fbuid to local user $user->id");
327 // Return to Facebook connection settings tab
328 common_redirect(common_local_url('FBConnectSettings'), 303);
333 common_debug("Trying Facebook Login...");
335 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
338 $user = $flink->getUser();
342 common_debug("Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
344 common_set_user($user);
345 common_real_login(true);
346 $this->goHome($user->nickname);
351 common_debug("No flink found for fbuid: $this->fbuid");
353 $this->showForm(null, $this->bestNewNickname());
357 function goHome($nickname)
359 $url = common_get_returnto();
361 // We don't have to return to it again
362 common_set_returnto(null);
364 $url = common_local_url('all',
369 common_redirect($url, 303);
372 function flinkUser($user_id, $fbuid)
374 $flink = new Foreign_link();
375 $flink->user_id = $user_id;
376 $flink->foreign_id = $fbuid;
377 $flink->service = FACEBOOK_CONNECT_SERVICE;
378 $flink->created = common_sql_now();
380 $flink_id = $flink->insert();
385 function bestNewNickname()
387 if (!empty($this->fb_fields['name'])) {
388 $nickname = $this->nicknamize($this->fb_fields['name']);
389 if ($this->isNewNickname($nickname)) {
396 $fullname = trim($this->fb_fields['firstname'] .
397 ' ' . $this->fb_fields['lastname']);
399 if (!empty($fullname)) {
400 $fullname = $this->nicknamize($fullname);
401 if ($this->isNewNickname($fullname)) {
409 // Given a string, try to make it work as a nickname
411 function nicknamize($str)
413 $str = preg_replace('/\W/', '', $str);
414 return strtolower($str);
417 function isNewNickname($str)
419 if (!Validate::string($str, array('min_length' => 1,
421 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
424 if (!User::allowed_nickname($str)) {
427 if (User::staticGet('nickname', $str)) {
433 // XXX: Consider moving this to lib/facebookutil.php
434 function getFacebookFields($fb_uid, $fields) {
437 $facebook = getFacebook();
439 $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
444 return reset($infos);
446 } catch (Exception $e) {
447 common_log(LOG_WARNING, "Facebook client failure when requesting " .
448 join(",", $fields) . " on uid " . $fb_uid .
449 " : ". $e->getMessage());