]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/TwitterBridgePlugin.php
Moved jbfavre's Twitter card support to Twitter plugin
[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                 // 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(&$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 (!empty($n2s)) {
389
390             $flink = Foreign_link::getByUserID($notice->profile_id,
391                                                TWITTER_SERVICE); // twitter service
392
393             if (empty($flink)) {
394                 return true;
395             }
396
397             if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
398                 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
399                 return true;
400             }
401
402             try {
403                 $token = TwitterOAuthClient::unpackToken($flink->credentials);
404                 $client = new TwitterOAuthClient($token->key, $token->secret);
405
406                 $client->statusesDestroy($n2s->status_id);
407             } catch (Exception $e) {
408                 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
409             }
410
411             $n2s->delete();
412         }
413         return true;
414     }
415
416     /**
417      * Notify remote users when their notices get favorited.
418      *
419      * @param Profile or User $profile of local user doing the faving
420      * @param Notice $notice being favored
421      * @return hook return value
422      */
423     function onEndFavorNotice(Profile $profile, Notice $notice)
424     {
425         $flink = Foreign_link::getByUserID($profile->id,
426                                            TWITTER_SERVICE); // twitter service
427
428         if (empty($flink)) {
429             return true;
430         }
431
432         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
433             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
434             return true;
435         }
436
437         $status_id = twitter_status_id($notice);
438
439         if (empty($status_id)) {
440             return true;
441         }
442
443         try {
444             $token = TwitterOAuthClient::unpackToken($flink->credentials);
445             $client = new TwitterOAuthClient($token->key, $token->secret);
446
447             $client->favoritesCreate($status_id);
448         } catch (Exception $e) {
449             common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
450         }
451
452         return true;
453     }
454
455     /**
456      * Notify remote users when their notices get de-favorited.
457      *
458      * @param Profile $profile Profile person doing the de-faving
459      * @param Notice  $notice  Notice being favored
460      *
461      * @return hook return value
462      */
463     function onEndDisfavorNotice(Profile $profile, Notice $notice)
464     {
465         $flink = Foreign_link::getByUserID($profile->id,
466                                            TWITTER_SERVICE); // twitter service
467
468         if (empty($flink)) {
469             return true;
470         }
471
472         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
473             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
474             return true;
475         }
476
477         $status_id = twitter_status_id($notice);
478
479         if (empty($status_id)) {
480             return true;
481         }
482
483         try {
484             $token = TwitterOAuthClient::unpackToken($flink->credentials);
485             $client = new TwitterOAuthClient($token->key, $token->secret);
486
487             $client->favoritesDestroy($status_id);
488         } catch (Exception $e) {
489             common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
490         }
491
492         return true;
493     }
494
495     function onStartGetProfileUri($profile, &$uri)
496     {
497         if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
498             $uri = $profile->profileurl;
499             return false;
500         }
501         return true;
502     }
503
504     /**
505      * Add links in the user's profile block to their Twitter profile URL.
506      *
507      * @param Profile $profile The profile being shown
508      * @param Array   &$links  Writeable array of arrays (href, text, image).
509      *
510      * @return boolean hook value (true)
511      */
512
513     function onOtherAccountProfiles($profile, &$links)
514     {
515         $fuser = null;
516
517         $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
518
519         if (!empty($flink)) {
520             $fuser = $flink->getForeignUser();
521
522             if (!empty($fuser)) {
523                 $links[] = array("href" => $fuser->uri,
524                                  "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
525                                  "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
526             }
527         }
528
529         return true;
530     }
531
532     public function onEndShowHeadElements(Action $action)
533     {
534         if (!($action instanceof AttachmentAction)) {
535             return true;
536         }
537
538         /* Twitter card support. See https://dev.twitter.com/docs/cards */
539         /* @fixme: should we display twitter cards only for attachments posted
540          *         by local users ? Seems mandatory to display twitter:creator
541          *
542          * Author: jbfavre
543          */
544         switch ($action->attachment->mimetype) {
545             case 'image/pjpeg':
546             case 'image/jpeg':
547             case 'image/jpg':
548             case 'image/png':
549             case 'image/gif':
550                 $action->element('meta', array('name'    => 'twitter:card',
551                                              'content' => 'photo'),
552                                        null);
553                 $action->element('meta', array('name'    => 'twitter:url',
554                                              'content' => common_local_url('attachment',
555                                                               array('attachment' => $action->attachment->id))),
556                                        null );
557                 $action->element('meta', array('name'    => 'twitter:image',
558                                              'content' => $action->attachment->url));
559                 $action->element('meta', array('name'    => 'twitter:title',
560                                              'content' => $action->attachment->title));
561
562                 $ns = new AttachmentNoticeSection($this);
563                 $notices = $ns->getNotices();
564                 $noticeArray = $notices->fetchAll();
565
566                 // Should not have more than 1 notice for this attachment.
567                 if( count($noticeArray) != 1 ) { break; }
568                 $post = $noticeArray[0];
569
570                 $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
571                 if( $flink ) { // Our local user has registered Twitter Gateway
572                     $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
573                     if( $fuser ) { // Got nickname for local user's Twitter account
574                         $action->element('meta', array('name'    => 'twitter:creator',
575                                                      'content' => '@'.$fuser->nickname));
576                     }
577                 }
578                 break;
579             default: break;
580         }
581
582         return true;
583     }
584 }