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