]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Facebook/FBConnectAuth.php
Fix for ticket 2756 - Calls to OAuth endpoints are redirected to the
[quix0rs-gnu-social.git] / plugins / Facebook / FBConnectAuth.php
1 <?php
2 /**
3  * StatusNet, 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   StatusNet
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/
28  */
29
30 require_once INSTALLDIR . '/plugins/Facebook/FacebookPlugin.php';
31
32 class FBConnectauthAction extends Action
33 {
34     var $fbuid      = null;
35     var $fb_fields  = null;
36
37     function prepare($args) {
38         parent::prepare($args);
39
40         $this->fbuid = getFacebook()->get_loggedin_user();
41
42         if ($this->fbuid > 0) {
43             $this->fb_fields = $this->getFacebookFields($this->fbuid,
44                                                         array('first_name', 'last_name', 'name'));
45         } else {
46             list($proxy, $ip) = common_client_ip();
47
48             common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
49                        "Failed auth attempt, proxy = $proxy, ip = $ip.");
50
51             $this->clientError(_m('You must be logged into Facebook to ' .
52                                   'use Facebook Connect.'));
53         }
54
55         return true;
56     }
57
58     function handle($args)
59     {
60         parent::handle($args);
61
62         if (common_is_real_login()) {
63
64             // User is already logged in.  Does she already have a linked Facebook acct?
65             $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
66
67             if (!empty($flink)) {
68
69                 // User already has a linked Facebook account and shouldn't be here
70                 common_debug('Facebook Connect Plugin - ' .
71                              'There is already a local user (' . $flink->user_id .
72                              ') linked with this Facebook (' . $this->fbuid . ').');
73
74                 // We don't want these cookies
75                 getFacebook()->clear_cookie_state();
76
77                 $this->clientError(_m('There is already a local user linked with this Facebook.'));
78
79             } else {
80
81                 // User came from the Facebook connect settings tab, and
82                 // probably just wants to link/relink their Facebook account
83                 $this->connectUser();
84             }
85
86         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
87
88             $token = $this->trimmed('token');
89             if (!$token || $token != common_session_token()) {
90                 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
91                 return;
92             }
93             if ($this->arg('create')) {
94                 if (!$this->boolean('license')) {
95                     $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
96                                     $this->trimmed('newname'));
97                     return;
98                 }
99                 $this->createNewUser();
100             } else if ($this->arg('connect')) {
101                 $this->connectNewUser();
102             } else {
103                 common_debug('Facebook Connect Plugin - ' .
104                              print_r($this->args, true));
105                 $this->showForm(_m('Something weird happened.'),
106                                 $this->trimmed('newname'));
107             }
108         } else {
109             $this->tryLogin();
110         }
111     }
112
113     function showPageNotice()
114     {
115         if ($this->error) {
116             $this->element('div', array('class' => 'error'), $this->error);
117         } else {
118             $this->element('div', 'instructions',
119                            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')));
120         }
121     }
122
123     function title()
124     {
125         return _m('Facebook Account Setup');
126     }
127
128     function showForm($error=null, $username=null)
129     {
130         $this->error = $error;
131         $this->username = $username;
132
133         $this->showPage();
134     }
135
136     function showPage()
137     {
138         parent::showPage();
139     }
140
141     /**
142      * @fixme much of this duplicates core code, which is very fragile.
143      * Should probably be replaced with an extensible mini version of
144      * the core registration form.
145      */
146     function showContent()
147     {
148         if (!empty($this->message_text)) {
149             $this->element('p', null, $this->message);
150             return;
151         }
152
153         $this->elementStart('form', array('method' => 'post',
154                                           'id' => 'form_settings_facebook_connect',
155                                           'class' => 'form_settings',
156                                           'action' => common_local_url('FBConnectAuth')));
157         $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',
162                                       'id' => 'license',
163                                       'class' => 'checkbox',
164                                       'name' => 'license',
165                                       'value' => 'true'));
166         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
167         $message = _('My text and files are available under %s ' .
168                      'except this private data: password, ' .
169                      'email address, IM address, and phone number.');
170         $link = '<a href="' .
171                 htmlspecialchars(common_config('license', 'url')) .
172                 '">' .
173                 htmlspecialchars(common_config('license', 'title')) .
174                 '</a>';
175         $this->raw(sprintf(htmlspecialchars($message), $link));
176         $this->elementEnd('label');
177         $this->elementEnd('li');
178         $this->elementEnd('ul');
179
180         $this->elementStart('fieldset');
181         $this->hidden('token', common_session_token());
182         $this->element('legend', null,
183                        _m('Create new account'));
184         $this->element('p', null,
185                        _m('Create a new user with this nickname.'));
186         $this->elementStart('ul', 'form_data');
187         $this->elementStart('li');
188         $this->input('newname', _m('New nickname'),
189                      ($this->username) ? $this->username : '',
190                      _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
191         $this->elementEnd('li');
192         $this->elementEnd('ul');
193         $this->submit('create', _m('Create'));
194         $this->elementEnd('fieldset');
195
196         $this->elementStart('fieldset');
197         $this->element('legend', null,
198                        _m('Connect existing account'));
199         $this->element('p', null,
200                        _m('If you already have an account, login with your username and password to connect it to your Facebook.'));
201         $this->elementStart('ul', 'form_data');
202         $this->elementStart('li');
203         $this->input('nickname', _m('Existing nickname'));
204         $this->elementEnd('li');
205         $this->elementStart('li');
206         $this->password('password', _m('Password'));
207         $this->elementEnd('li');
208         $this->elementEnd('ul');
209         $this->submit('connect', _m('Connect'));
210         $this->elementEnd('fieldset');
211
212         $this->elementEnd('fieldset');
213         $this->elementEnd('form');
214     }
215
216     function message($msg)
217     {
218         $this->message_text = $msg;
219         $this->showPage();
220     }
221
222     function createNewUser()
223     {
224         if (common_config('site', 'closed')) {
225             $this->clientError(_m('Registration not allowed.'));
226             return;
227         }
228
229         $invite = null;
230
231         if (common_config('site', 'inviteonly')) {
232             $code = $_SESSION['invitecode'];
233             if (empty($code)) {
234                 $this->clientError(_m('Registration not allowed.'));
235                 return;
236             }
237
238             $invite = Invitation::staticGet($code);
239
240             if (empty($invite)) {
241                 $this->clientError(_m('Not a valid invitation code.'));
242                 return;
243             }
244         }
245
246         $nickname = $this->trimmed('newname');
247
248         if (!Validate::string($nickname, array('min_length' => 1,
249                                                'max_length' => 64,
250                                                'format' => NICKNAME_FMT))) {
251             $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
252             return;
253         }
254
255         if (!User::allowed_nickname($nickname)) {
256             $this->showForm(_m('Nickname not allowed.'));
257             return;
258         }
259
260         if (User::staticGet('nickname', $nickname)) {
261             $this->showForm(_m('Nickname already in use. Try another one.'));
262             return;
263         }
264
265         $fullname = trim($this->fb_fields['firstname'] .
266             ' ' . $this->fb_fields['lastname']);
267
268         $args = array('nickname' => $nickname, 'fullname' => $fullname);
269
270         if (!empty($invite)) {
271             $args['code'] = $invite->code;
272         }
273
274         $user = User::register($args);
275
276         $result = $this->flinkUser($user->id, $this->fbuid);
277
278         if (!$result) {
279             $this->serverError(_m('Error connecting user to Facebook.'));
280             return;
281         }
282
283         common_set_user($user);
284         common_real_login(true);
285
286         common_debug('Facebook Connect Plugin - ' .
287                      "Registered new user $user->id from Facebook user $this->fbuid");
288
289         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
290                         303);
291     }
292
293     function connectNewUser()
294     {
295         $nickname = $this->trimmed('nickname');
296         $password = $this->trimmed('password');
297
298         if (!common_check_user($nickname, $password)) {
299             $this->showForm(_m('Invalid username or password.'));
300             return;
301         }
302
303         $user = User::staticGet('nickname', $nickname);
304
305         if (!empty($user)) {
306             common_debug('Facebook Connect Plugin - ' .
307                          "Legit user to connect to Facebook: $nickname");
308         }
309
310         $result = $this->flinkUser($user->id, $this->fbuid);
311
312         if (!$result) {
313             $this->serverError(_m('Error connecting user to Facebook.'));
314             return;
315         }
316
317         common_debug('Facebook Connnect Plugin - ' .
318                      "Connected Facebook user $this->fbuid to local user $user->id");
319
320         common_set_user($user);
321         common_real_login(true);
322
323         $this->goHome($user->nickname);
324     }
325
326     function connectUser()
327     {
328         $user = common_current_user();
329
330         $result = $this->flinkUser($user->id, $this->fbuid);
331
332         if (empty($result)) {
333             $this->serverError(_m('Error connecting user to Facebook.'));
334             return;
335         }
336
337         common_debug('Facebook Connect Plugin - ' .
338                      "Connected Facebook user $this->fbuid to local user $user->id");
339
340         // Return to Facebook connection settings tab
341         common_redirect(common_local_url('FBConnectSettings'), 303);
342     }
343
344     function tryLogin()
345     {
346         common_debug('Facebook Connect Plugin - ' .
347                      "Trying login for Facebook user $this->fbuid.");
348
349         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
350
351         if (!empty($flink)) {
352             $user = $flink->getUser();
353
354             if (!empty($user)) {
355
356                 common_debug('Facebook Connect Plugin - ' .
357                              "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
358
359                 common_set_user($user);
360                 common_real_login(true);
361                 $this->goHome($user->nickname);
362             }
363
364         } else {
365
366             common_debug('Facebook Connect Plugin - ' .
367                          "No flink found for fbuid: $this->fbuid - new user");
368
369             $this->showForm(null, $this->bestNewNickname());
370         }
371     }
372
373     function goHome($nickname)
374     {
375         $url = common_get_returnto();
376         if ($url) {
377             // We don't have to return to it again
378             common_set_returnto(null);
379         } else {
380             $url = common_local_url('all',
381                                     array('nickname' =>
382                                           $nickname));
383         }
384
385         common_redirect($url, 303);
386     }
387
388     function flinkUser($user_id, $fbuid)
389     {
390         $flink = new Foreign_link();
391         $flink->user_id = $user_id;
392         $flink->foreign_id = $fbuid;
393         $flink->service = FACEBOOK_CONNECT_SERVICE;
394         $flink->created = common_sql_now();
395
396         $flink_id = $flink->insert();
397
398         return $flink_id;
399     }
400
401     function bestNewNickname()
402     {
403         if (!empty($this->fb_fields['name'])) {
404             $nickname = $this->nicknamize($this->fb_fields['name']);
405             if ($this->isNewNickname($nickname)) {
406                 return $nickname;
407             }
408         }
409
410         // Try the full name
411
412         $fullname = trim($this->fb_fields['firstname'] .
413             ' ' . $this->fb_fields['lastname']);
414
415         if (!empty($fullname)) {
416             $fullname = $this->nicknamize($fullname);
417             if ($this->isNewNickname($fullname)) {
418                 return $fullname;
419             }
420         }
421
422         return null;
423     }
424
425      // Given a string, try to make it work as a nickname
426
427      function nicknamize($str)
428      {
429          $str = preg_replace('/\W/', '', $str);
430          return strtolower($str);
431      }
432
433     function isNewNickname($str)
434     {
435         if (!Validate::string($str, array('min_length' => 1,
436                                           'max_length' => 64,
437                                           'format' => NICKNAME_FMT))) {
438             return false;
439         }
440         if (!User::allowed_nickname($str)) {
441             return false;
442         }
443         if (User::staticGet('nickname', $str)) {
444             return false;
445         }
446         return true;
447     }
448
449     // XXX: Consider moving this to lib/facebookutil.php
450     function getFacebookFields($fb_uid, $fields) {
451         try {
452
453             $facebook = getFacebook();
454
455             $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
456
457             if (empty($infos)) {
458                 return null;
459             }
460             return reset($infos);
461
462         } catch (Exception $e) {
463             common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
464                        "Facebook client failure when requesting " .
465                 join(",", $fields) . " on uid " . $fb_uid .
466                     " : ". $e->getMessage());
467             return null;
468         }
469     }
470
471 }