]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterauthorization.php
Add email field to Twitter registration form; needed when RequireValidatedEmail plugi...
[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                 $this->showForm(_m('There was a problem with your session token. Try again, please.'));
121                 return;
122             }
123
124             if ($this->arg('create')) {
125                 if (!$this->boolean('license')) {
126                     $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
127                                     $this->trimmed('newname'));
128                     return;
129                 }
130                 $this->createNewUser();
131             } else if ($this->arg('connect')) {
132                 $this->connectNewUser();
133             } else {
134                 common_debug('Twitter bridge - ' . print_r($this->args, true));
135                 $this->showForm(_m('Something weird happened.'),
136                                 $this->trimmed('newname'));
137             }
138         } else {
139             // $this->oauth_token is only populated once Twitter authorizes our
140             // request token. If it's empty we're at the beginning of the auth
141             // process
142
143             if (empty($this->oauth_token)) {
144                 $this->authorizeRequestToken();
145             } else {
146                 $this->saveAccessToken();
147             }
148         }
149     }
150
151     /**
152      * Asks Twitter for a request token, and then redirects to Twitter
153      * to authorize it.
154      *
155      * @return nothing
156      */
157     function authorizeRequestToken()
158     {
159         try {
160
161             // Get a new request token and authorize it
162
163             $client  = new TwitterOAuthClient();
164             $req_tok = $client->getRequestToken();
165
166             // Sock the request token away in the session temporarily
167
168             $_SESSION['twitter_request_token']        = $req_tok->key;
169             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
170
171             $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
172
173         } catch (OAuthClientException $e) {
174             $msg = sprintf(
175                 'OAuth client error - code: %1s, msg: %2s',
176                 $e->getCode(),
177                 $e->getMessage()
178             );
179             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
180             $this->serverError(
181                 _m('Couldn\'t link your Twitter account.')
182             );
183         }
184
185         common_redirect($auth_link);
186     }
187
188     /**
189      * Called when Twitter returns an authorized request token. Exchanges
190      * it for an access token and stores it.
191      *
192      * @return nothing
193      */
194     function saveAccessToken()
195     {
196         // Check to make sure Twitter returned the same request
197         // token we sent them
198
199         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
200             $this->serverError(
201                 _m('Couldn\'t link your Twitter account: oauth_token mismatch.')
202             );
203         }
204
205         $twitter_user = null;
206
207         try {
208
209             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
210                 $_SESSION['twitter_request_token_secret']);
211
212             // Exchange the request token for an access token
213
214             $atok = $client->getAccessToken($this->verifier);
215
216             // Test the access token and get the user's Twitter info
217
218             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
219             $twitter_user = $client->verifyCredentials();
220
221         } catch (OAuthClientException $e) {
222             $msg = sprintf(
223                 'OAuth client error - code: %1$s, msg: %2$s',
224                 $e->getCode(),
225                 $e->getMessage()
226             );
227             common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
228             $this->serverError(
229                 _m('Couldn\'t link your Twitter account.')
230             );
231         }
232
233         if (common_logged_in()) {
234             // Save the access token and Twitter user info
235
236             $user = common_current_user();
237             $this->saveForeignLink($user->id, $twitter_user->id, $atok);
238             save_twitter_user($twitter_user->id, $twitter_user->screen_name);
239
240         } else {
241
242             $this->twuid = $twitter_user->id;
243             $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
244                                      "fullname" => $twitter_user->name);
245             $this->access_token = $atok;
246             $this->tryLogin();
247         }
248
249         // Clean up the the mess we made in the session
250
251         unset($_SESSION['twitter_request_token']);
252         unset($_SESSION['twitter_request_token_secret']);
253
254         if (common_logged_in()) {
255             common_redirect(common_local_url('twittersettings'));
256         }
257     }
258
259     /**
260      * Saves a Foreign_link between Twitter user and local user,
261      * which includes the access token and secret.
262      *
263      * @param int        $user_id StatusNet user ID
264      * @param int        $twuid   Twitter user ID
265      * @param OAuthToken $token   the access token to save
266      *
267      * @return nothing
268      */
269     function saveForeignLink($user_id, $twuid, $access_token)
270     {
271         $flink = new Foreign_link();
272
273         $flink->user_id = $user_id;
274         $flink->service = TWITTER_SERVICE;
275
276         // delete stale flink, if any
277         $result = $flink->find(true);
278
279         if (!empty($result)) {
280             $flink->safeDelete();
281         }
282
283         $flink->user_id     = $user_id;
284         $flink->foreign_id  = $twuid;
285         $flink->service     = TWITTER_SERVICE;
286
287         $creds = TwitterOAuthClient::packToken($access_token);
288
289         $flink->credentials = $creds;
290         $flink->created     = common_sql_now();
291
292         // Defaults: noticesync on, everything else off
293
294         $flink->set_flags(true, false, false, false);
295
296         $flink_id = $flink->insert();
297
298         if (empty($flink_id)) {
299             common_log_db_error($flink, 'INSERT', __FILE__);
300             $this->serverError(_m('Couldn\'t link your Twitter account.'));
301         }
302
303         return $flink_id;
304     }
305
306     function showPageNotice()
307     {
308         if ($this->error) {
309             $this->element('div', array('class' => 'error'), $this->error);
310         } else {
311             $this->element('div', 'instructions',
312                            sprintf(_m('This is the first time you\'ve 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')));
313         }
314     }
315
316     function title()
317     {
318         return _m('Twitter Account Setup');
319     }
320
321     function showForm($error=null, $username=null)
322     {
323         $this->error = $error;
324         $this->username = $username;
325
326         $this->showPage();
327     }
328
329     function showPage()
330     {
331         parent::showPage();
332     }
333
334     /**
335      * @fixme much of this duplicates core code, which is very fragile.
336      * Should probably be replaced with an extensible mini version of
337      * the core registration form.
338      */
339     function showContent()
340     {
341         if (!empty($this->message_text)) {
342             $this->element('p', null, $this->message);
343             return;
344         }
345
346         $this->elementStart('form', array('method' => 'post',
347                                           'id' => 'form_settings_twitter_connect',
348                                           'class' => 'form_settings',
349                                           'action' => common_local_url('twitterauthorization')));
350         $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
351         $this->element('legend', null, _m('Connection options'));
352         $this->elementStart('ul', 'form_data');
353         $this->elementStart('li');
354         $this->element('input', array('type' => 'checkbox',
355                                       'id' => 'license',
356                                       'class' => 'checkbox',
357                                       'name' => 'license',
358                                       'value' => 'true'));
359         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
360         $message = _m('My text and files are available under %s ' .
361                      'except this private data: password, ' .
362                      'email address, IM address, and phone number.');
363         $link = '<a href="' .
364                 htmlspecialchars(common_config('license', 'url')) .
365                 '">' .
366                 htmlspecialchars(common_config('license', 'title')) .
367                 '</a>';
368         $this->raw(sprintf(htmlspecialchars($message), $link));
369         $this->elementEnd('label');
370         $this->elementEnd('li');
371         $this->elementEnd('ul');
372         $this->hidden('access_token_key', $this->access_token->key);
373         $this->hidden('access_token_secret', $this->access_token->secret);
374         $this->hidden('twuid', $this->twuid);
375         $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
376         $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
377
378         $this->elementStart('fieldset');
379         $this->hidden('token', common_session_token());
380         $this->element('legend', null,
381                        _m('Create new account'));
382         $this->element('p', null,
383                        _m('Create a new user with this nickname.'));
384         $this->elementStart('ul', 'form_data');
385
386         // Hook point for captcha etc
387         Event::handle('StartRegistrationFormData', array($this));
388
389         $this->elementStart('li');
390         $this->input('newname', _m('New nickname'),
391                      ($this->username) ? $this->username : '',
392                      _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
393         $this->elementEnd('li');
394         $this->elementStart('li');
395         $this->input('email', _('Email'), $this->getEmail(),
396                      _('Used only for updates, announcements, '.
397                        'and password recovery'));
398         $this->elementEnd('li');
399
400         // Hook point for captcha etc
401         Event::handle('EndRegistrationFormData', array($this));
402
403         $this->elementEnd('ul');
404         $this->submit('create', _m('Create'));
405         $this->elementEnd('fieldset');
406
407         $this->elementStart('fieldset');
408         $this->element('legend', null,
409                        _m('Connect existing account'));
410         $this->element('p', null,
411                        _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
412         $this->elementStart('ul', 'form_data');
413         $this->elementStart('li');
414         $this->input('nickname', _m('Existing nickname'));
415         $this->elementEnd('li');
416         $this->elementStart('li');
417         $this->password('password', _m('Password'));
418         $this->elementEnd('li');
419         $this->elementEnd('ul');
420         $this->submit('connect', _m('Connect'));
421         $this->elementEnd('fieldset');
422
423         $this->elementEnd('fieldset');
424         $this->elementEnd('form');
425     }
426
427     /**
428      * Get specified e-mail from the form, or the invite code.
429      *
430      * @return string
431      */
432     function getEmail()
433     {
434         $email = $this->trimmed('email');
435         if (!empty($email)) {
436             return $email;
437         }
438
439         // Terrible hack for invites...
440         if (common_config('site', 'inviteonly')) {
441             $code = $_SESSION['invitecode'];
442             if ($code) {
443                 $invite = Invitation::staticGet($code);
444
445                 if ($invite && $invite->address_type == 'email') {
446                     return $invite->address;
447                 }
448             }
449         }
450         return '';
451     }
452
453     function message($msg)
454     {
455         $this->message_text = $msg;
456         $this->showPage();
457     }
458
459     function createNewUser()
460     {
461         if (!Event::handle('StartRegistrationTry', array($this))) {
462             return;
463         }
464
465         if (common_config('site', 'closed')) {
466             $this->clientError(_m('Registration not allowed.'));
467             return;
468         }
469
470         $invite = null;
471
472         if (common_config('site', 'inviteonly')) {
473             $code = $_SESSION['invitecode'];
474             if (empty($code)) {
475                 $this->clientError(_m('Registration not allowed.'));
476                 return;
477             }
478
479             $invite = Invitation::staticGet($code);
480
481             if (empty($invite)) {
482                 $this->clientError(_m('Not a valid invitation code.'));
483                 return;
484             }
485         }
486
487         try {
488             $nickname = Nickname::normalize($this->trimmed('newname'));
489         } catch (NicknameException $e) {
490             $this->showForm($e->getMessage());
491             return;
492         }
493
494         if (!User::allowed_nickname($nickname)) {
495             $this->showForm(_m('Nickname not allowed.'));
496             return;
497         }
498
499         if (User::staticGet('nickname', $nickname)) {
500             $this->showForm(_m('Nickname already in use. Try another one.'));
501             return;
502         }
503
504         $fullname = trim($this->tw_fields['fullname']);
505
506         $args = array('nickname' => $nickname, 'fullname' => $fullname);
507
508         if (!empty($invite)) {
509             $args['code'] = $invite->code;
510         }
511
512         $email = $this->getEmail();
513         if (!empty($email)) {
514             $args['email'] = $email;
515         }
516
517         $user = User::register($args);
518
519         if (empty($user)) {
520             $this->serverError(_m('Error registering user.'));
521             return;
522         }
523
524         $result = $this->saveForeignLink($user->id,
525                                          $this->twuid,
526                                          $this->access_token);
527
528         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
529
530         if (!$result) {
531             $this->serverError(_m('Error connecting user to Twitter.'));
532             return;
533         }
534
535         common_set_user($user);
536         common_real_login(true);
537
538         common_debug('TwitterBridge Plugin - ' .
539                      "Registered new user $user->id from Twitter user $this->twuid");
540
541         Event::handle('EndRegistrationTry', array($this));
542
543         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
544                         303);
545     }
546
547     function connectNewUser()
548     {
549         $nickname = $this->trimmed('nickname');
550         $password = $this->trimmed('password');
551
552         if (!common_check_user($nickname, $password)) {
553             $this->showForm(_m('Invalid username or password.'));
554             return;
555         }
556
557         $user = User::staticGet('nickname', $nickname);
558
559         if (!empty($user)) {
560             common_debug('TwitterBridge Plugin - ' .
561                          "Legit user to connect to Twitter: $nickname");
562         }
563
564         $result = $this->saveForeignLink($user->id,
565                                          $this->twuid,
566                                          $this->access_token);
567
568         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
569
570         if (!$result) {
571             $this->serverError(_m('Error connecting user to Twitter.'));
572             return;
573         }
574
575         common_debug('TwitterBridge Plugin - ' .
576                      "Connected Twitter user $this->twuid to local user $user->id");
577
578         common_set_user($user);
579         common_real_login(true);
580
581         $this->goHome($user->nickname);
582     }
583
584     function connectUser()
585     {
586         $user = common_current_user();
587
588         $result = $this->flinkUser($user->id, $this->twuid);
589
590         if (empty($result)) {
591             $this->serverError(_m('Error connecting user to Twitter.'));
592             return;
593         }
594
595         common_debug('TwitterBridge Plugin - ' .
596                      "Connected Twitter user $this->twuid to local user $user->id");
597
598         // Return to Twitter connection settings tab
599         common_redirect(common_local_url('twittersettings'), 303);
600     }
601
602     function tryLogin()
603     {
604         common_debug('TwitterBridge Plugin - ' .
605                      "Trying login for Twitter user $this->twuid.");
606
607         $flink = Foreign_link::getByForeignID($this->twuid,
608                                               TWITTER_SERVICE);
609
610         if (!empty($flink)) {
611             $user = $flink->getUser();
612
613             if (!empty($user)) {
614
615                 common_debug('TwitterBridge Plugin - ' .
616                              "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
617
618                 common_set_user($user);
619                 common_real_login(true);
620                 $this->goHome($user->nickname);
621             }
622
623         } else {
624
625             common_debug('TwitterBridge Plugin - ' .
626                          "No flink found for twuid: $this->twuid - new user");
627
628             $this->showForm(null, $this->bestNewNickname());
629         }
630     }
631
632     function goHome($nickname)
633     {
634         $url = common_get_returnto();
635         if ($url) {
636             // We don't have to return to it again
637             common_set_returnto(null);
638         } else {
639             $url = common_local_url('all',
640                                     array('nickname' =>
641                                           $nickname));
642         }
643
644         common_redirect($url, 303);
645     }
646
647     function bestNewNickname()
648     {
649         if (!empty($this->tw_fields['fullname'])) {
650             $nickname = $this->nicknamize($this->tw_fields['fullname']);
651             if ($this->isNewNickname($nickname)) {
652                 return $nickname;
653             }
654         }
655
656         return null;
657     }
658
659      // Given a string, try to make it work as a nickname
660
661      function nicknamize($str)
662      {
663          $str = preg_replace('/\W/', '', $str);
664          $str = str_replace(array('-', '_'), '', $str);
665          return strtolower($str);
666      }
667
668     function isNewNickname($str)
669     {
670         if (!Nickname::isValid($str)) {
671             return false;
672         }
673         if (!User::allowed_nickname($str)) {
674             return false;
675         }
676         if (User::staticGet('nickname', $str)) {
677             return false;
678         }
679         return true;
680     }
681
682 }
683