]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/TwitterBridgePlugin.php
Update translator documentation.
[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      * Add a Twitter tab to the admin panel
292      *
293      * @param Widget $nav Admin panel nav
294      *
295      * @return boolean hook value
296      */
297
298     function onEndAdminPanelNav($nav)
299     {
300         if (AdminPanelAction::canAdmin('twitter')) {
301
302             $action_name = $nav->action->trimmed('action');
303
304             $nav->out->menuItem(
305                 common_local_url('twitteradminpanel'),
306                 _m('Twitter'),
307                 _m('Twitter bridge configuration'),
308                 $action_name == 'twitteradminpanel',
309                 'nav_twitter_admin_panel'
310             );
311         }
312
313         return true;
314     }
315
316     /**
317      * Plugin version data
318      *
319      * @param array &$versions array of version blocks
320      *
321      * @return boolean hook value
322      */
323     function onPluginVersion(&$versions)
324     {
325         $versions[] = array(
326             'name' => 'TwitterBridge',
327             'version' => self::VERSION,
328             'author' => 'Zach Copley, Julien C',
329             'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
330             // TRANS: Plugin description.
331             'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
332                 'of a StatusNet instance with ' .
333                 '<a href="http://twitter.com/">Twitter</a>.'
334             )
335         );
336         return true;
337     }
338
339     /**
340      * Expose the adminImportControl setting to the administration panel code.
341      * This allows us to disable the import bridge enabling checkbox for administrators,
342      * since on a bulk farm site we can't yet automate the import daemon setup.
343      *
344      * @return boolean hook value;
345      */
346     function onTwitterBridgeAdminImportControl()
347     {
348         return (bool)$this->adminImportControl;
349     }
350
351     /**
352      * When the site is set to ssl=sometimes mode, we should make sure our
353      * various auth-related pages are on SSL to keep things looking happy.
354      * Although we're not submitting passwords directly, we do link out to
355      * an authentication source and it's a lot happier if we've got some
356      * protection against MitM.
357      *
358      * @param string $action name
359      * @param boolean $ssl outval to force SSL
360      * @return mixed hook return value
361      */
362     function onSensitiveAction($action, &$ssl)
363     {
364         $sensitive = array('twitteradminpanel',
365                            'twittersettings',
366                            'twitterauthorization',
367                            'twitterlogin');
368         if (in_array($action, $sensitive)) {
369             $ssl = true;
370             return false;
371         } else {
372             return true;
373         }
374     }
375
376     /**
377      * Database schema setup
378      *
379      * We maintain a table mapping StatusNet notices to Twitter statuses
380      *
381      * @see Schema
382      * @see ColumnDef
383      *
384      * @return boolean hook value; true means continue processing, false means stop.
385      */
386     function onCheckSchema()
387     {
388         $schema = Schema::get();
389
390         // For saving the last-synched status of various timelines
391         // home_timeline, messages (in), messages (out), ...
392
393         $schema->ensureTable('twitter_synch_status',
394                              array(new ColumnDef('foreign_id', 'bigint', null,
395                                                  false, 'PRI'),
396                                    new ColumnDef('timeline', 'varchar', 255,
397                                                  false, 'PRI'),
398                                    new ColumnDef('last_id', 'bigint', null, // XXX: check for PostgreSQL
399                                                  false),
400                                    new ColumnDef('created', 'datetime', null,
401                                                  false),
402                                    new ColumnDef('modified', 'datetime', null,
403                                                  false)));
404
405         // For storing user-submitted flags on profiles
406
407         $schema->ensureTable('notice_to_status',
408                              array(new ColumnDef('notice_id', 'integer', null,
409                                                  false, 'PRI'),
410                                    new ColumnDef('status_id', 'bigint', null, // XXX: check for PostgreSQL
411                                                  false, 'UNI'),
412                                    new ColumnDef('created', 'datetime', null,
413                                                  false)));
414
415         return true;
416     }
417
418     /**
419      * If a notice gets deleted, remove the Notice_to_status mapping and
420      * delete the status on Twitter.
421      *
422      * @param User   $user   The user doing the deleting
423      * @param Notice $notice The notice getting deleted
424      *
425      * @return boolean hook value
426      */
427     function onStartDeleteOwnNotice(User $user, Notice $notice)
428     {
429         $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
430
431         if (!empty($n2s)) {
432
433             $flink = Foreign_link::getByUserID($notice->profile_id,
434                                                TWITTER_SERVICE); // twitter service
435
436             if (empty($flink)) {
437                 return true;
438             }
439
440             if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
441                 $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
442                 return true;
443             }
444
445             try {
446                 $token = TwitterOAuthClient::unpackToken($flink->credentials);
447                 $client = new TwitterOAuthClient($token->key, $token->secret);
448
449                 $client->statusesDestroy($n2s->status_id);
450             } catch (Exception $e) {
451                 common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
452             }
453
454             $n2s->delete();
455         }
456         return true;
457     }
458
459     /**
460      * Notify remote users when their notices get favorited.
461      *
462      * @param Profile or User $profile of local user doing the faving
463      * @param Notice $notice being favored
464      * @return hook return value
465      */
466     function onEndFavorNotice(Profile $profile, Notice $notice)
467     {
468         $flink = Foreign_link::getByUserID($profile->id,
469                                            TWITTER_SERVICE); // twitter service
470
471         if (empty($flink)) {
472             return true;
473         }
474
475         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
476             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
477             return true;
478         }
479
480         $status_id = twitter_status_id($notice);
481
482         if (empty($status_id)) {
483             return true;
484         }
485
486         try {
487             $token = TwitterOAuthClient::unpackToken($flink->credentials);
488             $client = new TwitterOAuthClient($token->key, $token->secret);
489
490             $client->favoritesCreate($status_id);
491         } catch (Exception $e) {
492             common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
493         }
494
495         return true;
496     }
497
498     /**
499      * Notify remote users when their notices get de-favorited.
500      *
501      * @param Profile $profile Profile person doing the de-faving
502      * @param Notice  $notice  Notice being favored
503      *
504      * @return hook return value
505      */
506     function onEndDisfavorNotice(Profile $profile, Notice $notice)
507     {
508         $flink = Foreign_link::getByUserID($profile->id,
509                                            TWITTER_SERVICE); // twitter service
510
511         if (empty($flink)) {
512             return true;
513         }
514
515         if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
516             $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
517             return true;
518         }
519
520         $status_id = twitter_status_id($notice);
521
522         if (empty($status_id)) {
523             return true;
524         }
525
526         try {
527             $token = TwitterOAuthClient::unpackToken($flink->credentials);
528             $client = new TwitterOAuthClient($token->key, $token->secret);
529
530             $client->favoritesDestroy($status_id);
531         } catch (Exception $e) {
532             common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
533         }
534
535         return true;
536     }
537
538     function onStartGetProfileUri($profile, &$uri)
539     {
540         if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
541             $uri = $profile->profileurl;
542             return false;
543         }
544         return true;
545     }
546 }