git.gnu.io has moved to IP address 209.51.188.249 -- please double check where you are logging in.

TwitterBridgePlugin.php 18.2 KB
Newer Older
1 2
<?php
/**
3
 * StatusNet, the distributed open-source microblogging tool
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * PHP version 5
 *
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Plugin
21 22
 * @package   StatusNet
 * @author    Zach Copley <zach@status.net>
23 24
 * @author    Julien C <chaumond@gmail.com>
 * @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 35 36 37
/**
 * Plugin for sending and importing Twitter statuses
 *
 * This class allows users to link their Twitter accounts
 *
38 39
 * Depends on Favorite plugin.
 *
40
 * @category Plugin
41 42
 * @package  StatusNet
 * @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 47 48 49
 * @link     http://twitter.com/
 */
class TwitterBridgePlugin extends Plugin
{
50
    const VERSION = GNUSOCIAL_VERSION;
51
    public $adminImportControl = false; // Should the 'import' checkbox be exposed in the admin panel?
52

53 54 55
    /**
     * Initializer for the plugin.
     */
56
    function initialize()
57
    {
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        // Allow the key and secret to be passed in
        // Control panel will override

        if (isset($this->consumer_key)) {
            $key = common_config('twitter', 'consumer_key');
            if (empty($key)) {
                Config::save('twitter', 'consumer_key', $this->consumer_key);
            }
        }

        if (isset($this->consumer_secret)) {
            $secret = common_config('twitter', 'consumer_secret');
            if (empty($secret)) {
                Config::save(
                    'twitter',
                    'consumer_secret',
                    $this->consumer_secret
                );
            }
        }
78 79
    }

80 81 82 83 84 85 86 87
    /**
     * Check to see if there is a consumer key and secret defined
     * for Twitter integration.
     *
     * @return boolean result
     */
    static function hasKeys()
    {
88 89
        $ckey    = common_config('twitter', 'consumer_key');
        $csecret = common_config('twitter', 'consumer_secret');
90

91 92 93
        if (empty($ckey) && empty($csecret)) {
            $ckey    = common_config('twitter', 'global_consumer_key');
            $csecret = common_config('twitter', 'global_consumer_secret');
94 95
        }

96
        if (!empty($ckey) && !empty($csecret)) {
97 98 99 100 101 102
            return true;
        }

        return false;
    }

103 104 105 106 107
    /**
     * Add Twitter-related paths to the router table
     *
     * Hook for RouterInitialized event.
     *
108
     * @param URLMapper $m path-to-action mapper
109
     *
110 111
     * @return boolean hook return
     */
112
    public function onRouterInitialized(URLMapper $m)
113
    {
114
        $m->connect('panel/twitter', array('action' => 'twitteradminpanel'));
115

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
        if (self::hasKeys()) {
            $m->connect(
                'twitter/authorization',
                array('action' => 'twitterauthorization')
            );
            $m->connect(
                'settings/twitter', array(
                    'action' => 'twittersettings'
                    )
                );
            if (common_config('twitter', 'signin')) {
                $m->connect(
                    'main/twitterlogin',
                    array('action' => 'twitterlogin')
                );
            }
132 133
        }

134 135
        return true;
    }
136

137
    /*
138
     * Add a login tab for 'Sign in with Twitter'
139
     *
140
     * @param Action $action the current action
141 142 143
     *
     * @return void
     */
144
    function onEndLoginGroupNav($action)
145 146 147
    {
        $action_name = $action->trimmed('action');

148
        if (self::hasKeys() && common_config('twitter', 'signin')) {
149 150
            $action->menuItem(
                common_local_url('twitterlogin'),
151 152 153 154
                // TRANS: Menu item in login navigation.
                _m('MENU','Twitter'),
                // TRANS: Title for menu item in login navigation.
                _m('Login or register using Twitter.'),
155 156 157
                'twitterlogin' === $action_name
            );
        }
158 159 160

        return true;
    }
161

162 163 164
    /**
     * Add the Twitter Settings page to the Connect Settings menu
     *
165
     * @param Action $action The calling page
166 167 168
     *
     * @return boolean hook return
     */
169
    function onEndConnectSettingsNav($action)
170
    {
171 172
        if (self::hasKeys()) {
            $action_name = $action->trimmed('action');
173

174 175
            $action->menuItem(
                common_local_url('twittersettings'),
176 177 178
                // TRANS: Menu item in connection settings navigation.
                _m('MENU','Twitter'),
                // TRANS: Title for menu item in connection settings navigation.
179 180 181 182
                _m('Twitter integration options'),
                $action_name === 'twittersettings'
            );
        }
183 184 185
        return true;
    }

186 187 188
    /**
     * Add a Twitter queue item for each notice
     *
189 190
     * @param Notice $notice      the notice
     * @param array  &$transports the list of transports (queues)
191 192 193
     *
     * @return boolean hook return
     */
194
    function onStartEnqueueNotice($notice, &$transports)
195
    {
196
        if (self::hasKeys() && $notice->isLocal() && $notice->inScope(null)) {
197 198 199 200
            // Avoid a possible loop
            if ($notice->source != 'twitter') {
                array_push($transports, 'twitter');
            }
201
        }
202 203 204
        return true;
    }

205 206 207 208 209 210 211
    /**
     * Add Twitter bridge daemons to the list of daemons to start
     *
     * @param array $daemons the list fo daemons to run
     *
     * @return boolean hook return
     */
212
    function onGetValidDaemons(&$daemons)
213
    {
214
        if (self::hasKeys()) {
215 216 217
            array_push(
                $daemons,
                INSTALLDIR
218
                . '/plugins/TwitterBridge/daemons/synctwitterfriends.php'
219
            );
220 221 222 223 224 225 226
            if (common_config('twitterimport', 'enabled')) {
                array_push(
                    $daemons,
                    INSTALLDIR
                    . '/plugins/TwitterBridge/daemons/twitterstatusfetcher.php'
                    );
            }
227 228 229 230
        }

        return true;
    }
231

232 233 234 235 236 237 238 239 240
    /**
     * Register Twitter notice queue handler
     *
     * @param QueueManager $manager
     *
     * @return boolean hook return
     */
    function onEndInitializeQueueManager($manager)
    {
241
        if (self::hasKeys()) {
242
            // Outgoing notices -> twitter
243
            $manager->connect('twitter', 'TwitterQueueHandler');
244 245 246

            // Incoming statuses <- twitter
            $manager->connect('tweetin', 'TweetInQueueHandler');
247
        }
248 249 250
        return true;
    }

251 252 253 254 255 256 257 258 259 260 261 262
    /**
     * If the plugin's installed, this should be accessible to admins
     */
    function onAdminPanelCheck($name, &$isOK)
    {
        if ($name == 'twitter') {
            $isOK = true;
            return false;
        }
        return true;
    }

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    /**
     * Add a Twitter tab to the admin panel
     *
     * @param Widget $nav Admin panel nav
     *
     * @return boolean hook value
     */

