]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/TwitterBridgePlugin.php
don't push twitter stuff public if its not public
[quix0rs-gnu-social.git] / plugins / TwitterBridge / TwitterBridgePlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * PHP version 5
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  * @category  Plugin
21  * @package   StatusNet
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/
27  */
28
29 if (!defined('STATUSNET')) {
30     exit(1);
31 }
32
33 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
34
35 /**
36  * Plugin for sending and importing Twitter statuses
37  *
38  * This class allows users to link their Twitter accounts
39  *
40  * @category Plugin
41  * @package  StatusNet
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/
47  */
48 class TwitterBridgePlugin extends Plugin
49 {
50     const VERSION = STATUSNET_VERSION;
51     public $adminImportControl = false; // Should the 'import' checkbox be exposed in the admin panel?
52
53     /**
54      * Initializer for the plugin.
55      */
56     function initialize()
57     {
58         // Allow the key and secret to be passed in
59         // Control panel will override
60
61         if (isset($this->consumer_key)) {
62             $key = common_config('twitter', 'consumer_key');
63             if (empty($key)) {
64                 Config::save('twitter', 'consumer_key', $this->consumer_key);
65             }
66         }
67
68         if (isset($this->consumer_secret)) {
69             $secret = common_config('twitter', 'consumer_secret');
70             if (empty($secret)) {
71                 Config::save(
72                     'twitter',
73                     'consumer_secret',
74                     $this->consumer_secret
75                 );
76             }
77         }
78     }
79
80     /**
81      * Check to see if there is a consumer key and secret defined
82      * for Twitter integration.
83      *
84      * @return boolean result
85      */
86     static function hasKeys()
87     {
88         $ckey    = common_config('twitter', 'consumer_key');
89         $csecret = common_config('twitter', 'consumer_secret');
90
91         if (empty($ckey) && empty($csecret)) {
92             $ckey    = common_config('twitter', 'global_consumer_key');
93             $csecret = common_config('twitter', 'global_consumer_secret');
94         }
95
96         if (!empty($ckey) && !empty($csecret)) {
97             return true;
98         }
99
100         return false;
101     }
102
103     /**
104      * Add Twitter-related paths to the router table
105      *
106      * Hook for RouterInitialized event.
107      *
108      * @param Net_URL_Mapper $m path-to-action mapper
109      *
110      * @return boolean hook return
111      */
112     function onRouterInitialized($m)
113     {
114         $m->connect('panel/twitter', array('action' => 'twitteradminpanel'));
115
116         if (self::hasKeys()) {
117             $m->connect(
118                 'twitter/authorization',
119                 array('action' => 'twitterauthorization')
120             );
121             $m->connect(
122                 'settings/twitter', array(
123                     'action' => 'twittersettings'
124                     )
125                 );
126             if (common_config('twitter', 'signin')) {
127                 $m->connect(
128                     'main/twitterlogin',
129                     array('action' => 'twitterlogin')
130                 );
131             }
132         }
133
134         return true;
135     }
136
137     /*
138      * Add a login tab for 'Sign in with Twitter'
139      *
140      * @param Action $action the current action
141      *
142      * @return void
143      */
144     function onEndLoginGroupNav($action)
145     {
146         $action_name = $action->trimmed('action');
147
148         if (self::hasKeys() && common_config('twitter', 'signin')) {
149             $action->menuItem(
150                 common_local_url('twitterlogin'),
151                 _m('Twitter'),
152                 _m('Login or register using Twitter'),
153                 'twitterlogin' === $action_name
154             );
155         }
156
157         return true;
158     }
159
160     /**
161      * Add the Twitter Settings page to the Connect Settings menu
162      *
163      * @param Action $action The calling page
164      *
165      * @return boolean hook return
166      */
167     function onEndConnectSettingsNav($action)
168     {
169         if (self::hasKeys()) {
170             $action_name = $action->trimmed('action');
171
172             $action->menuItem(
173                 common_local_url('twittersettings'),
174                 _m('Twitter'),
175                 _m('Twitter integration options'),
176                 $action_name === 'twittersettings'
177             );
178         }
179         return true;
180     }
181
182     /**
183      * Automatically load the actions and libraries used by the Twitter bridge
184      *
185      * @param Class $cls the class
186      *
187      * @return boolean hook return
188      *
189      */
190     function onAutoload($cls)
191     {
192         $dir = dirname(__FILE__);
193
194         switch ($cls) {
195         case 'TwittersettingsAction':
196         case 'TwitterauthorizationAction':
197         case 'TwitterloginAction':
198         case 'TwitteradminpanelAction':
199             include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
200             return false;
201         case 'TwitterOAuthClient':
202         case 'TwitterQueueHandler':
203         case 'TwitterImport':
204         case 'JsonStreamReader':
205         case 'TwitterStreamReader':
206             include_once $dir . '/' . strtolower($cls) . '.php';
207             return false;
208         case 'TwitterSiteStream':
209         case 'TwitterUserStream':
210             include_once $dir . '/twitterstreamreader.php';
211             return false;
212         case 'Notice_to_status':
213         case 'Twitter_synch_status':
214             include_once $dir . '/' . $cls . '.php';
215             return false;
216         default:
217             return true;
218         }
219     }
220
221     /**
222      * Add a Twitter queue item for each notice
223      *
224      * @param Notice $notice      the notice
225      * @param array  &$transports the list of transports (queues)
226      *
227      * @return boolean hook return
228      */
229     function onStartEnqueueNotice($notice, &$transports)
230     {
231         if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
232             // Avoid a possible loop
233             if ($notice->source != 'twitter') {
234                 array_push($transports, 'twitter');
235             }
236         }
237         return true;
238     }
239
240     /**
241      * Add Twitter bridge daemons to the list of daemons to start
242      *
243      * @param array $daemons the list fo daemons to run
244      *
245      * @return boolean hook return
246      */
247     function onGetValidDaemons($daemons)
248     {
249         if (self::hasKeys()) {
250             array_push(
251                 $daemons,
252                 INSTALLDIR
253                 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
254             );
255             if (common_config('twitterimport', 'enabled')) {
256                 array_push(
257                     $daemons,
258                     INSTALLDIR
259                     . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
260                     );
261             }
262         }
263
264         return true;
265     }
266
267     /**
268      * Register Twitter notice queue handler
269      *
270      * @param QueueManager $manager
271      *
272      * @return boolean hook return
273      */
274     function onEndInitializeQueueManager($manager)
275     {
276         if (self::hasKeys()) {
277             // Outgoing notices -> twitter
278             $manager->connect('twitter', 'TwitterQueueHandler');
279
280             // Incoming statuses <- twitter
281             $manager->connect('tweetin', 'TweetInQueueHandler');
282         }
283         return true;
284     }
285
286     /**
287      * Add a Twitter tab to the admin panel
288      *
289      * @param Widget $nav Admin panel nav
290      *
291      * @return boolean hook value
292      */
293
294     function onEndAdminPanelNav($nav)
295     {
296         if (AdminPanelAction::canAdmin('twitter')) {
297
298             $action_name = $nav->action->trimmed('action');
299
300             $nav->out->menuItem(
301                 common_local_url('twitteradminpanel'),
302                 _m('Twitter'),
303                 _m('Twitter bridge configuration'),
304                 $action_name == 'twitteradminpanel',
305                 'nav_twitter_admin_panel'
306             );
307         }
308
309         return true;
310     }
311
312     /**
313      * Plugin version data
314      *
315      * @param array &$versions array of version blocks
316      *
317      * @return boolean hook value
318      */
319     function onPluginVersion(&$versions)
320     {
321         $versions[] = array(
322             'name' => 'TwitterBridge',
323             'version' => self::VERSION,
324             'author' => 'Zach Copley, Julien C',
325             'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
326             'rawdescription' => _m(
327                 'The Twitter "bridge" plugin allows integration ' .
328                 'of a StatusNet instance with ' .
329                 '<a href="http://twitter.com/">Twitter</a>.'
330             )
331         );
332         return true;
333     }
334
335     /**
336      * Expose the adminImportControl setting to the administration panel code.
337      * This allows us to disable the import bridge enabling checkbox for administrators,
338      * since on a bulk farm site we can't yet automate the import daemon setup.
339      *
340      * @return boolean hook value;
341      */
342     function onTwitterBridgeAdminImportControl()
343     {
344         return (bool)$this->adminImportControl;
345     }
346
347     /**
348      * When the site is set to ssl=sometimes mode, we should make sure our
349      * various auth-related pages are on SSL to keep things looking happy.
350      * Although we're not submitting passwords directly, we do link out to
351      * an authentication source and it's a lot happier if we've got some
352      * protection against MitM.
353      *
354      * @param string $action name
355      * @param boolean $ssl outval to force SSL
356      * @return mixed hook return value
357      */
358     function onSensitiveAction($action, &$ssl)
359     {
360         $sensitive = array('twitteradminpanel',
361                            'twittersettings',
362                            'twitterauthorization',
363                            'twitterlogin');
364         if (in_array($action, $sensitive)) {
365             $ssl = true;
366             return false;
367         } else {
368             return true;
369         }
370     }
371
372     /**
373      * Database schema setup
374      *
375      * We maintain a table mapping StatusNet notices to Twitter statuses
376      *
377      * @see Schema
378      * @see ColumnDef
379      *
380      * @return boolean hook value; true means continue processing, false means stop.
381      */
382     function onCheckSchema()
383     {
384         $schema = Schema::get();
385
386         // For saving the last-synched status of various timelines
387         // home_timeline, messages (in), messages (out), ...
388
389         $schema->ensureTable('twitter_synch_status',
390                              array(new ColumnDef('foreign_id', 'bigint', null,
391                                                  false, 'PRI'),
392                                    new ColumnDef('timeline', 'varchar', 255,
393                                                  false, 'PRI'),
394                                    new ColumnDef('last_id', 'bigint', null, // XXX: check for PostgreSQL
395                                                  false),
396                                    new ColumnDef('created', 'datetime', null,
397                                                  false),
398                                    new ColumnDef('modified', 'datetime', null,
399                                                  false)));
400
401         // For storing user-submitted flags on profiles
402
403         $schema->ensureTable('notice_to_status',
404                              array(new ColumnDef('notice_id', 'integer', null,
405                                                  false, 'PRI'),
406                                    new ColumnDef('status_id', 'bigint', null, // XXX: check for PostgreSQL
407                                                  false, 'UNI'),
408                                    new ColumnDef('created', 'datetime', null,
409                                                  false)));
410
411         return true;
412     }
413
414     /**
415      * If a notice gets deleted, remove the Notice_to_status mapping and
416      * delete the status on Twitter.
417      *
418      * @param User   $user   The user doing the deleting
419      * @param Notice $notice The notice getting deleted
420      *
421      * @return boolean hook value
422      */
423     function onStartDeleteOwnNotice(User $user, Notice $notice)
424     {
425         $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
426
427         if (!empty($n2s)) {
428
429             $flink = Foreign_link::getByUserID($notice->profile_id,
430                                                TWITTER_SERVICE); // twitter service
431
432             if (empty($flink)) {
433                 return true;
434             }
435
436             if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
437                 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
438                 return true;
439             }
440
441             try {
442                 $token = TwitterOAuthClient::unpackToken($flink->credentials);
443                 $client = new TwitterOAuthClient($token->key, $token->secret);
444
445                 $client->statusesDestroy($n2s->status_id);
446             } catch (Exception $e) {
447                 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
448             }
449
450             $n2s->delete();
451         }
452         return true;
453     }
454
455     /**
456      * Notify remote users when their notices get favorited.
457      *
458      * @param Profile or User $profile of local user doing the faving
459      * @param Notice $notice being favored
460      * @return hook return value
461      */
462     function onEndFavorNotice(Profile $profile, Notice $notice)
463     {
464         $flink = Foreign_link::getByUserID($profile->id,
465                                            TWITTER_SERVICE); // twitter service
466
467         if (empty($flink)) {
468             return true;
469         }
470
471         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
472             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
473             return true;
474         }
475
476         $status_id = twitter_status_id($notice);
477
478         if (empty($status_id)) {
479             return true;
480         }
481
482         try {
483             $token = TwitterOAuthClient::unpackToken($flink->credentials);
484             $client = new TwitterOAuthClient($token->key, $token->secret);
485
486             $client->favoritesCreate($status_id);
487         } catch (Exception $e) {
488             common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
489         }
490
491         return true;
492     }
493
494     /**
495      * Notify remote users when their notices get de-favorited.
496      *
497      * @param Profile $profile Profile person doing the de-faving
498      * @param Notice  $notice  Notice being favored
499      *
500      * @return hook return value
501      */
502     function onEndDisfavorNotice(Profile $profile, Notice $notice)
503     {
504         $flink = Foreign_link::getByUserID($profile->id,
505                                            TWITTER_SERVICE); // twitter service
506
507         if (empty($flink)) {
508             return true;
509         }
510
511         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
512             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
513             return true;
514         }
515
516         $status_id = twitter_status_id($notice);
517
518         if (empty($status_id)) {
519             return true;
520         }
521
522         try {
523             $token = TwitterOAuthClient::unpackToken($flink->credentials);
524             $client = new TwitterOAuthClient($token->key, $token->secret);
525
526             $client->favoritesDestroy($status_id);
527         } catch (Exception $e) {
528             common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
529         }
530
531         return true;
532     }
533 }