]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/actions/twitterauthorization.php
30f8141a97d4051be97930d688d109018d0724c1
[quix0rs-gnu-social.git] / plugins / TwitterBridge / actions / 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 dirname(__DIR__) . '/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://status.net/
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(array $args=array())
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(array $args=array())
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                 // TRANS: Client error displayed when the session token does not match or is not given.
121                 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
122                 return;
123             }
124
125             if ($this->arg('create')) {
126                 if (!$this->boolean('license')) {
127                     // TRANS: Form validation error displayed when the checkbox to agree to the license has not been checked.
128                     $this->showForm(_m('You cannot register if you do not agree to the license.'),
129                                     $this->trimmed('newname'));
130                     return;
131                 }
132                 $this->createNewUser();
133             } else if ($this->arg('connect')) {
134                 $this->connectNewUser();
135             } else {
136                 common_debug('Twitter bridge - ' . print_r($this->args, true));
137                 // TRANS: Form validation error displayed when an unhandled error occurs.
138                 $this->showForm(_m('Something weird happened.'),
139                                 $this->trimmed('newname'));
140             }
141         } else {
142             // $this->oauth_token is only populated once Twitter authorizes our
143             // request token. If it's empty we're at the beginning of the auth
144             // process
145
146             if (empty($this->oauth_token)) {
147                 $this->authorizeRequestToken();
148             } else {
149                 $this->saveAccessToken();
150             }
151         }
152     }
153
154     /**
155      * Asks Twitter for a request token, and then redirects to Twitter
156      * to authorize it.
157      *
158      * @return nothing
159      */
160     function authorizeRequestToken()
161     {
162         try {
163             // Get a new request token and authorize it
164
165             $client  = new TwitterOAuthClient();
166             $req_tok = $client->getRequestToken();
167
168             // Sock the request token away in the session temporarily
169
170             $_SESSION['twitter_request_token']        = $req_tok->key;
171             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
172
173             $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
174         } catch (OAuthClientException $e) {
175             $msg = sprintf(
176                 'OAuth client error - code: %1s, msg: %2s',
177                 $e->getCode(),
178                 $e->getMessage()
179             );
180             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
181             $this->serverError(
182                 // TRANS: Server error displayed when linking to a Twitter account fails.
183                 _m('Could not link your Twitter account.')
184             );
185         }
186
187         common_redirect($auth_link);
188     }
189
190     /**
191      * Called when Twitter returns an authorized request token. Exchanges
192      * it for an access token and stores it.
193      *
194      * @return nothing
195      */
196     function saveAccessToken()
197     {
198         // Check to make sure Twitter returned the same request
199         // token we sent them
200
201         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
202             $this->serverError(
203                 // TRANS: Server error displayed when linking to a Twitter account fails because of an incorrect oauth_token.
204                 _m('Could not link your Twitter account: oauth_token mismatch.')
205             );
206         }
207
208         $twitter_user = null;
209
210         try {
211
212             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
213                 $_SESSION['twitter_request_token_secret']);
214
215             // Exchange the request token for an access token
216
217             $atok = $client->getAccessToken($this->verifier);
218
219             // Test the access token and get the user's Twitter info
220
221             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
222             $twitter_user = $client->verifyCredentials();
223
224         } catch (OAuthClientException $e) {
225             $msg = sprintf(
226                 'OAuth client error - code: %1$s, msg: %2$s',
227                 $e->getCode(),
228                 $e->getMessage()
229             );
230             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
231             $this->serverError(
232                 // TRANS: Server error displayed when linking to a Twitter account fails.
233                 _m('Could not link your Twitter account.')
234             );
235         }
236
237         if (common_logged_in()) {
238             // Save the access token and Twitter user info
239
240             $user = common_current_user();
241             $this->saveForeignLink($user->id, $twitter_user->id, $atok);
242             save_twitter_user($twitter_user->id, $twitter_user->screen_name);
243
244         } else {
245
246             $this->twuid = $twitter_user->id;
247             $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
248                                      "fullname" => $twitter_user->name);
249             $this->access_token = $atok;
250             $this->tryLogin();
251         }
252
253         // Clean up the the mess we made in the session
254
255         unset($_SESSION['twitter_request_token']);
256         unset($_SESSION['twitter_request_token_secret']);
257
258         if (common_logged_in()) {
259             common_redirect(common_local_url('twittersettings'));
260         }
261     }
262
263     /**
264      * Saves a Foreign_link between Twitter user and local user,
265      * which includes the access token and secret.
266      *
267      * @param int        $user_id StatusNet user ID
268      * @param int        $twuid   Twitter user ID
269      * @param OAuthToken $token   the access token to save
270      *
271      * @return nothing
272      */
273     function saveForeignLink($user_id, $twuid, $access_token)
274     {
275         $flink = new Foreign_link();
276
277         $flink->user_id = $user_id;
278         $flink->service = TWITTER_SERVICE;
279
280         // delete stale flink, if any
281         $result = $flink->find(true);
282
283         if (!empty($result)) {
284             $flink->safeDelete();
285         }
286
287         $flink->user_id     = $user_id;
288         $flink->foreign_id  = $twuid;
289         $flink->service     = TWITTER_SERVICE;
290
291         $creds = TwitterOAuthClient::packToken($access_token);
292
293         $flink->credentials = $creds;
294         $flink->created     = common_sql_now();
295
296         // Defaults: noticesync on, everything else off
297
298         $flink->set_flags(true, false, false, false);
299
300         $flink_id = $flink->insert();
301
302         if (empty($flink_id)) {
303             common_log_db_error($flink, 'INSERT', __FILE__);
304             // TRANS: Server error displayed when linking to a Twitter account fails.
305             $this->serverError(_m('Could not link your Twitter account.'));
306         }
307
308         return $flink_id;
309     }
310
311     function showPageNotice()
312     {
313         if ($this->error) {
314             $this->element('div', array('class' => 'error'), $this->error);
315         } else {
316             $this->element('div', 'instructions',
317                            // TRANS: Page instruction. %s is the StatusNet sitename.
318                            sprintf(_m('This is the first time you have 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')));
319         }
320     }
321
322     function title()
323     {
324         // TRANS: Page title.
325         return _m('Twitter Account Setup');
326     }
327
328     function showForm($error=null, $username=null)
329     {
330         $this->error = $error;
331         $this->username = $username;
332
333         $this->showPage();
334     }
335
336     function showPage()
337     {
338         parent::showPage();
339     }
340
341     /**
342      * @fixme much of this duplicates core code, which is very fragile.
343      * Should probably be replaced with an extensible mini version of
344      * the core registration form.
345      */
346     function showContent()
347     {
348         if (!empty($this->message_text)) {
349             $this->element('p', null, $this->message);
350             return;
351         }
352
353         $this->elementStart('form', array('method' => 'post',
354                                           'id' => 'form_settings_twitter_connect',
355                                           'class' => 'form_settings',
356                                           'action' => common_local_url('twitterauthorization')));
357         $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
358         // TRANS: Fieldset legend.
359         $this->element('legend', null, _m('Connection options'));
360
361         $this->hidden('access_token_key', $this->access_token->key);
362         $this->hidden('access_token_secret', $this->access_token->secret);
363         $this->hidden('twuid', $this->twuid);
364         $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
365         $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
366         $this->hidden('token', common_session_token());
367
368         // Don't allow new account creation if site is flagged as invite only
369         if (common_config('site', 'inviteonly') == false) {
370             $this->elementStart('fieldset');
371             $this->element('legend', null,
372                            // TRANS: Fieldset legend.
373                            _m('Create new account'));
374             $this->element('p', null,
375                            // TRANS: Sub form introduction text.
376                           _m('Create a new user with this nickname.'));
377             $this->elementStart('ul', 'form_data');
378
379             // Hook point for captcha etc
380             Event::handle('StartRegistrationFormData', array($this));
381
382             $this->elementStart('li');
383             // TRANS: Field label.
384             $this->input('newname', _m('New nickname'),
385                          ($this->username) ? $this->username : '',
386                          // TRANS: Field title for nickname field.
387                          _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
388             $this->elementEnd('li');
389             $this->elementStart('li');
390             // TRANS: Field label.
391             $this->input('email', _m('LABEL','Email'), $this->getEmail(),
392                          // TRANS: Field title for e-mail address field.
393                          _m('Used only for updates, announcements, '.
394                            'and password recovery'));
395             $this->elementEnd('li');
396
397             // Hook point for captcha etc
398             Event::handle('EndRegistrationFormData', array($this));
399
400             $this->elementEnd('ul');
401             // TRANS: Button text for creating a new StatusNet account in the Twitter connect page.
402             $this->submit('create', _m('BUTTON','Create'));
403             $this->elementEnd('fieldset');
404         }
405
406         $this->elementStart('fieldset');
407         $this->element('legend', null,
408                        // TRANS: Fieldset legend.
409                        _m('Connect existing account'));
410         $this->element('p', null,
411                        // TRANS: Sub form introduction text.
412                        _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
413         $this->elementStart('ul', 'form_data');
414         $this->elementStart('li');
415         // TRANS: Field label.
416         $this->input('nickname', _m('Existing nickname'));
417         $this->elementEnd('li');
418         $this->elementStart('li');
419         // TRANS: Field label.
420         $this->password('password', _m('Password'));
421         $this->elementEnd('li');
422         $this->elementEnd('ul');
423         $this->elementEnd('fieldset');
424
425         $this->elementStart('fieldset');
426         $this->element('legend', null,
427                        // TRANS: Fieldset legend.
428                        _m('License'));
429         $this->elementStart('ul', 'form_data');
430         $this->elementStart('li');
431         $this->element('input', array('type' => 'checkbox',
432                                       'id' => 'license',
433                                       'class' => 'checkbox',
434                                       'name' => 'license',
435                                       'value' => 'true'));
436         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
437         // TRANS: Text for license agreement checkbox.
438         // TRANS: %s is the license as configured for the StatusNet site.
439         $message = _m('My text and files are available under %s ' .
440                      'except this private data: password, ' .
441                      'email address, IM address, and phone number.');
442         $link = '<a href="' .
443                 htmlspecialchars(common_config('license', 'url')) .
444                 '">' .
445                 htmlspecialchars(common_config('license', 'title')) .
446                 '</a>';
447         $this->raw(sprintf(htmlspecialchars($message), $link));
448         $this->elementEnd('label');
449         $this->elementEnd('li');
450         $this->elementEnd('ul');
451         $this->elementEnd('fieldset');
452         // TRANS: Button text for connecting an existing StatusNet account in the Twitter connect page..
453         $this->submit('connect', _m('BUTTON','Connect'));
454         $this->elementEnd('fieldset');
455         $this->elementEnd('form');
456     }
457
458     /**
459      * Get specified e-mail from the form, or the invite code.
460      *
461      * @return string
462      */
463     function getEmail()
464     {
465         $email = $this->trimmed('email');
466         if (!empty($email)) {
467             return $email;
468         }
469
470         // Terrible hack for invites...
471         if (common_config('site', 'inviteonly')) {
472             $code = $_SESSION['invitecode'];
473             if ($code) {
474                 $invite = Invitation::getKV($code);
475
476                 if ($invite && $invite->address_type == 'email') {
477                     return $invite->address;
478                 }
479             }
480         }
481         return '';
482     }
483
484     function message($msg)
485     {
486         $this->message_text = $msg;
487         $this->showPage();
488     }
489
490     function createNewUser()
491     {
492         if (!Event::handle('StartRegistrationTry', array($this))) {
493             return;
494         }
495
496         if (common_config('site', 'closed')) {
497             // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
498             $this->clientError(_m('Registration not allowed.'));
499         }
500
501         $invite = null;
502
503         if (common_config('site', 'inviteonly')) {
504             $code = $_SESSION['invitecode'];
505             if (empty($code)) {
506                 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
507                 $this->clientError(_m('Registration not allowed.'));
508             }
509
510             $invite = Invitation::getKV($code);
511
512             if (empty($invite)) {
513                 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
514                 $this->clientError(_m('Not a valid invitation code.'));
515             }
516         }
517
518         try {
519             $nickname = Nickname::normalize($this->trimmed('newname'), true);
520         } catch (NicknameException $e) {
521             $this->showForm($e->getMessage());
522             return;
523         }
524
525         $fullname = trim($this->tw_fields['fullname']);
526
527         $args = array('nickname' => $nickname, 'fullname' => $fullname);
528
529         if (!empty($invite)) {
530             $args['code'] = $invite->code;
531         }
532
533         $email = $this->getEmail();
534         if (!empty($email)) {
535             $args['email'] = $email;
536         }
537
538         $user = User::register($args);
539
540         if (empty($user)) {
541             // TRANS: Server error displayed when creating a new user has failed.
542             $this->serverError(_m('Error registering user.'));
543         }
544
545         $result = $this->saveForeignLink($user->id,
546                                          $this->twuid,
547                                          $this->access_token);
548
549         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
550
551         if (!$result) {
552             // TRANS: Server error displayed when connecting a user to a Twitter user has failed.
553             $this->serverError(_m('Error connecting user to Twitter.'));
554         }
555
556         common_set_user($user);
557         common_real_login(true);
558
559         common_debug('TwitterBridge Plugin - ' .
560                      "Registered new user $user->id from Twitter user $this->twuid");
561
562         Event::handle('EndRegistrationTry', array($this));
563
564         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)), 303);
565     }
566
567     function connectNewUser()
568     {
569         $nickname = $this->trimmed('nickname');
570         $password = $this->trimmed('password');
571
572         if (!common_check_user($nickname, $password)) {
573             // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
574             // TRANS: the provided username and/or password are incorrect.
575             $this->showForm(_m('Invalid username or password.'));
576             return;
577         }
578
579         $user = User::getKV('nickname', $nickname);
580
581         if (!empty($user)) {
582             common_debug('TwitterBridge Plugin - ' .
583                          "Legit user to connect to Twitter: $nickname");
584         }
585
586         $result = $this->saveForeignLink($user->id,
587                                          $this->twuid,
588                                          $this->access_token);
589
590         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
591
592         if (!$result) {
593             // TRANS: Server error displayed connecting a user to a Twitter user has failed.
594             $this->serverError(_m('Error connecting user to Twitter.'));
595         }
596
597         common_debug('TwitterBridge Plugin - ' .
598                      "Connected Twitter user $this->twuid to local user $user->id");
599
600         common_set_user($user);
601         common_real_login(true);
602
603         $this->goHome($user->nickname);
604     }
605
606     function connectUser()
607     {
608         $user = common_current_user();
609
610         $result = $this->flinkUser($user->id, $this->twuid);
611
612         if (empty($result)) {
613             // TRANS: Server error displayed connecting a user to a Twitter user has failed.
614             $this->serverError(_m('Error connecting user to Twitter.'));
615         }
616
617         common_debug('TwitterBridge Plugin - ' .
618                      "Connected Twitter user $this->twuid to local user $user->id");
619
620         // Return to Twitter connection settings tab
621         common_redirect(common_local_url('twittersettings'), 303);
622     }
623
624     function tryLogin()
625     {
626         common_debug('TwitterBridge Plugin - ' .
627                      "Trying login for Twitter user $this->twuid.");
628
629         $flink = Foreign_link::getByForeignID($this->twuid,
630                                               TWITTER_SERVICE);
631
632         if (!empty($flink)) {
633             $user = $flink->getUser();
634
635             if (!empty($user)) {
636
637                 common_debug('TwitterBridge Plugin - ' .
638                              "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
639
640                 common_set_user($user);
641                 common_real_login(true);
642                 $this->goHome($user->nickname);
643             }
644
645         } else {
646
647             common_debug('TwitterBridge Plugin - ' .
648                          "No flink found for twuid: $this->twuid - new user");
649
650             $this->showForm(null, $this->bestNewNickname());
651         }
652     }
653
654     function goHome($nickname)
655     {
656         $url = common_get_returnto();
657         if ($url) {
658             // We don't have to return to it again
659             common_set_returnto(null);
660         } else {
661             $url = common_local_url('all',
662                                     array('nickname' =>
663                                           $nickname));
664         }
665
666         common_redirect($url, 303);
667     }
668
669     function bestNewNickname()
670     {
671         try {
672             return Nickname::normalize($this->tw_fields['fullname'], true);
673         } catch (NicknameException $e) {
674             return null;
675         }
676     }
677 }