    function onEndAdminPanelNav($nav)
    {
        if (AdminPanelAction::canAdmin('twitter')) {

            $action_name = $nav->action->trimmed('action');

            $nav->out->menuItem(
                common_local_url('twitteradminpanel'),
279
                // TRANS: Menu item in administrative panel that leads to the Twitter bridge configuration.
280
                _m('Twitter'),
281 282
                // TRANS: Menu item title in administrative panel that leads to the Twitter bridge configuration.
                _m('Twitter bridge configuration page.'),
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
                $action_name == 'twitteradminpanel',
                'nav_twitter_admin_panel'
            );
        }

        return true;
    }

    /**
     * Plugin version data
     *
     * @param array &$versions array of version blocks
     *
     * @return boolean hook value
     */
298
    function onPluginVersion(array &$versions)
299
    {
300 301 302
        $versions[] = array(
            'name' => 'TwitterBridge',
            'version' => self::VERSION,
303
            'author' => 'Zach Copley, Julien C, Jean Baptiste Favre',
304
            'homepage' => 'http://status.net/wiki/Plugin:TwitterBridge',
305 306
            // TRANS: Plugin description.
            'rawdescription' => _m('The Twitter "bridge" plugin allows integration ' .
Siebrand Mazeland's avatar
Siebrand Mazeland committed
307
                'of a StatusNet instance with ' .
308 309 310
                '<a href="http://twitter.com/">Twitter</a>.'
            )
        );
311 312 313
        return true;
    }

314 315 316 317 318 319 320 321 322 323 324 325
    /**
     * Expose the adminImportControl setting to the administration panel code.
     * This allows us to disable the import bridge enabling checkbox for administrators,
     * since on a bulk farm site we can't yet automate the import daemon setup.
     *
     * @return boolean hook value;
     */
    function onTwitterBridgeAdminImportControl()
    {
        return (bool)$this->adminImportControl;
    }

326 327 328 329 330 331 332 333 334 335 336 337 338 339
    /**
     * Database schema setup
     *
     * We maintain a table mapping StatusNet notices to Twitter statuses
     *
     * @see Schema
     * @see ColumnDef
     *
     * @return boolean hook value; true means continue processing, false means stop.
     */
    function onCheckSchema()
    {
        $schema = Schema::get();

340 341
        // For saving the last-synched status of various timelines
        // 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 348
        return true;
    }
349 350

