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 'TwitterImport':
208 case 'JsonStreamReader':
209 case 'TwitterStreamReader':
210 include_once $dir . '/' . strtolower($cls) . '.php';
212 case 'TwitterSiteStream':
213 case 'TwitterUserStream':
214 include_once $dir . '/twitterstreamreader.php';
216 case 'Notice_to_status':
217 case 'Twitter_synch_status':
218 include_once $dir . '/' . $cls . '.php';
226 * Add a Twitter queue item for each notice
228 * @param Notice $notice the notice
229 * @param array &$transports the list of transports (queues)
231 * @return boolean hook return
233 function onStartEnqueueNotice($notice, &$transports)
235 if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
236 // Avoid a possible loop
237 if ($notice->source != 'twitter') {
238 array_push($transports, 'twitter');
245 * Add Twitter bridge daemons to the list of daemons to start
247 * @param array $daemons the list fo daemons to run
249 * @return boolean hook return
251 function onGetValidDaemons($daemons)
253 if (self::hasKeys()) {
257 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
259 if (common_config('twitterimport', 'enabled')) {
263 . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
272 * Register Twitter notice queue handler
274 * @param QueueManager $manager
276 * @return boolean hook return
278 function onEndInitializeQueueManager($manager)
280 if (self::hasKeys()) {
281 // Outgoing notices -> twitter
282 $manager->connect('twitter', 'TwitterQueueHandler');
284 // Incoming statuses <- twitter
285 $manager->connect('tweetin', 'TweetInQueueHandler');
291 * If the plugin's installed, this should be accessible to admins
293 function onAdminPanelCheck($name, &$isOK)
295 if ($name == 'twitter') {
303 * Add a Twitter tab to the admin panel
305 * @param Widget $nav Admin panel nav
307 * @return boolean hook value
310 function onEndAdminPanelNav($nav)
312 if (AdminPanelAction::canAdmin('twitter')) {
314 $action_name = $nav->action->trimmed('action');
317 common_local_url('twitteradminpanel'),
318 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
320 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
321 _m('Twitter bridge configuration page.'),
322 $action_name == 'twitteradminpanel',
323 'nav_twitter_admin_panel'
331 * Plugin version data
333 * @param array &$versions array of version blocks
335 * @return boolean hook value
337 function onPluginVersion(&$versions)
340 'name' => 'TwitterBridge',
341 'version' => self::VERSION,
342 'author' => 'Zach Copley, Julien C',
343 'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
344 // TRANS: Plugin description.
345 'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
346 'of a StatusNet instance with ' .
347 '<a href="http://twitter.com/">Twitter</a>.'
354 * Expose the adminImportControl setting to the administration panel code.
355 * This allows us to disable the import bridge enabling checkbox for administrators,
356 * since on a bulk farm site we can't yet automate the import daemon setup.
358 * @return boolean hook value;
360 function onTwitterBridgeAdminImportControl()
362 return (bool)$this->adminImportControl;
366 * When the site is set to ssl=sometimes mode, we should make sure our
367 * various auth-related pages are on SSL to keep things looking happy.
368 * Although we're not submitting passwords directly, we do link out to
369 * an authentication source and it's a lot happier if we've got some
370 * protection against MitM.
372 * @param string $action name
373 * @param boolean $ssl outval to force SSL
374 * @return mixed hook return value
376 function onSensitiveAction($action, &$ssl)
378 $sensitive = array('twitteradminpanel',
380 'twitterauthorization',
382 if (in_array($action, $sensitive)) {
391 * Database schema setup
393 * We maintain a table mapping StatusNet notices to Twitter statuses
398 * @return boolean hook value; true means continue processing, false means stop.
400 function onCheckSchema()
402 $schema = Schema::get();
404 // For saving the last-synched status of various timelines
405 // home_timeline, messages (in), messages (out), ...
407 $schema->ensureTable('twitter_synch_status',
408 array(new ColumnDef('foreign_id', 'bigint', null,
410 new ColumnDef('timeline', 'varchar', 255,
412 new ColumnDef('last_id', 'bigint', null, // XXX: check for PostgreSQL
414 new ColumnDef('created', 'datetime', null,
416 new ColumnDef('modified', 'datetime', null,
419 // For storing user-submitted flags on profiles
421 $schema->ensureTable('notice_to_status',
422 array(new ColumnDef('notice_id', 'integer', null,
424 new ColumnDef('status_id', 'bigint', null, // XXX: check for PostgreSQL
426 new ColumnDef('created', 'datetime', null,
433 * If a notice gets deleted, remove the Notice_to_status mapping and
434 * delete the status on Twitter.
436 * @param User $user The user doing the deleting
437 * @param Notice $notice The notice getting deleted
439 * @return boolean hook value
441 function onStartDeleteOwnNotice(User $user, Notice $notice)
443 $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
447 $flink = Foreign_link::getByUserID($notice->profile_id,
448 TWITTER_SERVICE); // twitter service
454 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
455 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
460 $token = TwitterOAuthClient::unpackToken($flink->credentials);
461 $client = new TwitterOAuthClient($token->key, $token->secret);
463 $client->statusesDestroy($n2s->status_id);
464 } catch (Exception $e) {
465 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
474 * Notify remote users when their notices get favorited.
476 * @param Profile or User $profile of local user doing the faving
477 * @param Notice $notice being favored
478 * @return hook return value
480 function onEndFavorNotice(Profile $profile, Notice $notice)
482 $flink = Foreign_link::getByUserID($profile->id,
483 TWITTER_SERVICE); // twitter service
489 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
490 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
494 $status_id = twitter_status_id($notice);
496 if (empty($status_id)) {
501 $token = TwitterOAuthClient::unpackToken($flink->credentials);
502 $client = new TwitterOAuthClient($token->key, $token->secret);
504 $client->favoritesCreate($status_id);
505 } catch (Exception $e) {
506 common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
513 * Notify remote users when their notices get de-favorited.
515 * @param Profile $profile Profile person doing the de-faving
516 * @param Notice $notice Notice being favored
518 * @return hook return value
520 function onEndDisfavorNotice(Profile $profile, Notice $notice)
522 $flink = Foreign_link::getByUserID($profile->id,
523 TWITTER_SERVICE); // twitter service
529 if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
530 $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
534 $status_id = twitter_status_id($notice);
536 if (empty($status_id)) {
541 $token = TwitterOAuthClient::unpackToken($flink->credentials);
542 $client = new TwitterOAuthClient($token->key, $token->secret);
544 $client->favoritesDestroy($status_id);
545 } catch (Exception $e) {
546 common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
552 function onStartGetProfileUri($profile, &$uri)
554 if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
555 $uri = $profile->profileurl;