]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FBConnect/FBConnectAuth.php
5399326d65a35abb317eed64a060a0e382a790c8
[quix0rs-gnu-social.git] / plugins / FBConnect / FBConnectAuth.php
1 <?php
2 /**
3  * Laconica, 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   Laconica
24  * @author    Zach Copley <zach@controlyourself.ca>
25  * @copyright 2009 Control Yourself, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://laconi.ca/
28  */
29
30 require_once INSTALLDIR . '/plugins/FBConnect/FBConnectPlugin.php';
31
32 class FBConnectauthAction extends Action
33 {
34
35     var $fbuid      = null;
36     var $fb_fields  = null;
37
38     function prepare($args) {
39         parent::prepare($args);
40
41         try {
42
43             $this->fbuid = getFacebook()->get_loggedin_user();
44
45             if ($this->fbuid > 0) {
46                 $this->fb_fields = $this->getFacebookFields($this->fbuid,
47                     array('first_name', 'last_name', 'name'));
48             } else {
49                 common_debug("No Facebook User found.");
50             }
51
52         } catch (Exception $e) {
53             common_log(LOG_WARNING, 'Problem getting Facebook uid: ' .
54                 $e->getMessage());
55         }
56
57         return true;
58     }
59
60     function handle($args)
61     {
62         parent::handle($args);
63
64         if (common_is_real_login()) {
65             $this->clientError(_('Already logged in.'));
66         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
67
68             $token = $this->trimmed('token');
69             if (!$token || $token != common_session_token()) {
70                 $this->showForm(_('There was a problem with your session token. Try again, please.'));
71                 return;
72             }
73             if ($this->arg('create')) {
74                 if (!$this->boolean('license')) {
75                     $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
76                                     $this->trimmed('newname'));
77                     return;
78                 }
79                 $this->createNewUser();
80             } else if ($this->arg('connect')) {
81                 $this->connectUser();
82             } else {
83                 common_debug(print_r($this->args, true), __FILE__);
84                 $this->showForm(_('Something weird happened.'),
85                                 $this->trimmed('newname'));
86             }
87         } else {
88             $this->tryLogin();
89         }
90     }
91
92     function showPageNotice()
93     {
94         if ($this->error) {
95             $this->element('div', array('class' => 'error'), $this->error);
96         } else {
97             $this->element('div', 'instructions',
98                            sprintf(_('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')));
99         }
100     }
101
102     function title()
103     {
104         return _('Facebook Account Setup');
105     }
106
107     function showForm($error=null, $username=null)
108     {
109         $this->error = $error;
110         $this->username = $username;
111
112         $this->showPage();
113     }
114
115     function showPage()
116     {
117         parent::showPage();
118     }
119
120     function showContent()
121     {
122         if (!empty($this->message_text)) {
123             $this->element('p', null, $this->message);
124             return;
125         }
126
127         $this->elementStart('form', array('method' => 'post',
128                                           'id' => 'form_facebook_account_connect',
129                                           'class' => 'form_settings',
130                                           'action' => common_local_url('FBConnectAuth')));
131         $this->elementStart('fieldset');
132         $this->hidden('token', common_session_token());
133         $this->element('legend', null,
134                        _('Create new account'));
135         $this->element('p', null,
136                        _('Create a new user with this nickname.'));
137         $this->elementStart('ul', 'form_data');
138         $this->elementStart('li');
139         $this->input('newname', _('New nickname'),
140                      ($this->username) ? $this->username : '',
141                      _('1-64 lowercase letters or numbers, no punctuation or spaces'));
142         $this->elementEnd('li');
143         $this->elementStart('li');
144         $this->element('input', array('type' => 'checkbox',
145                                       'id' => 'license',
146                                       'class' => 'checkbox',
147                                       'name' => 'license',
148                                       'value' => 'true'));
149         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
150         $this->text(_('My text and files are available under '));
151         $this->element('a', array('href' => common_config('license', 'url')),
152                        common_config('license', 'title'));
153         $this->text(_(' except this private data: password, email address, IM address, phone number.'));
154         $this->elementEnd('label');
155         $this->elementEnd('li');
156         $this->elementEnd('ul');
157         $this->submit('create', _('Create'));
158         $this->elementEnd('fieldset');
159
160         $this->elementStart('fieldset');
161         $this->element('legend', null,
162                        _('Connect existing account'));
163         $this->element('p', null,
164                        _('If you already have an account, login with your username and password to connect it to your Facebook.'));
165
166         $this->elementStart('ul', 'form_data');
167         $this->elementStart('li');
168         $this->input('nickname', _('Existing nickname'));
169         $this->elementEnd('li');
170         $this->elementStart('li');
171         $this->password('password', _('Password'));
172         $this->elementEnd('li');
173         $this->elementEnd('ul');
174         $this->submit('connect', _('Connect'));
175         $this->elementEnd('fieldset');
176         $this->elementEnd('form');
177     }
178
179     function message($msg)
180     {
181         $this->message_text = $msg;
182         $this->showPage();
183     }
184
185     function createNewUser()
186     {
187
188         if (common_config('site', 'closed')) {
189             $this->clientError(_('Registration not allowed.'));
190             return;
191         }
192
193         $invite = null;
194
195         if (common_config('site', 'inviteonly')) {
196             $code = $_SESSION['invitecode'];
197             if (empty($code)) {
198                 $this->clientError(_('Registration not allowed.'));
199                 return;
200             }
201
202             $invite = Invitation::staticGet($code);
203
204             if (empty($invite)) {
205                 $this->clientError(_('Not a valid invitation code.'));
206                 return;
207             }
208         }
209
210         $nickname = $this->trimmed('newname');
211
212         if (!Validate::string($nickname, array('min_length' => 1,
213                                                'max_length' => 64,
214                                                'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
215             $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
216             return;
217         }
218
219         if (!User::allowed_nickname($nickname)) {
220             $this->showForm(_('Nickname not allowed.'));
221             return;
222         }
223
224         if (User::staticGet('nickname', $nickname)) {
225             $this->showForm(_('Nickname already in use. Try another one.'));
226             return;
227         }
228
229         $fullname = trim($this->fb_fields['firstname'] .
230             ' ' . $this->fb_fields['lastname']);
231
232         $args = array('nickname' => $nickname, 'fullname' => $fullname);
233
234         if (!empty($invite)) {
235             $args['code'] = $invite->code;
236         }
237
238         $user = User::register($args);
239
240         $result = $this->flinkUser($user->id, $this->fbuid);
241
242         if (!$result) {
243             $this->serverError(_('Error connecting user to Facebook.'));
244             return;
245         }
246
247         common_set_user($user);
248         common_real_login(true);
249
250         common_debug("Registered new user $user->id from Facebook user $this->fbuid");
251
252         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
253                         303);
254     }
255
256     function connectUser()
257     {
258         $nickname = $this->trimmed('nickname');
259         $password = $this->trimmed('password');
260
261         if (!common_check_user($nickname, $password)) {
262             $this->showForm(_('Invalid username or password.'));
263             return;
264         }
265
266         $user = User::staticGet('nickname', $nickname);
267
268         if ($user) {
269             common_debug("Legit user to connect to Facebook: $nickname");
270         }
271
272         $result = $this->flinkUser($user->id, $this->fbuid);
273
274         if (!$result) {
275             $this->serverError(_('Error connecting user to Facebook.'));
276             return;
277         }
278
279         common_debug("Connected Facebook user $this->fbuid to local user $user->id");
280
281         common_set_user($user);
282         common_real_login(true);
283
284         $this->goHome($user->nickname);
285     }
286
287     function tryLogin()
288     {
289         common_debug("Trying Facebook Login...");
290
291         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
292
293         if ($flink) {
294             $user = $flink->getUser();
295
296             if ($user) {
297
298                 common_debug("Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
299
300                 common_set_user($user);
301                 common_real_login(true);
302                 $this->goHome($user->nickname);
303             }
304
305         } else {
306
307             common_debug("No flink found for fbuid: $this->fbuid");
308
309             $this->showForm(null, $this->bestNewNickname());
310         }
311     }
312
313     function goHome($nickname)
314     {
315         $url = common_get_returnto();
316         if ($url) {
317             // We don't have to return to it again
318             common_set_returnto(null);
319         } else {
320             $url = common_local_url('all',
321                                     array('nickname' =>
322                                           $nickname));
323         }
324
325         common_redirect($url, 303);
326     }
327
328     function flinkUser($user_id, $fbuid)
329     {
330         $flink = new Foreign_link();
331         $flink->user_id = $user_id;
332         $flink->foreign_id = $fbuid;
333         $flink->service = FACEBOOK_CONNECT_SERVICE;
334         $flink->created = common_sql_now();
335
336         $flink_id = $flink->insert();
337
338         return $flink_id;
339     }
340
341     function bestNewNickname()
342     {
343         if (!empty($this->fb_fields['name'])) {
344             $nickname = $this->nicknamize($this->fb_fields['name']);
345             if ($this->isNewNickname($nickname)) {
346                 return $nickname;
347             }
348         }
349
350         // Try the full name
351
352         $fullname = trim($this->fb_fields['firstname'] .
353             ' ' . $this->fb_fields['lastname']);
354
355         if (!empty($fullname)) {
356             $fullname = $this->nicknamize($fullname);
357             if ($this->isNewNickname($fullname)) {
358                 return $fullname;
359             }
360         }
361
362         return null;
363     }
364
365      // Given a string, try to make it work as a nickname
366
367      function nicknamize($str)
368      {
369          $str = preg_replace('/\W/', '', $str);
370          return strtolower($str);
371      }
372
373     function isNewNickname($str)
374     {
375         if (!Validate::string($str, array('min_length' => 1,
376                                           'max_length' => 64,
377                                           'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
378             return false;
379         }
380         if (!User::allowed_nickname($str)) {
381             return false;
382         }
383         if (User::staticGet('nickname', $str)) {
384             return false;
385         }
386         return true;
387     }
388
389     // XXX: Consider moving this to lib/facebookutil.php
390     function getFacebookFields($fb_uid, $fields) {
391         try {
392
393             $facebook = getFacebook();
394
395             $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
396
397             if (empty($infos)) {
398                 return null;
399             }
400             return reset($infos);
401
402         } catch (Exception $e) {
403             common_log(LOG_WARNING, "Facebook client failure when requesting " .
404                 join(",", $fields) . " on uid " . $fb_uid .
405                     " : ". $e->getMessage());
406             return null;
407         }
408     }
409
410 }