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