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