c9b892b6408d74ec5b388cf0333704c92699dfae
[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 $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->oauth_token = $this->arg('oauth_token');
64         $this->verifier    = $this->arg('oauth_verifier');
65
66         if ($this->scoped instanceof Profile) {
67             try {
68                 $flink = Foreign_link::getByUserID($this->scoped->getID(), TWITTER_SERVICE);
69                 $fuser = $flink->getForeignUser();
70
71                 // If there's already a foreign link record and a foreign user
72                 // (no exceptions were thrown when fetching either of them...)
73                 // it means the accounts are already linked, and this is unecessary.
74                 // So go back.
75
76                 common_redirect(common_local_url('twittersettings'));
77             } catch (NoResultException $e) {
78                 // but if we don't have a foreign user linked, let's continue authorization procedure.                
79             }
80         }
81     }
82
83     protected function doPost()
84     {
85         // User was not logged in to StatusNet before
86
87         $this->twuid = $this->trimmed('twuid');
88
89         $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
90                                  'fullname' => $this->trimmed('tw_fields_fullname'));
91
92         $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
93
94         if ($this->arg('create')) {
95             common_debug('TwitterBridgeDebug - POST with create');
96             if (!$this->boolean('license')) {
97                 // TRANS: Form validation error displayed when the checkbox to agree to the license has not been checked.
98                 throw new ClientException(_m('You cannot register if you do not agree to the license.'));
99             }
100             return $this->createNewUser();
101         } elseif ($this->arg('connect')) {
102             common_debug('TwitterBridgeDebug - POST with connect');
103             return $this->connectNewUser();
104         }
105
106         common_debug('TwitterBridgeDebug - ' . print_r($this->args, true));
107         // TRANS: Form validation error displayed when an unhandled error occurs.
108         throw new ClientException(_m('No known action for POST.'));
109     }
110
111     /**
112      * Asks Twitter for a request token, and then redirects to Twitter
113      * to authorize it.
114      */
115     protected function authorizeRequestToken()
116     {
117         try {
118             // Get a new request token and authorize it
119             $client  = new TwitterOAuthClient();
120             $req_tok = $client->getTwitterRequestToken();
121
122             // Sock the request token away in the session temporarily
123             $_SESSION['twitter_request_token']        = $req_tok->key;
124             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
125
126             $auth_link = $client->getTwitterAuthorizeLink($req_tok, $this->boolean('signin'));
127         } catch (OAuthClientException $e) {
128             $msg = sprintf(
129                 'OAuth client error - code: %1s, msg: %2s',
130                 $e->getCode(),
131                 $e->getMessage()
132             );
133             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
134             // TRANS: Server error displayed when linking to a Twitter account fails.
135             throw new ServerException(_m('Could not link your Twitter account.'));
136         }
137
138         common_redirect($auth_link);
139     }
140
141     /**
142      * Called when Twitter returns an authorized request token. Exchanges
143      * it for an access token and stores it.
144      *
145      * @return nothing
146      */
147     function saveAccessToken()
148     {
149         // Check to make sure Twitter returned the same request
150         // token we sent them
151
152         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
153             // TRANS: Server error displayed when linking to a Twitter account fails because of an incorrect oauth_token.
154             throw new ServerException(_m('Could not link your Twitter account: oauth_token mismatch.'));
155         }
156
157         $twitter_user = null;
158
159         try {
160             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], $_SESSION['twitter_request_token_secret']);
161
162             // Exchange the request token for an access token
163             $atok = $client->getTwitterAccessToken($this->verifier);
164
165             // Test the access token and get the user's Twitter info
166             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
167             $twitter_user = $client->verifyCredentials();
168
169         } catch (OAuthClientException $e) {
170             $msg = sprintf(
171                 'OAuth client error - code: %1$s, msg: %2$s',
172                 $e->getCode(),
173                 $e->getMessage()
174             );
175             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
176             // TRANS: Server error displayed when linking to a Twitter account fails.
177             throw new ServerException(_m('Could not link your Twitter account.'));
178         }
179
180         if ($this->scoped instanceof Profile) {
181             // Save the access token and Twitter user info
182
183             $this->saveForeignLink($this->scoped->getID(), $twitter_user->id, $atok);
184             save_twitter_user($twitter_user->id, $twitter_user->screen_name);
185
186         } else {
187
188             $this->twuid = $twitter_user->id;
189             $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
190                                      "fullname" => $twitter_user->name);
191             $this->access_token = $atok;
192             return $this->tryLogin();
193         }
194
195         // Clean up the the mess we made in the session
196
197         unset($_SESSION['twitter_request_token']);
198         unset($_SESSION['twitter_request_token_secret']);
199
200         if (common_logged_in()) {
201             common_redirect(common_local_url('twittersettings'));
202         }
203     }
204
205     /**
206      * Saves a Foreign_link between Twitter user and local user,
207      * which includes the access token and secret.
208      *
209      * @param int        $user_id StatusNet user ID
210      * @param int        $twuid   Twitter user ID
211      * @param OAuthToken $token   the access token to save
212      *
213      * @return nothing
214      */
215     function saveForeignLink($user_id, $twuid, $access_token)
216     {
217         $flink = new Foreign_link();
218
219         $flink->user_id = $user_id;
220         $flink->service = TWITTER_SERVICE;
221
222         // delete stale flink, if any
223         $result = $flink->find(true);
224
225         if (!empty($result)) {
226             $flink->safeDelete();
227         }
228
229         $flink->user_id     = $user_id;
230         $flink->foreign_id  = $twuid;
231         $flink->service     = TWITTER_SERVICE;
232
233         $creds = TwitterOAuthClient::packToken($access_token);
234
235         $flink->credentials = $creds;
236         $flink->created     = common_sql_now();
237
238         // Defaults: noticesync on, everything else off
239
240         $flink->set_flags(true, false, false, false);
241
242         $flink_id = $flink->insert();
243
244         // We want to make sure we got a numerical >0 value, not just failed the insert (which would be === false)
245         if (empty($flink_id)) {
246             common_log_db_error($flink, 'INSERT', __FILE__);
247             // TRANS: Server error displayed when linking to a Twitter account fails.
248             throw new ServerException(_m('Could not link your Twitter account.'));
249         }
250
251         return $flink_id;
252     }
253
254     function getInstructions()
255     {
256         // TRANS: Page instruction. %s is the StatusNet sitename.
257         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'));
258     }
259
260     function title()
261     {
262         // TRANS: Page title.
263         return _m('Twitter Account Setup');
264     }
265
266     public function showPage()
267     {
268         // $this->oauth_token is only populated once Twitter authorizes our
269         // request token. If it's empty we're at the beginning of the auth
270         // process
271         if (empty($this->error)) {
272             if (empty($this->oauth_token)) {
273                 // authorizeRequestToken either throws an exception or redirects
274                 $this->authorizeRequestToken();
275             } else {
276                 $this->saveAccessToken();
277             }
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         // Only allow new account creation if site is not flagged invite-only
306         if (!common_config('site', 'inviteonly')) {
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     protected function createNewUser()
422     {
423         common_debug('TwitterBridgeDebug - createNewUser');
424         if (!Event::handle('StartRegistrationTry', array($this))) {
425             common_debug('TwitterBridgeDebug - StartRegistrationTry failed');
426             // TRANS: Client error displayed when trying to create a new user but a plugin aborted the process.
427             throw new ClientException(_m('Registration of new user was aborted, maybe you failed a captcha?'));
428         }
429
430         if (common_config('site', 'closed')) {
431             common_debug('TwitterBridgeDebug - site is closed for registrations');
432             // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
433             throw new ClientException(_m('Registration not allowed.'));
434         }
435
436         $invite = null;
437
438         if (common_config('site', 'inviteonly')) {
439             common_debug('TwitterBridgeDebug - site is inviteonly');
440             $code = $_SESSION['invitecode'];
441             if (empty($code)) {
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 = Invitation::getKV('code', $code);
447
448             if (!$invite instanceof Invite) {
449                 common_debug('TwitterBridgeDebug - and we failed the invite code test');
450                 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
451                 throw new ClientException(_m('Not a valid invitation code.'));
452             }
453         }
454
455         common_debug('TwitterBridgeDebug - trying our nickname: '.$this->trimmed('newname'));
456         // Nickname::normalize throws exception if the nickname is taken
457         $nickname = Nickname::normalize($this->trimmed('newname'), true);
458
459         $fullname = trim($this->tw_fields['fullname']);
460
461         $args = array('nickname' => $nickname, 'fullname' => $fullname);
462
463         if (!empty($invite)) {
464             $args['code'] = $invite->code;
465         }
466
467         $email = $this->getEmail();
468         if (!empty($email)) {
469             $args['email'] = $email;
470         }
471
472         common_debug('TwitterBridgeDebug - registering user with args:'.var_export($args,true));
473         $user = User::register($args);
474
475         common_debug('TwitterBridgeDebug - registered the user and saving foreign link for '.$user->id);
476
477         $this->saveForeignLink($user->id,
478                                $this->twuid,
479                                $this->access_token);
480
481         common_debug('TwitterBridgeDebug - saving twitter user after creating new local user '.$user->id);
482         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
483
484         common_set_user($user);
485         common_real_login(true);
486
487         common_debug('TwitterBridge Plugin - ' .
488                      "Registered new user $user->id from Twitter user $this->twuid");
489
490         Event::handle('EndRegistrationTry', array($this));
491
492         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)), 303);
493     }
494
495     function connectNewUser()
496     {
497         $nickname = $this->trimmed('nickname');
498         $password = $this->trimmed('password');
499
500         if (!common_check_user($nickname, $password)) {
501             // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
502             // TRANS: the provided username and/or password are incorrect.
503             throw new ClientException(_m('Invalid username or password.'));
504         }
505
506         $user = User::getKV('nickname', $nickname);
507
508         if ($user instanceof User) {
509             common_debug('TwitterBridge Plugin - ' .
510                          "Legit user to connect to Twitter: $nickname");
511         }
512
513         // throws exception on failure
514         $this->saveForeignLink($user->id,
515                                $this->twuid,
516                                $this->access_token);
517
518         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
519
520         common_debug('TwitterBridge Plugin - ' .
521                      "Connected Twitter user $this->twuid to local user $user->id");
522
523         common_set_user($user);
524         common_real_login(true);
525
526         $this->goHome($user->nickname);
527     }
528
529     function connectUser()
530     {
531         $user = common_current_user();
532
533         $result = $this->flinkUser($user->id, $this->twuid);
534
535         if (empty($result)) {
536             // TRANS: Server error displayed connecting a user to a Twitter user has failed.
537             $this->serverError(_m('Error connecting user to Twitter.'));
538         }
539
540         common_debug('TwitterBridge Plugin - ' .
541                      "Connected Twitter user $this->twuid to local user $user->id");
542
543         // Return to Twitter connection settings tab
544         common_redirect(common_local_url('twittersettings'), 303);
545     }
546
547     protected function tryLogin()
548     {
549         common_debug('TwitterBridge Plugin - ' .
550                      "Trying login for Twitter user $this->twuid.");
551
552         try {
553             $flink = Foreign_link::getByForeignID($this->twuid, TWITTER_SERVICE);
554             $user = $flink->getUser();
555
556             common_debug('TwitterBridge Plugin - ' .
557                          "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
558
559             common_set_user($user);
560             common_real_login(true);
561             $this->goHome($user->nickname);
562         } catch (NoResultException $e) {
563             // Either no Foreign_link was found or not the user connected to it.
564             // Let's just continue to allow creating or logging in as a new user.
565         }
566         common_debug("TwitterBridge Plugin - No flink found for twuid: {$this->twuid} - new user");
567
568         // FIXME: what do we want to do here? I forgot
569         return;
570         throw new ServerException(_m('No foreign link found for Twitter user'));
571     }
572
573     function goHome($nickname)
574     {
575         $url = common_get_returnto();
576         if ($url) {
577             // We don't have to return to it again
578             common_set_returnto(null);
579         } else {
580             $url = common_local_url('all',
581                                     array('nickname' =>
582                                           $nickname));
583         }
584
585         common_redirect($url, 303);
586     }
587
588     function bestNewNickname()
589     {
590         try {
591             return Nickname::normalize($this->tw_fields['fullname'], true);
592         } catch (NicknameException $e) {
593             return null;
594         }
595     }
596 }