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