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