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 INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
36 * Plugin for sending and importing Twitter statuses
38 * This class allows users to link their Twitter accounts
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 = STATUSNET_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 Net_URL_Mapper $m path-to-action mapper
110 * @return boolean hook return
112 function onRouterInitialized($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 * Automatically load the actions and libraries used by the Twitter bridge
189 * @param Class $cls the class
191 * @return boolean hook return
194 function onAutoload($cls)
196 $dir = dirname(__FILE__);
199 case 'TwittersettingsAction':
200 case 'TwitterauthorizationAction':
201 case 'TwitterloginAction':
202 case 'TwitteradminpanelAction':
203 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
205 case 'TwitterOAuthClient':
206 case 'TwitterQueueHandler':
207 case 'TweetInQueueHandler':
208 case 'TwitterImport':
209 case 'JsonStreamReader':
210 case 'TwitterStreamReader':
211 include_once $dir . '/' . strtolower($cls) . '.php';
213 case 'TwitterSiteStream':
214 case 'TwitterUserStream':
215 include_once $dir . '/twitterstreamreader.php';
217 case 'Notice_to_status':
218 case 'Twitter_synch_status':
219 include_once $dir . '/' . $cls . '.php';
227 * Add a Twitter queue item for each notice
229 * @param Notice $notice the notice
230 * @param array &$transports the list of transports (queues)
232 * @return boolean hook return
234 function onStartEnqueueNotice($notice, &$transports)
236 if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
237 // Avoid a possible loop
238 if ($notice->source != 'twitter') {
239 array_push($transports, 'twitter');
246 * Add Twitter bridge daemons to the list of daemons to start
248 * @param array $daemons the list fo daemons to run
250 * @return boolean hook return
252 function onGetValidDaemons(&$daemons)
254 if (self::hasKeys()) {
258 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
260 if (common_config('twitterimport', 'enabled')) {
264 . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
273 * Register Twitter notice queue handler
275 * @param QueueManager $manager
277 * @return boolean hook return
279 function onEndInitializeQueueManager($manager)
281 if (self::hasKeys()) {
282 // Outgoing notices -> twitter
283 $manager->connect('twitter', 'TwitterQueueHandler');
285 // Incoming statuses <- twitter
286 $manager->connect('tweetin', 'TweetInQueueHandler');
292 * If the plugin's installed, this should be accessible to admins
294 function onAdminPanelCheck($name, &$isOK)
296 if ($name == 'twitter') {
304 * Add a Twitter tab to the admin panel
306 * @param Widget $nav Admin panel nav
308 * @return boolean hook value
311 function onEndAdminPanelNav($nav)
313 if (AdminPanelAction::canAdmin('twitter')) {
315 $action_name = $nav->action->trimmed('action');
318 common_local_url('twitteradminpanel'),
319 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
321 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
322 _m('Twitter bridge configuration page.'),
323 $action_name == 'twitteradminpanel',
324 'nav_twitter_admin_panel'
332 * Plugin version data
334 * @param array &$versions array of version blocks
336 * @return boolean hook value
338 function onPluginVersion(&$versions)
341 'name' => 'TwitterBridge',
342 'version' => self::VERSION,
343 'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
344 'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
345 // TRANS: Plugin description.
346 'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
347 'of a StatusNet instance with ' .
348 '<a href="http://twitter.com/">Twitter</a>.'
355 * Expose the adminImportControl setting to the administration panel code.
356 * This allows us to disable the import bridge enabling checkbox for administrators,
357 * since on a bulk farm site we can't yet automate the import daemon setup.
359 * @return boolean hook value;
361 function onTwitterBridgeAdminImportControl()
363 return (bool)$this->adminImportControl;
367 * When the site is set to ssl=sometimes mode, we should make sure our
368 * various auth-related pages are on SSL to keep things looking happy.
369 * Although we're not submitting passwords directly, we do link out to
370 * an authentication source and it's a lot happier if we've got some
371 * protection against MitM.
373 * @param string $action name
374 * @param boolean $ssl outval to force SSL
375 * @return mixed hook return value
377 function onSensitiveAction($action, &$ssl)
379 $sensitive = array('twitteradminpanel',
381 'twitterauthorization',
383 if (in_array($action, $sensitive)) {
392 * Database schema setup
394 * We maintain a table mapping StatusNet notices to Twitter statuses
399 * @return boolean hook value; true means continue processing, false means stop.
401 function onCheckSchema()
403 $schema = Schema::get();
405 // For saving the last-synched status of various timelines
406 // home_timeline, messages (in), messages (out), ...
408 $schema->ensureTable('twitter_synch_status',
409 array(new ColumnDef('foreign_id', 'bigint', null,
411 new ColumnDef('timeline', 'varchar', 255,
413 new ColumnDef('last_id', 'bigint', null, // XXX: check for PostgreSQL
415 new ColumnDef('created', 'datetime', null,
417 new ColumnDef('modified', 'datetime', null,
420 // For storing user-submitted flags on profiles
422 $schema->ensureTable('notice_to_status',
423 array(new ColumnDef('notice_id', 'integer', null,
425 new ColumnDef('status_id', 'bigint', null, // XXX: check for PostgreSQL
427 new ColumnDef('created', 'datetime', null,
434 * If a notice gets deleted, remove the Notice_to_status mapping and
435 * delete the status on Twitter.
437 * @param User $user The user doing the deleting
438 * @param Notice $notice The notice getting deleted
440 * @return boolean hook value
442 function onStartDeleteOwnNotice(User $user, Notice $notice)
444 $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
448 $flink = Foreign_link::getByUserID($notice->profile_id,
449 TWITTER_SERVICE); // twitter service
455 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
456 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
461 $token = TwitterOAuthClient::unpackToken($flink->credentials);
462 $client = new TwitterOAuthClient($token->key, $token->secret);
464 $client->statusesDestroy($n2s->status_id);
465 } catch (Exception $e) {
466 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
475 * Notify remote users when their notices get favorited.
477 * @param Profile or User $profile of local user doing the faving
478 * @param Notice $notice being favored
479 * @return hook return value
481 function onEndFavorNotice(Profile $profile, Notice $notice)
483 $flink = Foreign_link::getByUserID($profile->id,
484 TWITTER_SERVICE); // twitter service
490 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
491 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
495 $status_id = twitter_status_id($notice);
497 if (empty($status_id)) {
502 $token = TwitterOAuthClient::unpackToken($flink->credentials);
503 $client = new TwitterOAuthClient($token->key, $token->secret);
505 $client->favoritesCreate($status_id);
506 } catch (Exception $e) {
507 common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
514 * Notify remote users when their notices get de-favorited.
516 * @param Profile $profile Profile person doing the de-faving
517 * @param Notice $notice Notice being favored
519 * @return hook return value
521 function onEndDisfavorNotice(Profile $profile, Notice $notice)
523 $flink = Foreign_link::getByUserID($profile->id,
524 TWITTER_SERVICE); // twitter service
530 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
531 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
535 $status_id = twitter_status_id($notice);
537 if (empty($status_id)) {
542 $token = TwitterOAuthClient::unpackToken($flink->credentials);
543 $client = new TwitterOAuthClient($token->key, $token->secret);
545 $client->favoritesDestroy($status_id);
546 } catch (Exception $e) {
547 common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
553 function onStartGetProfileUri($profile, &$uri)
555 if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
556 $uri = $profile->profileurl;