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