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()) {
65 $this->clientError(_('Already logged in.'));
66 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
68 $token = $this->trimmed('token');
69 if (!$token || $token != common_session_token()) {
70 $this->showForm(_('There was a problem with your session token. Try again, please.'));
73 if ($this->arg('create')) {
74 if (!$this->boolean('license')) {
75 $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
76 $this->trimmed('newname'));
79 $this->createNewUser();
80 } else if ($this->arg('connect')) {
83 common_debug(print_r($this->args, true), __FILE__);
84 $this->showForm(_('Something weird happened.'),
85 $this->trimmed('newname'));
92 function showPageNotice()
95 $this->element('div', array('class' => 'error'), $this->error);
97 $this->element('div', 'instructions',
98 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')));
104 return _('Facebook Account Setup');
107 function showForm($error=null, $username=null)
109 $this->error = $error;
110 $this->username = $username;
120 function showContent()
122 if (!empty($this->message_text)) {
123 $this->element('p', null, $this->message);
127 $this->elementStart('form', array('method' => 'post',
128 'id' => 'account_connect',
129 'action' => common_local_url('FBConnectAuth')));
130 $this->hidden('token', common_session_token());
131 $this->element('h2', null,
132 _('Create new account'));
133 $this->element('p', null,
134 _('Create a new user with this nickname.'));
135 $this->input('newname', _('New nickname'),
136 ($this->username) ? $this->username : '',
137 _('1-64 lowercase letters or numbers, no punctuation or spaces'));
138 $this->elementStart('p');
139 $this->element('input', array('type' => 'checkbox',
143 $this->text(_('My text and files are available under '));
144 $this->element('a', array('href' => common_config('license', 'url')),
145 common_config('license', 'title'));
146 $this->text(_(' except this private data: password, email address, IM address, phone number.'));
147 $this->elementEnd('p');
148 $this->submit('create', _('Create'));
149 $this->element('h2', null,
150 _('Connect existing account'));
151 $this->element('p', null,
152 _('If you already have an account, login with your username and password to connect it to your Facebook.'));
153 $this->input('nickname', _('Existing nickname'));
154 $this->password('password', _('Password'));
155 $this->submit('connect', _('Connect'));
156 $this->elementEnd('form');
159 function message($msg)
161 $this->message_text = $msg;
165 function createNewUser()
168 if (common_config('site', 'closed')) {
169 $this->clientError(_('Registration not allowed.'));
175 if (common_config('site', 'inviteonly')) {
176 $code = $_SESSION['invitecode'];
178 $this->clientError(_('Registration not allowed.'));
182 $invite = Invitation::staticGet($code);
184 if (empty($invite)) {
185 $this->clientError(_('Not a valid invitation code.'));
190 $nickname = $this->trimmed('newname');
192 if (!Validate::string($nickname, array('min_length' => 1,
194 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
195 $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
199 if (!User::allowed_nickname($nickname)) {
200 $this->showForm(_('Nickname not allowed.'));
204 if (User::staticGet('nickname', $nickname)) {
205 $this->showForm(_('Nickname already in use. Try another one.'));
209 $fullname = trim($this->fb_fields['firstname'] .
210 ' ' . $this->fb_fields['lastname']);
212 $args = array('nickname' => $nickname, 'fullname' => $fullname);
214 if (!empty($invite)) {
215 $args['code'] = $invite->code;
218 $user = User::register($args);
220 $result = $this->flinkUser($user->id, $this->fbuid);
223 $this->serverError(_('Error connecting user to Facebook.'));
227 common_set_user($user);
228 common_real_login(true);
230 common_debug("Registered new user $user->id from Facebook user $this->fbuid");
232 common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
236 function connectUser()
238 $nickname = $this->trimmed('nickname');
239 $password = $this->trimmed('password');
241 if (!common_check_user($nickname, $password)) {
242 $this->showForm(_('Invalid username or password.'));
246 $user = User::staticGet('nickname', $nickname);
249 common_debug("Legit user to connect to Facebook: $nickname");
252 $result = $this->flinkUser($user->id, $this->fbuid);
255 $this->serverError(_('Error connecting user to Facebook.'));
259 common_debug("Connected Facebook user $this->fbuid to local user $user->id");
261 common_set_user($user);
262 common_real_login(true);
264 $this->goHome($user->nickname);
269 common_debug("Trying Facebook Login...");
271 $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
274 $user = $flink->getUser();
278 common_debug("Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
280 common_set_user($user);
281 common_real_login(true);
282 $this->goHome($user->nickname);
287 common_debug("No flink found for fbuid: $this->fbuid");
289 $this->showForm(null, $this->bestNewNickname());
293 function goHome($nickname)
295 $url = common_get_returnto();
297 // We don't have to return to it again
298 common_set_returnto(null);
300 $url = common_local_url('all',
305 common_redirect($url, 303);
308 function flinkUser($user_id, $fbuid)
310 $flink = new Foreign_link();
311 $flink->user_id = $user_id;
312 $flink->foreign_id = $fbuid;
313 $flink->service = FACEBOOK_CONNECT_SERVICE;
314 $flink->created = common_sql_now();
316 $flink_id = $flink->insert();
321 function bestNewNickname()
323 if (!empty($this->fb_fields['name'])) {
324 $nickname = $this->nicknamize($this->fb_fields['name']);
325 if ($this->isNewNickname($nickname)) {
332 $fullname = trim($this->fb_fields['firstname'] .
333 ' ' . $this->fb_fields['lastname']);
335 if (!empty($fullname)) {
336 $fullname = $this->nicknamize($fullname);
337 if ($this->isNewNickname($fullname)) {
345 // Given a string, try to make it work as a nickname
347 function nicknamize($str)
349 $str = preg_replace('/\W/', '', $str);
350 return strtolower($str);
353 function isNewNickname($str)
355 if (!Validate::string($str, array('min_length' => 1,
357 'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
360 if (!User::allowed_nickname($str)) {
363 if (User::staticGet('nickname', $str)) {
369 // XXX: Consider moving this to lib/facebookutil.php
370 function getFacebookFields($fb_uid, $fields) {
373 $facebook = getFacebook();
375 $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
380 return reset($infos);
382 } catch (Exception $e) {
383 common_log(LOG_WARNING, "Facebook client failure when requesting " .
384 join(",", $fields) . " on uid " . $fb_uid .
385 " : ". $e->getMessage());