]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/TwitterBridgePlugin.php
Merge branch 'master' of git.gnu.io:gnu/gnu-social into mmn_fixes
[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' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/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      * Database schema setup
328      *
329      * We maintain a table mapping StatusNet notices to Twitter statuses
330      *
331      * @see Schema
332      * @see ColumnDef
333      *
334      * @return boolean hook value; true means continue processing, false means stop.
335      */
336     function onCheckSchema()
337     {
338         $schema = Schema::get();
339
340         // For saving the last-synched status of various timelines
341         // home_timeline, messages (in), messages (out), ...
342         $schema->ensureTable('twitter_synch_status', Twitter_synch_status::schemaDef());
343
344         // For storing user-submitted flags on profiles
345         $schema->ensureTable('notice_to_status', Notice_to_status::schemaDef());
346
347         return true;
348     }
349
350     /**
351      * If a notice gets deleted, remove the Notice_to_status mapping and
352      * delete the status on Twitter.
353      *
354      * @param User   $user   The user doing the deleting
355      * @param Notice $notice The notice getting deleted
356      *
357      * @return boolean hook value
358      */
359     function onStartDeleteOwnNotice(User $user, Notice $notice)
360     {
361         $n2s = Notice_to_status::getKV('notice_id', $notice->id);
362
363         if ($n2s instanceof Notice_to_status) {
364
365             try {
366                 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); // twitter service
367             } catch (NoResultException $e) {
368                 return true;
369             }
370
371             if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
372                 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
373                 return true;
374             }
375
376             try {
377                 $token = TwitterOAuthClient::unpackToken($flink->credentials);
378                 $client = new TwitterOAuthClient($token->key, $token->secret);
379
380                 $client->statusesDestroy($n2s->status_id);
381             } catch (Exception $e) {
382                 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
383             }
384
385             $n2s->delete();
386         }
387         return true;
388     }
389
390     /**
391      * Notify remote users when their notices get favorited.
392      *
393      * @param Profile or User $profile of local user doing the faving
394      * @param Notice $notice being favored
395      * @return hook return value
396      */
397     function onEndFavorNotice(Profile $profile, Notice $notice)
398     {
399         try {
400             $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
401         } catch (NoResultException $e) {
402             return true;
403         }
404
405         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
406             $this->log(LOG_INFO, "Skipping fave processing for {$profile->getID()} since link is not OAuth.");
407             return true;
408         }
409
410         $status_id = twitter_status_id($notice);
411
412         if (empty($status_id)) {
413             return true;
414         }
415
416         try {
417             $token = TwitterOAuthClient::unpackToken($flink->credentials);
418             $client = new TwitterOAuthClient($token->key, $token->secret);
419
420             $client->favoritesCreate($status_id);
421         } catch (Exception $e) {
422             common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
423         }
424
425         return true;
426     }
427
428     /**
429      * Notify remote users when their notices get de-favorited.
430      *
431      * @param Profile $profile Profile person doing the de-faving
432      * @param Notice  $notice  Notice being favored
433      *
434      * @return hook return value
435      */
436     function onEndDisfavorNotice(Profile $profile, Notice $notice)
437     {
438         try {
439             $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
440         } catch (NoResultException $e) {
441             return true;
442         }
443
444         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
445             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
446             return true;
447         }
448
449         $status_id = twitter_status_id($notice);
450
451         if (empty($status_id)) {
452             return true;
453         }
454
455         try {
456             $token = TwitterOAuthClient::unpackToken($flink->credentials);
457             $client = new TwitterOAuthClient($token->key, $token->secret);
458
459             $client->favoritesDestroy($status_id);
460         } catch (Exception $e) {
461             common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
462         }
463
464         return true;
465     }
466
467     function onStartGetProfileUri($profile, &$uri)
468     {
469         if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
470             $uri = $profile->profileurl;
471             return false;
472         }
473         return true;
474     }
475
476     /**
477      * Add links in the user's profile block to their Twitter profile URL.
478      *
479      * @param Profile $profile The profile being shown
480      * @param Array   &$links  Writeable array of arrays (href, text, image).
481      *
482      * @return boolean hook value (true)
483      */
484
485     function onOtherAccountProfiles($profile, &$links)
486     {
487         $fuser = null;
488
489         try {
490             $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
491             $fuser = $flink->getForeignUser();
492
493             $links[] = array("href" => $fuser->uri,
494                              "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
495                              "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
496         } catch (NoResultException $e) {
497             // no foreign link and/or user for Twitter on this profile ID
498         }
499
500         return true;
501     }
502
503     public function onEndShowHeadElements(Action $action)
504     {
505         if($action instanceof ShowNoticeAction) { // Showing a notice
506             $notice = Notice::getKV('id', $action->arg('notice'));
507
508             try {
509                 $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE);
510                 $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
511             } catch (NoResultException $e) {
512                 return true;
513             }
514
515             $statusId = twitter_status_id($notice);
516             if($notice instanceof Notice && $notice->isLocal() && $statusId) {
517                 $tweetUrl = 'https://twitter.com/' . $fuser->nickname . '/status/' . $statusId;
518                 $action->element('link', array('rel' => 'syndication', 'href' => $tweetUrl));
519             }
520         }
521
522         if (!($action instanceof AttachmentAction)) {
523             return true;
524         }
525
526         /* Twitter card support. See https://dev.twitter.com/docs/cards */
527         /* @fixme: should we display twitter cards only for attachments posted
528          *         by local users ? Seems mandatory to display twitter:creator
529          *
530          * Author: jbfavre
531          */
532         switch ($action->attachment->mimetype) {
533             case 'image/pjpeg':
534             case 'image/jpeg':
535             case 'image/jpg':
536             case 'image/png':
537             case 'image/gif':
538                 $action->element('meta', array('name'    => 'twitter:card',
539                                              'content' => 'photo'),
540                                        null);
541                 $action->element('meta', array('name'    => 'twitter:url',
542                                              'content' => common_local_url('attachment',
543                                                               array('attachment' => $action->attachment->id))),
544                                        null );
545                 $action->element('meta', array('name'    => 'twitter:image',
546                                              'content' => $action->attachment->url));
547                 $action->element('meta', array('name'    => 'twitter:title',
548                                              'content' => $action->attachment->title));
549
550                 $ns = new AttachmentNoticeSection($action);
551                 $notices = $ns->getNotices();
552                 $noticeArray = $notices->fetchAll();
553
554                 // Should not have more than 1 notice for this attachment.
555                 if( count($noticeArray) != 1 ) { break; }
556                 $post = $noticeArray[0];
557
558                 try {
559                     $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
560                     $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
561                     $action->element('meta', array('name'    => 'twitter:creator',
562                                                    'content' => '@'.$fuser->nickname));
563                 } catch (NoResultException $e) {
564                     // no foreign link and/or user for Twitter on this profile ID
565                 }
566                 break;
567             default:
568                 break;
569         }
570
571         return true;
572     }
573 }