    /**
351 352
     * If a notice gets deleted, remove the Notice_to_status mapping and
     * delete the status on Twitter.
353
     *
354
     * @param User   $user   The user doing the deleting
355 356 357 358
     * @param Notice $notice The notice getting deleted
     *
     * @return boolean hook value
     */
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 366 367
            try {
                $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE); // twitter service
            } catch (NoResultException $e) {
368 369 370 371 372 373 374 375
                return true;
            }

            if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
                $this->log(LOG_INFO, "Skipping deleting notice for {$notice->id} since link is not OAuth.");
                return true;
            }

376 377 378
            try {
                $token = TwitterOAuthClient::unpackToken($flink->credentials);
                $client = new TwitterOAuthClient($token->key, $token->secret);
379

380 381 382 383
                $client->statusesDestroy($n2s->status_id);
            } catch (Exception $e) {
                common_log(LOG_ERR, "Error attempting to delete bridged notice from Twitter: " . $e->getMessage());
            }
384

385 386 387 388
            $n2s->delete();
        }
        return true;
    }
389 390 391 392 393 394 395 396 397 398

    /**
     * Notify remote users when their notices get favorited.
     *
     * @param Profile or User $profile of local user doing the faving
     * @param Notice $notice being favored
     * @return hook return value
     */
    function onEndFavorNotice(Profile $profile, Notice $notice)
    {
399 400 401
        try {
            $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
        } catch (NoResultException $e) {
402 403 404 405
            return true;
        }

        if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
406
            $this->log(LOG_INFO, "Skipping fave processing for {$profile->getID()} since link is not OAuth.");
407 408 409 410 411 412 413 414 415
            return true;
        }

        $status_id = twitter_status_id($notice);

        if (empty($status_id)) {
            return true;
        }

416 417 418
        try {
            $token = TwitterOAuthClient::unpackToken($flink->credentials);
            $client = new TwitterOAuthClient($token->key, $token->secret);
419

420 421 422 423
            $client->favoritesCreate($status_id);
        } catch (Exception $e) {
            common_log(LOG_ERR, "Error attempting to favorite bridged notice on Twitter: " . $e->getMessage());
        }
424 425 426 427 428 429 430 431 432 433 434 435 436 437

        return true;
    }

    /**
     * Notify remote users when their notices get de-favorited.
     *
     * @param Profile $profile Profile person doing the de-faving
     * @param Notice  $notice  Notice being favored
     *
     * @return hook return value
     */
    function onEndDisfavorNotice(Profile $profile, Notice $notice)
    {
438 439 440
        try {
            $flink = Foreign_link::getByUserID($profile->getID(), TWITTER_SERVICE); // twitter service
        } catch (NoResultException $e) {
441 442 443 444 445 446 447 448 449 450 451 452 453 454
            return true;
        }

        if (!TwitterOAuthClient::isPackedToken($flink->credentials)) {
            $this->log(LOG_INFO, "Skipping fave processing for {$profile->id} since link is not OAuth.");
            return true;
        }

        $status_id = twitter_status_id($notice);

        if (empty($status_id)) {
            return true;
        }

455 456 457
        try {
            $token = TwitterOAuthClient::unpackToken($flink->credentials);
            $client = new TwitterOAuthClient($token->key, $token->secret);
458

459 460 461 462
            $client->favoritesDestroy($status_id);
        } catch (Exception $e) {
            common_log(LOG_ERR, "Error attempting to unfavorite bridged notice on Twitter: " . $e->getMessage());
        }
463 464 465

        return true;
    }
