]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Facebook/FBConnectAuth.php
Just a label change. Since the user already went ahead with
[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     function showContent()
142     {
143         if (!empty($this->message_text)) {
144             $this->element('p', null, $this->message);
145             return;
146         }
147
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, _m('Connection options'));
154         $this->elementStart('ul', 'form_data');
155         $this->elementStart('li');
156         $this->element('input', array('type' => 'checkbox',
157                                       'id' => 'license',
158                                       'class' => 'checkbox',
159                                       'name' => 'license',
160                                       'value' => 'true'));
161         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
162         $this->text(_m('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(_m(' except this private data: password, email address, IM address, phone number.'));
166         $this->elementEnd('label');
167         $this->elementEnd('li');
168         $this->elementEnd('ul');
169
170         $this->elementStart('fieldset');
171         $this->hidden('token', common_session_token());
172         $this->element('legend', null,
173                        _m('Create new account'));
174         $this->element('p', null,
175                        _m('Create a new user with this nickname.'));
176         $this->elementStart('ul', 'form_data');
177         $this->elementStart('li');
178         $this->input('newname', _m('New nickname'),
179                      ($this->username) ? $this->username : '',
180                      _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
181         $this->elementEnd('li');
182         $this->elementEnd('ul');
183         $this->submit('create', _m('Create'));
184         $this->elementEnd('fieldset');
185
186         $this->elementStart('fieldset');
187         $this->element('legend', null,
188                        _m('Connect existing account'));
189         $this->element('p', null,
190                        _m('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', _m('Existing nickname'));
194         $this->elementEnd('li');
195         $this->elementStart('li');
196         $this->password('password', _m('Password'));
197         $this->elementEnd('li');
198         $this->elementEnd('ul');
199         $this->submit('connect', _m('Connect'));
200         $this->elementEnd('fieldset');
201
202         $this->elementEnd('fieldset');
203         $this->elementEnd('form');
204     }
205
206     function message($msg)
207     {
208         $this->message_text = $msg;
209         $this->showPage();
210     }
211
212     function createNewUser()
213     {
214         if (common_config('site', 'closed')) {
215             $this->clientError(_m('Registration not allowed.'));
216             return;
217         }
218
219         $invite = null;
220
221         if (common_config('site', 'inviteonly')) {
222             $code = $_SESSION['invitecode'];
223             if (empty($code)) {
224                 $this->clientError(_m('Registration not allowed.'));
225                 return;
226             }
227
228             $invite = Invitation::staticGet($code);
229
230             if (empty($invite)) {
231                 $this->clientError(_m('Not a valid invitation code.'));
232                 return;
233             }
234         }
235
236         $nickname = $this->trimmed('newname');
237
238         if (!Validate::string($nickname, array('min_length' => 1,
239                                                'max_length' => 64,
240                                                'format' => NICKNAME_FMT))) {
241             $this->showForm(_m('Nickname must have only lowercase letters and numbers and no spaces.'));
242             return;
243         }
244
245         if (!User::allowed_nickname($nickname)) {
246             $this->showForm(_m('Nickname not allowed.'));
247             return;
248         }
249
250         if (User::staticGet('nickname', $nickname)) {
251             $this->showForm(_m('Nickname already in use. Try another one.'));
252             return;
253         }
254
255         $fullname = trim($this->fb_fields['firstname'] .
256             ' ' . $this->fb_fields['lastname']);
257
258         $args = array('nickname' => $nickname, 'fullname' => $fullname);
259
260         if (!empty($invite)) {
261             $args['code'] = $invite->code;
262         }
263
264         $user = User::register($args);
265
266         $result = $this->flinkUser($user->id, $this->fbuid);
267
268         if (!$result) {
269             $this->serverError(_m('Error connecting user to Facebook.'));
270             return;
271         }
272
273         common_set_user($user);
274         common_real_login(true);
275
276         common_debug('Facebook Connect Plugin - ' .
277                      "Registered new user $user->id from Facebook user $this->fbuid");
278
279         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
280                         303);
281     }
282
283     function connectNewUser()
284     {
285         $nickname = $this->trimmed('nickname');
286         $password = $this->trimmed('password');
287
288         if (!common_check_user($nickname, $password)) {
289             $this->showForm(_m('Invalid username or password.'));
290             return;
291         }
292
293         $user = User::staticGet('nickname', $nickname);
294
295         if (!empty($user)) {
296             common_debug('Facebook Connect Plugin - ' .
297                          "Legit user to connect to Facebook: $nickname");
298         }
299
300         $result = $this->flinkUser($user->id, $this->fbuid);
301
302         if (!$result) {
303             $this->serverError(_m('Error connecting user to Facebook.'));
304             return;
305         }
306
307         common_debug('Facebook Connnect Plugin - ' .
308                      "Connected Facebook user $this->fbuid to local user $user->id");
309
310         common_set_user($user);
311         common_real_login(true);
312
313         $this->goHome($user->nickname);
314     }
315
316     function connectUser()
317     {
318         $user = common_current_user();
319
320         $result = $this->flinkUser($user->id, $this->fbuid);
321
322         if (empty($result)) {
323             $this->serverError(_m('Error connecting user to Facebook.'));
324             return;
325         }
326
327         common_debug('Facebook Connect Plugin - ' .
328                      "Connected Facebook user $this->fbuid to local user $user->id");
329
330         // Return to Facebook connection settings tab
331         common_redirect(common_local_url('FBConnectSettings'), 303);
332     }
333
334     function tryLogin()
335     {
336         common_debug('Facebook Connect Plugin - ' .
337                      "Trying login for Facebook user $this->fbuid.");
338
339         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
340
341         if (!empty($flink)) {
342             $user = $flink->getUser();
343
344             if (!empty($user)) {
345
346                 common_debug('Facebook Connect Plugin - ' .
347                              "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
348
349                 common_set_user($user);
350                 common_real_login(true);
351                 $this->goHome($user->nickname);
352             }
353
354         } else {
355
356             common_debug('Facebook Connect Plugin - ' .
357                          "No flink found for fbuid: $this->fbuid - new user");
358
359             $this->showForm(null, $this->bestNewNickname());
360         }
361     }
362
363     function goHome($nickname)
364     {
365         $url = common_get_returnto();
366         if ($url) {
367             // We don't have to return to it again
368             common_set_returnto(null);
369         } else {
370             $url = common_local_url('all',
371                                     array('nickname' =>
372                                           $nickname));
373         }
374
375         common_redirect($url, 303);
376     }
377
378     function flinkUser($user_id, $fbuid)
379     {
380         $flink = new Foreign_link();
381         $flink->user_id = $user_id;
382         $flink->foreign_id = $fbuid;
383         $flink->service = FACEBOOK_CONNECT_SERVICE;
384         $flink->created = common_sql_now();
385
386         $flink_id = $flink->insert();
387
388         return $flink_id;
389     }
390
391     function bestNewNickname()
392     {
393         if (!empty($this->fb_fields['name'])) {
394             $nickname = $this->nicknamize($this->fb_fields['name']);
395             if ($this->isNewNickname($nickname)) {
396                 return $nickname;
397             }
398         }
399
400         // Try the full name
401
402         $fullname = trim($this->fb_fields['firstname'] .
403             ' ' . $this->fb_fields['lastname']);
404
405         if (!empty($fullname)) {
406             $fullname = $this->nicknamize($fullname);
407             if ($this->isNewNickname($fullname)) {
408                 return $fullname;
409             }
410         }
411
412         return null;
413     }
414
415      // Given a string, try to make it work as a nickname
416
417      function nicknamize($str)
418      {
419          $str = preg_replace('/\W/', '', $str);
420          return strtolower($str);
421      }
422
423     function isNewNickname($str)
424     {
425         if (!Validate::string($str, array('min_length' => 1,
426                                           'max_length' => 64,
427                                           'format' => NICKNAME_FMT))) {
428             return false;
429         }
430         if (!User::allowed_nickname($str)) {
431             return false;
432         }
433         if (User::staticGet('nickname', $str)) {
434             return false;
435         }
436         return true;
437     }
438
439     // XXX: Consider moving this to lib/facebookutil.php
440     function getFacebookFields($fb_uid, $fields) {
441         try {
442
443             $facebook = getFacebook();
444
445             $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
446
447             if (empty($infos)) {
448                 return null;
449             }
450             return reset($infos);
451
452         } catch (Exception $e) {
453             common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
454                        "Facebook client failure when requesting " .
455                 join(",", $fields) . " on uid " . $fb_uid .
456                     " : ". $e->getMessage());
457             return null;
458         }
459     }
460
461 }