]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterauthorization.php
Merge branch '0.9.x' of git@gitorious.org:statusnet/mainline into 0.9.x
[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(_('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(_('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(_('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
235             // Save the access token and Twitter user info
236
237             $user = common_current_user();
238             $this->saveForeignLink($user->id, $twitter_user->id, $atok);
239             save_twitter_user($twitter_user->id, $twitter_user->screen_name);
240
241         } else {
242
243             $this->twuid = $twitter_user->id;
244             $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
245                                      "name" => $twitter_user->name);
246             $this->access_token = $atok;
247             $this->tryLogin();
248         }
249
250         // Clean up the the mess we made in the session
251
252         unset($_SESSION['twitter_request_token']);
253         unset($_SESSION['twitter_request_token_secret']);
254
255         if (common_logged_in()) {
256             common_redirect(common_local_url('twittersettings'));
257         }
258     }
259
260     /**
261      * Saves a Foreign_link between Twitter user and local user,
262      * which includes the access token and secret.
263      *
264      * @param int        $user_id StatusNet user ID
265      * @param int        $twuid   Twitter user ID
266      * @param OAuthToken $token   the access token to save
267      *
268      * @return nothing
269      */
270     function saveForeignLink($user_id, $twuid, $access_token)
271     {
272         $flink = new Foreign_link();
273
274         $flink->user_id = $user_id;
275         $flink->service = TWITTER_SERVICE;
276
277         // delete stale flink, if any
278         $result = $flink->find(true);
279
280         if (!empty($result)) {
281             $flink->safeDelete();
282         }
283
284         $flink->user_id     = $user_id;
285         $flink->foreign_id  = $twuid;
286         $flink->service     = TWITTER_SERVICE;
287
288         $creds = TwitterOAuthClient::packToken($access_token);
289
290         $flink->credentials = $creds;
291         $flink->created     = common_sql_now();
292
293         // Defaults: noticesync on, everything else off
294
295         $flink->set_flags(true, false, false, false);
296
297         $flink_id = $flink->insert();
298
299         if (empty($flink_id)) {
300             common_log_db_error($flink, 'INSERT', __FILE__);
301             $this->serverError(_('Couldn\'t link your Twitter account.'));
302         }
303
304         return $flink_id;
305     }
306
307     function showPageNotice()
308     {
309         if ($this->error) {
310             $this->element('div', array('class' => 'error'), $this->error);
311         } else {
312             $this->element('div', 'instructions',
313                            sprintf(_('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')));
314         }
315     }
316
317     function title()
318     {
319         return _('Twitter Account Setup');
320     }
321
322     function showForm($error=null, $username=null)
323     {
324         $this->error = $error;
325         $this->username = $username;
326
327         $this->showPage();
328     }
329
330     function showPage()
331     {
332         parent::showPage();
333     }
334
335     function showContent()
336     {
337         if (!empty($this->message_text)) {
338             $this->element('p', null, $this->message);
339             return;
340         }
341
342         $this->elementStart('form', array('method' => 'post',
343                                           'id' => 'form_settings_twitter_connect',
344                                           'class' => 'form_settings',
345                                           'action' => common_local_url('twitterauthorization')));
346         $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
347         $this->element('legend', null, _('Connection options'));
348         $this->elementStart('ul', 'form_data');
349         $this->elementStart('li');
350         $this->element('input', array('type' => 'checkbox',
351                                       'id' => 'license',
352                                       'class' => 'checkbox',
353                                       'name' => 'license',
354                                       'value' => 'true'));
355         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
356         $this->text(_('My text and files are available under '));
357         $this->element('a', array('href' => common_config('license', 'url')),
358                        common_config('license', 'title'));
359         $this->text(_(' except this private data: password, email address, IM address, phone number.'));
360         $this->elementEnd('label');
361         $this->elementEnd('li');
362         $this->elementEnd('ul');
363         $this->hidden('access_token_key', $this->access_token->key);
364         $this->hidden('access_token_secret', $this->access_token->secret);
365         $this->hidden('twuid', $this->twuid);
366         $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
367         $this->hidden('tw_fields_name', $this->tw_fields['name']);
368
369         $this->elementStart('fieldset');
370         $this->hidden('token', common_session_token());
371         $this->element('legend', null,
372                        _('Create new account'));
373         $this->element('p', null,
374                        _('Create a new user with this nickname.'));
375         $this->elementStart('ul', 'form_data');
376         $this->elementStart('li');
377         $this->input('newname', _('New nickname'),
378                      ($this->username) ? $this->username : '',
379                      _('1-64 lowercase letters or numbers, no punctuation or spaces'));
380         $this->elementEnd('li');
381         $this->elementEnd('ul');
382         $this->submit('create', _('Create'));
383         $this->elementEnd('fieldset');
384
385         $this->elementStart('fieldset');
386         $this->element('legend', null,
387                        _('Connect existing account'));
388         $this->element('p', null,
389                        _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
390         $this->elementStart('ul', 'form_data');
391         $this->elementStart('li');
392         $this->input('nickname', _('Existing nickname'));
393         $this->elementEnd('li');
394         $this->elementStart('li');
395         $this->password('password', _('Password'));
396         $this->elementEnd('li');
397         $this->elementEnd('ul');
398         $this->submit('connect', _('Connect'));
399         $this->elementEnd('fieldset');
400
401         $this->elementEnd('fieldset');
402         $this->elementEnd('form');
403     }
404
405     function message($msg)
406     {
407         $this->message_text = $msg;
408         $this->showPage();
409     }
410
411     function createNewUser()
412     {
413         if (common_config('site', 'closed')) {
414             $this->clientError(_('Registration not allowed.'));
415             return;
416         }
417
418         $invite = null;
419
420         if (common_config('site', 'inviteonly')) {
421             $code = $_SESSION['invitecode'];
422             if (empty($code)) {
423                 $this->clientError(_('Registration not allowed.'));
424                 return;
425             }
426
427             $invite = Invitation::staticGet($code);
428
429             if (empty($invite)) {
430                 $this->clientError(_('Not a valid invitation code.'));
431                 return;
432             }
433         }
434
435         $nickname = $this->trimmed('newname');
436
437         if (!Validate::string($nickname, array('min_length' => 1,
438                                                'max_length' => 64,
439                                                'format' => NICKNAME_FMT))) {
440             $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
441             return;
442         }
443
444         if (!User::allowed_nickname($nickname)) {
445             $this->showForm(_('Nickname not allowed.'));
446             return;
447         }
448
449         if (User::staticGet('nickname', $nickname)) {
450             $this->showForm(_('Nickname already in use. Try another one.'));
451             return;
452         }
453
454         $fullname = trim($this->tw_fields['name']);
455
456         $args = array('nickname' => $nickname, 'fullname' => $fullname);
457
458         if (!empty($invite)) {
459             $args['code'] = $invite->code;
460         }
461
462         $user = User::register($args);
463
464         if (empty($user)) {
465             $this->serverError(_('Error registering user.'));
466             return;
467         }
468
469         $result = $this->saveForeignLink($user->id,
470                                          $this->twuid,
471                                          $this->access_token);
472
473         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
474
475         if (!$result) {
476             $this->serverError(_('Error connecting user to Twitter.'));
477             return;
478         }
479
480         common_set_user($user);
481         common_real_login(true);
482
483         common_debug('TwitterBridge Plugin - ' .
484                      "Registered new user $user->id from Twitter user $this->twuid");
485
486         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
487                         303);
488     }
489
490     function connectNewUser()
491     {
492         $nickname = $this->trimmed('nickname');
493         $password = $this->trimmed('password');
494
495         if (!common_check_user($nickname, $password)) {
496             $this->showForm(_('Invalid username or password.'));
497             return;
498         }
499
500         $user = User::staticGet('nickname', $nickname);
501
502         if (!empty($user)) {
503             common_debug('TwitterBridge Plugin - ' .
504                          "Legit user to connect to Twitter: $nickname");
505         }
506
507         $result = $this->saveForeignLink($user->id,
508                                          $this->twuid,
509                                          $this->access_token);
510
511         save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
512
513         if (!$result) {
514             $this->serverError(_('Error connecting user to Twitter.'));
515             return;
516         }
517
518         common_debug('TwitterBridge Plugin - ' .
519                      "Connected Twitter user $this->twuid to local user $user->id");
520
521         common_set_user($user);
522         common_real_login(true);
523
524         $this->goHome($user->nickname);
525     }
526
527     function connectUser()
528     {
529         $user = common_current_user();
530
531         $result = $this->flinkUser($user->id, $this->twuid);
532
533         if (empty($result)) {
534             $this->serverError(_('Error connecting user to Twitter.'));
535             return;
536         }
537
538         common_debug('TwitterBridge Plugin - ' .
539                      "Connected Twitter user $this->twuid to local user $user->id");
540
541         // Return to Twitter connection settings tab
542         common_redirect(common_local_url('twittersettings'), 303);
543     }
544
545     function tryLogin()
546     {
547         common_debug('TwitterBridge Plugin - ' .
548                      "Trying login for Twitter user $this->twuid.");
549
550         $flink = Foreign_link::getByForeignID($this->twuid,
551                                               TWITTER_SERVICE);
552
553         if (!empty($flink)) {
554             $user = $flink->getUser();
555
556             if (!empty($user)) {
557
558                 common_debug('TwitterBridge Plugin - ' .
559                              "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
560
561                 common_set_user($user);
562                 common_real_login(true);
563                 $this->goHome($user->nickname);
564             }
565
566         } else {
567
568             common_debug('TwitterBridge Plugin - ' .
569                          "No flink found for twuid: $this->twuid - new user");
570
571             $this->showForm(null, $this->bestNewNickname());
572         }
573     }
574
575     function goHome($nickname)
576     {
577         $url = common_get_returnto();
578         if ($url) {
579             // We don't have to return to it again
580             common_set_returnto(null);
581         } else {
582             $url = common_local_url('all',
583                                     array('nickname' =>
584                                           $nickname));
585         }
586
587         common_redirect($url, 303);
588     }
589
590     function bestNewNickname()
591     {
592         if (!empty($this->tw_fields['name'])) {
593             $nickname = $this->nicknamize($this->tw_fields['name']);
594             if ($this->isNewNickname($nickname)) {
595                 return $nickname;
596             }
597         }
598
599         return null;
600     }
601
602      // Given a string, try to make it work as a nickname
603
604      function nicknamize($str)
605      {
606          $str = preg_replace('/\W/', '', $str);
607          $str = str_replace(array('-', '_'), '', $str);
608          return strtolower($str);
609      }
610
611     function isNewNickname($str)
612     {
613         if (!Validate::string($str, array('min_length' => 1,
614                                           'max_length' => 64,
615                                           'format' => NICKNAME_FMT))) {
616             return false;
617         }
618         if (!User::allowed_nickname($str)) {
619             return false;
620         }
621         if (User::staticGet('nickname', $str)) {
622             return false;
623         }
624         return true;
625     }
626
627 }
628