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