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