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 PLUGIN_VERSION = '2.0.0';
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', ['action' => 'twitteradminpanel']);
116 if (self::hasKeys()) {
117 $m->connect('twitter/authorization',
118 ['action' => 'twitterauthorization']);
119 $m->connect('settings/twitter',
120 ['action' => 'twittersettings']);
122 if (common_config('twitter', 'signin')) {
123 $m->connect('main/twitterlogin',
124 ['action' => 'twitterlogin']);
132 * Add a login tab for 'Sign in with Twitter'
134 * @param Action $action the current action
138 function onEndLoginGroupNav($action)
140 $action_name = $action->trimmed('action');
142 if (self::hasKeys() && common_config('twitter', 'signin')) {
144 common_local_url('twitterlogin'),
145 // TRANS: Menu item in login navigation.
146 _m('MENU','Twitter'),
147 // TRANS: Title for menu item in login navigation.
148 _m('Login or register using Twitter.'),
149 'twitterlogin' === $action_name
157 * Add the Twitter Settings page to the Connect Settings menu
159 * @param Action $action The calling page
161 * @return boolean hook return
163 function onEndConnectSettingsNav($action)
165 if (self::hasKeys()) {
166 $action_name = $action->trimmed('action');
169 common_local_url('twittersettings'),
170 // TRANS: Menu item in connection settings navigation.
171 _m('MENU','Twitter'),
172 // TRANS: Title for menu item in connection settings navigation.
173 _m('Twitter integration options'),
174 $action_name === 'twittersettings'
181 * Add a Twitter queue item for each notice
183 * @param Notice $notice the notice
184 * @param array &$transports the list of transports (queues)
186 * @return boolean hook return
188 function onStartEnqueueNotice($notice, &$transports)
190 if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
191 // Avoid a possible loop
192 if ($notice->source != 'twitter') {
193 array_push($transports, 'twitter');
200 * Add Twitter bridge daemons to the list of daemons to start
202 * @param array $daemons the list fo daemons to run
204 * @return boolean hook return
206 function onGetValidDaemons(&$daemons)
208 if (self::hasKeys()) {
212 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
214 if (common_config('twitterimport', 'enabled')) {
218 . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
227 * Register Twitter notice queue handler
229 * @param QueueManager $manager
231 * @return boolean hook return
233 function onEndInitializeQueueManager($manager)
235 if (self::hasKeys()) {
236 // Outgoing notices -> twitter
237 $manager->connect('twitter', 'TwitterQueueHandler');
239 // Incoming statuses <- twitter
240 $manager->connect('tweetin', 'TweetInQueueHandler');
246 * If the plugin's installed, this should be accessible to admins
248 function onAdminPanelCheck($name, &$isOK)
250 if ($name == 'twitter') {
258 * Add a Twitter tab to the admin panel
260 * @param Widget $nav Admin panel nav
262 * @return boolean hook value
265 function onEndAdminPanelNav($nav)
267 if (AdminPanelAction::canAdmin('twitter')) {
269 $action_name = $nav->action->trimmed('action');
272 common_local_url('twitteradminpanel'),
273 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
275 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
276 _m('Twitter bridge configuration page.'),
277 $action_name == 'twitteradminpanel',
278 'nav_twitter_admin_panel'
286 * Plugin version data
288 * @param array &$versions array of version blocks
290 * @return boolean hook value
292 function onPluginVersion(array &$versions)
295 'name' => 'TwitterBridge',
296 'version' => self::PLUGIN_VERSION,
297 'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
298 'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/TwitterBridge',
299 // TRANS: Plugin description.
300 'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
301 'of a StatusNet instance with ' .
302 '<a href="http://twitter.com/">Twitter</a>.'
309 * Expose the adminImportControl setting to the administration panel code.
310 * This allows us to disable the import bridge enabling checkbox for administrators,
311 * since on a bulk farm site we can't yet automate the import daemon setup.
313 * @return boolean hook value;
315 function onTwitterBridgeAdminImportControl()
317 return (bool)$this->adminImportControl;
321 * Database schema setup
323 * We maintain a table mapping StatusNet notices to Twitter statuses
328 * @return boolean hook value; true means continue processing, false means stop.
330 function onCheckSchema()
332 $schema = Schema::get();
334 // For saving the last-synched status of various timelines
335 // home_timeline, messages (in), messages (out), ...
336 $schema->ensureTable('twitter_synch_status', Twitter_synch_status::schemaDef());
338 // For storing user-submitted flags on profiles
339 $schema->ensureTable('notice_to_status', Notice_to_status::schemaDef());
345 * If a notice gets deleted, remove the Notice_to_status mapping and
346 * delete the status on Twitter.
348 * @param User $user The user doing the deleting
349 * @param Notice $notice The notice getting deleted
351 * @return boolean hook value
353 function onStartDeleteOwnNotice(User $user, Notice $notice)
355 $n2s = Notice_to_status::getKV('notice_id', $notice->id);
357 if ($n2s instanceof Notice_to_status) {
360 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); // twitter service
361 } catch (NoResultException $e) {
365 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
366 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
371 $token = TwitterOAuthClient::unpackToken($flink->credentials);
372 $client = new TwitterOAuthClient($token->key, $token->secret);
374 $client->statusesDestroy($n2s->status_id);
375 } catch (Exception $e) {
376 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
385 * Notify remote users when their notices get favorited.
387 * @param Profile or User $profile of local user doing the faving
388 * @param Notice $notice being favored
389 * @return hook return value
391 function onEndFavorNotice(Profile $profile, Notice $notice)
394 $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
395 } catch (NoResultException $e) {
399 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
400 $this->log(LOG_INFO, "Skipping fave processing for {$profile->getID()} since link is not OAuth.");
404 $status_id = twitter_status_id($notice);
406 if (empty($status_id)) {
411 $token = TwitterOAuthClient::unpackToken($flink->credentials);
412 $client = new TwitterOAuthClient($token->key, $token->secret);
414 $client->favoritesCreate($status_id);
415 } catch (Exception $e) {
416 common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
423 * Notify remote users when their notices get de-favorited.
425 * @param Profile $profile Profile person doing the de-faving
426 * @param Notice $notice Notice being favored
428 * @return hook return value
430 function onEndDisfavorNotice(Profile $profile, Notice $notice)
433 $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
434 } catch (NoResultException $e) {
438 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
439 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
443 $status_id = twitter_status_id($notice);
445 if (empty($status_id)) {
450 $token = TwitterOAuthClient::unpackToken($flink->credentials);
451 $client = new TwitterOAuthClient($token->key, $token->secret);
453 $client->favoritesDestroy($status_id);
454 } catch (Exception $e) {
455 common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
461 function onStartGetProfileUri($profile, &$uri)
463 if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
464 $uri = $profile->profileurl;
471 * Add links in the user's profile block to their Twitter profile URL.
473 * @param Profile $profile The profile being shown
474 * @param Array &$links Writeable array of arrays (href, text, image).
476 * @return boolean hook value (true)
479 function onOtherAccountProfiles($profile, &$links)
484 $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
485 $fuser = $flink->getForeignUser();
487 $links[] = array("href" => $fuser->uri,
488 "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
489 "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
490 } catch (NoResultException $e) {
491 // no foreign link and/or user for Twitter on this profile ID
497 public function onEndShowHeadElements(Action $action)
499 if($action instanceof ShowNoticeAction) { // Showing a notice
500 $notice = Notice::getKV('id', $action->arg('notice'));
503 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE);
504 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
505 } catch (NoResultException $e) {
509 $statusId = twitter_status_id($notice);
510 if($notice instanceof Notice && $notice->isLocal() && $statusId) {
511 $tweetUrl = 'https://twitter.com/' . $fuser->nickname . '/status/' . $statusId;
512 $action->element('link', array('rel' => 'syndication', 'href' => $tweetUrl));
516 if (!($action instanceof AttachmentAction)) {
520 /* Twitter card support. See https://dev.twitter.com/docs/cards */
521 /* @fixme: should we display twitter cards only for attachments posted
522 * by local users ? Seems mandatory to display twitter:creator
526 switch ($action->attachment->mimetype) {
532 $action->element('meta', array('name' => 'twitter:card',
533 'content' => 'photo'),
535 $action->element('meta', array('name' => 'twitter:url',
536 'content' => common_local_url('attachment',
537 array('attachment' => $action->attachment->id))),
539 $action->element('meta', array('name' => 'twitter:image',
540 'content' => $action->attachment->url));
541 $action->element('meta', array('name' => 'twitter:title',
542 'content' => $action->attachment->title));
544 $ns = new AttachmentNoticeSection($action);
545 $notices = $ns->getNotices();
546 $noticeArray = $notices->fetchAll();
548 // Should not have more than 1 notice for this attachment.
549 if( count($noticeArray) != 1 ) { break; }
550 $post = $noticeArray[0];
553 $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
554 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
555 $action->element('meta', array('name' => 'twitter:creator',
556 'content' => '@'.$fuser->nickname));
557 } catch (NoResultException $e) {
558 // no foreign link and/or user for Twitter on this profile ID
569 * Set the object_type field of previously imported Twitter notices to
570 * ActivityObject::NOTE if they are unset. Null object_type caused a notice
571 * not to show on the timeline.
573 public function onEndUpgrade()
575 printfnq("Ensuring all Twitter notices have an object_type...");
577 $notice = new Notice();
578 $notice->whereAdd("source='twitter'");
579 $notice->whereAdd('object_type IS NULL');
581 if ($notice->find()) {
582 while ($notice->fetch()) {
583 $orig = Notice::getKV('id', $notice->id);
584 $notice->object_type = ActivityObject::NOTE;
585 $notice->update($orig);