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' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/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 * Database schema setup
329 * We maintain a table mapping StatusNet notices to Twitter statuses
334 * @return boolean hook value; true means continue processing, false means stop.
336 function onCheckSchema()
338 $schema = Schema::get();
340 // For saving the last-synched status of various timelines
341 // home_timeline, messages (in), messages (out), ...
342 $schema->ensureTable('twitter_synch_status', Twitter_synch_status::schemaDef());
344 // For storing user-submitted flags on profiles
345 $schema->ensureTable('notice_to_status', Notice_to_status::schemaDef());
351 * If a notice gets deleted, remove the Notice_to_status mapping and
352 * delete the status on Twitter.
354 * @param User $user The user doing the deleting
355 * @param Notice $notice The notice getting deleted
357 * @return boolean hook value
359 function onStartDeleteOwnNotice(User $user, Notice $notice)
361 $n2s = Notice_to_status::getKV('notice_id', $notice->id);
363 if ($n2s instanceof Notice_to_status) {
366 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); // twitter service
367 } catch (NoResultException $e) {
371 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
372 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
377 $token = TwitterOAuthClient::unpackToken($flink->credentials);
378 $client = new TwitterOAuthClient($token->key, $token->secret);
380 $client->statusesDestroy($n2s->status_id);
381 } catch (Exception $e) {
382 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
391 * Notify remote users when their notices get favorited.
393 * @param Profile or User $profile of local user doing the faving
394 * @param Notice $notice being favored
395 * @return hook return value
397 function onEndFavorNotice(Profile $profile, Notice $notice)
400 $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
401 } catch (NoResultException $e) {
405 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
406 $this->log(LOG_INFO, "Skipping fave processing for {$profile->getID()} since link is not OAuth.");
410 $status_id = twitter_status_id($notice);
412 if (empty($status_id)) {
417 $token = TwitterOAuthClient::unpackToken($flink->credentials);
418 $client = new TwitterOAuthClient($token->key, $token->secret);
420 $client->favoritesCreate($status_id);
421 } catch (Exception $e) {
422 common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
429 * Notify remote users when their notices get de-favorited.
431 * @param Profile $profile Profile person doing the de-faving
432 * @param Notice $notice Notice being favored
434 * @return hook return value
436 function onEndDisfavorNotice(Profile $profile, Notice $notice)
439 $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
440 } catch (NoResultException $e) {
444 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
445 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
449 $status_id = twitter_status_id($notice);
451 if (empty($status_id)) {
456 $token = TwitterOAuthClient::unpackToken($flink->credentials);
457 $client = new TwitterOAuthClient($token->key, $token->secret);
459 $client->favoritesDestroy($status_id);
460 } catch (Exception $e) {
461 common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
467 function onStartGetProfileUri($profile, &$uri)
469 if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
470 $uri = $profile->profileurl;
477 * Add links in the user's profile block to their Twitter profile URL.
479 * @param Profile $profile The profile being shown
480 * @param Array &$links Writeable array of arrays (href, text, image).
482 * @return boolean hook value (true)
485 function onOtherAccountProfiles($profile, &$links)
490 $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
491 $fuser = $flink->getForeignUser();
493 $links[] = array("href" => $fuser->uri,
494 "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
495 "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
496 } catch (NoResultException $e) {
497 // no foreign link and/or user for Twitter on this profile ID
503 public function onEndShowHeadElements(Action $action)
505 if($action instanceof ShowNoticeAction) { // Showing a notice
506 $notice = Notice::getKV('id', $action->arg('notice'));
509 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE);
510 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
511 } catch (NoResultException $e) {
515 $statusId = twitter_status_id($notice);
516 if($notice instanceof Notice && $notice->isLocal() && $statusId) {
517 $tweetUrl = 'https://twitter.com/' . $fuser->nickname . '/status/' . $statusId;
518 $action->element('link', array('rel' => 'syndication', 'href' => $tweetUrl));
522 if (!($action instanceof AttachmentAction)) {
526 /* Twitter card support. See https://dev.twitter.com/docs/cards */
527 /* @fixme: should we display twitter cards only for attachments posted
528 * by local users ? Seems mandatory to display twitter:creator
532 switch ($action->attachment->mimetype) {
538 $action->element('meta', array('name' => 'twitter:card',
539 'content' => 'photo'),
541 $action->element('meta', array('name' => 'twitter:url',
542 'content' => common_local_url('attachment',
543 array('attachment' => $action->attachment->id))),
545 $action->element('meta', array('name' => 'twitter:image',
546 'content' => $action->attachment->url));
547 $action->element('meta', array('name' => 'twitter:title',
548 'content' => $action->attachment->title));
550 $ns = new AttachmentNoticeSection($action);
551 $notices = $ns->getNotices();
552 $noticeArray = $notices->fetchAll();
554 // Should not have more than 1 notice for this attachment.
555 if( count($noticeArray) != 1 ) { break; }
556 $post = $noticeArray[0];
559 $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
560 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
561 $action->element('meta', array('name' => 'twitter:creator',
562 'content' => '@'.$fuser->nickname));
563 } catch (NoResultException $e) {
564 // no foreign link and/or user for Twitter on this profile ID