]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FBConnect/FBConnectAuth.php
Kick user out if she doesn't have FB cookies
[quix0rs-gnu-social.git] / plugins / FBConnect / FBConnectAuth.php
1 <?php
2 /**
3  * Laconica, the distributed open-source microblogging tool
4  *
5  * Plugin to enable Facebook Connect
6  *
7  * PHP version 5
8  *
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.
13  *
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.
18  *
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/>.
21  *
22  * @category  Plugin
23  * @package   Laconica
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/
28  */
29
30 require_once INSTALLDIR . '/plugins/FBConnect/FBConnectPlugin.php';
31
32 class FBConnectauthAction extends Action
33 {
34
35     var $fbuid      = null;
36     var $fb_fields  = null;
37
38     function prepare($args) {
39         parent::prepare($args);
40
41         $this->fbuid = getFacebook()->get_loggedin_user();
42
43         if ($this->fbuid > 0) {
44             $this->fb_fields = $this->getFacebookFields($this->fbuid,
45                                                         array('first_name', 'last_name', 'name'));
46         } else {
47             $this->clientError(_('You must be logged into Facebook to ' .
48                                  'use Facebook Connect.'));
49         }
50
51         return true;
52     }
53
54     function handle($args)
55     {
56         parent::handle($args);
57
58         if (common_is_real_login()) {
59
60             // User is already logged in.  Does she already have a linked Facebook acct?
61             $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
62
63             if (!empty($flink)) {
64
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 . ').');
68
69                 // We don't want these cookies
70                 getFacebook()->clear_cookie_state();
71
72                 $this->clientError(_('There is already a local user linked with this Facebook.'));
73
74             } else {
75
76                 // User came from the Facebook connect settings tab, and
77                 // probably just wants to link/relink their Facebook account
78                 $this->connectUser();
79             }
80
81         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
82
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.'));
86                 return;
87             }
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'));
92                     return;
93                 }
94                 $this->createNewUser();
95             } else if ($this->arg('connect')) {
96                 $this->connectNewUser();
97             } else {
98                 common_debug(print_r($this->args, true), __FILE__);
99                 $this->showForm(_('Something weird happened.'),
100                                 $this->trimmed('newname'));
101             }
102         } else {
103             $this->tryLogin();
104         }
105     }
106
107     function showPageNotice()
108     {
109         if ($this->error) {
110             $this->element('div', array('class' => 'error'), $this->error);
111         } else {
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')));
114         }
115     }
116
117     function title()
118     {
119         return _('Facebook Account Setup');
120     }
121
122     function showForm($error=null, $username=null)
123     {
124         $this->error = $error;
125         $this->username = $username;
126
127         $this->showPage();
128     }
129
130     function showPage()
131     {
132         parent::showPage();
133     }
134
135     function showContent()
136     {
137         if (!empty($this->message_text)) {
138             $this->element('p', null, $this->message);
139             return;
140         }
141
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',
151                                       'id' => 'license',
152                                       'class' => 'checkbox',
153                                       'name' => 'license',
154                                       'value' => 'true'));
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');
163
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');
179
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');
195
196         $this->elementEnd('fieldset');
197         $this->elementEnd('form');
198     }
199
200     function message($msg)
201     {
202         $this->message_text = $msg;
203         $this->showPage();
204     }
205
206     function createNewUser()
207     {
208
209         if (common_config('site', 'closed')) {
210             $this->clientError(_('Registration not allowed.'));
211             return;
212         }
213
214         $invite = null;
215
216         if (common_config('site', 'inviteonly')) {
217             $code = $_SESSION['invitecode'];
218             if (empty($code)) {
219                 $this->clientError(_('Registration not allowed.'));
220                 return;
221             }
222
223             $invite = Invitation::staticGet($code);
224
225             if (empty($invite)) {
226                 $this->clientError(_('Not a valid invitation code.'));
227                 return;
228             }
229         }
230
231         $nickname = $this->trimmed('newname');
232
233         if (!Validate::string($nickname, array('min_length' => 1,
234                                                'max_length' => 64,
235                                                'format' => NICKNAME_FMT))) {
236             $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
237             return;
238         }
239
240         if (!User::allowed_nickname($nickname)) {
241             $this->showForm(_('Nickname not allowed.'));
242             return;
243         }
244
245         if (User::staticGet('nickname', $nickname)) {
246             $this->showForm(_('Nickname already in use. Try another one.'));
247             return;
248         }
249
250         $fullname = trim($this->fb_fields['firstname'] .
251             ' ' . $this->fb_fields['lastname']);
252
253         $args = array('nickname' => $nickname, 'fullname' => $fullname);
254
255         if (!empty($invite)) {
256             $args['code'] = $invite->code;
257         }
258
259         $user = User::register($args);
260
261         $result = $this->flinkUser($user->id, $this->fbuid);
262
263         if (!$result) {
264             $this->serverError(_('Error connecting user to Facebook.'));
265             return;
266         }
267
268         common_set_user($user);
269         common_real_login(true);
270
271         common_debug("Registered new user $user->id from Facebook user $this->fbuid");
272
273         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
274                         303);
275     }
276
277     function connectNewUser()
278     {
279         $nickname = $this->trimmed('nickname');
280         $password = $this->trimmed('password');
281
282         if (!common_check_user($nickname, $password)) {
283             $this->showForm(_('Invalid username or password.'));
284             return;
285         }
286
287         $user = User::staticGet('nickname', $nickname);
288
289         if ($user) {
290             common_debug("Legit user to connect to Facebook: $nickname");
291         }
292
293         $result = $this->flinkUser($user->id, $this->fbuid);
294
295         if (!$result) {
296             $this->serverError(_('Error connecting user to Facebook.'));
297             return;
298         }
299
300         common_debug("Connected Facebook user $this->fbuid to local user $user->id");
301
302         common_set_user($user);
303         common_real_login(true);
304
305         $this->goHome($user->nickname);
306     }
307
308     function connectUser()
309     {
310         $user = common_current_user();
311
312         $result = $this->flinkUser($user->id, $this->fbuid);
313
314         if (!$result) {
315             $this->serverError(_('Error connecting user to Facebook.'));
316             return;
317         }
318
319         common_debug("Connected Facebook user $this->fbuid to local user $user->id");
320
321         // Return to Facebook connection settings tab
322         common_redirect(common_local_url('FBConnectSettings'), 303);
323     }
324
325     function tryLogin()
326     {
327         common_debug("Trying Facebook Login...");
328
329         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
330
331         if ($flink) {
332             $user = $flink->getUser();
333
334             if (!empty($user)) {
335
336                 common_debug("Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
337
338                 common_set_user($user);
339                 common_real_login(true);
340                 $this->goHome($user->nickname);
341             }
342
343         } else {
344
345             common_debug("No flink found for fbuid: $this->fbuid");
346
347             $this->showForm(null, $this->bestNewNickname());
348         }
349     }
350
351     function goHome($nickname)
352     {
353         $url = common_get_returnto();
354         if ($url) {
355             // We don't have to return to it again
356             common_set_returnto(null);
357         } else {
358             $url = common_local_url('all',
359                                     array('nickname' =>
360                                           $nickname));
361         }
362
363         common_redirect($url, 303);
364     }
365
366     function flinkUser($user_id, $fbuid)
367     {
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();
373
374         $flink_id = $flink->insert();
375
376         return $flink_id;
377     }
378
379     function bestNewNickname()
380     {
381         if (!empty($this->fb_fields['name'])) {
382             $nickname = $this->nicknamize($this->fb_fields['name']);
383             if ($this->isNewNickname($nickname)) {
384                 return $nickname;
385             }
386         }
387
388         // Try the full name
389
390         $fullname = trim($this->fb_fields['firstname'] .
391             ' ' . $this->fb_fields['lastname']);
392
393         if (!empty($fullname)) {
394             $fullname = $this->nicknamize($fullname);
395             if ($this->isNewNickname($fullname)) {
396                 return $fullname;
397             }
398         }
399
400         return null;
401     }
402
403      // Given a string, try to make it work as a nickname
404
405      function nicknamize($str)
406      {
407          $str = preg_replace('/\W/', '', $str);
408          return strtolower($str);
409      }
410
411     function isNewNickname($str)
412     {
413         if (!Validate::string($str, array('min_length' => 1,
414                                           'max_length' => 64,
415                                           'format' => NICKNAME_FMT))) {
416             return false;
417         }
418         if (!User::allowed_nickname($str)) {
419             return false;
420         }
421         if (User::staticGet('nickname', $str)) {
422             return false;
423         }
424         return true;
425     }
426
427     // XXX: Consider moving this to lib/facebookutil.php
428     function getFacebookFields($fb_uid, $fields) {
429         try {
430
431             $facebook = getFacebook();
432
433             $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
434
435             if (empty($infos)) {
436                 return null;
437             }
438             return reset($infos);
439
440         } catch (Exception $e) {
441             common_log(LOG_WARNING, "Facebook client failure when requesting " .
442                 join(",", $fields) . " on uid " . $fb_uid .
443                     " : ". $e->getMessage());
444             return null;
445         }
446     }
447
448 }