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