]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterauthorization.php
Upgrade Twitter bridge to use OAuth 1.0a. It's more secure, and allows
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitterauthorization.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Class for doing OAuth authentication against Twitter
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   StatusNet
24  * @author    Zach Copley <zach@status.net>
25  * @author    Julien C <chaumond@gmail.com>
26  * @copyright 2009-2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET') && !defined('LACONICA')) {
32     exit(1);
33 }
34
35 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
36
37 /**
38  * Class for doing OAuth authentication against Twitter
39  *
40  * Peforms the OAuth "dance" between StatusNet and Twitter -- requests a token,
41  * authorizes it, and exchanges it for an access token.  It also creates a link
42  * (Foreign_link) between the StatusNet user and Twitter user and stores the
43  * access token and secret in the link.
44  *
45  * @category Plugin
46  * @package  StatusNet
47  * @author   Zach Copley <zach@status.net>
48  * @author   Julien C <chaumond@gmail.com>
49  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
50  * @link     http://laconi.ca/
51  *
52  */
53 class TwitterauthorizationAction extends Action
54 {
55     var $twuid        = null;
56     var $tw_fields    = null;
57     var $access_token = null;
58     var $signin       = null;
59     var $verifier     = null;
60
61     /**
62      * Initialize class members. Looks for 'oauth_token' parameter.
63      *
64      * @param array $args misc. arguments
65      *
66      * @return boolean true
67      */
68     function prepare($args)
69     {
70         parent::prepare($args);
71
72         $this->signin      = $this->boolean('signin');
73         $this->oauth_token = $this->arg('oauth_token');
74         $this->verifier    = $this->arg('oauth_verifier');
75
76         return true;
77     }
78
79     /**
80      * Handler method
81      *
82      * @param array $args is ignored since it's now passed in in prepare()
83      *
84      * @return nothing
85      */
86     function handle($args)
87     {
88         parent::handle($args);
89
90         if (common_logged_in()) {
91             $user  = common_current_user();
92             $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
93
94             // If there's already a foreign link record and a foreign user
95             // it means the accounts are already linked, and this is unecessary.
96             // So go back.
97
98             if (isset($flink)) {
99                 $fuser = $flink->getForeignUser();
100                 if (!empty($fuser)) {
101                     common_redirect(common_local_url('twittersettings'));
102                 }
103             }
104         }
105
106         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
107
108             // User was not logged in to StatusNet before
109
110             $this->twuid = $this->trimmed('twuid');
111
112             $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
113                                      'fullname' => $this->trimmed('tw_fields_fullname'));
114
115             $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
116
117             $token = $this->trimmed('token');
118
119             if (!$token || $token != common_session_token()) {
120                 $this->showForm(_('There was a problem with your session token. Try again, please.'));
121                 return;
122             }
123
124             if ($this->arg('create')) {
125                 if (!$this->boolean('license')) {
126                     $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
127                                     $this->trimmed('newname'));
128                     return;
129                 }
130                 $this->createNewUser();
131             } else if ($this->arg('connect')) {
132                 $this->connectNewUser();
133             } else {
134                 common_debug('Twitter Connect Plugin - ' .
135                              print_r($this->args, true));
136                 $this->showForm(_('Something weird happened.'),
137                                 $this->trimmed('newname'));
138             }
139         } else {
140             // $this->oauth_token is only populated once Twitter authorizes our
141             // request token. If it's empty we're at the beginning of the auth
142             // process
143
144             if (empty($this->oauth_token)) {
145                 $this->authorizeRequestToken();
146             } else {
147                 $this->saveAccessToken();
148             }
149         }
150     }
151
152     /**
153      * Asks Twitter for a request token, and then redirects to Twitter
154      * to authorize it.
155      *
156      * @return nothing
157      */
158     function authorizeRequestToken()
159     {
160         try {
161
162             // Get a new request token and authorize it
163
164             $client  = new TwitterOAuthClient();
165             $req_tok = $client->getRequestToken();
166
167             // Sock the request token away in the session temporarily
168
169             $_SESSION['twitter_request_token']        = $req_tok->key;
170             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
171
172             $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
173
174         } catch (OAuthClientException $e) {
175             $msg = sprintf('OAuth client error - code: %1s, msg: %2s',
176                            $e->getCode(), $e->getMessage());
177             $this->serverError(_m('Couldn\'t link your Twitter account.'));
178         }
179
180         common_redirect($auth_link);
181     }
182
183     /**
184      * Called when Twitter returns an authorized request token. Exchanges
185      * it for an access token and stores it.
186      *
187      * @return nothing
188      */
189     function saveAccessToken()
190     {
191         // Check to make sure Twitter returned the same request
192         // token we sent them
193
194         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
195             $this->serverError(_m('Couldn\'t link your Twitter account.'));
196         }
197
198         $twitter_user = null;
199
200         try {
201
202             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
203                 $_SESSION['twitter_request_token_secret']);
204
205             // Exchange the request token for an access token
206
207             $atok = $client->getAccessToken($this->verifier);
208
209             // Test the access token and get the user's Twitter info
210
211             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
212             $twitter_user = $client->verifyCredentials();
213
214         } catch (OAuthClientException $e) {
215             $msg = sprintf('OAuth client error - code: %1$s, msg: %2$s',
216                            $e->getCode(), $e->getMessage());
217             $this->serverError(_m('Couldn\'t link your Twitter account.'));
218         }
219
220         if (common_logged_in()) {
221
222             // Save the access token and Twitter user info
223
224             $user = common_current_user();
225             $this->saveForeignLink($user->id, $twitter_user->id, $atok);
226             save_twitter_user($twitter_user->id, $twitter_user->screen_name);
227
228         } else {
229
230             $this->twuid = $twitter_user->id;
231             $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
232                                      "name" => $twitter_user->name);
233             $this->access_token = $atok;
234             $this->tryLogin();
235         }
236
237         // Clean up the the mess we made in the session
238
239         unset($_SESSION['twitter_request_token']);
240         unset($_SESSION['twitter_request_token_secret']);
241
242         if (common_logged_in()) {
243             common_redirect(common_local_url('twittersettings'));
244         }
245     }
246
247     /**
248      * Saves a Foreign_link between Twitter user and local user,
249      * which includes the access token and secret.
250      *
251      * @param int        $user_id StatusNet user ID
252      * @param int        $twuid   Twitter user ID
253      * @param OAuthToken $token   the access token to save
254      *
255      * @return nothing
256      */
257     function saveForeignLink($user_id, $twuid, $access_token)
258     {
259         $flink = new Foreign_link();
260
261         $flink->user_id = $user_id;
262         $flink->service = TWITTER_SERVICE;
263         $flink->delete(); // delete stale flink, if any
264
265         $flink->user_id     = $user_id;
266         $flink->foreign_id  = $twuid;
267         $flink->service     = TWITTER_SERVICE;
268
269         $creds = TwitterOAuthClient::packToken($access_token);
270
271         $flink->credentials = $creds;
272         $flink->created     = common_sql_now();
273
274         // Defaults: noticesync on, everything else off
275
276         $flink->set_flags(true, false, false, false);
277
278         $flink_id = $flink->insert();
279
280         if (empty($flink_id)) {
281             common_log_db_error($flink, 'INSERT', __FILE__);
282                 $this->serverError(_('Couldn\'t link your Twitter account.'));
283         }
284
285         return $flink_id;
286     }
287
288     function showPageNotice()
289     {
290         if ($this->error) {
291             $this->element('div', array('class' => 'error'), $this->error);
292         } else {
293             $this->element('div', 'instructions',
294                            sprintf(_('This is the first time you\'ve logged into %s so we must connect your Twitter account 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')));
295         }
296     }
297
298     function title()
299     {
300         return _('Twitter Account Setup');
301     }
302
303     function showForm($error=null, $username=null)
304     {
305         $this->error = $error;
306         $this->username = $username;
307
308         $this->showPage();
309     }
310
311     function showPage()
312     {
313         parent::showPage();
314     }
315
316     function showContent()
317     {
318         if (!empty($this->message_text)) {
319             $this->element('p', null, $this->message);
320             return;
321         }
322
323         $this->elementStart('form', array('method' => 'post',
324                                           'id' => 'form_settings_twitter_connect',
325                                           'class' => 'form_settings',
326                                           'action' => common_local_url('twitterauthorization')));
327         $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
328         $this->element('legend', null, _('Connection options'));
329         $this->elementStart('ul', 'form_data');
330         $this->elementStart('li');
331         $this->element('input', array('type' => 'checkbox',
332                                       'id' => 'license',
333                                       'class' => 'checkbox',
334                                       'name' => 'license',
335                                       'value' => 'true'));
336         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
337         $this->text(_('My text and files are available under '));
338         $this->element('a', array('href' => common_config('license', 'url')),
339                        common_config('license', 'title'));
340         $this->text(_(' except this private data: password, email address, IM address, phone number.'));
341         $this->elementEnd('label');
342         $this->elementEnd('li');
343         $this->elementEnd('ul');
344         $this->hidden('access_token_key', $this->access_token->key);
345         $this->hidden('access_token_secret', $this->access_token->secret);
346         $this->hidden('twuid', $this->twuid);
347         $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
348         $this->hidden('tw_fields_name', $this->tw_fields['name']);
349
350         $this->elementStart('fieldset');
351         $this->hidden('token', common_session_token());
352         $this->element('legend', null,
353                        _('Create new account'));
354         $this->element('p', null,
355                        _('Create a new user with this nickname.'));
356         $this->elementStart('ul', 'form_data');
357         $this->elementStart('li');
358         $this->input('newname', _('New nickname'),
359                      ($this->username) ? $this->username : '',
360                      _('1-64 lowercase letters or numbers, no punctuation or spaces'));
361         $this->elementEnd('li');
362         $this->elementEnd('ul');
363         $this->submit('create', _('Create'));
364         $this->elementEnd('fieldset');
365
366         $this->elementStart('fieldset');
367         $this->element('legend', null,
368                        _('Connect existing account'));
369         $this->element('p', null,
370                        _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
371         $this->elementStart('ul', 'form_data');
372         $this->elementStart('li');
373         $this->input('nickname', _('Existing nickname'));
374         $this->elementEnd('li');
375         $this->elementStart('li');
376         $this->password('password', _('Password'));
377         $this->elementEnd('li');
378         $this->elementEnd('ul');
379         $this->submit('connect', _('Connect'));
380         $this->elementEnd('fieldset');
381
382         $this->elementEnd('fieldset');
383         $this->elementEnd('form');
384     }
385
386     function message($msg)
387     {
388         $this->message_text = $msg;
389         $this->showPage();
390     }
391
392     function createNewUser()
393     {
394         if (common_config('site', 'closed')) {
395             $this->clientError(_('Registration not allowed.'));
396             return;
397         }
398
399         $invite = null;
400
401         if (common_config('site', 'inviteonly')) {
402             $code = $_SESSION['invitecode'];
403             if (empty($code)) {
404                 $this->clientError(_('Registration not allowed.'));
405                 return;
406             }
407
408             $invite = Invitation::staticGet($code);
409
410             if (empty($invite)) {
411                 $this->clientError(_('Not a valid invitation code.'));
412                 return;
413             }
414         }
415
416         $nickname = $this->trimmed('newname');
417
418         if (!Validate::string($nickname, array('min_length' => 1,
419                                                'max_length' => 64,
420                                                'format' => NICKNAME_FMT))) {
421             $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
422             return;
423         }
424
425         if (!User::allowed_nickname($nickname)) {
426             $this->showForm(_('Nickname not allowed.'));
427             return;
428         }
429
430         if (User::staticGet('nickname', $nickname)) {
431             $this->showForm(_('Nickname already in use. Try another one.'));
432             return;
433         }
434
435         $fullname = trim($this->tw_fields['name']);
436
437         $args = array('nickname' => $nickname, 'fullname' => $fullname);
438
439         if (!empty($invite)) {
440             $args['code'] = $invite->code;
441         }
442
443         $user = User::register($args);
444
445         $result = $this->saveForeignLink($user->id,
446                                          $this->twuid,
447                                          $this->access_token);
448
449         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
450
451         if (!$result) {
452             $this->serverError(_('Error connecting user to Twitter.'));
453             return;
454         }
455
456         common_set_user($user);
457         common_real_login(true);
458
459         common_debug('TwitterBridge Plugin - ' .
460                      "Registered new user $user->id from Twitter user $this->twuid");
461
462         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
463                         303);
464     }
465
466     function connectNewUser()
467     {
468         $nickname = $this->trimmed('nickname');
469         $password = $this->trimmed('password');
470
471         if (!common_check_user($nickname, $password)) {
472             $this->showForm(_('Invalid username or password.'));
473             return;
474         }
475
476         $user = User::staticGet('nickname', $nickname);
477
478         if (!empty($user)) {
479             common_debug('TwitterBridge Plugin - ' .
480                          "Legit user to connect to Twitter: $nickname");
481         }
482
483         $result = $this->saveForeignLink($user->id,
484                                          $this->twuid,
485                                          $this->access_token);
486
487         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
488
489         if (!$result) {
490             $this->serverError(_('Error connecting user to Twitter.'));
491             return;
492         }
493
494         common_debug('TwitterBridge Plugin - ' .
495                      "Connected Twitter user $this->twuid to local user $user->id");
496
497         common_set_user($user);
498         common_real_login(true);
499
500         $this->goHome($user->nickname);
501     }
502
503     function connectUser()
504     {
505         $user = common_current_user();
506
507         $result = $this->flinkUser($user->id, $this->twuid);
508
509         if (empty($result)) {
510             $this->serverError(_('Error connecting user to Twitter.'));
511             return;
512         }
513
514         common_debug('TwitterBridge Plugin - ' .
515                      "Connected Twitter user $this->twuid to local user $user->id");
516
517         // Return to Twitter connection settings tab
518         common_redirect(common_local_url('twittersettings'), 303);
519     }
520
521     function tryLogin()
522     {
523         common_debug('TwitterBridge Plugin - ' .
524                      "Trying login for Twitter user $this->twuid.");
525
526         $flink = Foreign_link::getByForeignID($this->twuid,
527                                               TWITTER_SERVICE);
528
529         if (!empty($flink)) {
530             $user = $flink->getUser();
531
532             if (!empty($user)) {
533
534                 common_debug('TwitterBridge Plugin - ' .
535                              "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
536
537                 common_set_user($user);
538                 common_real_login(true);
539                 $this->goHome($user->nickname);
540             }
541
542         } else {
543
544             common_debug('TwitterBridge Plugin - ' .
545                          "No flink found for twuid: $this->twuid - new user");
546
547             $this->showForm(null, $this->bestNewNickname());
548         }
549     }
550
551     function goHome($nickname)
552     {
553         $url = common_get_returnto();
554         if ($url) {
555             // We don't have to return to it again
556             common_set_returnto(null);
557         } else {
558             $url = common_local_url('all',
559                                     array('nickname' =>
560                                           $nickname));
561         }
562
563         common_redirect($url, 303);
564     }
565
566     function bestNewNickname()
567     {
568         if (!empty($this->tw_fields['name'])) {
569             $nickname = $this->nicknamize($this->tw_fields['name']);
570             if ($this->isNewNickname($nickname)) {
571                 return $nickname;
572             }
573         }
574
575         return null;
576     }
577
578      // Given a string, try to make it work as a nickname
579
580      function nicknamize($str)
581      {
582          $str = preg_replace('/\W/', '', $str);
583          $str = str_replace(array('-', '_'), '', $str);
584          return strtolower($str);
585      }
586
587     function isNewNickname($str)
588     {
589         if (!Validate::string($str, array('min_length' => 1,
590                                           'max_length' => 64,
591                                           'format' => NICKNAME_FMT))) {
592             return false;
593         }
594         if (!User::allowed_nickname($str)) {
595             return false;
596         }
597         if (User::staticGet('nickname', $str)) {
598             return false;
599         }
600         return true;
601     }
602
603 }
604