466 467 468 469 470 471 472 473 474

    function onStartGetProfileUri($profile, &$uri)
    {
        if (preg_match('!^https?://twitter.com/!', $profile->profileurl)) {
            $uri = $profile->profileurl;
            return false;
        }
        return true;
    }
475 476 477 478 479 480 481 482 483 484 485 486 487 488

    /**
     * Add links in the user's profile block to their Twitter profile URL.
     *
     * @param Profile $profile The profile being shown
     * @param Array   &$links  Writeable array of arrays (href, text, image).
     *
     * @return boolean hook value (true)
     */

    function onOtherAccountProfiles($profile, &$links)
    {
        $fuser = null;

489 490
        try {
            $flink = Foreign_link::getByUserID($profile->id, TWITTER_SERVICE);
491 492
            $fuser = $flink->getForeignUser();

493 494 495 496
            $links[] = array("href" => $fuser->uri,
                             "text" => sprintf(_("@%s on Twitter"), $fuser->nickname),
                             "image" => $this->path("icons/twitter-bird-white-on-blue.png"));
        } catch (NoResultException $e) {
497
            // no foreign link and/or user for Twitter on this profile ID
498 499 500 501
        }

        return true;
    }
502 503 504

    public function onEndShowHeadElements(Action $action)
    {
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        if($action instanceof ShowNoticeAction) { // Showing a notice
            $notice = Notice::getKV('id', $action->arg('notice'));

            try {
                $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE);
                $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
            } catch (NoResultException $e) {
                return true;
            }

            $statusId = twitter_status_id($notice);
            if($notice instanceof Notice && $notice->isLocal() && $statusId) {
                $tweetUrl = 'https://twitter.com/' . $fuser->nickname . '/status/' . $statusId;
                $action->element('link', array('rel' => 'syndication', 'href' => $tweetUrl));
            }
        }

522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
        if (!($action instanceof AttachmentAction)) {
            return true;
        }

        /* Twitter card support. See https://dev.twitter.com/docs/cards */
        /* @fixme: should we display twitter cards only for attachments posted
         *         by local users ? Seems mandatory to display twitter:creator
         *
         * Author: jbfavre
         */
        switch ($action->attachment->mimetype) {
            case 'image/pjpeg':
            case 'image/jpeg':
            case 'image/jpg':
            case 'image/png':
            case 'image/gif':
                $action->element('meta', array('name'    => 'twitter:card',
                                             'content' => 'photo'),
                                       null);
                $action->element('meta', array('name'    => 'twitter:url',
                                             'content' => common_local_url('attachment',
                                                              array('attachment' => $action->attachment->id))),
                                       null );
                $action->element('meta', array('name'    => 'twitter:image',
                                             'content' => $action->attachment->url));
                $action->element('meta', array('name'    => 'twitter:title',
                                             'content' => $action->attachment->title));

550
                $ns = new AttachmentNoticeSection($action);
551 552 553 554 555 556 557
                $notices = $ns->getNotices();
                $noticeArray = $notices->fetchAll();

                // Should not have more than 1 notice for this attachment.
                if( count($noticeArray) != 1 ) { break; }
                $post = $noticeArray[0];

558 559
                try {
                    $flink = Foreign_link::getByUserID($post->profile_id, TWITTER_SERVICE);
560
                    $fuser = Foreign_user::getForeignUser($flink->foreign_id, TWITTER_SERVICE);
561 562 563 564
                    $action->element('meta', array('name'    => 'twitter:creator',
                                                   'content' => '@'.$fuser->nickname));
                } catch (NoResultException $e) {
                    // no foreign link and/or user for Twitter on this profile ID
565 566
                }
                break;
567 568
            default:
                break;
569 570 571 572
        }

        return true;
    }
573
}