3 * StatusNet, the distributed open-source microblogging tool
7 * LICENCE: This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 * @author Zach Copley <zach@status.net>
23 * @author Julien C <chaumond@gmail.com>
24 * @copyright 2009-2010 Control Yourself, Inc.
25 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
26 * @link http://status.net/
29 if (!defined('STATUSNET')) {
33 require_once __DIR__ . '/twitter.php';
36 * Plugin for sending and importing Twitter statuses
38 * This class allows users to link their Twitter accounts
40 * Depends on Favorite plugin.
44 * @author Zach Copley <zach@status.net>
45 * @author Julien C <chaumond@gmail.com>
46 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47 * @link http://status.net/
48 * @link http://twitter.com/
50 class TwitterBridgePlugin extends Plugin
52 const VERSION = GNUSOCIAL_VERSION;
53 public $adminImportControl = false; // Should the 'import' checkbox be exposed in the admin panel?
56 * Initializer for the plugin.
60 // Allow the key and secret to be passed in
61 // Control panel will override
63 if (isset($this->consumer_key)) {
64 $key = common_config('twitter', 'consumer_key');
66 Config::save('twitter', 'consumer_key', $this->consumer_key);
70 if (isset($this->consumer_secret)) {
71 $secret = common_config('twitter', 'consumer_secret');
76 $this->consumer_secret
83 * Check to see if there is a consumer key and secret defined
84 * for Twitter integration.
86 * @return boolean result
88 static function hasKeys()
90 $ckey = common_config('twitter', 'consumer_key');
91 $csecret = common_config('twitter', 'consumer_secret');
93 if (empty($ckey) && empty($csecret)) {
94 $ckey = common_config('twitter', 'global_consumer_key');
95 $csecret = common_config('twitter', 'global_consumer_secret');
98 if (!empty($ckey) && !empty($csecret)) {
106 * Add Twitter-related paths to the router table
108 * Hook for RouterInitialized event.
110 * @param URLMapper $m path-to-action mapper
112 * @return boolean hook return
114 public function onRouterInitialized(URLMapper $m)
116 $m->connect('panel/twitter', array('action' => 'twitteradminpanel'));
118 if (self::hasKeys()) {
120 'twitter/authorization',
121 array('action' => 'twitterauthorization')
124 'settings/twitter', array(
125 'action' => 'twittersettings'
128 if (common_config('twitter', 'signin')) {
131 array('action' => 'twitterlogin')
140 * Add a login tab for 'Sign in with Twitter'
142 * @param Action $action the current action
146 function onEndLoginGroupNav($action)
148 $action_name = $action->trimmed('action');
150 if (self::hasKeys() && common_config('twitter', 'signin')) {
152 common_local_url('twitterlogin'),
153 // TRANS: Menu item in login navigation.
154 _m('MENU','Twitter'),
155 // TRANS: Title for menu item in login navigation.
156 _m('Login or register using Twitter.'),
157 'twitterlogin' === $action_name
165 * Add the Twitter Settings page to the Connect Settings menu
167 * @param Action $action The calling page
169 * @return boolean hook return
171 function onEndConnectSettingsNav($action)
173 if (self::hasKeys()) {
174 $action_name = $action->trimmed('action');
177 common_local_url('twittersettings'),
178 // TRANS: Menu item in connection settings navigation.
179 _m('MENU','Twitter'),
180 // TRANS: Title for menu item in connection settings navigation.
181 _m('Twitter integration options'),
182 $action_name === 'twittersettings'
189 * Add a Twitter queue item for each notice
191 * @param Notice $notice the notice
192 * @param array &$transports the list of transports (queues)
194 * @return boolean hook return
196 function onStartEnqueueNotice($notice, &$transports)
198 if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
199 // Avoid a possible loop
200 if ($notice->source != 'twitter') {
201 array_push($transports, 'twitter');
208 * Add Twitter bridge daemons to the list of daemons to start
210 * @param array $daemons the list fo daemons to run
212 * @return boolean hook return
214 function onGetValidDaemons(&$daemons)
216 if (self::hasKeys()) {
220 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
222 if (common_config('twitterimport', 'enabled')) {
226 . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
235 * Register Twitter notice queue handler
237 * @param QueueManager $manager
239 * @return boolean hook return
241 function onEndInitializeQueueManager($manager)
243 if (self::hasKeys()) {
244 // Outgoing notices -> twitter
245 $manager->connect('twitter', 'TwitterQueueHandler');
247 // Incoming statuses <- twitter
248 $manager->connect('tweetin', 'TweetInQueueHandler');
254 * If the plugin's installed, this should be accessible to admins
256 function onAdminPanelCheck($name, &$isOK)
258 if ($name == 'twitter') {
266 * Add a Twitter tab to the admin panel
268 * @param Widget $nav Admin panel nav
270 * @return boolean hook value
273 function onEndAdminPanelNav($nav)
275 if (AdminPanelAction::canAdmin('twitter')) {
277 $action_name = $nav->action->trimmed('action');
280 common_local_url('twitteradminpanel'),
281 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
283 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
284 _m('Twitter bridge configuration page.'),
285 $action_name == 'twitteradminpanel',
286 'nav_twitter_admin_panel'
294 * Plugin version data
296 * @param array &$versions array of version blocks
298 * @return boolean hook value
300 function onPluginVersion(array &$versions)
303 'name' => 'TwitterBridge',
304 'version' => self::VERSION,
305 'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
306 'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
307 // TRANS: Plugin description.
308 'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
309 'of a StatusNet instance with ' .
310 '<a href="http://twitter.com/">Twitter</a>.'
317 * Expose the adminImportControl setting to the administration panel code.
318 * This allows us to disable the import bridge enabling checkbox for administrators,
319 * since on a bulk farm site we can't yet automate the import daemon setup.
321 * @return boolean hook value;
323 function onTwitterBridgeAdminImportControl()
325 return (bool)$this->adminImportControl;
329 * When the site is set to ssl=sometimes mode, we should make sure our
330 * various auth-related pages are on SSL to keep things looking happy.
331 * Although we're not submitting passwords directly, we do link out to
332 * an authentication source and it's a lot happier if we've got some
333 * protection against MitM.
335 * @param string $action name
336 * @param boolean $ssl outval to force SSL
337 * @return mixed hook return value
339 function onSensitiveAction($action, &$ssl)
341 $sensitive = array('twitteradminpanel',
343 'twitterauthorization',
345 if (in_array($action, $sensitive)) {
354 * Database schema setup
356 * We maintain a table mapping StatusNet notices to Twitter statuses
361 * @return boolean hook value; true means continue processing, false means stop.
363 function onCheckSchema()
365 $schema = Schema::get();
367 // For saving the last-synched status of various timelines
368 // home_timeline, messages (in), messages (out), ...
369 $schema->ensureTable('twitter_synch_status', Twitter_synch_status::schemaDef());
371 // For storing user-submitted flags on profiles
372 $schema->ensureTable('notice_to_status', Notice_to_status::schemaDef());
378 * If a notice gets deleted, remove the Notice_to_status mapping and
379 * delete the status on Twitter.
381 * @param User $user The user doing the deleting
382 * @param Notice $notice The notice getting deleted
384 * @return boolean hook value
386 function onStartDeleteOwnNotice(User $user, Notice $notice)
388 $n2s = Notice_to_status::getKV('notice_id', $notice->id);
392 $flink = Foreign_link::getByUserID($notice->profile_id,
393 TWITTER_SERVICE); // twitter service
399 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
400 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
405 $token = TwitterOAuthClient::unpackToken($flink->credentials);
406 $client = new TwitterOAuthClient($token->key, $token->secret);
408 $client->statusesDestroy($n2s->status_id);
409 } catch (Exception $e) {
410 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
419 * Notify remote users when their notices get favorited.
421 * @param Profile or User $profile of local user doing the faving
422 * @param Notice $notice being favored
423 * @return hook return value
425 function onEndFavorNotice(Profile $profile, Notice $notice)
427 $flink = Foreign_link::getByUserID($profile->id,
428 TWITTER_SERVICE); // twitter service
434 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
435 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
439 $status_id = twitter_status_id($notice);
441 if (empty($status_id)) {
446 $token = TwitterOAuthClient::unpackToken($flink->credentials);
447 $client = new TwitterOAuthClient($token->key, $token->secret);
449 $client->favoritesCreate($status_id);
450 } catch (Exception $e) {
451 common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
458 * Notify remote users when their notices get de-favorited.
460 * @param Profile $profile Profile person doing the de-faving
461 * @param Notice $notice Notice being favored
463 * @return hook return value
465 function onEndDisfavorNotice(Profile $profile, Notice $notice)
467 $flink = Foreign_link::getByUserID($profile->id,
468 TWITTER_SERVICE); // twitter service
474 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
475 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
479 $status_id = twitter_status_id($notice);
481 if (empty($status_id)) {
486 $token = TwitterOAuthClient::unpackToken($flink->credentials);
487 $client = new TwitterOAuthClient($token->key, $token->secret);
489 $client->favoritesDestroy($status_id);
490 } catch (Exception $e) {
491 common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
497 function onStartGetProfileUri($profile, &$uri)
499 if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
500 $uri = $profile->profileurl;
507 * Add links in the user's profile block to their Twitter profile URL.
509 * @param Profile $profile The profile being shown
510 * @param Array &$links Writeable array of arrays (href, text, image).
512 * @return boolean hook value (true)
515 function onOtherAccountProfiles($profile, &$links)
519 $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
521 if (!empty($flink)) {
522 $fuser = $flink->getForeignUser();
524 if (!empty($fuser)) {
525 $links[] = array("href" => $fuser->uri,
526 "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
527 "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
534 public function onEndShowHeadElements(Action $action)
536 if (!($action instanceof AttachmentAction)) {
540 /* Twitter card support. See https://dev.twitter.com/docs/cards */
541 /* @fixme: should we display twitter cards only for attachments posted
542 * by local users ? Seems mandatory to display twitter:creator
546 switch ($action->attachment->mimetype) {
552 $action->element('meta', array('name' => 'twitter:card',
553 'content' => 'photo'),
555 $action->element('meta', array('name' => 'twitter:url',
556 'content' => common_local_url('attachment',
557 array('attachment' => $action->attachment->id))),
559 $action->element('meta', array('name' => 'twitter:image',
560 'content' => $action->attachment->url));
561 $action->element('meta', array('name' => 'twitter:title',
562 'content' => $action->attachment->title));
564 $ns = new AttachmentNoticeSection($action);
565 $notices = $ns->getNotices();
566 $noticeArray = $notices->fetchAll();
568 // Should not have more than 1 notice for this attachment.
569 if( count($noticeArray) != 1 ) { break; }
570 $post = $noticeArray[0];
572 $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
573 if( $flink ) { // Our local user has registered Twitter Gateway
574 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
575 if( $fuser ) { // Got nickname for local user's Twitter account
576 $action->element('meta', array('name' => 'twitter:creator',
577 'content' => '@'.$fuser->nickname));