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