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