]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/TwitterBridgePlugin.php
Merge commit 'refs/merge-requests/182' of gitorious.org:statusnet/mainline into 1.1.x
[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      * Automatically load the actions and libraries used by the Twitter bridge
188      *
189      * @param Class $cls the class
190      *
191      * @return boolean hook return
192      *
193      */
194     function onAutoload($cls)
195     {
196         $dir = dirname(__FILE__);
197
198         switch ($cls) {
199         case 'TwittersettingsAction':
200         case 'TwitterauthorizationAction':
201         case 'TwitterloginAction':
202         case 'TwitteradminpanelAction':
203             include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
204             return false;
205         case 'TwitterOAuthClient':
206         case 'TwitterQueueHandler':
207         case 'TwitterImport':
208         case 'JsonStreamReader':
209         case 'TwitterStreamReader':
210             include_once $dir . '/' . strtolower($cls) . '.php';
211             return false;
212         case 'TwitterSiteStream':
213         case 'TwitterUserStream':
214             include_once $dir . '/twitterstreamreader.php';
215             return false;
216         case 'Notice_to_status':
217         case 'Twitter_synch_status':
218             include_once $dir . '/' . $cls . '.php';
219             return false;
220         default:
221             return true;
222         }
223     }
224
225     /**
226      * Add a Twitter queue item for each notice
227      *
228      * @param Notice $notice      the notice
229      * @param array  &$transports the list of transports (queues)
230      *
231      * @return boolean hook return
232      */
233     function onStartEnqueueNotice($notice, &$transports)
234     {
235         if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
236             // Avoid a possible loop
237             if ($notice->source != 'twitter') {
238                 array_push($transports, 'twitter');
239             }
240         }
241         return true;
242     }
243
244     /**
245      * Add Twitter bridge daemons to the list of daemons to start
246      *
247      * @param array $daemons the list fo daemons to run
248      *
249      * @return boolean hook return
250      */
251     function onGetValidDaemons($daemons)
252     {
253         if (self::hasKeys()) {
254             array_push(
255                 $daemons,
256                 INSTALLDIR
257                 . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
258             );
259             if (common_config('twitterimport', 'enabled')) {
260                 array_push(
261                     $daemons,
262                     INSTALLDIR
263                     . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
264                     );
265             }
266         }
267
268         return true;
269     }
270
271     /**
272      * Register Twitter notice queue handler
273      *
274      * @param QueueManager $manager
275      *
276      * @return boolean hook return
277      */
278     function onEndInitializeQueueManager($manager)
279     {
280         if (self::hasKeys()) {
281             // Outgoing notices -> twitter
282             $manager->connect('twitter', 'TwitterQueueHandler');
283
284             // Incoming statuses <- twitter
285             $manager->connect('tweetin', 'TweetInQueueHandler');
286         }
287         return true;
288     }
289
290     /**
291      * If the plugin's installed, this should be accessible to admins
292      */
293     function onAdminPanelCheck($name, &$isOK)
294     {
295         if ($name == 'twitter') {
296             $isOK = true;
297             return false;
298         }
299         return true;
300     }
301
302     /**
303      * Add a Twitter tab to the admin panel
304      *
305      * @param Widget $nav Admin panel nav
306      *
307      * @return boolean hook value
308      */
309
310     function onEndAdminPanelNav($nav)
311     {
312         if (AdminPanelAction::canAdmin('twitter')) {
313
314             $action_name = $nav->action->trimmed('action');
315
316             $nav->out->menuItem(
317                 common_local_url('twitteradminpanel'),
318                 // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
319                 _m('Twitter'),
320                 // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
321                 _m('Twitter bridge configuration page.'),
322                 $action_name == 'twitteradminpanel',
323                 'nav_twitter_admin_panel'
324             );
325         }
326
327         return true;
328     }
329
330     /**
331      * Plugin version data
332      *
333      * @param array &$versions array of version blocks
334      *
335      * @return boolean hook value
336      */
337     function onPluginVersion(&$versions)
338     {
339         $versions[] = array(
340             'name' => 'TwitterBridge',
341             'version' => self::VERSION,
342             'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
343             'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
344             // TRANS: Plugin description.
345             'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
346                 'of a StatusNet instance with ' .
347                 '<a href="http://twitter.com/">Twitter</a>.'
348             )
349         );
350         return true;
351     }
352
353     /**
354      * Expose the adminImportControl setting to the administration panel code.
355      * This allows us to disable the import bridge enabling checkbox for administrators,
356      * since on a bulk farm site we can't yet automate the import daemon setup.
357      *
358      * @return boolean hook value;
359      */
360     function onTwitterBridgeAdminImportControl()
361     {
362         return (bool)$this->adminImportControl;
363     }
364
365     /**
366      * When the site is set to ssl=sometimes mode, we should make sure our
367      * various auth-related pages are on SSL to keep things looking happy.
368      * Although we're not submitting passwords directly, we do link out to
369      * an authentication source and it's a lot happier if we've got some
370      * protection against MitM.
371      *
372      * @param string $action name
373      * @param boolean $ssl outval to force SSL
374      * @return mixed hook return value
375      */
376     function onSensitiveAction($action, &$ssl)
377     {
378         $sensitive = array('twitteradminpanel',
379                            'twittersettings',
380                            'twitterauthorization',
381                            'twitterlogin');
382         if (in_array($action, $sensitive)) {
383             $ssl = true;
384             return false;
385         } else {
386             return true;
387         }
388     }
389
390     /**
391      * Database schema setup
392      *
393      * We maintain a table mapping StatusNet notices to Twitter statuses
394      *
395      * @see Schema
396      * @see ColumnDef
397      *
398      * @return boolean hook value; true means continue processing, false means stop.
399      */
400     function onCheckSchema()
401     {
402         $schema = Schema::get();
403
404         // For saving the last-synched status of various timelines
405         // home_timeline, messages (in), messages (out), ...
406
407         $schema->ensureTable('twitter_synch_status',
408                              array(new ColumnDef('foreign_id', 'bigint', null,
409                                                  false, 'PRI'),
410                                    new ColumnDef('timeline', 'varchar', 255,
411                                                  false, 'PRI'),
412                                    new ColumnDef('last_id', 'bigint', null, // XXX: check for PostgreSQL
413                                                  false),
414                                    new ColumnDef('created', 'datetime', null,
415                                                  false),
416                                    new ColumnDef('modified', 'datetime', null,
417                                                  false)));
418
419         // For storing user-submitted flags on profiles
420
421         $schema->ensureTable('notice_to_status',
422                              array(new ColumnDef('notice_id', 'integer', null,
423                                                  false, 'PRI'),
424                                    new ColumnDef('status_id', 'bigint', null, // XXX: check for PostgreSQL
425                                                  false, 'UNI'),
426                                    new ColumnDef('created', 'datetime', null,
427                                                  false)));
428
429         return true;
430     }
431
432     /**
433      * If a notice gets deleted, remove the Notice_to_status mapping and
434      * delete the status on Twitter.
435      *
436      * @param User   $user   The user doing the deleting
437      * @param Notice $notice The notice getting deleted
438      *
439      * @return boolean hook value
440      */
441     function onStartDeleteOwnNotice(User $user, Notice $notice)
442     {
443         $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
444
445         if (!empty($n2s)) {
446
447             $flink = Foreign_link::getByUserID($notice->profile_id,
448                                                TWITTER_SERVICE); // twitter service
449
450             if (empty($flink)) {
451                 return true;
452             }
453
454             if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
455                 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
456                 return true;
457             }
458
459             try {
460                 $token = TwitterOAuthClient::unpackToken($flink->credentials);
461                 $client = new TwitterOAuthClient($token->key, $token->secret);
462
463                 $client->statusesDestroy($n2s->status_id);
464             } catch (Exception $e) {
465                 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
466             }
467
468             $n2s->delete();
469         }
470         return true;
471     }
472
473     /**
474      * Notify remote users when their notices get favorited.
475      *
476      * @param Profile or User $profile of local user doing the faving
477      * @param Notice $notice being favored
478      * @return hook return value
479      */
480     function onEndFavorNotice(Profile $profile, Notice $notice)
481     {
482         $flink = Foreign_link::getByUserID($profile->id,
483                                            TWITTER_SERVICE); // twitter service
484
485         if (empty($flink)) {
486             return true;
487         }
488
489         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
490             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
491             return true;
492         }
493
494         $status_id = twitter_status_id($notice);
495
496         if (empty($status_id)) {
497             return true;
498         }
499
500         try {
501             $token = TwitterOAuthClient::unpackToken($flink->credentials);
502             $client = new TwitterOAuthClient($token->key, $token->secret);
503
504             $client->favoritesCreate($status_id);
505         } catch (Exception $e) {
506             common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
507         }
508
509         return true;
510     }
511
512     /**
513      * Notify remote users when their notices get de-favorited.
514      *
515      * @param Profile $profile Profile person doing the de-faving
516      * @param Notice  $notice  Notice being favored
517      *
518      * @return hook return value
519      */
520     function onEndDisfavorNotice(Profile $profile, Notice $notice)
521     {
522         $flink = Foreign_link::getByUserID($profile->id,
523                                            TWITTER_SERVICE); // twitter service
524
525         if (empty($flink)) {
526             return true;
527         }
528
529         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
530             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
531             return true;
532         }
533
534         $status_id = twitter_status_id($notice);
535
536         if (empty($status_id)) {
537             return true;
538         }
539
540         try {
541             $token = TwitterOAuthClient::unpackToken($flink->credentials);
542             $client = new TwitterOAuthClient($token->key, $token->secret);
543
544             $client->favoritesDestroy($status_id);
545         } catch (Exception $e) {
546             common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
547         }
548
549         return true;
550     }
551
552     function onStartGetProfileUri($profile, &$uri)
553     {
554         if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
555             $uri = $profile->profileurl;
556             return false;
557         }
558         return true;
559     }
560 }