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