From 6f4b2f0ac2f235332c850b050d9e4563fc71f89d Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Sat, 1 Aug 2009 08:20:44 +0000 Subject: Twitter OAuth server dance working --- actions/twitterauthorization.php | 136 +++++++++++++++++++++++++++++++++++++++ actions/twittersettings.php | 111 ++++++++++++++------------------ 2 files changed, 186 insertions(+), 61 deletions(-) create mode 100644 actions/twitterauthorization.php (limited to 'actions') diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php new file mode 100644 index 000000000..f19cd7f65 --- /dev/null +++ b/actions/twitterauthorization.php @@ -0,0 +1,136 @@ +. + * + * @category TwitterauthorizationAction + * @package Laconica + * @author Zach Copely + * @copyright 2009 Control Yourself, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +if (!defined('LACONICA')) { + exit(1); +} + +class TwitterauthorizationAction extends Action +{ + + function prepare($args) + { + parent::prepare($args); + + $this->oauth_token = $this->arg('oauth_token'); + + return true; + } + + function handle($args) + { + parent::handle($args); + + if (!common_logged_in()) { + $this->clientError(_('Not logged in.'), 403); + } + + $user = common_current_user(); + $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); + + // If there's already a foreign link record, it means we already + // have an access token, and this is unecessary. So go back. + + if (isset($flink)) { + common_redirect(common_local_url('twittersettings')); + } + + // $this->oauth_token is only populated once Twitter authorizes our + // request token. If it's empty we're at the beginning of the auth + // process + + if (empty($this->oauth_token)) { + + // Get a new request token and authorize it + + $client = new TwitterOAuthClient(); + $req_tok = $client->getRequestToken(); + + // Sock the request token away in the session temporarily + + $_SESSION['twitter_request_token'] = $req_tok->key; + $_SESSION['twitter_request_token_secret'] = $req_tok->key; + + $auth_link = $client->getAuthorizeLink($req_tok); + common_redirect($auth_link); + + } else { + + // Check to make sure Twitter sent us the same request token we sent + + if ($_SESSION['twitter_request_token'] != $this->oauth_token) { + $this->serverError(_('Couldn\'t link your Twitter account.')); + } + + $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], + $_SESSION['twitter_request_token_secret']); + + // Exchange the request token for an access token + + $atok = $client->getAccessToken(); + + // Save the access token and Twitter user info + + $client = new TwitterOAuthClient($atok->key, $atok->secret); + + $twitter_user = $client->verify_credentials(); + + $user = common_current_user(); + + $flink = new Foreign_link(); + + $flink->user_id = $user->id; + $flink->foreign_id = $twitter_user->id; + $flink->service = TWITTER_SERVICE; + $flink->token = $atok->key; + $flink->credentials = $atok->secret; + $flink->created = common_sql_now(); + + $flink->set_flags(true, false, false, false); + + $flink_id = $flink->insert(); + + if (empty($flink_id)) { + common_log_db_error($flink, 'INSERT', __FILE__); + $this->serverError(_('Couldn\'t link your Twitter account.')); + } + + save_twitter_user($twitter_user->id, $twitter_user->screen_name); + + // clean up the the mess we made in the session + + unset($_SESSION['twitter_request_token']); + unset($_SESSION['twitter_request_token_secret']); + + common_redirect(common_local_url('twittersettings')); + } + } + +} + diff --git a/actions/twittersettings.php b/actions/twittersettings.php index 2b742788e..acc9fb935 100644 --- a/actions/twittersettings.php +++ b/actions/twittersettings.php @@ -69,9 +69,8 @@ class TwittersettingsAction extends ConnectSettingsAction function getInstructions() { - return _('Add your Twitter account to automatically send '. - ' your notices to Twitter, ' . - 'and subscribe to Twitter friends already here.'); + return _('Connect your Twitter account to share your updates ' . + 'with your Twitter friends and vice-versa.'); } /** @@ -93,7 +92,7 @@ class TwittersettingsAction extends ConnectSettingsAction $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); - if ($flink) { + if (!empty($flink)) { $fuser = $flink->getForeignUser(); } @@ -102,73 +101,61 @@ class TwittersettingsAction extends ConnectSettingsAction 'class' => 'form_settings', 'action' => common_local_url('twittersettings'))); - $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); - $this->element('legend', null, _('Twitter Account')); + $this->hidden('token', common_session_token()); - if ($fuser) { + + + if (empty($fuser)) { + + $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); $this->elementStart('ul', 'form_data'); - $this->elementStart('li', array('id' => 'settings_twitter_remove')); - $this->element('span', 'twitter_user', $fuser->nickname); - $this->element('a', array('href' => $fuser->uri), $fuser->uri); - $this->element('p', 'form_note', - _('Current verified Twitter account.')); - $this->hidden('flink_foreign_id', $flink->foreign_id); - $this->elementEnd('li'); + $this->elementStart('li', array('id' => 'settings_twitter_login_button')); + $this->element('a', array('href' => common_local_url('twitterauthorization')), + 'Connect my Twitter account'); + $this->elementEnd('li'); $this->elementEnd('ul'); - $this->submit('remove', _('Remove')); + $this->elementEnd('fieldset'); + } else { + + $this->elementStart('fieldset', + array('id' => 'settings_twitter_preferences')); + $this->element('legend', null, _('Preferences')); + $this->elementStart('ul', 'form_data'); - $this->elementStart('li', array('id' => 'settings_twitter_login')); - $this->input('twitter_username', _('Twitter user name'), - ($this->arg('twitter_username')) ? - $this->arg('twitter_username') : - $profile->nickname, - _('No spaces, please.')); // hey, it's what Twitter says + $this->elementStart('li'); + $this->checkbox('noticesend', + _('Automatically send my notices to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND) : + true); $this->elementEnd('li'); $this->elementStart('li'); - $this->password('twitter_password', _('Twitter password')); - $this->elementend('li'); - $this->elementEnd('ul'); - } - $this->elementEnd('fieldset'); + $this->checkbox('replysync', + _('Send local "@" replies to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : + true); + $this->elementEnd('li'); + $this->elementStart('li'); + $this->checkbox('friendsync', + _('Subscribe to my Twitter friends here.'), + ($flink) ? + ($flink->friendsync & FOREIGN_FRIEND_RECV) : + false); + $this->elementEnd('li'); - $this->elementStart('fieldset', - array('id' => 'settings_twitter_preferences')); - $this->element('legend', null, _('Preferences')); - - $this->elementStart('ul', 'form_data'); - $this->elementStart('li'); - $this->checkbox('noticesend', - _('Automatically send my notices to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND) : - true); - $this->elementEnd('li'); - $this->elementStart('li'); - $this->checkbox('replysync', - _('Send local "@" replies to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : - true); - $this->elementEnd('li'); - $this->elementStart('li'); - $this->checkbox('friendsync', - _('Subscribe to my Twitter friends here.'), - ($flink) ? - ($flink->friendsync & FOREIGN_FRIEND_RECV) : - false); - $this->elementEnd('li'); - - if (common_config('twitterbridge','enabled')) { + if (common_config('twitterbridge','enabled')) { $this->elementStart('li'); $this->checkbox('noticerecv', - _('Import my Friends Timeline.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_RECV) : - false); + _('Import my Friends Timeline.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_RECV) : + false); $this->elementEnd('li'); - } else { + // preserve setting even if bidrection bridge toggled off + if ($flink && ($flink->noticesync & FOREIGN_NOTICE_RECV)) { $this->hidden('noticerecv', true, 'noticerecv'); } @@ -181,11 +168,13 @@ class TwittersettingsAction extends ConnectSettingsAction } else { $this->submit('add', _('Add')); } + $this->elementEnd('fieldset'); + } - $this->showTwitterSubscriptions(); + $this->showTwitterSubscriptions(); - $this->elementEnd('form'); + $this->elementEnd('form'); } /** -- cgit v1.2.3-54-g00ecf From 981fa1b33a8073bd0d53d8bee7dfccd171685e61 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Mon, 3 Aug 2009 22:46:01 +0000 Subject: Make the TwitterQueuehandler post to Twitter using OAuth --- actions/twitterauthorization.php | 48 +++++++++++----- lib/mail.php | 19 ++++--- lib/twitter.php | 117 +++++++++++++++------------------------ lib/twitteroauthclient.php | 39 +++++++++---- 4 files changed, 116 insertions(+), 107 deletions(-) (limited to 'actions') diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php index f19cd7f65..519427dac 100644 --- a/actions/twitterauthorization.php +++ b/actions/twitterauthorization.php @@ -67,39 +67,57 @@ class TwitterauthorizationAction extends Action if (empty($this->oauth_token)) { - // Get a new request token and authorize it + try { - $client = new TwitterOAuthClient(); - $req_tok = $client->getRequestToken(); + // Get a new request token and authorize it - // Sock the request token away in the session temporarily + $client = new TwitterOAuthClient(); + $req_tok = $client->getRequestToken(); - $_SESSION['twitter_request_token'] = $req_tok->key; - $_SESSION['twitter_request_token_secret'] = $req_tok->key; + // Sock the request token away in the session temporarily + + $_SESSION['twitter_request_token'] = $req_tok->key; + $_SESSION['twitter_request_token_secret'] = $req_tok->key; + + $auth_link = $client->getAuthorizeLink($req_tok); + + } catch (TwitterOAuthClientException $e) { + $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', + $e->getCode(), $e->getMessage()); + $this->serverError(_('Couldn\'t link your Twitter account.')); + } - $auth_link = $client->getAuthorizeLink($req_tok); common_redirect($auth_link); } else { - // Check to make sure Twitter sent us the same request token we sent + // Check to make sure Twitter returned the same request + // token we sent them if ($_SESSION['twitter_request_token'] != $this->oauth_token) { $this->serverError(_('Couldn\'t link your Twitter account.')); } - $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], - $_SESSION['twitter_request_token_secret']); + try { - // Exchange the request token for an access token + $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], + $_SESSION['twitter_request_token_secret']); - $atok = $client->getAccessToken(); + // Exchange the request token for an access token - // Save the access token and Twitter user info + $atok = $client->getAccessToken(); - $client = new TwitterOAuthClient($atok->key, $atok->secret); + // Save the access token and Twitter user info - $twitter_user = $client->verify_credentials(); + $client = new TwitterOAuthClient($atok->key, $atok->secret); + + $twitter_user = $client->verify_credentials(); + + } catch (OAuthClientException $e) { + $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', + $e->getCode(), $e->getMessage()); + $this->serverError(_('Couldn\'t link your Twitter account.')); + } $user = common_current_user(); diff --git a/lib/mail.php b/lib/mail.php index 0050ad810..16c1b0f30 100644 --- a/lib/mail.php +++ b/lib/mail.php @@ -645,13 +645,14 @@ function mail_twitter_bridge_removed($user) $subject = sprintf(_('Your Twitter bridge has been disabled.')); - $body = sprintf(_("Hi, %1\$s. We're sorry to inform you that your " . - 'link to Twitter has been disabled. Your Twitter credentials ' . - 'have either changed (did you recently change your Twitter ' . - 'password?) or you have otherwise revoked our access to your ' . - "Twitter account.\n\n" . - 'You can re-enable your Twitter bridge by visiting your ' . - "Twitter settings page:\n\n\t%2\$s\n\n" . + $site_name = common_config('site', 'name'); + + $body = sprintf(_('Hi, %1$s. We\'re sorry to inform you that your ' . + 'link to Twitter has been disabled. We no longer seem to have ' . + 'permission to update your Twitter status. (Did you revoke ' . + '%3$s\'s access?)' . "\n\n" . + 'You can re-enable your Twitter bridge by visiting your ' . + "Twitter settings page:\n\n\t%2\$s\n\n" . "Regards,\n%3\$s\n"), $profile->getBestName(), common_local_url('twittersettings'), @@ -679,11 +680,11 @@ function mail_facebook_app_removed($user) $site_name = common_config('site', 'name'); $subject = sprintf( - _('Your %1\$s Facebook application access has been disabled.', + _('Your %1$s Facebook application access has been disabled.', $site_name)); $body = sprintf(_("Hi, %1\$s. We're sorry to inform you that we are " . - 'unable to update your Facebook status from %2\$s, and have disabled ' . + 'unable to update your Facebook status from %2$s, and have disabled ' . 'the Facebook application for your account. This may be because ' . 'you have removed the Facebook application\'s authorization, or ' . 'have deleted your Facebook account. You can re-enable the ' . diff --git a/lib/twitter.php b/lib/twitter.php index 47af32e61..2369ac267 100644 --- a/lib/twitter.php +++ b/lib/twitter.php @@ -360,104 +360,72 @@ function is_twitter_bound($notice, $flink) { function broadcast_twitter($notice) { - $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); if (is_twitter_bound($notice, $flink)) { - $fuser = $flink->getForeignUser(); - $twitter_user = $fuser->nickname; - $twitter_password = $flink->credentials; - $uri = 'http://www.twitter.com/statuses/update.json'; + $user = $flink->getUser(); // XXX: Hack to get around PHP cURL's use of @ being a a meta character $statustxt = preg_replace('/^@/', ' @', $notice->content); - $options = array( - CURLOPT_USERPWD => "$twitter_user:$twitter_password", - CURLOPT_POST => true, - CURLOPT_POSTFIELDS => - array( - 'status' => $statustxt, - 'source' => common_config('integration', 'source') - ), - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FAILONERROR => true, - CURLOPT_HEADER => false, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_USERAGENT => "Laconica", - CURLOPT_CONNECTTIMEOUT => 120, // XXX: How long should this be? - CURLOPT_TIMEOUT => 120, - - # Twitter is strict about accepting invalid "Expect" headers - CURLOPT_HTTPHEADER => array('Expect:') - ); - - $ch = curl_init($uri); - curl_setopt_array($ch, $options); - $data = curl_exec($ch); - $errmsg = curl_error($ch); - $errno = curl_errno($ch); + $client = new TwitterOAuthClient($flink->token, $flink->credentials); - if (!empty($errmsg)) { - common_debug("cURL error ($errno): $errmsg - " . - "trying to send notice for $twitter_user.", - __FILE__); + $status = null; - $user = $flink->getUser(); + try { + $status = $client->statuses_update($statustxt); + } catch (OAuthClientCurlException $e) { - if ($errmsg == 'The requested URL returned error: 401') { - common_debug(sprintf('User %s (user id: %s) ' . - 'has bad Twitter credentials!', - $user->nickname, $user->id)); + if ($e->getMessage() == 'The requested URL returned error: 401') { - // Bad credentials we need to delete the foreign_link - // to Twitter and inform the user. + $errmsg = sprintf('User %1$s (user id: %2$s) has an invalid ' . + 'Twitter OAuth access token.', + $user->nickname, $user->id); + common_log(LOG_WARNING, $errmsg); - remove_twitter_link($flink); + // Bad auth token! We need to delete the foreign_link + // to Twitter and inform the user. - return true; + remove_twitter_link($flink); + return true; - } else { + } else { - // Some other error happened, so we should try to - // send again later + // Some other error happened, so we should probably + // try to send again later. - return false; - } + $errmsg = sprintf('cURL error trying to send notice to Twitter ' . + 'for user %1$s (user id: %2$s) - ' . + 'code: %3$s message: $4$s.', + $user->nickname, $user->id, + $e->getCode(), $e->getMessage()); + common_log(LOG_WARNING, $errmsg); + return false; } + } - curl_close($ch); - - if (empty($data)) { - common_debug("No data returned by Twitter's " . - "API trying to send update for $twitter_user", - __FILE__); + if (empty($status)) { - // XXX: Not sure this represents a failure to send, but it - // probably does + // This could represent a failure posting, + // or the Twitter API might just be behaving flakey. - return false; + $errmsg = sprint('No data returned by Twitter API when ' . + 'trying to send update for %1$s (user id %2$s).', + $user->nickname, $user->id); + common_log(LOG_WARNING, $errmsg); - } else { - - // Twitter should return a status - $status = json_decode($data); + return false; + } - if (empty($status)) { - common_debug("Unexpected data returned by Twitter " . - " API trying to send update for $twitter_user", - __FILE__); + // Notice crossed the great divide - // XXX: Again, this could represent a failure posting - // or the Twitter API might just be behaving flakey. - // We're treating it as a failure to post. + $msg = sprintf('Twitter bridge posted notice %s to Twitter.', + $notice->id); + common_log(LOG_INFO, $msg); - return false; - } - } } return true; @@ -480,17 +448,20 @@ function remove_twitter_link($flink) // Notify the user that her Twitter bridge is down + if (isset($user->email)) { + $result = mail_twitter_bridge_removed($user); if (!$result) { $msg = 'Unable to send email to notify ' . - "$user->nickname (user id: $user->id) " . - 'that their Twitter bridge link was ' . + "$user->nickname (user id: $user->id) " . + 'that their Twitter bridge link was ' . 'removed!'; common_log(LOG_WARNING, $msg); } + } } diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index 616fbc213..63ffe1c7c 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -2,6 +2,8 @@ require_once('OAuth.php'); +class OAuthClientCurlException extends Exception { } + class TwitterOAuthClient { public static $requestTokenURL = 'https://twitter.com/oauth/request_token'; @@ -54,6 +56,16 @@ class TwitterOAuthClient return $twitter_user; } + function statuses_update($status, $in_reply_to_status_id = null) + { + $url = 'https://twitter.com/statuses/update.json'; + $params = array('status' => $status, + 'in_reply_to_status_id' => $in_reply_to_status_id); + $response = $this->oAuthPost($url, $params); + $status = json_decode($response); + return $status; + } + function oAuthGet($url) { $request = OAuthRequest::from_consumer_and_token($this->consumer, @@ -91,19 +103,26 @@ class TwitterOAuthClient // Twitter is strict about accepting invalid "Expect" headers CURLOPT_HTTPHEADER => array('Expect:') - ); + ); - if (isset($params)) { - $options[CURLOPT_POST] = true; - $options[CURLOPT_POSTFIELDS] = $params; - } + if (isset($params)) { + $options[CURLOPT_POST] = true; + $options[CURLOPT_POSTFIELDS] = $params; + } + + $ch = curl_init($url); + curl_setopt_array($ch, $options); + $response = curl_exec($ch); + + if ($response === false) { + $msg = curl_error($ch); + $code = curl_errno($ch); + throw new OAuthClientCurlException($msg, $code); + } - $ch = curl_init($url); - curl_setopt_array($ch, $options); - $response = curl_exec($ch); - curl_close($ch); + curl_close($ch); - return $response; + return $response; } } -- cgit v1.2.3-54-g00ecf From 1f9d1772c091e1f09cc741e3e21cfe5ba7fa3560 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 00:02:07 +0000 Subject: Allow removal of Twitter account. Deleted dead code. --- actions/twittersettings.php | 344 +++++++------------------------------------- 1 file changed, 52 insertions(+), 292 deletions(-) (limited to 'actions') diff --git a/actions/twittersettings.php b/actions/twittersettings.php index acc9fb935..7fffa0af0 100644 --- a/actions/twittersettings.php +++ b/actions/twittersettings.php @@ -34,8 +34,6 @@ if (!defined('LACONICA')) { require_once INSTALLDIR.'/lib/connectsettingsaction.php'; require_once INSTALLDIR.'/lib/twitter.php'; -define('SUBSCRIPTIONS', 80); - /** * Settings for Twitter integration * @@ -70,7 +68,7 @@ class TwittersettingsAction extends ConnectSettingsAction function getInstructions() { return _('Connect your Twitter account to share your updates ' . - 'with your Twitter friends and vice-versa.'); + 'with your Twitter friends and vice-versa.'); } /** @@ -104,179 +102,83 @@ class TwittersettingsAction extends ConnectSettingsAction $this->hidden('token', common_session_token()); + $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); if (empty($fuser)) { - - $this->elementStart('fieldset', array('id' => 'settings_twitter_account')); $this->elementStart('ul', 'form_data'); $this->elementStart('li', array('id' => 'settings_twitter_login_button')); $this->element('a', array('href' => common_local_url('twitterauthorization')), - 'Connect my Twitter account'); - $this->elementEnd('li'); + 'Connect my Twitter account'); + $this->elementEnd('li'); $this->elementEnd('ul'); - $this->elementEnd('fieldset'); + $this->elementEnd('fieldset'); } else { + $this->element('legend', null, _('Twitter account')); + $this->elementStart('p', array('id' => 'form_confirmed')); + $this->element('a', array('href' => $fuser->uri), $fuser->nickname); + $this->elementEnd('p'); + $this->element('p', 'form_note', + _('Connected Twitter account')); - $this->elementStart('fieldset', - array('id' => 'settings_twitter_preferences')); - $this->element('legend', null, _('Preferences')); + $this->submit('remove', _('Remove')); + + $this->elementEnd('fieldset'); + $this->elementStart('fieldset', array('id' => 'settings_twitter_preferences')); + + $this->element('legend', null, _('Preferences')); $this->elementStart('ul', 'form_data'); $this->elementStart('li'); $this->checkbox('noticesend', - _('Automatically send my notices to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND) : - true); + _('Automatically send my notices to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND) : + true); $this->elementEnd('li'); $this->elementStart('li'); $this->checkbox('replysync', - _('Send local "@" replies to Twitter.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : - true); + _('Send local "@" replies to Twitter.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : + true); $this->elementEnd('li'); $this->elementStart('li'); $this->checkbox('friendsync', - _('Subscribe to my Twitter friends here.'), - ($flink) ? - ($flink->friendsync & FOREIGN_FRIEND_RECV) : - false); + _('Subscribe to my Twitter friends here.'), + ($flink) ? + ($flink->friendsync & FOREIGN_FRIEND_RECV) : + false); $this->elementEnd('li'); if (common_config('twitterbridge','enabled')) { - $this->elementStart('li'); - $this->checkbox('noticerecv', - _('Import my Friends Timeline.'), - ($flink) ? - ($flink->noticesync & FOREIGN_NOTICE_RECV) : - false); - $this->elementEnd('li'); - - // preserve setting even if bidrection bridge toggled off - - if ($flink && ($flink->noticesync & FOREIGN_NOTICE_RECV)) { - $this->hidden('noticerecv', true, 'noticerecv'); - } - } - - $this->elementEnd('ul'); - - if ($flink) { - $this->submit('save', _('Save')); - } else { - $this->submit('add', _('Add')); - } - - $this->elementEnd('fieldset'); - } - - $this->showTwitterSubscriptions(); - - $this->elementEnd('form'); - } - - /** - * Gets some of the user's Twitter friends - * - * Gets the number of Twitter friends that are on this - * instance of Laconica. - * - * @return array array of User objects - */ - - function subscribedTwitterUsers() - { - - $current_user = common_current_user(); - - $qry = 'SELECT "user".* ' . - 'FROM subscription ' . - 'JOIN "user" ON subscription.subscribed = "user".id ' . - 'JOIN foreign_link ON foreign_link.user_id = "user".id ' . - 'WHERE subscriber = %d ' . - 'ORDER BY "user".nickname'; - - $user = new User(); - - $user->query(sprintf($qry, $current_user->id)); - - $users = array(); - - while ($user->fetch()) { - - // Don't include the user's own self-subscription - if ($user->id != $current_user->id) { - $users[] = clone($user); - } - } - - return $users; - } - - /** - * Show user's Twitter friends - * - * Gets the number of Twitter friends that are on this - * instance of Laconica, and shows their mini-avatars. - * - * @return void - */ - - function showTwitterSubscriptions() - { - - $friends = $this->subscribedTwitterUsers(); - - $friends_count = count($friends); - - if ($friends_count > 0) { - $this->elementStart('div', array('id' => 'entity_subscriptions', - 'class' => 'section')); - $this->element('h2', null, _('Twitter Friends')); - $this->elementStart('ul', 'entities users xoxo'); - - for ($i = 0; $i < min($friends_count, SUBSCRIPTIONS); $i++) { + $this->elementStart('li'); + $this->checkbox('noticerecv', + _('Import my Friends Timeline.'), + ($flink) ? + ($flink->noticesync & FOREIGN_NOTICE_RECV) : + false); + $this->elementEnd('li'); - $other = Profile::staticGet($friends[$i]->id); + // preserve setting even if bidrection bridge toggled off - if (!$other) { - common_log_db_error($subs, 'SELECT', __FILE__); - continue; + if ($flink && ($flink->noticesync & FOREIGN_NOTICE_RECV)) { + $this->hidden('noticerecv', true, 'noticerecv'); } - - $this->elementStart('li', 'vcard'); - $this->elementStart('a', array('title' => ($other->fullname) ? - $other->fullname : - $other->nickname, - 'href' => $other->profileurl, - 'class' => 'url')); - - $avatar = $other->getAvatar(AVATAR_MINI_SIZE); - - $avatar_url = ($avatar) ? - $avatar->displayUrl() : - Avatar::defaultImage(AVATAR_MINI_SIZE); - - $this->element('img', array('src' => $avatar_url, - 'width' => AVATAR_MINI_SIZE, - 'height' => AVATAR_MINI_SIZE, - 'class' => 'avatar photo', - 'alt' => ($other->fullname) ? - $other->fullname : - $other->nickname)); - - $this->element('span', 'fn nickname', $other->nickname); - $this->elementEnd('a'); - $this->elementEnd('li'); - } $this->elementEnd('ul'); - $this->elementEnd('div'); + if ($flink) { + $this->submit('save', _('Save')); + } else { + $this->submit('add', _('Add')); + } + + $this->elementEnd('fieldset'); } + + $this->elementEnd('form'); } /** @@ -292,7 +194,6 @@ class TwittersettingsAction extends ConnectSettingsAction function handlePost() { - // CSRF protection $token = $this->trimmed('token'); if (!$token || $token != common_session_token()) { @@ -303,8 +204,6 @@ class TwittersettingsAction extends ConnectSettingsAction if ($this->arg('save')) { $this->savePreferences(); - } else if ($this->arg('add')) { - $this->addTwitterAccount(); } else if ($this->arg('remove')) { $this->removeTwitterAccount(); } else { @@ -312,82 +211,6 @@ class TwittersettingsAction extends ConnectSettingsAction } } - /** - * Associate a Twitter account with the user's account - * - * Validates post input; verifies it against Twitter; and if - * successful stores in the database. - * - * @return void - */ - - function addTwitterAccount() - { - $screen_name = $this->trimmed('twitter_username'); - $password = $this->trimmed('twitter_password'); - $noticesend = $this->boolean('noticesend'); - $noticerecv = $this->boolean('noticerecv'); - $replysync = $this->boolean('replysync'); - $friendsync = $this->boolean('friendsync'); - - if (!Validate::string($screen_name, - array('min_length' => 1, - 'max_length' => 15, - 'format' => VALIDATE_NUM.VALIDATE_ALPHA.'_'))) { - $this->showForm(_('Username must have only numbers, '. - 'upper- and lowercase letters, '. - 'and underscore (_). 15 chars max.')); - return; - } - - if (!$this->verifyCredentials($screen_name, $password)) { - $this->showForm(_('Could not verify your Twitter credentials!')); - return; - } - - $twit_user = twitter_user_info($screen_name, $password); - - if (!$twit_user) { - $this->showForm(sprintf(_('Unable to retrieve account information '. - 'For "%s" from Twitter.'), - $screen_name)); - return; - } - - if (!save_twitter_user($twit_user->id, $screen_name)) { - $this->showForm(_('Unable to save your Twitter settings!')); - return; - } - - $user = common_current_user(); - - $flink = new Foreign_link(); - - $flink->user_id = $user->id; - $flink->foreign_id = $twit_user->id; - $flink->service = TWITTER_SERVICE; - $flink->credentials = $password; - $flink->created = common_sql_now(); - - $flink->set_flags($noticesend, $noticerecv, $replysync, $friendsync); - - $flink_id = $flink->insert(); - - if (!$flink_id) { - common_log_db_error($flink, 'INSERT', __FILE__); - $this->showForm(_('Unable to save your Twitter settings!')); - return; - } - - if ($friendsync) { - save_twitter_friends($user, $twit_user->id, $screen_name, $password); - $flink->last_friendsync = common_sql_now(); - $flink->update(); - } - - $this->showForm(_('Twitter settings saved.'), true); - } - /** * Disassociate an existing Twitter account from this account * @@ -397,20 +220,11 @@ class TwittersettingsAction extends ConnectSettingsAction function removeTwitterAccount() { $user = common_current_user(); - - $flink = Foreign_link::getByUserID($user->id, 1); - - $flink_foreign_id = $this->arg('flink_foreign_id'); - - // Maybe an old tab open...? - if ($flink->foreign_id != $flink_foreign_id) { - $this->showForm(_('That is not your Twitter account.')); - return; - } + $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); $result = $flink->delete(); - if (!$result) { + if (empty($result)) { common_log_db_error($flink, 'DELETE', __FILE__); $this->serverError(_('Couldn\'t remove Twitter user.')); return; @@ -433,32 +247,16 @@ class TwittersettingsAction extends ConnectSettingsAction $replysync = $this->boolean('replysync'); $user = common_current_user(); + $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); - $flink = Foreign_link::getByUserID($user->id, 1); - - if (!$flink) { + if (empty($flink)) { common_log_db_error($flink, 'SELECT', __FILE__); $this->showForm(_('Couldn\'t save Twitter preferences.')); return; } - $twitter_id = $flink->foreign_id; - $password = $flink->credentials; - - $fuser = $flink->getForeignUser(); - - if (!$fuser) { - common_log_db_error($fuser, 'SELECT', __FILE__); - $this->showForm(_('Couldn\'t save Twitter preferences.')); - return; - } - - $screen_name = $fuser->nickname; - $original = clone($flink); - $flink->set_flags($noticesend, $noticerecv, $replysync, $friendsync); - $result = $flink->update($original); if ($result === false) { @@ -467,45 +265,7 @@ class TwittersettingsAction extends ConnectSettingsAction return; } - if ($friendsync) { - save_twitter_friends($user, $flink->foreign_id, $screen_name, $password); - } - $this->showForm(_('Twitter preferences saved.'), true); } - /** - * Verifies a username and password against Twitter's API - * - * @param string $screen_name Twitter user name - * @param string $password Twitter password - * - * @return boolean success flag - */ - - function verifyCredentials($screen_name, $password) - { - $uri = 'http://twitter.com/account/verify_credentials.json'; - - $data = get_twitter_data($uri, $screen_name, $password); - - if (!$data) { - return false; - } - - $user = json_decode($data); - - if (!$user) { - return false; - } - - $twitter_id = $user->id; - - if ($twitter_id) { - return $twitter_id; - } - - return false; - } - } -- cgit v1.2.3-54-g00ecf From f94ee5597d09dd46c0580ce043907ea960ace358 Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Tue, 4 Aug 2009 00:46:18 +0000 Subject: Moved some stuff to a base class --- actions/twitterauthorization.php | 2 +- lib/oauthclient.php | 111 +++++++++++++++++++++++++++++++++++++++ lib/twitteroauthclient.php | 98 +++------------------------------- 3 files changed, 118 insertions(+), 93 deletions(-) create mode 100644 lib/oauthclient.php (limited to 'actions') diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php index 519427dac..2390034cd 100644 --- a/actions/twitterauthorization.php +++ b/actions/twitterauthorization.php @@ -80,7 +80,7 @@ class TwitterauthorizationAction extends Action $_SESSION['twitter_request_token_secret'] = $req_tok->key; $auth_link = $client->getAuthorizeLink($req_tok); - + } catch (TwitterOAuthClientException $e) { $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', $e->getCode(), $e->getMessage()); diff --git a/lib/oauthclient.php b/lib/oauthclient.php new file mode 100644 index 000000000..11de991c8 --- /dev/null +++ b/lib/oauthclient.php @@ -0,0 +1,111 @@ +sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); + $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); + $this->token = null; + + if (isset($oauth_token) && isset($oauth_token_secret)) { + $this->token = new OAuthToken($oauth_token, $oauth_token_secret); + } + } + + function getRequestToken() + { + $response = $this->oAuthGet(TwitterOAuthClient::$requestTokenURL); + parse_str($response); + $token = new OAuthToken($oauth_token, $oauth_token_secret); + return $token; + } + + function getAuthorizeLink($request_token, $oauth_callback = null) + { + $url = TwitterOAuthClient::$authorizeURL . '?oauth_token=' . + $request_token->key; + + if (isset($oauth_callback)) { + $url .= '&oauth_callback=' . urlencode($oauth_callback); + } + + return $url; + } + + function getAccessToken() + { + $response = $this->oAuthPost(TwitterOAuthClient::$accessTokenURL); + parse_str($response); + $token = new OAuthToken($oauth_token, $oauth_token_secret); + return $token; + } + + function oAuthGet($url) + { + $request = OAuthRequest::from_consumer_and_token($this->consumer, + $this->token, 'GET', $url, null); + $request->sign_request($this->sha1_method, + $this->consumer, $this->token); + + return $this->httpRequest($request->to_url()); + } + + function oAuthPost($url, $params = null) + { + $request = OAuthRequest::from_consumer_and_token($this->consumer, + $this->token, 'POST', $url, $params); + $request->sign_request($this->sha1_method, + $this->consumer, $this->token); + + return $this->httpRequest($request->get_normalized_http_url(), + $request->to_postdata()); + } + + function httpRequest($url, $params = null) + { + $options = array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_FAILONERROR => true, + CURLOPT_HEADER => false, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_USERAGENT => 'Laconica', + CURLOPT_CONNECTTIMEOUT => 120, + CURLOPT_TIMEOUT => 120, + CURLOPT_HTTPAUTH => CURLAUTH_ANY, + CURLOPT_SSL_VERIFYPEER => false, + + // Twitter is strict about accepting invalid "Expect" headers + + CURLOPT_HTTPHEADER => array('Expect:') + ); + + if (isset($params)) { + $options[CURLOPT_POST] = true; + $options[CURLOPT_POSTFIELDS] = $params; + } + + $ch = curl_init($url); + curl_setopt_array($ch, $options); + $response = curl_exec($ch); + + if ($response === false) { + $msg = curl_error($ch); + $code = curl_errno($ch); + throw new OAuthClientCurlException($msg, $code); + } + + curl_close($ch); + + return $response; + } + +} diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index 63ffe1c7c..e1190f167 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -1,10 +1,6 @@ sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); $consumer_key = common_config('twitter', 'consumer_key'); $consumer_secret = common_config('twitter', 'consumer_secret'); - $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); - $this->token = null; - if (isset($oauth_token) && isset($oauth_token_secret)) { - $this->token = new OAuthToken($oauth_token, $oauth_token_secret); - } + parent::__construct($consumer_key, $consumer_secret, + $oauth_token, $oauth_token_secret); } - function getRequestToken() - { - $response = $this->oAuthGet(TwitterOAuthClient::$requestTokenURL); - parse_str($response); - $token = new OAuthToken($oauth_token, $oauth_token_secret); - return $token; - } - - function getAuthorizeLink($request_token) - { - // Not sure Twitter actually looks at oauth_callback - - return TwitterOAuthClient::$authorizeURL . - '?oauth_token=' . $request_token->key . '&oauth_callback=' . - urlencode(common_local_url('twitterauthorization')); - } + function getAuthorizeLink($request_token) { + return parent::getAuthorizeLink($request_token, + common_local_url('twitterauthorization')); - function getAccessToken() - { - $response = $this->oAuthPost(TwitterOAuthClient::$accessTokenURL); - parse_str($response); - $token = new OAuthToken($oauth_token, $oauth_token_secret); - return $token; } function verify_credentials() @@ -66,63 +39,4 @@ class TwitterOAuthClient return $status; } - function oAuthGet($url) - { - $request = OAuthRequest::from_consumer_and_token($this->consumer, - $this->token, 'GET', $url, null); - $request->sign_request($this->sha1_method, - $this->consumer, $this->token); - - return $this->httpRequest($request->to_url()); - } - - function oAuthPost($url, $params = null) - { - $request = OAuthRequest::from_consumer_and_token($this->consumer, - $this->token, 'POST', $url, $params); - $request->sign_request($this->sha1_method, - $this->consumer, $this->token); - - return $this->httpRequest($request->get_normalized_http_url(), - $request->to_postdata()); - } - - function httpRequest($url, $params = null) - { - $options = array( - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FAILONERROR => true, - CURLOPT_HEADER => false, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_USERAGENT => 'Laconica', - CURLOPT_CONNECTTIMEOUT => 120, - CURLOPT_TIMEOUT => 120, - CURLOPT_HTTPAUTH => CURLAUTH_ANY, - CURLOPT_SSL_VERIFYPEER => false, - - // Twitter is strict about accepting invalid "Expect" headers - - CURLOPT_HTTPHEADER => array('Expect:') - ); - - if (isset($params)) { - $options[CURLOPT_POST] = true; - $options[CURLOPT_POSTFIELDS] = $params; - } - - $ch = curl_init($url); - curl_setopt_array($ch, $options); - $response = curl_exec($ch); - - if ($response === false) { - $msg = curl_error($ch); - $code = curl_errno($ch); - throw new OAuthClientCurlException($msg, $code); - } - - curl_close($ch); - - return $response; - } - } -- cgit v1.2.3-54-g00ecf From df12206421ca74b5c352bb663ca43e9aabe667fd Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Sat, 8 Aug 2009 18:13:19 +0000 Subject: Broke some stuff out into functions. Ran it through phpcs. --- actions/twitterauthorization.php | 174 +++++++++++++++++++++++++++------------ 1 file changed, 120 insertions(+), 54 deletions(-) (limited to 'actions') diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php index 2390034cd..cf27d69cf 100644 --- a/actions/twitterauthorization.php +++ b/actions/twitterauthorization.php @@ -19,7 +19,7 @@ * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . * - * @category TwitterauthorizationAction + * @category Twitter * @package Laconica * @author Zach Copely * @copyright 2009 Control Yourself, Inc. @@ -31,9 +31,31 @@ if (!defined('LACONICA')) { exit(1); } +/** + * Class for doing OAuth authentication against Twitter + * + * Peforms the OAuth "dance" between Laconica and Twitter -- requests a token, + * authorizes it, and exchanges it for an access token. It also creates a link + * (Foreign_link) between the Laconica user and Twitter user and stores the + * access token and secret in the link. + * + * @category Twitter + * @package Laconica + * @author Zach Copley + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * + */ class TwitterauthorizationAction extends Action { + /** + * Initialize class members. Looks for 'oauth_token' parameter. + * + * @param array $args misc. arguments + * + * @return boolean true + */ function prepare($args) { parent::prepare($args); @@ -43,6 +65,13 @@ class TwitterauthorizationAction extends Action return true; } + /** + * Handler method + * + * @param array $args is ignored since it's now passed in in prepare() + * + * @return nothing + */ function handle($args) { parent::handle($args); @@ -51,7 +80,7 @@ class TwitterauthorizationAction extends Action $this->clientError(_('Not logged in.'), 403); } - $user = common_current_user(); + $user = common_current_user(); $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE); // If there's already a foreign link record, it means we already @@ -66,88 +95,125 @@ class TwitterauthorizationAction extends Action // process if (empty($this->oauth_token)) { + $this->authorizeRequestToken(); + } else { + $this->saveAccessToken(); + } + } - try { + /** + * Asks Twitter for a request token, and then redirects to Twitter + * to authorize it. + * + * @return nothing + */ + function authorizeRequestToken() + { + try { - // Get a new request token and authorize it + // Get a new request token and authorize it - $client = new TwitterOAuthClient(); - $req_tok = $client->getRequestToken(); + $client = new TwitterOAuthClient(); + $req_tok = $client->getRequestToken(); - // Sock the request token away in the session temporarily + // Sock the request token away in the session temporarily - $_SESSION['twitter_request_token'] = $req_tok->key; - $_SESSION['twitter_request_token_secret'] = $req_tok->key; + $_SESSION['twitter_request_token'] = $req_tok->key; + $_SESSION['twitter_request_token_secret'] = $req_tok->key; - $auth_link = $client->getAuthorizeLink($req_tok); - - } catch (TwitterOAuthClientException $e) { - $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', - $e->getCode(), $e->getMessage()); - $this->serverError(_('Couldn\'t link your Twitter account.')); - } + $auth_link = $client->getAuthorizeLink($req_tok); - common_redirect($auth_link); + } catch (TwitterOAuthClientException $e) { + $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', + $e->getCode(), $e->getMessage()); + $this->serverError(_('Couldn\'t link your Twitter account.')); + } - } else { + common_redirect($auth_link); + } - // Check to make sure Twitter returned the same request - // token we sent them + /** + * Called when Twitter returns an authorized request token. Exchanges + * it for an access token and stores it. + * + * @return nothing + */ + function saveAccessToken() + { - if ($_SESSION['twitter_request_token'] != $this->oauth_token) { - $this->serverError(_('Couldn\'t link your Twitter account.')); - } + // Check to make sure Twitter returned the same request + // token we sent them - try { + if ($_SESSION['twitter_request_token'] != $this->oauth_token) { + $this->serverError(_('Couldn\'t link your Twitter account.')); + } - $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], - $_SESSION['twitter_request_token_secret']); + try { - // Exchange the request token for an access token + $client = new TwitterOAuthClient($_SESSION['twitter_request_token'], + $_SESSION['twitter_request_token_secret']); - $atok = $client->getAccessToken(); + // Exchange the request token for an access token - // Save the access token and Twitter user info + $atok = $client->getAccessToken(); - $client = new TwitterOAuthClient($atok->key, $atok->secret); + // Test the access token and get the user's Twitter info - $twitter_user = $client->verify_credentials(); + $client = new TwitterOAuthClient($atok->key, $atok->secret); + $twitter_user = $client->verify_credentials(); - } catch (OAuthClientException $e) { - $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s', + } catch (OAuthClientException $e) { + $msg = sprintf('OAuth client cURL error - code: %1$s, msg: %2$s', $e->getCode(), $e->getMessage()); - $this->serverError(_('Couldn\'t link your Twitter account.')); - } + $this->serverError(_('Couldn\'t link your Twitter account.')); + } - $user = common_current_user(); + // Save the access token and Twitter user info - $flink = new Foreign_link(); + $this->saveForeignLink($atok, $twitter_user); - $flink->user_id = $user->id; - $flink->foreign_id = $twitter_user->id; - $flink->service = TWITTER_SERVICE; - $flink->token = $atok->key; - $flink->credentials = $atok->secret; - $flink->created = common_sql_now(); + // Clean up the the mess we made in the session - $flink->set_flags(true, false, false, false); + unset($_SESSION['twitter_request_token']); + unset($_SESSION['twitter_request_token_secret']); - $flink_id = $flink->insert(); + common_redirect(common_local_url('twittersettings')); + } - if (empty($flink_id)) { - common_log_db_error($flink, 'INSERT', __FILE__); - $this->serverError(_('Couldn\'t link your Twitter account.')); - } + /** + * Saves a Foreign_link between Twitter user and local user, + * which includes the access token and secret. + * + * @param OAuthToken $access_token the access token to save + * @param mixed $twitter_user twitter API user object + * + * @return nothing + */ + function saveForeignLink($access_token, $twitter_user) + { + $user = common_current_user(); - save_twitter_user($twitter_user->id, $twitter_user->screen_name); + $flink = new Foreign_link(); - // clean up the the mess we made in the session + $flink->user_id = $user->id; + $flink->foreign_id = $twitter_user->id; + $flink->service = TWITTER_SERVICE; + $flink->token = $access_token->key; + $flink->credentials = $access_token->secret; + $flink->created = common_sql_now(); - unset($_SESSION['twitter_request_token']); - unset($_SESSION['twitter_request_token_secret']); + // Defaults: noticesync on, everything else off - common_redirect(common_local_url('twittersettings')); + $flink->set_flags(true, false, false, false); + + $flink_id = $flink->insert(); + + if (empty($flink_id)) { + common_log_db_error($flink, 'INSERT', __FILE__); + $this->serverError(_('Couldn\'t link your Twitter account.')); } + + save_twitter_user($twitter_user->id, $twitter_user->screen_name); } } -- cgit v1.2.3-54-g00ecf From fa8433308f5ba1209ec490d6c0835d28da18eacb Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Mon, 10 Aug 2009 06:05:43 +0000 Subject: Moved some stuff around. More comments and phpcs compliance. --- actions/twitterauthorization.php | 10 +-- lib/oauthclient.php | 144 ++++++++++++++++++++++++++++++++++---- lib/twitter.php | 2 +- lib/twitteroauthclient.php | 146 +++++++++++++++++++++++++++++++++------ scripts/synctwitterfriends.php | 4 +- scripts/twitterstatusfetcher.php | 4 +- 6 files changed, 264 insertions(+), 46 deletions(-) (limited to 'actions') diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php index cf27d69cf..c40f27164 100644 --- a/actions/twitterauthorization.php +++ b/actions/twitterauthorization.php @@ -48,7 +48,6 @@ if (!defined('LACONICA')) { */ class TwitterauthorizationAction extends Action { - /** * Initialize class members. Looks for 'oauth_token' parameter. * @@ -114,12 +113,13 @@ class TwitterauthorizationAction extends Action // Get a new request token and authorize it $client = new TwitterOAuthClient(); - $req_tok = $client->getRequestToken(); + $req_tok = + $client->getRequestToken(TwitterOAuthClient::$requestTokenURL); // Sock the request token away in the session temporarily $_SESSION['twitter_request_token'] = $req_tok->key; - $_SESSION['twitter_request_token_secret'] = $req_tok->key; + $_SESSION['twitter_request_token_secret'] = $req_tok->secret; $auth_link = $client->getAuthorizeLink($req_tok); @@ -155,12 +155,12 @@ class TwitterauthorizationAction extends Action // Exchange the request token for an access token - $atok = $client->getAccessToken(); + $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL); // Test the access token and get the user's Twitter info $client = new TwitterOAuthClient($atok->key, $atok->secret); - $twitter_user = $client->verify_credentials(); + $twitter_user = $client->verifyCredentials(); } catch (OAuthClientException $e) { $msg = sprintf('OAuth client cURL error - code: %1$s, msg: %2$s', diff --git a/lib/oauthclient.php b/lib/oauthclient.php index 11de991c8..878e47091 100644 --- a/lib/oauthclient.php +++ b/lib/oauthclient.php @@ -1,54 +1,154 @@ . + * + * @category Action + * @package Laconica + * @author Zach Copley + * @copyright 2008 Control Yourself, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +if (!defined('LACONICA')) { + exit(1); +} -require_once('OAuth.php'); - -class OAuthClientCurlException extends Exception { } +require_once 'OAuth.php'; + +/** + * Exception wrapper for cURL errors + * + * @category Integration + * @package Laconica + * @author Zach Copley + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * + */ +class OAuthClientCurlException extends Exception +{ +} +/** + * Base class for doing OAuth calls as a consumer + * + * @category Integration + * @package Laconica + * @author Zach Copley + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * + */ class OAuthClient { var $consumer; var $token; + /** + * Constructor + * + * Can be initialized with just consumer key and secret for requesting new + * tokens or with additional request token or access token + * + * @param string $consumer_key consumer key + * @param string $consumer_secret consumer secret + * @param string $oauth_token user's token + * @param string $oauth_token_secret user's secret + * + * @return nothing + */ function __construct($consumer_key, $consumer_secret, $oauth_token = null, $oauth_token_secret = null) { $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1(); - $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); - $this->token = null; + $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret); + $this->token = null; if (isset($oauth_token) && isset($oauth_token_secret)) { $this->token = new OAuthToken($oauth_token, $oauth_token_secret); } } - function getRequestToken() + /** + * Gets a request token from the given url + * + * @param string $url OAuth endpoint for grabbing request tokens + * + * @return OAuthToken $token the request token + */ + function getRequestToken($url) { - $response = $this->oAuthGet(TwitterOAuthClient::$requestTokenURL); + $response = $this->oAuthGet($url); parse_str($response); $token = new OAuthToken($oauth_token, $oauth_token_secret); return $token; } - function getAuthorizeLink($request_token, $oauth_callback = null) + /** + * Builds a link that can be redirected to in order to + * authorize a request token. + * + * @param string $url endpoint for authorizing request tokens + * @param OAuthToken $request_token the request token to be authorized + * @param string $oauth_callback optional callback url + * + * @return string $authorize_url the url to redirect to + */ + function getAuthorizeLink($url, $request_token, $oauth_callback = null) { - $url = TwitterOAuthClient::$authorizeURL . '?oauth_token=' . + $authorize_url = $url . '?oauth_token=' . $request_token->key; if (isset($oauth_callback)) { - $url .= '&oauth_callback=' . urlencode($oauth_callback); + $authorize_url .= '&oauth_callback=' . urlencode($oauth_callback); } - return $url; + common_debug("$authorize_url"); + + return $authorize_url; } - function getAccessToken() + /** + * Fetches an access token + * + * @param string $url OAuth endpoint for exchanging authorized request tokens + * for access tokens + * + * @return OAuthToken $token the access token + */ + function getAccessToken($url) { - $response = $this->oAuthPost(TwitterOAuthClient::$accessTokenURL); + $response = $this->oAuthPost($url); parse_str($response); $token = new OAuthToken($oauth_token, $oauth_token_secret); return $token; } + /** + * Use HTTP GET to make a signed OAuth request + * + * @param string $url OAuth endpoint + * + * @return mixed the request + */ function oAuthGet($url) { $request = OAuthRequest::from_consumer_and_token($this->consumer, @@ -59,6 +159,14 @@ class OAuthClient return $this->httpRequest($request->to_url()); } + /** + * Use HTTP POST to make a signed OAuth request + * + * @param string $url OAuth endpoint + * @param array $params additional post parameters + * + * @return mixed the request + */ function oAuthPost($url, $params = null) { $request = OAuthRequest::from_consumer_and_token($this->consumer, @@ -70,6 +178,14 @@ class OAuthClient $request->to_postdata()); } + /** + * Make a HTTP request using cURL. + * + * @param string $url Where to make the + * @param array $params post parameters + * + * @return mixed the request + */ function httpRequest($url, $params = null) { $options = array( @@ -89,7 +205,7 @@ class OAuthClient ); if (isset($params)) { - $options[CURLOPT_POST] = true; + $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = $params; } diff --git a/lib/twitter.php b/lib/twitter.php index 345516997..4e2f67c66 100644 --- a/lib/twitter.php +++ b/lib/twitter.php @@ -165,7 +165,7 @@ function broadcast_twitter($notice) $status = null; try { - $status = $client->statuses_update($statustxt); + $status = $client->statusesUpdate($statustxt); } catch (OAuthClientCurlException $e) { if ($e->getMessage() == 'The requested URL returned error: 401') { diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index 2636a3833..c798ac877 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -1,11 +1,60 @@ . + * + * @category Integration + * @package Laconica + * @author Zach Copley + * @copyright 2008 Control Yourself, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +if (!defined('LACONICA')) { + exit(1); +} +/** + * Class for talking to the Twitter API with OAuth. + * + * @category Integration + * @package Laconica + * @author Zach Copley + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + * + */ class TwitterOAuthClient extends OAuthClient { public static $requestTokenURL = 'https://twitter.com/oauth/request_token'; public static $authorizeURL = 'https://twitter.com/oauth/authorize'; public static $accessTokenURL = 'https://twitter.com/oauth/access_token'; + /** + * Constructor + * + * @param string $oauth_token the user's token + * @param string $oauth_token_secret the user's token secret + * + * @return nothing + */ function __construct($oauth_token = null, $oauth_token_secret = null) { $consumer_key = common_config('twitter', 'consumer_key'); @@ -15,39 +64,72 @@ class TwitterOAuthClient extends OAuthClient $oauth_token, $oauth_token_secret); } - function getAuthorizeLink($request_token) { - return parent::getAuthorizeLink($request_token, + /** + * Builds a link to Twitter's endpoint for authorizing a request token + * + * @param OAuthToken $request_token token to authorize + * + * @return the link + */ + function getAuthorizeLink($request_token) + { + return parent::getAuthorizeLink(self::$authorizeURL, + $request_token, common_local_url('twitterauthorization')); - } - function verify_credentials() + /** + * Calls Twitter's /account/verify_credentials API method + * + * @return mixed the Twitter user + */ + function verifyCredentials() { - $url = 'https://twitter.com/account/verify_credentials.json'; - $response = $this->oAuthGet($url); + $url = 'https://twitter.com/account/verify_credentials.json'; + $response = $this->oAuthGet($url); $twitter_user = json_decode($response); return $twitter_user; } - function statuses_update($status, $in_reply_to_status_id = null) + /** + * Calls Twitter's /stutuses/update API method + * + * @param string $status text of the status + * @param int $in_reply_to_status_id optional id of the status it's + * a reply to + * + * @return mixed the status + */ + function statusesUpdate($status, $in_reply_to_status_id = null) { - $url = 'https://twitter.com/statuses/update.json'; - $params = array('status' => $status, + $url = 'https://twitter.com/statuses/update.json'; + $params = array('status' => $status, 'in_reply_to_status_id' => $in_reply_to_status_id); $response = $this->oAuthPost($url, $params); - $status = json_decode($response); + $status = json_decode($response); return $status; } - function statuses_friends_timeline($since_id = null, $max_id = null, - $cnt = null, $page = null) { + /** + * Calls Twitter's /stutuses/friends_timeline API method + * + * @param int $since_id show statuses after this id + * @param int $max_id show statuses before this id + * @param int $cnt number of statuses to show + * @param int $page page number + * + * @return mixed an array of statuses + */ + function statusesFriendsTimeline($since_id = null, $max_id = null, + $cnt = null, $page = null) + { - $url = 'https://twitter.com/statuses/friends_timeline.json'; + $url = 'https://twitter.com/statuses/friends_timeline.json'; $params = array('since_id' => $since_id, 'max_id' => $max_id, 'count' => $cnt, 'page' => $page); - $qry = http_build_query($params); + $qry = http_build_query($params); if (!empty($qry)) { $url .= "?$qry"; @@ -58,8 +140,18 @@ class TwitterOAuthClient extends OAuthClient return $statuses; } - function statuses_friends($id = null, $user_id = null, $screen_name = null, - $page = null) + /** + * Calls Twitter's /stutuses/friends API method + * + * @param int $id id of the user whom you wish to see friends of + * @param int $user_id numerical user id + * @param int $screen_name screen name + * @param int $page page number + * + * @return mixed an array of twitter users and their latest status + */ + function statusesFriends($id = null, $user_id = null, $screen_name = null, + $page = null) { $url = "https://twitter.com/statuses/friends.json"; @@ -67,18 +159,28 @@ class TwitterOAuthClient extends OAuthClient 'user_id' => $user_id, 'screen_name' => $screen_name, 'page' => $page); - $qry = http_build_query($params); + $qry = http_build_query($params); if (!empty($qry)) { $url .= "?$qry"; } $response = $this->oAuthGet($url); - $ids = json_decode($response); - return $ids; + $friends = json_decode($response); + return $friends; } - function friends_ids($id = null, $user_id = null, $screen_name = null, + /** + * Calls Twitter's /stutuses/friends/ids API method + * + * @param int $id id of the user whom you wish to see friends of + * @param int $user_id numerical user id + * @param int $screen_name screen name + * @param int $page page number + * + * @return mixed a list of ids, 100 per page + */ + function friendsIds($id = null, $user_id = null, $screen_name = null, $page = null) { $url = "https://twitter.com/friends/ids.json"; @@ -87,14 +189,14 @@ class TwitterOAuthClient extends OAuthClient 'user_id' => $user_id, 'screen_name' => $screen_name, 'page' => $page); - $qry = http_build_query($params); + $qry = http_build_query($params); if (!empty($qry)) { $url .= "?$qry"; } $response = $this->oAuthGet($url); - $ids = json_decode($response); + $ids = json_decode($response); return $ids; } diff --git a/scripts/synctwitterfriends.php b/scripts/synctwitterfriends.php index 37f7842a1..39b9ad612 100755 --- a/scripts/synctwitterfriends.php +++ b/scripts/synctwitterfriends.php @@ -145,7 +145,7 @@ class SyncTwitterFriendsDaemon extends ParallelizingDaemon $client = new TwitterOAuthClient($flink->token, $flink->credentials); try { - $friends_ids = $client->friends_ids(); + $friends_ids = $client->friendsIds(); } catch (OAuthCurlException $e) { common_log(LOG_WARNING, $this->name() . ' - cURL error getting friend ids ' . @@ -174,7 +174,7 @@ class SyncTwitterFriendsDaemon extends ParallelizingDaemon for ($i = 1; $i <= $pages; $i++) { try { - $more_friends = $client->statuses_friends(null, null, null, $i); + $more_friends = $client->statusesFriends(null, null, null, $i); } catch (OAuthCurlException $e) { common_log(LOG_WARNING, $this->name() . ' - cURL error getting Twitter statuses/friends ' . diff --git a/scripts/twitterstatusfetcher.php b/scripts/twitterstatusfetcher.php index fa37f894c..e04a8993f 100755 --- a/scripts/twitterstatusfetcher.php +++ b/scripts/twitterstatusfetcher.php @@ -166,7 +166,7 @@ class TwitterStatusFetcher extends ParallelizingDaemon $timeline = null; try { - $timeline = $client->statuses_friends_timeline(); + $timeline = $client->statusesFriendsTimeline(); } catch (OAuthClientCurlException $e) { common_log(LOG_WARNING, $this->name() . ' - OAuth client unable to get friends timeline for user ' . @@ -175,7 +175,7 @@ class TwitterStatusFetcher extends ParallelizingDaemon } if (empty($timeline)) { - common_log(LOG_WARNING, $this->name . " - Empty timeline."); + common_log(LOG_WARNING, $this->name() . " - Empty timeline."); return; } -- cgit v1.2.3-54-g00ecf From 27548c690350bdf0376d846a5e8e86477359297d Mon Sep 17 00:00:00 2001 From: Zach Copley Date: Mon, 10 Aug 2009 07:00:59 +0000 Subject: I forgot that we don't do database upgrades for point releases. So I've changed Twitter OAuth to store token and token secret in the same field in foreign_link (credentials). This should be changed in 0.9. --- actions/twitterauthorization.php | 8 +++++--- lib/oauthclient.php | 2 -- lib/twitter.php | 4 +++- lib/twitteroauthclient.php | 17 +++++++++++++++++ scripts/synctwitterfriends.php | 4 +++- scripts/twitterstatusfetcher.php | 4 +++- 6 files changed, 31 insertions(+), 8 deletions(-) (limited to 'actions') diff --git a/actions/twitterauthorization.php b/actions/twitterauthorization.php index c40f27164..b04f35327 100644 --- a/actions/twitterauthorization.php +++ b/actions/twitterauthorization.php @@ -113,7 +113,7 @@ class TwitterauthorizationAction extends Action // Get a new request token and authorize it $client = new TwitterOAuthClient(); - $req_tok = + $req_tok = $client->getRequestToken(TwitterOAuthClient::$requestTokenURL); // Sock the request token away in the session temporarily @@ -198,8 +198,10 @@ class TwitterauthorizationAction extends Action $flink->user_id = $user->id; $flink->foreign_id = $twitter_user->id; $flink->service = TWITTER_SERVICE; - $flink->token = $access_token->key; - $flink->credentials = $access_token->secret; + + $creds = TwitterOAuthClient::packToken($access_token); + + $flink->credentials = $creds; $flink->created = common_sql_now(); // Defaults: noticesync on, everything else off diff --git a/lib/oauthclient.php b/lib/oauthclient.php index 878e47091..b66a24be4 100644 --- a/lib/oauthclient.php +++ b/lib/oauthclient.php @@ -121,8 +121,6 @@ class OAuthClient $authorize_url .= '&oauth_callback=' . urlencode($oauth_callback); } - common_debug("$authorize_url"); - return $authorize_url; } diff --git a/lib/twitter.php b/lib/twitter.php index 4e2f67c66..280cdb0a3 100644 --- a/lib/twitter.php +++ b/lib/twitter.php @@ -160,7 +160,9 @@ function broadcast_twitter($notice) // XXX: Hack to get around PHP cURL's use of @ being a a meta character $statustxt = preg_replace('/^@/', ' @', $notice->content); - $client = new TwitterOAuthClient($flink->token, $flink->credentials); + $token = TwitterOAuthClient::unpackToken($flink->credentials); + + $client = new TwitterOAuthClient($token->key, $token->secret); $status = null; diff --git a/lib/twitteroauthclient.php b/lib/twitteroauthclient.php index c798ac877..b7dc4a80c 100644 --- a/lib/twitteroauthclient.php +++ b/lib/twitteroauthclient.php @@ -64,6 +64,23 @@ class TwitterOAuthClient extends OAuthClient $oauth_token, $oauth_token_secret); } + // XXX: the following two functions are to support the horrible hack + // of using the credentils field in Foreign_link to store both + // the access token and token secret. This hack should go away with + // 0.9, in which we can make DB changes and add a new column for the + // token itself. + + static function packToken($token) + { + return implode(chr(0), array($token->key, $token->secret)); + } + + static function unpackToken($str) + { + $vals = explode(chr(0), $str); + return new OAuthToken($vals[0], $vals[1]); + } + /** * Builds a link to Twitter's endpoint for authorizing a request token * diff --git a/scripts/synctwitterfriends.php b/scripts/synctwitterfriends.php index 39b9ad612..d13500e97 100755 --- a/scripts/synctwitterfriends.php +++ b/scripts/synctwitterfriends.php @@ -142,7 +142,9 @@ class SyncTwitterFriendsDaemon extends ParallelizingDaemon { $friends = array(); - $client = new TwitterOAuthClient($flink->token, $flink->credentials); + $token = TwitterOAuthClient::unpackToken($flink->credentials); + + $client = new TwitterOAuthClient($token->key, $token->secret); try { $friends_ids = $client->friendsIds(); diff --git a/scripts/twitterstatusfetcher.php b/scripts/twitterstatusfetcher.php index e04a8993f..f5289c5f4 100755 --- a/scripts/twitterstatusfetcher.php +++ b/scripts/twitterstatusfetcher.php @@ -161,7 +161,9 @@ class TwitterStatusFetcher extends ParallelizingDaemon // to start importing? How many statuses? Right now I'm going // with the default last 20. - $client = new TwitterOAuthClient($flink->token, $flink->credentials); + $token = TwitterOAuthClient::unpackToken($flink->credentials); + + $client = new TwitterOAuthClient($token->key, $token->secret); $timeline = null; -- cgit v1.2.3-54-g00ecf