]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/TwitterBridgePlugin.php
Added more checked type-hints.
[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 __DIR__ . '/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  * Depends on Favorite plugin.
41  *
42  * @category Plugin
43  * @package  StatusNet
44  * @author   Zach Copley <zach@status.net>
45  * @author   Julien C <chaumond@gmail.com>
46  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47  * @link     http://status.net/
48  * @link     http://twitter.com/
49  */
50 class TwitterBridgePlugin extends Plugin
51 {
52     const VERSION = GNUSOCIAL_VERSION;
53     public $adminImportControl = false; // Should the 'import' checkbox be exposed in the admin panel?
54
55     /**
56      * Initializer for the plugin.
57      */
58     function initialize()
59     {
60         // Allow the key and secret to be passed in
61         // Control panel will override
62
63         if (isset($this->consumer_key)) {
64             $key = common_config('twitter', 'consumer_key');
65             if (empty($key)) {
66                 Config::save('twitter', 'consumer_key', $this->consumer_key);
67             }
68         }
69
70         if (isset($this->consumer_secret)) {
71             $secret = common_config('twitter', 'consumer_secret');
72             if (empty($secret)) {
73                 Config::save(
74                     'twitter',
75                     'consumer_secret',
76                     $this->consumer_secret
77                 );
78             }
79         }
80     }
81
82     /**
83      * Check to see if there is a consumer key and secret defined
84      * for Twitter integration.
85      *
86      * @return boolean result
87      */
88     static function hasKeys()
89     {
90         $ckey    = common_config('twitter', 'consumer_key');
91         $csecret = common_config('twitter', 'consumer_secret');
92
93         if (empty($ckey) && empty($csecret)) {
94             $ckey    = common_config('twitter', 'global_consumer_key');
95             $csecret = common_config('twitter', 'global_consumer_secret');
96         }
97
98         if (!empty($ckey) && !empty($csecret)) {
99             return true;
100         }
101
102         return false;
103     }
104
105     /**
106      * Add Twitter-related paths to the router table
107      *
108      * Hook for RouterInitialized event.
109      *
110      * @param URLMapper $m path-to-action mapper
111      *
112      * @return boolean hook return
113      */
114     public function onRouterInitialized(URLMapper $m)
115     {
116         $m->connect('panel/twitter', array('action' => 'twitteradminpanel'));
117
118         if (self::hasKeys()) {
119             $m->connect(
120                 'twitter/authorization',
121                 array('action' => 'twitterauthorization')
122             );
123             $m->connect(
124                 'settings/twitter', array(
125                     'action' => 'twittersettings'
126                     )
127                 );
128             if (common_config('twitter', 'signin')) {
129                 $m->connect(
130                     'main/twitterlogin',
131                     array('action' => 'twitterlogin')
132                 );
133             }
134         }
135
136         return true;
137     }
138
139     /*
140      * Add a login tab for 'Sign in with Twitter'
141      *
142      * @param Action $action the current action
143      *
144      * @return void
145      */
146     function onEndLoginGroupNav($action)
147     {
148         $action_name = $action->trimmed('action');
149
150         if (self::hasKeys() && common_config('twitter', 'signin')) {
151             $action->menuItem(
152                 common_local_url('twitterlogin'),
153                 // TRANS: Menu item in login navigation.
154                 _m('MENU','Twitter'),
155                 // TRANS: Title for menu item in login navigation.
156                 _m('Login or register using Twitter.'),
157                 'twitterlogin' === $action_name
158             );
159         }
160
161         return true;
162     }
163
164     /**
165      * Add the Twitter Settings page to the Connect Settings menu
166      *
167      * @param Action $action The calling page
168      *
169      * @return boolean hook return
170      */
171     function onEndConnectSettingsNav($action)
172     {
173         if (self::hasKeys()) {
174             $action_name = $action->trimmed('action');
175
176             $action->menuItem(
177                 common_local_url('twittersettings'),
178                 // TRANS: Menu item in connection settings navigation.
179                 _m('MENU','Twitter'),
180                 // TRANS: Title for menu item in connection settings navigation.
181                 _m('Twitter integration options'),
182                 $action_name === 'twittersettings'
183             );
184         }
185         return true;
186     }
187
188     /**
189      * Add a Twitter queue item for each notice
190      *
191      * @param Notice $notice      the notice
192      * @param array  &$transports the list of transports (queues)
193      *
194      * @return boolean hook return
195      */
196     function onStartEnqueueNotice(Notice $notice, array &$transports)
197     {
198         if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
199             // Avoid a possible loop
200             if ($notice->source != 'twitter') {
201                 array_push($transports, 'twitter');
202             }
203         }
204         return true;
205     }
206
207     /**
208      * Add Twitter bridge daemons to the list of daemons to start
209      *
210      * @param array $daemons the list fo daemons to run
211      *
212      * @return boolean hook return
213      */
214     function onGetValidDaemons(array &$daemons)
215     {
216         if (self::hasKeys()) {
217             array_push(
218                 $daemons,
219                 INSTALLDIR
220                 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
221             );
222             if (common_config('twitterimport', 'enabled')) {
223                 array_push(
224                     $daemons,
225                     INSTALLDIR
226                     . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
227                     );
228             }
229         }
230
231         return true;
232     }
233
234     /**
235      * Register Twitter notice queue handler
236      *
237      * @param QueueManager $manager
238      *
239      * @return boolean hook return
240      */
241     function onEndInitializeQueueManager($manager)
242     {
243         if (self::hasKeys()) {
244             // Outgoing notices -> twitter
245             $manager->connect('twitter', 'TwitterQueueHandler');
246
247             // Incoming statuses <- twitter
248             $manager->connect('tweetin', 'TweetInQueueHandler');
249         }
250         return true;
251     }
252
253     /**
254      * If the plugin's installed, this should be accessible to admins
255      */
256     function onAdminPanelCheck($name, &$isOK)
257     {
258         if ($name == 'twitter') {
259             $isOK = true;
260             return false;
261         }
262         return true;
263     }
264
265     /**
266      * Add a Twitter tab to the admin panel
267      *
268      * @param Widget $nav Admin panel nav
269      *
270      * @return boolean hook value
271      */
272
273     function onEndAdminPanelNav(Menu $nav)
274     {
275         if (AdminPanelAction::canAdmin('twitter')) {
276
277             $action_name = $nav->action->trimmed('action');
278
279             $nav->out->menuItem(
280                 common_local_url('twitteradminpanel'),
281                 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
282                 _m('Twitter'),
283                 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
284                 _m('Twitter bridge configuration page.'),
285                 $action_name == 'twitteradminpanel',
286                 'nav_twitter_admin_panel'
287             );
288         }
289
290         return true;
291     }
292
293     /**
294      * Plugin version data
295      *
296      * @param array &$versions array of version blocks
297      *
298      * @return boolean hook value
299      */
300     function onPluginVersion(array &$versions)
301     {
302         $versions[] = array(
303             'name' => 'TwitterBridge',
304             'version' => self::VERSION,
305             'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
306             'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
307             // TRANS: Plugin description.
308             'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
309                 'of a StatusNet instance with ' .
310                 '<a href="http://twitter.com/">Twitter</a>.'
311             )
312         );
313         return true;
314     }
315
316     /**
317      * Expose the adminImportControl setting to the administration panel code.
318      * This allows us to disable the import bridge enabling checkbox for administrators,
319      * since on a bulk farm site we can't yet automate the import daemon setup.
320      *
321      * @return boolean hook value;
322      */
323     function onTwitterBridgeAdminImportControl()
324     {
325         return (bool)$this->adminImportControl;
326     }
327
328     /**
329      * When the site is set to ssl=sometimes mode, we should make sure our
330      * various auth-related pages are on SSL to keep things looking happy.
331      * Although we're not submitting passwords directly, we do link out to
332      * an authentication source and it's a lot happier if we've got some
333      * protection against MitM.
334      *
335      * @param string $action name
336      * @param boolean $ssl outval to force SSL
337      * @return mixed hook return value
338      */
339     function onSensitiveAction($action, &$ssl)
340     {
341         $sensitive = array('twitteradminpanel',
342                            'twittersettings',
343                            'twitterauthorization',
344                            'twitterlogin');
345         if (in_array($action, $sensitive)) {
346             $ssl = true;
347             return false;
348         } else {
349             return true;
350         }
351     }
352
353     /**
354      * Database schema setup
355      *
356      * We maintain a table mapping StatusNet notices to Twitter statuses
357      *
358      * @see Schema
359      * @see ColumnDef
360      *
361      * @return boolean hook value; true means continue processing, false means stop.
362      */
363     function onCheckSchema()
364     {
365         $schema = Schema::get();
366
367         // For saving the last-synched status of various timelines
368         // home_timeline, messages (in), messages (out), ...
369         $schema->ensureTable('twitter_synch_status', Twitter_synch_status::schemaDef());
370
371         // For storing user-submitted flags on profiles
372         $schema->ensureTable('notice_to_status', Notice_to_status::schemaDef());
373
374         return true;
375     }
376
377     /**
378      * If a notice gets deleted, remove the Notice_to_status mapping and
379      * delete the status on Twitter.
380      *
381      * @param User   $user   The user doing the deleting
382      * @param Notice $notice The notice getting deleted
383      *
384      * @return boolean hook value
385      */
386     function onStartDeleteOwnNotice(User $user, Notice $notice)
387     {
388         $n2s = Notice_to_status::getKV('notice_id', $notice->id);
389
390         if (!empty($n2s)) {
391
392             $flink = Foreign_link::getByUserID($notice->profile_id,
393                                                TWITTER_SERVICE); // twitter service
394
395             if (empty($flink)) {
396                 return true;
397             }
398
399             if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
400                 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
401                 return true;
402             }
403
404             try {
405                 $token = TwitterOAuthClient::unpackToken($flink->credentials);
406                 $client = new TwitterOAuthClient($token->key, $token->secret);
407
408                 $client->statusesDestroy($n2s->status_id);
409             } catch (Exception $e) {
410                 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
411             }
412
413             $n2s->delete();
414         }
415         return true;
416     }
417
418     /**
419      * Notify remote users when their notices get favorited.
420      *
421      * @param Profile or User $profile of local user doing the faving
422      * @param Notice $notice being favored
423      * @return hook return value
424      */
425     function onEndFavorNotice(Profile $profile, Notice $notice)
426     {
427         $flink = Foreign_link::getByUserID($profile->id,
428                                            TWITTER_SERVICE); // twitter service
429
430         if (empty($flink)) {
431             return true;
432         }
433
434         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
435             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
436             return true;
437         }
438
439         $status_id = twitter_status_id($notice);
440
441         if (empty($status_id)) {
442             return true;
443         }
444
445         try {
446             $token = TwitterOAuthClient::unpackToken($flink->credentials);
447             $client = new TwitterOAuthClient($token->key, $token->secret);
448
449             $client->favoritesCreate($status_id);
450         } catch (Exception $e) {
451             common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
452         }
453
454         return true;
455     }
456
457     /**
458      * Notify remote users when their notices get de-favorited.
459      *
460      * @param Profile $profile Profile person doing the de-faving
461      * @param Notice  $notice  Notice being favored
462      *
463      * @return hook return value
464      */
465     function onEndDisfavorNotice(Profile $profile, Notice $notice)
466     {
467         $flink = Foreign_link::getByUserID($profile->id,
468                                            TWITTER_SERVICE); // twitter service
469
470         if (empty($flink)) {
471             return true;
472         }
473
474         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
475             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
476             return true;
477         }
478
479         $status_id = twitter_status_id($notice);
480
481         if (empty($status_id)) {
482             return true;
483         }
484
485         try {
486             $token = TwitterOAuthClient::unpackToken($flink->credentials);
487             $client = new TwitterOAuthClient($token->key, $token->secret);
488
489             $client->favoritesDestroy($status_id);
490         } catch (Exception $e) {
491             common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
492         }
493
494         return true;
495     }
496
497     function onStartGetProfileUri($profile, &$uri)
498     {
499         if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
500             $uri = $profile->profileurl;
501             return false;
502         }
503         return true;
504     }
505
506     /**
507      * Add links in the user's profile block to their Twitter profile URL.
508      *
509      * @param Profile $profile The profile being shown
510      * @param Array   &$links  Writeable array of arrays (href, text, image).
511      *
512      * @return boolean hook value (true)
513      */
514
515     function onOtherAccountProfiles($profile, &$links)
516     {
517         $fuser = null;
518
519         $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
520
521         if (!empty($flink)) {
522             $fuser = $flink->getForeignUser();
523
524             if (!empty($fuser)) {
525                 $links[] = array("href" => $fuser->uri,
526                                  "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
527                                  "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
528             }
529         }
530
531         return true;
532     }
533
534     public function onEndShowHeadElements(Action $action)
535     {
536         if (!($action instanceof AttachmentAction)) {
537             return true;
538         }
539
540         /* Twitter card support. See https://dev.twitter.com/docs/cards */
541         /* @fixme: should we display twitter cards only for attachments posted
542          *         by local users ? Seems mandatory to display twitter:creator
543          *
544          * Author: jbfavre
545          */
546         switch ($action->attachment->mimetype) {
547             case 'image/pjpeg':
548             case 'image/jpeg':
549             case 'image/jpg':
550             case 'image/png':
551             case 'image/gif':
552                 $action->element('meta', array('name'    => 'twitter:card',
553                                              'content' => 'photo'),
554                                        null);
555                 $action->element('meta', array('name'    => 'twitter:url',
556                                              'content' => common_local_url('attachment',
557                                                               array('attachment' => $action->attachment->id))),
558                                        null );
559                 $action->element('meta', array('name'    => 'twitter:image',
560                                              'content' => $action->attachment->url));
561                 $action->element('meta', array('name'    => 'twitter:title',
562                                              'content' => $action->attachment->title));
563
564                 $ns = new AttachmentNoticeSection($action);
565                 $notices = $ns->getNotices();
566                 $noticeArray = $notices->fetchAll();
567
568                 // Should not have more than 1 notice for this attachment.
569                 if( count($noticeArray) != 1 ) { break; }
570                 $post = $noticeArray[0];
571
572                 $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
573                 if( $flink ) { // Our local user has registered Twitter Gateway
574                     $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
575                     if( $fuser ) { // Got nickname for local user's Twitter account
576                         $action->element('meta', array('name'    => 'twitter:creator',
577                                                      'content' => '@'.$fuser->nickname));
578                     }
579                 }
580                 break;
581             default: break;
582         }
583
584         return true;
585     }
586 }