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