]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/TwitterBridgePlugin.php
XSS vulnerability when remote-subscribing
[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('GNUSOCIAL')) { exit(1); }
30
31 require_once __DIR__ . '/twitter.php';
32
33 /**
34  * Plugin for sending and importing Twitter statuses
35  *
36  * This class allows users to link their Twitter accounts
37  *
38  * Depends on Favorite plugin.
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 = GNUSOCIAL_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 URLMapper $m path-to-action mapper
109      *
110      * @return boolean hook return
111      */
112     public function onRouterInitialized(URLMapper $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                 // 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
156             );
157         }
158
159         return true;
160     }
161
162     /**
163      * Add the Twitter Settings page to the Connect Settings menu
164      *
165      * @param Action $action The calling page
166      *
167      * @return boolean hook return
168      */
169     function onEndConnectSettingsNav($action)
170     {
171         if (self::hasKeys()) {
172             $action_name = $action->trimmed('action');
173
174             $action->menuItem(
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'
181             );
182         }
183         return true;
184     }
185
186     /**
187      * Add a Twitter queue item for each notice
188      *
189      * @param Notice $notice      the notice
190      * @param array  &$transports the list of transports (queues)
191      *
192      * @return boolean hook return
193      */
194     function onStartEnqueueNotice($notice, &$transports)
195     {
196         if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
197             // Avoid a possible loop
198             if ($notice->source != 'twitter') {
199                 array_push($transports, 'twitter');
200             }
201         }
202         return true;
203     }
204
205     /**
206      * Add Twitter bridge daemons to the list of daemons to start
207      *
208      * @param array $daemons the list fo daemons to run
209      *
210      * @return boolean hook return
211      */
212     function onGetValidDaemons(&$daemons)
213     {
214         if (self::hasKeys()) {
215             array_push(
216                 $daemons,
217                 INSTALLDIR
218                 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
219             );
220             if (common_config('twitterimport', 'enabled')) {
221                 array_push(
222                     $daemons,
223                     INSTALLDIR
224                     . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
225                     );
226             }
227         }
228
229         return true;
230     }
231
232     /**
233      * Register Twitter notice queue handler
234      *
235      * @param QueueManager $manager
236      *
237      * @return boolean hook return
238      */
239     function onEndInitializeQueueManager($manager)
240     {
241         if (self::hasKeys()) {
242             // Outgoing notices -> twitter
243             $manager->connect('twitter', 'TwitterQueueHandler');
244
245             // Incoming statuses <- twitter
246             $manager->connect('tweetin', 'TweetInQueueHandler');
247         }
248         return true;
249     }
250
251     /**
252      * If the plugin's installed, this should be accessible to admins
253      */
254     function onAdminPanelCheck($name, &$isOK)
255     {
256         if ($name == 'twitter') {
257             $isOK = true;
258             return false;
259         }
260         return true;
261     }
262
263     /**
264      * Add a Twitter tab to the admin panel
265      *
266      * @param Widget $nav Admin panel nav
267      *
268      * @return boolean hook value
269      */
270
271     function onEndAdminPanelNav($nav)
272     {
273         if (AdminPanelAction::canAdmin('twitter')) {
274
275             $action_name = $nav->action->trimmed('action');
276
277             $nav->out->menuItem(
278                 common_local_url('twitteradminpanel'),
279                 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
280                 _m('Twitter'),
281                 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
282                 _m('Twitter bridge configuration page.'),
283                 $action_name == 'twitteradminpanel',
284                 'nav_twitter_admin_panel'
285             );
286         }
287
288         return true;
289     }
290
291     /**
292      * Plugin version data
293      *
294      * @param array &$versions array of version blocks
295      *
296      * @return boolean hook value
297      */
298     function onPluginVersion(array &$versions)
299     {
300         $versions[] = array(
301             'name' => 'TwitterBridge',
302             'version' => self::VERSION,
303             'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
304             'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
305             // TRANS: Plugin description.
306             'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
307                 'of a StatusNet instance with ' .
308                 '<a href="http://twitter.com/">Twitter</a>.'
309             )
310         );
311         return true;
312     }
313
314     /**
315      * Expose the adminImportControl setting to the administration panel code.
316      * This allows us to disable the import bridge enabling checkbox for administrators,
317      * since on a bulk farm site we can't yet automate the import daemon setup.
318      *
319      * @return boolean hook value;
320      */
321     function onTwitterBridgeAdminImportControl()
322     {
323         return (bool)$this->adminImportControl;
324     }
325
326     /**
327      * When the site is set to ssl=sometimes mode, we should make sure our
328      * various auth-related pages are on SSL to keep things looking happy.
329      * Although we're not submitting passwords directly, we do link out to
330      * an authentication source and it's a lot happier if we've got some
331      * protection against MitM.
332      *
333      * @param string $action name
334      * @param boolean $ssl outval to force SSL
335      * @return mixed hook return value
336      */
337     function onSensitiveAction($action, &$ssl)
338     {
339         $sensitive = array('twitteradminpanel',
340                            'twittersettings',
341                            'twitterauthorization',
342                            'twitterlogin');
343         if (in_array($action, $sensitive)) {
344             $ssl = true;
345             return false;
346         } else {
347             return true;
348         }
349     }
350
351     /**
352      * Database schema setup
353      *
354      * We maintain a table mapping StatusNet notices to Twitter statuses
355      *
356      * @see Schema
357      * @see ColumnDef
358      *
359      * @return boolean hook value; true means continue processing, false means stop.
360      */
361     function onCheckSchema()
362     {
363         $schema = Schema::get();
364
365         // For saving the last-synched status of various timelines
366         // home_timeline, messages (in), messages (out), ...
367         $schema->ensureTable('twitter_synch_status', Twitter_synch_status::schemaDef());
368
369         // For storing user-submitted flags on profiles
370         $schema->ensureTable('notice_to_status', Notice_to_status::schemaDef());
371
372         return true;
373     }
374
375     /**
376      * If a notice gets deleted, remove the Notice_to_status mapping and
377      * delete the status on Twitter.
378      *
379      * @param User   $user   The user doing the deleting
380      * @param Notice $notice The notice getting deleted
381      *
382      * @return boolean hook value
383      */
384     function onStartDeleteOwnNotice(User $user, Notice $notice)
385     {
386         $n2s = Notice_to_status::getKV('notice_id', $notice->id);
387
388         if ($n2s instanceof Notice_to_status) {
389
390             try {
391                 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); // twitter service
392             } catch (NoResultException $e) {
393                 return true;
394             }
395
396             if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
397                 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
398                 return true;
399             }
400
401             try {
402                 $token = TwitterOAuthClient::unpackToken($flink->credentials);
403                 $client = new TwitterOAuthClient($token->key, $token->secret);
404
405                 $client->statusesDestroy($n2s->status_id);
406             } catch (Exception $e) {
407                 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
408             }
409
410             $n2s->delete();
411         }
412         return true;
413     }
414
415     /**
416      * Notify remote users when their notices get favorited.
417      *
418      * @param Profile or User $profile of local user doing the faving
419      * @param Notice $notice being favored
420      * @return hook return value
421      */
422     function onEndFavorNotice(Profile $profile, Notice $notice)
423     {
424         try {
425             $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
426         } catch (NoResultException $e) {
427             return true;
428         }
429
430         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
431             $this->log(LOG_INFO, "Skipping fave processing for {$profile->getID()} since link is not OAuth.");
432             return true;
433         }
434
435         $status_id = twitter_status_id($notice);
436
437         if (empty($status_id)) {
438             return true;
439         }
440
441         try {
442             $token = TwitterOAuthClient::unpackToken($flink->credentials);
443             $client = new TwitterOAuthClient($token->key, $token->secret);
444
445             $client->favoritesCreate($status_id);
446         } catch (Exception $e) {
447             common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
448         }
449
450         return true;
451     }
452
453     /**
454      * Notify remote users when their notices get de-favorited.
455      *
456      * @param Profile $profile Profile person doing the de-faving
457      * @param Notice  $notice  Notice being favored
458      *
459      * @return hook return value
460      */
461     function onEndDisfavorNotice(Profile $profile, Notice $notice)
462     {
463         try {
464             $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
465         } catch (NoResultException $e) {
466             return true;
467         }
468
469         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
470             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
471             return true;
472         }
473
474         $status_id = twitter_status_id($notice);
475
476         if (empty($status_id)) {
477             return true;
478         }
479
480         try {
481             $token = TwitterOAuthClient::unpackToken($flink->credentials);
482             $client = new TwitterOAuthClient($token->key, $token->secret);
483
484             $client->favoritesDestroy($status_id);
485         } catch (Exception $e) {
486             common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
487         }
488
489         return true;
490     }
491
492     function onStartGetProfileUri($profile, &$uri)
493     {
494         if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
495             $uri = $profile->profileurl;
496             return false;
497         }
498         return true;
499     }
500
501     /**
502      * Add links in the user's profile block to their Twitter profile URL.
503      *
504      * @param Profile $profile The profile being shown
505      * @param Array   &$links  Writeable array of arrays (href, text, image).
506      *
507      * @return boolean hook value (true)
508      */
509
510     function onOtherAccountProfiles($profile, &$links)
511     {
512         $fuser = null;
513
514         try {
515             $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
516             $fuser = $flink->getForeignUser();
517
518             $links[] = array("href" => $fuser->uri,
519                              "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
520                              "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
521         } catch (NoResultException $e) {
522             // no foreign link and/or user for Twitter on this profile ID
523         }
524
525         return true;
526     }
527
528     public function onEndShowHeadElements(Action $action)
529     {
530         if($action instanceof ShowNoticeAction) { // Showing a notice
531             $notice = Notice::getKV('id', $action->arg('notice'));
532
533             try {
534                 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE);
535                 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
536             } catch (NoResultException $e) {
537                 return true;
538             }
539
540             $statusId = twitter_status_id($notice);
541             if($notice instanceof Notice && $notice->isLocal() && $statusId) {
542                 $tweetUrl = 'https://twitter.com/' . $fuser->nickname . '/status/' . $statusId;
543                 $action->element('link', array('rel' => 'syndication', 'href' => $tweetUrl));
544             }
545         }
546
547         if (!($action instanceof AttachmentAction)) {
548             return true;
549         }
550
551         /* Twitter card support. See https://dev.twitter.com/docs/cards */
552         /* @fixme: should we display twitter cards only for attachments posted
553          *         by local users ? Seems mandatory to display twitter:creator
554          *
555          * Author: jbfavre
556          */
557         switch ($action->attachment->mimetype) {
558             case 'image/pjpeg':
559             case 'image/jpeg':
560             case 'image/jpg':
561             case 'image/png':
562             case 'image/gif':
563                 $action->element('meta', array('name'    => 'twitter:card',
564                                              'content' => 'photo'),
565                                        null);
566                 $action->element('meta', array('name'    => 'twitter:url',
567                                              'content' => common_local_url('attachment',
568                                                               array('attachment' => $action->attachment->id))),
569                                        null );
570                 $action->element('meta', array('name'    => 'twitter:image',
571                                              'content' => $action->attachment->url));
572                 $action->element('meta', array('name'    => 'twitter:title',
573                                              'content' => $action->attachment->title));
574
575                 $ns = new AttachmentNoticeSection($action);
576                 $notices = $ns->getNotices();
577                 $noticeArray = $notices->fetchAll();
578
579                 // Should not have more than 1 notice for this attachment.
580                 if( count($noticeArray) != 1 ) { break; }
581                 $post = $noticeArray[0];
582
583                 try {
584                     $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
585                     $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
586                     $action->element('meta', array('name'    => 'twitter:creator',
587                                                    'content' => '@'.$fuser->nickname));
588                 } catch (NoResultException $e) {
589                     // no foreign link and/or user for Twitter on this profile ID
590                 }
591                 break;
592             default:
593                 break;
594         }
595
596         return true;
597     }
598 }