]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Facebook/FBConnectAuth.php
Merge branch 'master' into 0.9.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 (!Event::handle('StartRegistrationTry', array($this))) {
236             return;
237         }
238
239         if (common_config('site', 'closed')) {
240             // TRANS: Client error trying to register with registrations not allowed.
241             $this->clientError(_m('Registration not allowed.'));
242             return;
243         }
244
245         $invite = null;
246
247         if (common_config('site', 'inviteonly')) {
248             $code = $_SESSION['invitecode'];
249             if (empty($code)) {
250                 // TRANS: Client error trying to register with registrations 'invite only'.
251                 $this->clientError(_m('Registration not allowed.'));
252                 return;
253             }
254
255             $invite = Invitation::staticGet($code);
256
257             if (empty($invite)) {
258                 // TRANS: Client error trying to register with an invalid invitation code.
259                 $this->clientError(_m('Not a valid invitation code.'));
260                 return;
261             }
262         }
263
264         try {
265             $nickname = Nickname::normalize($this->trimmed('newname'));
266         } catch (NicknameException $e) {
267             $this->showForm($e->getMessage());
268         }
269
270         if (!User::allowed_nickname($nickname)) {
271             $this->showForm(_m('Nickname not allowed.'));
272             return;
273         }
274
275         if (User::staticGet('nickname', $nickname)) {
276             $this->showForm(_m('Nickname already in use. Try another one.'));
277             return;
278         }
279
280         $fullname = trim($this->fb_fields['firstname'] .
281             ' ' . $this->fb_fields['lastname']);
282
283         $args = array('nickname' => $nickname, 'fullname' => $fullname);
284
285         if (!empty($invite)) {
286             $args['code'] = $invite->code;
287         }
288
289         $user = User::register($args);
290
291         $result = $this->flinkUser($user->id, $this->fbuid);
292
293         if (!$result) {
294             $this->serverError(_m('Error connecting user to Facebook.'));
295             return;
296         }
297
298         common_set_user($user);
299         common_real_login(true);
300
301         common_debug('Facebook Connect Plugin - ' .
302                      "Registered new user $user->id from Facebook user $this->fbuid");
303
304         Event::handle('EndRegistrationTry', array($this));
305
306         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
307                         303);
308     }
309
310     function connectNewUser()
311     {
312         $nickname = $this->trimmed('nickname');
313         $password = $this->trimmed('password');
314
315         if (!common_check_user($nickname, $password)) {
316             $this->showForm(_m('Invalid username or password.'));
317             return;
318         }
319
320         $user = User::staticGet('nickname', $nickname);
321
322         if (!empty($user)) {
323             common_debug('Facebook Connect Plugin - ' .
324                          "Legit user to connect to Facebook: $nickname");
325         }
326
327         $result = $this->flinkUser($user->id, $this->fbuid);
328
329         if (!$result) {
330             $this->serverError(_m('Error connecting user to Facebook.'));
331             return;
332         }
333
334         common_debug('Facebook Connnect Plugin - ' .
335                      "Connected Facebook user $this->fbuid to local user $user->id");
336
337         common_set_user($user);
338         common_real_login(true);
339
340         $this->goHome($user->nickname);
341     }
342
343     function connectUser()
344     {
345         $user = common_current_user();
346
347         $result = $this->flinkUser($user->id, $this->fbuid);
348
349         if (empty($result)) {
350             $this->serverError(_m('Error connecting user to Facebook.'));
351             return;
352         }
353
354         common_debug('Facebook Connect Plugin - ' .
355                      "Connected Facebook user $this->fbuid to local user $user->id");
356
357         // Return to Facebook connection settings tab
358         common_redirect(common_local_url('FBConnectSettings'), 303);
359     }
360
361     function tryLogin()
362     {
363         common_debug('Facebook Connect Plugin - ' .
364                      "Trying login for Facebook user $this->fbuid.");
365
366         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
367
368         if (!empty($flink)) {
369             $user = $flink->getUser();
370
371             if (!empty($user)) {
372
373                 common_debug('Facebook Connect Plugin - ' .
374                              "Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
375
376                 common_set_user($user);
377                 common_real_login(true);
378                 $this->goHome($user->nickname);
379             }
380
381         } else {
382
383             common_debug('Facebook Connect Plugin - ' .
384                          "No flink found for fbuid: $this->fbuid - new user");
385
386             $this->showForm(null, $this->bestNewNickname());
387         }
388     }
389
390     function goHome($nickname)
391     {
392         $url = common_get_returnto();
393         if ($url) {
394             // We don't have to return to it again
395             common_set_returnto(null);
396         } else {
397             $url = common_local_url('all',
398                                     array('nickname' =>
399                                           $nickname));
400         }
401
402         common_redirect($url, 303);
403     }
404
405     function flinkUser($user_id, $fbuid)
406     {
407         $flink = new Foreign_link();
408         $flink->user_id = $user_id;
409         $flink->foreign_id = $fbuid;
410         $flink->service = FACEBOOK_CONNECT_SERVICE;
411         $flink->created = common_sql_now();
412
413         $flink_id = $flink->insert();
414
415         return $flink_id;
416     }
417
418     function bestNewNickname()
419     {
420         if (!empty($this->fb_fields['name'])) {
421             $nickname = $this->nicknamize($this->fb_fields['name']);
422             if ($this->isNewNickname($nickname)) {
423                 return $nickname;
424             }
425         }
426
427         // Try the full name
428
429         $fullname = trim($this->fb_fields['firstname'] .
430             ' ' . $this->fb_fields['lastname']);
431
432         if (!empty($fullname)) {
433             $fullname = $this->nicknamize($fullname);
434             if ($this->isNewNickname($fullname)) {
435                 return $fullname;
436             }
437         }
438
439         return null;
440     }
441
442      /**
443       * Given a string, try to make it work as a nickname
444       */
445      function nicknamize($str)
446      {
447          $str = preg_replace('/\W/', '', $str);
448          return strtolower($str);
449      }
450
451     function isNewNickname($str)
452     {
453         if (!Nickname::isValid($str)) {
454             return false;
455         }
456         if (!User::allowed_nickname($str)) {
457             return false;
458         }
459         if (User::staticGet('nickname', $str)) {
460             return false;
461         }
462         return true;
463     }
464
465     // XXX: Consider moving this to lib/facebookutil.php
466     function getFacebookFields($fb_uid, $fields) {
467         try {
468
469             $facebook = getFacebook();
470
471             $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
472
473             if (empty($infos)) {
474                 return null;
475             }
476             return reset($infos);
477
478         } catch (Exception $e) {
479             common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
480                        "Facebook client failure when requesting " .
481                 join(",", $fields) . " on uid " . $fb_uid .
482                     " : ". $e->getMessage());
483             return null;
484         }
485     }
486 }