]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FBConnect/FBConnectAuth.php
Merge branch '0.8.x' of git://gitorious.org/laconica/dev into 0.8.x
[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_settings_facebook_connect',
129                                           'class' => 'form_settings',
130                                           'action' => common_local_url('FBConnectAuth')));
131         $this->elementStart('fieldset', array('id' => 'settings_facebook_connect_options'));
132         $this->element('legend', null, _('Connection options'));
133         $this->elementStart('ul', 'form_data');
134         $this->elementStart('li');
135         $this->element('input', array('type' => 'checkbox',
136                                       'id' => 'license',
137                                       'class' => 'checkbox',
138                                       'name' => 'license',
139                                       'value' => 'true'));
140         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
141         $this->text(_('My text and files are available under '));
142         $this->element('a', array('href' => common_config('license', 'url')),
143                        common_config('license', 'title'));
144         $this->text(_(' except this private data: password, email address, IM address, phone number.'));
145         $this->elementEnd('label');
146         $this->elementEnd('li');
147         $this->elementEnd('ul');
148
149         $this->elementStart('fieldset');
150         $this->hidden('token', common_session_token());
151         $this->element('legend', null,
152                        _('Create new account'));
153         $this->element('p', null,
154                        _('Create a new user with this nickname.'));
155         $this->elementStart('ul', 'form_data');
156         $this->elementStart('li');
157         $this->input('newname', _('New nickname'),
158                      ($this->username) ? $this->username : '',
159                      _('1-64 lowercase letters or numbers, no punctuation or spaces'));
160         $this->elementEnd('li');
161         $this->elementEnd('ul');
162         $this->submit('create', _('Create'));
163         $this->elementEnd('fieldset');
164
165         $this->elementStart('fieldset');
166         $this->element('legend', null,
167                        _('Connect existing account'));
168         $this->element('p', null,
169                        _('If you already have an account, login with your username and password to connect it to your Facebook.'));
170         $this->elementStart('ul', 'form_data');
171         $this->elementStart('li');
172         $this->input('nickname', _('Existing nickname'));
173         $this->elementEnd('li');
174         $this->elementStart('li');
175         $this->password('password', _('Password'));
176         $this->elementEnd('li');
177         $this->elementEnd('ul');
178         $this->submit('connect', _('Connect'));
179         $this->elementEnd('fieldset');
180
181         $this->elementEnd('fieldset');
182         $this->elementEnd('form');
183     }
184
185     function message($msg)
186     {
187         $this->message_text = $msg;
188         $this->showPage();
189     }
190
191     function createNewUser()
192     {
193
194         if (common_config('site', 'closed')) {
195             $this->clientError(_('Registration not allowed.'));
196             return;
197         }
198
199         $invite = null;
200
201         if (common_config('site', 'inviteonly')) {
202             $code = $_SESSION['invitecode'];
203             if (empty($code)) {
204                 $this->clientError(_('Registration not allowed.'));
205                 return;
206             }
207
208             $invite = Invitation::staticGet($code);
209
210             if (empty($invite)) {
211                 $this->clientError(_('Not a valid invitation code.'));
212                 return;
213             }
214         }
215
216         $nickname = $this->trimmed('newname');
217
218         if (!Validate::string($nickname, array('min_length' => 1,
219                                                'max_length' => 64,
220                                                'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
221             $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
222             return;
223         }
224
225         if (!User::allowed_nickname($nickname)) {
226             $this->showForm(_('Nickname not allowed.'));
227             return;
228         }
229
230         if (User::staticGet('nickname', $nickname)) {
231             $this->showForm(_('Nickname already in use. Try another one.'));
232             return;
233         }
234
235         $fullname = trim($this->fb_fields['firstname'] .
236             ' ' . $this->fb_fields['lastname']);
237
238         $args = array('nickname' => $nickname, 'fullname' => $fullname);
239
240         if (!empty($invite)) {
241             $args['code'] = $invite->code;
242         }
243
244         $user = User::register($args);
245
246         $result = $this->flinkUser($user->id, $this->fbuid);
247
248         if (!$result) {
249             $this->serverError(_('Error connecting user to Facebook.'));
250             return;
251         }
252
253         common_set_user($user);
254         common_real_login(true);
255
256         common_debug("Registered new user $user->id from Facebook user $this->fbuid");
257
258         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
259                         303);
260     }
261
262     function connectUser()
263     {
264         $nickname = $this->trimmed('nickname');
265         $password = $this->trimmed('password');
266
267         if (!common_check_user($nickname, $password)) {
268             $this->showForm(_('Invalid username or password.'));
269             return;
270         }
271
272         $user = User::staticGet('nickname', $nickname);
273
274         if ($user) {
275             common_debug("Legit user to connect to Facebook: $nickname");
276         }
277
278         $result = $this->flinkUser($user->id, $this->fbuid);
279
280         if (!$result) {
281             $this->serverError(_('Error connecting user to Facebook.'));
282             return;
283         }
284
285         common_debug("Connected Facebook user $this->fbuid to local user $user->id");
286
287         common_set_user($user);
288         common_real_login(true);
289
290         $this->goHome($user->nickname);
291     }
292
293     function tryLogin()
294     {
295         common_debug("Trying Facebook Login...");
296
297         $flink = Foreign_link::getByForeignID($this->fbuid, FACEBOOK_CONNECT_SERVICE);
298
299         if ($flink) {
300             $user = $flink->getUser();
301
302             if ($user) {
303
304                 common_debug("Logged in Facebook user $flink->foreign_id as user $user->id ($user->nickname)");
305
306                 common_set_user($user);
307                 common_real_login(true);
308                 $this->goHome($user->nickname);
309             }
310
311         } else {
312
313             common_debug("No flink found for fbuid: $this->fbuid");
314
315             $this->showForm(null, $this->bestNewNickname());
316         }
317     }
318
319     function goHome($nickname)
320     {
321         $url = common_get_returnto();
322         if ($url) {
323             // We don't have to return to it again
324             common_set_returnto(null);
325         } else {
326             $url = common_local_url('all',
327                                     array('nickname' =>
328                                           $nickname));
329         }
330
331         common_redirect($url, 303);
332     }
333
334     function flinkUser($user_id, $fbuid)
335     {
336         $flink = new Foreign_link();
337         $flink->user_id = $user_id;
338         $flink->foreign_id = $fbuid;
339         $flink->service = FACEBOOK_CONNECT_SERVICE;
340         $flink->created = common_sql_now();
341
342         $flink_id = $flink->insert();
343
344         return $flink_id;
345     }
346
347     function bestNewNickname()
348     {
349         if (!empty($this->fb_fields['name'])) {
350             $nickname = $this->nicknamize($this->fb_fields['name']);
351             if ($this->isNewNickname($nickname)) {
352                 return $nickname;
353             }
354         }
355
356         // Try the full name
357
358         $fullname = trim($this->fb_fields['firstname'] .
359             ' ' . $this->fb_fields['lastname']);
360
361         if (!empty($fullname)) {
362             $fullname = $this->nicknamize($fullname);
363             if ($this->isNewNickname($fullname)) {
364                 return $fullname;
365             }
366         }
367
368         return null;
369     }
370
371      // Given a string, try to make it work as a nickname
372
373      function nicknamize($str)
374      {
375          $str = preg_replace('/\W/', '', $str);
376          return strtolower($str);
377      }
378
379     function isNewNickname($str)
380     {
381         if (!Validate::string($str, array('min_length' => 1,
382                                           'max_length' => 64,
383                                           'format' => VALIDATE_NUM . VALIDATE_ALPHA_LOWER))) {
384             return false;
385         }
386         if (!User::allowed_nickname($str)) {
387             return false;
388         }
389         if (User::staticGet('nickname', $str)) {
390             return false;
391         }
392         return true;
393     }
394
395     // XXX: Consider moving this to lib/facebookutil.php
396     function getFacebookFields($fb_uid, $fields) {
397         try {
398
399             $facebook = getFacebook();
400
401             $infos = $facebook->api_client->users_getInfo($fb_uid, $fields);
402
403             if (empty($infos)) {
404                 return null;
405             }
406             return reset($infos);
407
408         } catch (Exception $e) {
409             common_log(LOG_WARNING, "Facebook client failure when requesting " .
410                 join(",", $fields) . " on uid " . $fb_uid .
411                     " : ". $e->getMessage());
412             return null;
413         }
414     }
415
416 }