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