]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterauthorization.php
Move license checkbox to the end of the form
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitterauthorization.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Class for doing OAuth authentication against Twitter
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Plugin
23  * @package   StatusNet
24  * @author    Zach Copley <zach@status.net>
25  * @author    Julien C <chaumond@gmail.com>
26  * @copyright 2009-2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET') && !defined('LACONICA')) {
32     exit(1);
33 }
34
35 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
36
37 /**
38  * Class for doing OAuth authentication against Twitter
39  *
40  * Peforms the OAuth "dance" between StatusNet and Twitter -- requests a token,
41  * authorizes it, and exchanges it for an access token.  It also creates a link
42  * (Foreign_link) between the StatusNet user and Twitter user and stores the
43  * access token and secret in the link.
44  *
45  * @category Plugin
46  * @package  StatusNet
47  * @author   Zach Copley <zach@status.net>
48  * @author   Julien C <chaumond@gmail.com>
49  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
50  * @link     http://status.net/
51  *
52  */
53 class TwitterauthorizationAction extends Action
54 {
55     var $twuid        = null;
56     var $tw_fields    = null;
57     var $access_token = null;
58     var $signin       = null;
59     var $verifier     = null;
60
61     /**
62      * Initialize class members. Looks for 'oauth_token' parameter.
63      *
64      * @param array $args misc. arguments
65      *
66      * @return boolean true
67      */
68     function prepare($args)
69     {
70         parent::prepare($args);
71
72         $this->signin      = $this->boolean('signin');
73         $this->oauth_token = $this->arg('oauth_token');
74         $this->verifier    = $this->arg('oauth_verifier');
75
76         return true;
77     }
78
79     /**
80      * Handler method
81      *
82      * @param array $args is ignored since it's now passed in in prepare()
83      *
84      * @return nothing
85      */
86     function handle($args)
87     {
88         parent::handle($args);
89
90         if (common_logged_in()) {
91             $user  = common_current_user();
92             $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
93
94             // If there's already a foreign link record and a foreign user
95             // it means the accounts are already linked, and this is unecessary.
96             // So go back.
97
98             if (isset($flink)) {
99                 $fuser = $flink->getForeignUser();
100                 if (!empty($fuser)) {
101                     common_redirect(common_local_url('twittersettings'));
102                 }
103             }
104         }
105
106         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
107
108             // User was not logged in to StatusNet before
109
110             $this->twuid = $this->trimmed('twuid');
111
112             $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
113                                      'fullname' => $this->trimmed('tw_fields_fullname'));
114
115             $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
116
117             $token = $this->trimmed('token');
118
119             if (!$token || $token != common_session_token()) {
120                 // TRANS: Client error displayed when the session token does not match or is not given.
121                 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
122                 return;
123             }
124
125             if ($this->arg('create')) {
126                 if (!$this->boolean('license')) {
127                     // TRANS: Form validation error displayed when the checkbox to agree to the license has not been checked.
128                     $this->showForm(_m('You cannot register if you do not agree to the license.'),
129                                     $this->trimmed('newname'));
130                     return;
131                 }
132                 $this->createNewUser();
133             } else if ($this->arg('connect')) {
134                 $this->connectNewUser();
135             } else {
136                 common_debug('Twitter bridge - ' . print_r($this->args, true));
137                 // TRANS: Form validation error displayed when an unhandled error occurs.
138                 $this->showForm(_m('Something weird happened.'),
139                                 $this->trimmed('newname'));
140             }
141         } else {
142             // $this->oauth_token is only populated once Twitter authorizes our
143             // request token. If it's empty we're at the beginning of the auth
144             // process
145
146             if (empty($this->oauth_token)) {
147                 $this->authorizeRequestToken();
148             } else {
149                 $this->saveAccessToken();
150             }
151         }
152     }
153
154     /**
155      * Asks Twitter for a request token, and then redirects to Twitter
156      * to authorize it.
157      *
158      * @return nothing
159      */
160     function authorizeRequestToken()
161     {
162         try {
163             // Get a new request token and authorize it
164
165             $client  = new TwitterOAuthClient();
166             $req_tok = $client->getRequestToken();
167
168             // Sock the request token away in the session temporarily
169
170             $_SESSION['twitter_request_token']        = $req_tok->key;
171             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
172
173             $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
174         } catch (OAuthClientException $e) {
175             $msg = sprintf(
176                 'OAuth client error - code: %1s, msg: %2s',
177                 $e->getCode(),
178                 $e->getMessage()
179             );
180             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
181             $this->serverError(
182                 // TRANS: Server error displayed when linking to a Twitter account fails.
183                 _m('Could not link your Twitter account.')
184             );
185         }
186
187         common_redirect($auth_link);
188     }
189
190     /**
191      * Called when Twitter returns an authorized request token. Exchanges
192      * it for an access token and stores it.
193      *
194      * @return nothing
195      */
196     function saveAccessToken()
197     {
198         // Check to make sure Twitter returned the same request
199         // token we sent them
200
201         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
202             $this->serverError(
203                 // TRANS: Server error displayed when linking to a Twitter account fails because of an incorrect oauth_token.
204                 _m('Could not link your Twitter account: oauth_token mismatch.')
205             );
206         }
207
208         $twitter_user = null;
209
210         try {
211
212             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
213                 $_SESSION['twitter_request_token_secret']);
214
215             // Exchange the request token for an access token
216
217             $atok = $client->getAccessToken($this->verifier);
218
219             // Test the access token and get the user's Twitter info
220
221             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
222             $twitter_user = $client->verifyCredentials();
223
224         } catch (OAuthClientException $e) {
225             $msg = sprintf(
226                 'OAuth client error - code: %1$s, msg: %2$s',
227                 $e->getCode(),
228                 $e->getMessage()
229             );
230             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
231             $this->serverError(
232                 // TRANS: Server error displayed when linking to a Twitter account fails.
233                 _m('Could not link your Twitter account.')
234             );
235         }
236
237         if (common_logged_in()) {
238             // Save the access token and Twitter user info
239
240             $user = common_current_user();
241             $this->saveForeignLink($user->id, $twitter_user->id, $atok);
242             save_twitter_user($twitter_user->id, $twitter_user->screen_name);
243
244         } else {
245
246             $this->twuid = $twitter_user->id;
247             $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
248                                      "fullname" => $twitter_user->name);
249             $this->access_token = $atok;
250             $this->tryLogin();
251         }
252
253         // Clean up the the mess we made in the session
254
255         unset($_SESSION['twitter_request_token']);
256         unset($_SESSION['twitter_request_token_secret']);
257
258         if (common_logged_in()) {
259             common_redirect(common_local_url('twittersettings'));
260         }
261     }
262
263     /**
264      * Saves a Foreign_link between Twitter user and local user,
265      * which includes the access token and secret.
266      *
267      * @param int        $user_id StatusNet user ID
268      * @param int        $twuid   Twitter user ID
269      * @param OAuthToken $token   the access token to save
270      *
271      * @return nothing
272      */
273     function saveForeignLink($user_id, $twuid, $access_token)
274     {
275         $flink = new Foreign_link();
276
277         $flink->user_id = $user_id;
278         $flink->service = TWITTER_SERVICE;
279
280         // delete stale flink, if any
281         $result = $flink->find(true);
282
283         if (!empty($result)) {
284             $flink->safeDelete();
285         }
286
287         $flink->user_id     = $user_id;
288         $flink->foreign_id  = $twuid;
289         $flink->service     = TWITTER_SERVICE;
290
291         $creds = TwitterOAuthClient::packToken($access_token);
292
293         $flink->credentials = $creds;
294         $flink->created     = common_sql_now();
295
296         // Defaults: noticesync on, everything else off
297
298         $flink->set_flags(true, false, false, false);
299
300         $flink_id = $flink->insert();
301
302         if (empty($flink_id)) {
303             common_log_db_error($flink, 'INSERT', __FILE__);
304             // TRANS: Server error displayed when linking to a Twitter account fails.
305             $this->serverError(_m('Could not link your Twitter account.'));
306         }
307
308         return $flink_id;
309     }
310
311     function showPageNotice()
312     {
313         if ($this->error) {
314             $this->element('div', array('class' => 'error'), $this->error);
315         } else {
316             $this->element('div', 'instructions',
317                            // TRANS: Page instruction. %s is the StatusNet sitename.
318                            sprintf(_m('This is the first time you have logged into %s so we must connect your Twitter account to a local account. You can either create a new account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
319         }
320     }
321
322     function title()
323     {
324         // TRANS: Page title.
325         return _m('Twitter Account Setup');
326     }
327
328     function showForm($error=null, $username=null)
329     {
330         $this->error = $error;
331         $this->username = $username;
332
333         $this->showPage();
334     }
335
336     function showPage()
337     {
338         parent::showPage();
339     }
340
341     /**
342      * @fixme much of this duplicates core code, which is very fragile.
343      * Should probably be replaced with an extensible mini version of
344      * the core registration form.
345      */
346     function showContent()
347     {
348         if (!empty($this->message_text)) {
349             $this->element('p', null, $this->message);
350             return;
351         }
352
353         $this->elementStart('form', array('method' => 'post',
354                                           'id' => 'form_settings_twitter_connect',
355                                           'class' => 'form_settings',
356                                           'action' => common_local_url('twitterauthorization')));
357         $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
358         // TRANS: Fieldset legend.
359         $this->element('legend', null, _m('Connection options'));
360
361         $this->hidden('access_token_key', $this->access_token->key);
362         $this->hidden('access_token_secret', $this->access_token->secret);
363         $this->hidden('twuid', $this->twuid);
364         $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
365         $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
366
367         // Don't allow new account creation if site is flagged as invite only
368         if (common_config('site', 'inviteonly') == false) {
369             $this->elementStart('fieldset');
370             $this->hidden('token', common_session_token());
371             $this->element('legend', null,
372                            // TRANS: Fieldset legend.
373                            _m('Create new account'));
374             $this->element('p', null,
375                            // TRANS: Sub form introduction text.
376                           _m('Create a new user with this nickname.'));
377             $this->elementStart('ul', 'form_data');
378
379             // Hook point for captcha etc
380             Event::handle('StartRegistrationFormData', array($this));
381
382             $this->elementStart('li');
383             // TRANS: Field label.
384             $this->input('newname', _m('New nickname'),
385                          ($this->username) ? $this->username : '',
386                          // TRANS: Field title for nickname field.
387                          _m('1-64 lowercase letters or numbers, no punctuation or spaces.'));
388             $this->elementEnd('li');
389             $this->elementStart('li');
390             // TRANS: Field label.
391             $this->input('email', _m('LABEL','Email'), $this->getEmail(),
392                          // TRANS: Field title for e-mail address field.
393                          _m('Used only for updates, announcements, '.
394                            'and password recovery'));
395             $this->elementEnd('li');
396
397             // Hook point for captcha etc
398             Event::handle('EndRegistrationFormData', array($this));
399
400             $this->elementEnd('ul');
401             // TRANS: Button text for creating a new StatusNet account in the Twitter connect page.
402             $this->submit('create', _m('BUTTON','Create'));
403             $this->elementEnd('fieldset');
404         }
405
406         $this->elementStart('fieldset');
407         $this->element('legend', null,
408                        // TRANS: Fieldset legend.
409                        _m('Connect existing account'));
410         $this->element('p', null,
411                        // TRANS: Sub form introduction text.
412                        _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
413         $this->elementStart('ul', 'form_data');
414         $this->elementStart('li');
415         // TRANS: Field label.
416         $this->input('nickname', _m('Existing nickname'));
417         $this->elementEnd('li');
418         $this->elementStart('li');
419         // TRANS: Field label.
420         $this->password('password', _m('Password'));
421         $this->elementEnd('li');
422         $this->elementEnd('ul');
423         // TRANS: Button text for connecting an existing StatusNet account in the Twitter connect page..
424         $this->submit('connect', _m('BUTTON','Connect'));
425         $this->elementEnd('fieldset');
426
427         $this->elementStart('fieldset');
428         $this->element('legend', null,
429                        // TRANS: Fieldset legend.
430                        _m('License'));
431         $this->elementStart('ul', 'form_data');
432         $this->elementStart('li');
433         $this->element('input', array('type' => 'checkbox',
434                                       'id' => 'license',
435                                       'class' => 'checkbox',
436                                       'name' => 'license',
437                                       'value' => 'true'));
438         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
439         // TRANS: Text for license agreement checkbox.
440         // TRANS: %s is the license as configured for the StatusNet site.
441         $message = _m('My text and files are available under %s ' .
442                      'except this private data: password, ' .
443                      'email address, IM address, and phone number.');
444         $link = '<a href="' .
445                 htmlspecialchars(common_config('license', 'url')) .
446                 '">' .
447                 htmlspecialchars(common_config('license', 'title')) .
448                 '</a>';
449         $this->raw(sprintf(htmlspecialchars($message), $link));
450         $this->elementEnd('label');
451         $this->elementEnd('li');
452         $this->elementEnd('ul');
453         $this->elementEnd('fieldset');
454
455         $this->elementEnd('fieldset');
456         $this->elementEnd('form');
457     }
458
459     /**
460      * Get specified e-mail from the form, or the invite code.
461      *
462      * @return string
463      */
464     function getEmail()
465     {
466         $email = $this->trimmed('email');
467         if (!empty($email)) {
468             return $email;
469         }
470
471         // Terrible hack for invites...
472         if (common_config('site', 'inviteonly')) {
473             $code = $_SESSION['invitecode'];
474             if ($code) {
475                 $invite = Invitation::staticGet($code);
476
477                 if ($invite && $invite->address_type == 'email') {
478                     return $invite->address;
479                 }
480             }
481         }
482         return '';
483     }
484
485     function message($msg)
486     {
487         $this->message_text = $msg;
488         $this->showPage();
489     }
490
491     function createNewUser()
492     {
493         if (!Event::handle('StartRegistrationTry', array($this))) {
494             return;
495         }
496
497         if (common_config('site', 'closed')) {
498             // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
499             $this->clientError(_m('Registration not allowed.'));
500             return;
501         }
502
503         $invite = null;
504
505         if (common_config('site', 'inviteonly')) {
506             $code = $_SESSION['invitecode'];
507             if (empty($code)) {
508                 // TRANS: Client error displayed when trying to create a new user while creating new users is not allowed.
509                 $this->clientError(_m('Registration not allowed.'));
510                 return;
511             }
512
513             $invite = Invitation::staticGet($code);
514
515             if (empty($invite)) {
516                 // TRANS: Client error displayed when trying to create a new user with an invalid invitation code.
517                 $this->clientError(_m('Not a valid invitation code.'));
518                 return;
519             }
520         }
521
522         try {
523             $nickname = Nickname::normalize($this->trimmed('newname'));
524         } catch (NicknameException $e) {
525             $this->showForm($e->getMessage());
526             return;
527         }
528
529         if (!User::allowed_nickname($nickname)) {
530             // TRANS: Client error displayed when trying to create a new user with an invalid username.
531             $this->showForm(_m('Nickname not allowed.'));
532             return;
533         }
534
535         if (User::staticGet('nickname', $nickname)) {
536             // TRANS: Client error displayed when trying to create a new user with a username that is already in use.
537             $this->showForm(_m('Nickname already in use. Try another one.'));
538             return;
539         }
540
541         $fullname = trim($this->tw_fields['fullname']);
542
543         $args = array('nickname' => $nickname, 'fullname' => $fullname);
544
545         if (!empty($invite)) {
546             $args['code'] = $invite->code;
547         }
548
549         $email = $this->getEmail();
550         if (!empty($email)) {
551             $args['email'] = $email;
552         }
553
554         $user = User::register($args);
555
556         if (empty($user)) {
557             // TRANS: Server error displayed when creating a new user has failed.
558             $this->serverError(_m('Error registering user.'));
559             return;
560         }
561
562         $result = $this->saveForeignLink($user->id,
563                                          $this->twuid,
564                                          $this->access_token);
565
566         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
567
568         if (!$result) {
569             // TRANS: Server error displayed when connecting a user to a Twitter user has failed.
570             $this->serverError(_m('Error connecting user to Twitter.'));
571             return;
572         }
573
574         common_set_user($user);
575         common_real_login(true);
576
577         common_debug('TwitterBridge Plugin - ' .
578                      "Registered new user $user->id from Twitter user $this->twuid");
579
580         Event::handle('EndRegistrationTry', array($this));
581
582         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
583                         303);
584     }
585
586     function connectNewUser()
587     {
588         $nickname = $this->trimmed('nickname');
589         $password = $this->trimmed('password');
590
591         if (!common_check_user($nickname, $password)) {
592             // TRANS: Form validation error displayed when connecting an existing user to a Twitter user fails because
593             // TRANS: the provided username and/or password are incorrect.
594             $this->showForm(_m('Invalid username or password.'));
595             return;
596         }
597
598         $user = User::staticGet('nickname', $nickname);
599
600         if (!empty($user)) {
601             common_debug('TwitterBridge Plugin - ' .
602                          "Legit user to connect to Twitter: $nickname");
603         }
604
605         $result = $this->saveForeignLink($user->id,
606                                          $this->twuid,
607                                          $this->access_token);
608
609         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
610
611         if (!$result) {
612             // TRANS: Server error displayed connecting a user to a Twitter user has failed.
613             $this->serverError(_m('Error connecting user to Twitter.'));
614             return;
615         }
616
617         common_debug('TwitterBridge Plugin - ' .
618                      "Connected Twitter user $this->twuid to local user $user->id");
619
620         common_set_user($user);
621         common_real_login(true);
622
623         $this->goHome($user->nickname);
624     }
625
626     function connectUser()
627     {
628         $user = common_current_user();
629
630         $result = $this->flinkUser($user->id, $this->twuid);
631
632         if (empty($result)) {
633             // TRANS: Server error displayed connecting a user to a Twitter user has failed.
634             $this->serverError(_m('Error connecting user to Twitter.'));
635             return;
636         }
637
638         common_debug('TwitterBridge Plugin - ' .
639                      "Connected Twitter user $this->twuid to local user $user->id");
640
641         // Return to Twitter connection settings tab
642         common_redirect(common_local_url('twittersettings'), 303);
643     }
644
645     function tryLogin()
646     {
647         common_debug('TwitterBridge Plugin - ' .
648                      "Trying login for Twitter user $this->twuid.");
649
650         $flink = Foreign_link::getByForeignID($this->twuid,
651                                               TWITTER_SERVICE);
652
653         if (!empty($flink)) {
654             $user = $flink->getUser();
655
656             if (!empty($user)) {
657
658                 common_debug('TwitterBridge Plugin - ' .
659                              "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
660
661                 common_set_user($user);
662                 common_real_login(true);
663                 $this->goHome($user->nickname);
664             }
665
666         } else {
667
668             common_debug('TwitterBridge Plugin - ' .
669                          "No flink found for twuid: $this->twuid - new user");
670
671             $this->showForm(null, $this->bestNewNickname());
672         }
673     }
674
675     function goHome($nickname)
676     {
677         $url = common_get_returnto();
678         if ($url) {
679             // We don't have to return to it again
680             common_set_returnto(null);
681         } else {
682             $url = common_local_url('all',
683                                     array('nickname' =>
684                                           $nickname));
685         }
686
687         common_redirect($url, 303);
688     }
689
690     function bestNewNickname()
691     {
692         if (!empty($this->tw_fields['fullname'])) {
693             $nickname = $this->nicknamize($this->tw_fields['fullname']);
694             if ($this->isNewNickname($nickname)) {
695                 return $nickname;
696             }
697         }
698
699         return null;
700     }
701
702      // Given a string, try to make it work as a nickname
703
704      function nicknamize($str)
705      {
706          $str = preg_replace('/\W/', '', $str);
707          $str = str_replace(array('-', '_'), '', $str);
708          return strtolower($str);
709      }
710
711     function isNewNickname($str)
712     {
713         if (!Nickname::isValid($str)) {
714             return false;
715         }
716         if (!User::allowed_nickname($str)) {
717             return false;
718         }
719         if (User::staticGet('nickname', $str)) {
720             return false;
721         }
722         return true;
723     }
724 }