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('GNUSOCIAL')) { exit(1); }
31 require_once __DIR__ . '/twitter.php';
34 * Plugin for sending and importing Twitter statuses
36 * This class allows users to link their Twitter accounts
38 * Depends on Favorite plugin.
42 * @author Zach Copley <zach@status.net>
43 * @author Julien C <chaumond@gmail.com>
44 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45 * @link http://status.net/
46 * @link http://twitter.com/
48 class TwitterBridgePlugin extends Plugin
50 const VERSION = GNUSOCIAL_VERSION;
51 public $adminImportControl = false; // Should the 'import' checkbox be exposed in the admin panel?
54 * Initializer for the plugin.
58 // Allow the key and secret to be passed in
59 // Control panel will override
61 if (isset($this->consumer_key)) {
62 $key = common_config('twitter', 'consumer_key');
64 Config::save('twitter', 'consumer_key', $this->consumer_key);
68 if (isset($this->consumer_secret)) {
69 $secret = common_config('twitter', 'consumer_secret');
74 $this->consumer_secret
81 * Check to see if there is a consumer key and secret defined
82 * for Twitter integration.
84 * @return boolean result
86 static function hasKeys()
88 $ckey = common_config('twitter', 'consumer_key');
89 $csecret = common_config('twitter', 'consumer_secret');
91 if (empty($ckey) && empty($csecret)) {
92 $ckey = common_config('twitter', 'global_consumer_key');
93 $csecret = common_config('twitter', 'global_consumer_secret');
96 if (!empty($ckey) && !empty($csecret)) {
104 * Add Twitter-related paths to the router table
106 * Hook for RouterInitialized event.
108 * @param URLMapper $m path-to-action mapper
110 * @return boolean hook return
112 public function onRouterInitialized(URLMapper $m)
114 $m->connect('panel/twitter', array('action' => 'twitteradminpanel'));
116 if (self::hasKeys()) {
118 'twitter/authorization',
119 array('action' => 'twitterauthorization')
122 'settings/twitter', array(
123 'action' => 'twittersettings'
126 if (common_config('twitter', 'signin')) {
129 array('action' => 'twitterlogin')
138 * Add a login tab for 'Sign in with Twitter'
140 * @param Action $action the current action
144 function onEndLoginGroupNav($action)
146 $action_name = $action->trimmed('action');
148 if (self::hasKeys() && common_config('twitter', 'signin')) {
150 common_local_url('twitterlogin'),
151 // TRANS: Menu item in login navigation.
152 _m('MENU','Twitter'),
153 // TRANS: Title for menu item in login navigation.
154 _m('Login or register using Twitter.'),
155 'twitterlogin' === $action_name
163 * Add the Twitter Settings page to the Connect Settings menu
165 * @param Action $action The calling page
167 * @return boolean hook return
169 function onEndConnectSettingsNav($action)
171 if (self::hasKeys()) {
172 $action_name = $action->trimmed('action');
175 common_local_url('twittersettings'),
176 // TRANS: Menu item in connection settings navigation.
177 _m('MENU','Twitter'),
178 // TRANS: Title for menu item in connection settings navigation.
179 _m('Twitter integration options'),
180 $action_name === 'twittersettings'
187 * Add a Twitter queue item for each notice
189 * @param Notice $notice the notice
190 * @param array &$transports the list of transports (queues)
192 * @return boolean hook return
194 function onStartEnqueueNotice($notice, &$transports)
196 if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
197 // Avoid a possible loop
198 if ($notice->source != 'twitter') {
199 array_push($transports, 'twitter');
206 * Add Twitter bridge daemons to the list of daemons to start
208 * @param array $daemons the list fo daemons to run
210 * @return boolean hook return
212 function onGetValidDaemons(&$daemons)
214 if (self::hasKeys()) {
218 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
220 if (common_config('twitterimport', 'enabled')) {
224 . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
233 * Register Twitter notice queue handler
235 * @param QueueManager $manager
237 * @return boolean hook return
239 function onEndInitializeQueueManager($manager)
241 if (self::hasKeys()) {
242 // Outgoing notices -> twitter
243 $manager->connect('twitter', 'TwitterQueueHandler');
245 // Incoming statuses <- twitter
246 $manager->connect('tweetin', 'TweetInQueueHandler');
252 * If the plugin's installed, this should be accessible to admins
254 function onAdminPanelCheck($name, &$isOK)
256 if ($name == 'twitter') {
264 * Add a Twitter tab to the admin panel
266 * @param Widget $nav Admin panel nav
268 * @return boolean hook value
271 function onEndAdminPanelNav($nav)
273 if (AdminPanelAction::canAdmin('twitter')) {
275 $action_name = $nav->action->trimmed('action');
278 common_local_url('twitteradminpanel'),
279 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
281 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
282 _m('Twitter bridge configuration page.'),
283 $action_name == 'twitteradminpanel',
284 'nav_twitter_admin_panel'
292 * Plugin version data
294 * @param array &$versions array of version blocks
296 * @return boolean hook value
298 function onPluginVersion(array &$versions)
301 'name' => 'TwitterBridge',
302 'version' => self::VERSION,
303 'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
304 'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
305 // TRANS: Plugin description.
306 'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
307 'of a StatusNet instance with ' .
308 '<a href="http://twitter.com/">Twitter</a>.'
315 * Expose the adminImportControl setting to the administration panel code.
316 * This allows us to disable the import bridge enabling checkbox for administrators,
317 * since on a bulk farm site we can't yet automate the import daemon setup.
319 * @return boolean hook value;
321 function onTwitterBridgeAdminImportControl()
323 return (bool)$this->adminImportControl;
327 * When the site is set to ssl=sometimes mode, we should make sure our
328 * various auth-related pages are on SSL to keep things looking happy.
329 * Although we're not submitting passwords directly, we do link out to
330 * an authentication source and it's a lot happier if we've got some
331 * protection against MitM.
333 * @param string $action name
334 * @param boolean $ssl outval to force SSL
335 * @return mixed hook return value
337 function onSensitiveAction($action, &$ssl)
339 $sensitive = array('twitteradminpanel',
341 'twitterauthorization',
343 if (in_array($action, $sensitive)) {
352 * Database schema setup
354 * We maintain a table mapping StatusNet notices to Twitter statuses
359 * @return boolean hook value; true means continue processing, false means stop.
361 function onCheckSchema()
363 $schema = Schema::get();
365 // For saving the last-synched status of various timelines
366 // home_timeline, messages (in), messages (out), ...
367 $schema->ensureTable('twitter_synch_status', Twitter_synch_status::schemaDef());
369 // For storing user-submitted flags on profiles
370 $schema->ensureTable('notice_to_status', Notice_to_status::schemaDef());
376 * If a notice gets deleted, remove the Notice_to_status mapping and
377 * delete the status on Twitter.
379 * @param User $user The user doing the deleting
380 * @param Notice $notice The notice getting deleted
382 * @return boolean hook value
384 function onStartDeleteOwnNotice(User $user, Notice $notice)
386 $n2s = Notice_to_status::getKV('notice_id', $notice->id);
388 if ($n2s instanceof Notice_to_status) {
391 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); // twitter service
392 } catch (NoResultException $e) {
396 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
397 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
402 $token = TwitterOAuthClient::unpackToken($flink->credentials);
403 $client = new TwitterOAuthClient($token->key, $token->secret);
405 $client->statusesDestroy($n2s->status_id);
406 } catch (Exception $e) {
407 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
416 * Notify remote users when their notices get favorited.
418 * @param Profile or User $profile of local user doing the faving
419 * @param Notice $notice being favored
420 * @return hook return value
422 function onEndFavorNotice(Profile $profile, Notice $notice)
425 $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
426 } catch (NoResultException $e) {
430 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
431 $this->log(LOG_INFO, "Skipping fave processing for {$profile->getID()} since link is not OAuth.");
435 $status_id = twitter_status_id($notice);
437 if (empty($status_id)) {
442 $token = TwitterOAuthClient::unpackToken($flink->credentials);
443 $client = new TwitterOAuthClient($token->key, $token->secret);
445 $client->favoritesCreate($status_id);
446 } catch (Exception $e) {
447 common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
454 * Notify remote users when their notices get de-favorited.
456 * @param Profile $profile Profile person doing the de-faving
457 * @param Notice $notice Notice being favored
459 * @return hook return value
461 function onEndDisfavorNotice(Profile $profile, Notice $notice)
464 $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
465 } catch (NoResultException $e) {
469 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
470 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
474 $status_id = twitter_status_id($notice);
476 if (empty($status_id)) {
481 $token = TwitterOAuthClient::unpackToken($flink->credentials);
482 $client = new TwitterOAuthClient($token->key, $token->secret);
484 $client->favoritesDestroy($status_id);
485 } catch (Exception $e) {
486 common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
492 function onStartGetProfileUri($profile, &$uri)
494 if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
495 $uri = $profile->profileurl;
502 * Add links in the user's profile block to their Twitter profile URL.
504 * @param Profile $profile The profile being shown
505 * @param Array &$links Writeable array of arrays (href, text, image).
507 * @return boolean hook value (true)
510 function onOtherAccountProfiles($profile, &$links)
515 $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
516 $fuser = $flink->getForeignUser();
518 $links[] = array("href" => $fuser->uri,
519 "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
520 "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
521 } catch (NoResultException $e) {
522 // no foreign link and/or user for Twitter on this profile ID
528 public function onEndShowHeadElements(Action $action)
530 if (!($action instanceof AttachmentAction)) {
534 /* Twitter card support. See https://dev.twitter.com/docs/cards */
535 /* @fixme: should we display twitter cards only for attachments posted
536 * by local users ? Seems mandatory to display twitter:creator
540 switch ($action->attachment->mimetype) {
546 $action->element('meta', array('name' => 'twitter:card',
547 'content' => 'photo'),
549 $action->element('meta', array('name' => 'twitter:url',
550 'content' => common_local_url('attachment',
551 array('attachment' => $action->attachment->id))),
553 $action->element('meta', array('name' => 'twitter:image',
554 'content' => $action->attachment->url));
555 $action->element('meta', array('name' => 'twitter:title',
556 'content' => $action->attachment->title));
558 $ns = new AttachmentNoticeSection($action);
559 $notices = $ns->getNotices();
560 $noticeArray = $notices->fetchAll();
562 // Should not have more than 1 notice for this attachment.
563 if( count($noticeArray) != 1 ) { break; }
564 $post = $noticeArray[0];
567 $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
568 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
569 $action->element('meta', array('name' => 'twitter:creator',
570 'content' => '@'.$fuser->nickname));
571 } catch (NoResultException $e) {
572 // no foreign link and/or user for Twitter on this profile ID