We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

OStatusPlugin.php 47.8 KB
Newer Older
1 2 3
<?php
/*
 * StatusNet - the distributed open-source microblogging tool
4
 * Copyright (C) 2009-2010, StatusNet, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * 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/>.
 */

/**
21
 * @package OStatusPlugin
22 23 24
 * @maintainer Brion Vibber <brion@status.net>
 */

25 26 27
if (!defined('STATUSNET')) {
    exit(1);
}
28

James Walker's avatar
James Walker committed
29 30
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/');

31 32
class FeedSubException extends Exception
{
33 34 35 36 37 38 39 40 41
    function __construct($msg=null)
    {
        $type = get_class($this);
        if ($msg) {
            parent::__construct("$type: $msg");
        } else {
            parent::__construct($type);
        }
    }
42 43
}

44
class OStatusPlugin extends Plugin
45 46 47 48 49 50 51 52 53
{
    /**
     * Hook for RouterInitialized event.
     *
     * @param Net_URL_Mapper $m path-to-action mapper
     * @return boolean hook return
     */
    function onRouterInitialized($m)
    {
James Walker's avatar
James Walker committed
54
        // Discovery actions
55 56
        $m->connect('main/ownerxrd',
                    array('action' => 'ownerxrd'));
57 58
        $m->connect('main/ostatus',
                    array('action' => 'ostatusinit'));
Shashi Gowda's avatar
Shashi Gowda committed
59 60 61 62
        $m->connect('main/ostatustag',
                    array('action' => 'ostatustag'));
        $m->connect('main/ostatustag?nickname=:nickname',
                    array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
63 64
        $m->connect('main/ostatus?nickname=:nickname',
                  array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
65 66
        $m->connect('main/ostatus?group=:group',
                  array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
Shashi Gowda's avatar
Shashi Gowda committed
67 68 69 70 71
        $m->connect('main/ostatus?peopletag=:peopletag&tagger=:tagger',
                  array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
                                                          'peopletag' => '[A-Za-z0-9_-]+'));

        // Remote subscription actions
72
        $m->connect('main/ostatussub',
73
                    array('action' => 'ostatussub'));
74 75
        $m->connect('main/ostatusgroup',
                    array('action' => 'ostatusgroup'));
Shashi Gowda's avatar
Shashi Gowda committed
76 77
        $m->connect('main/ostatuspeopletag',
                    array('action' => 'ostatuspeopletag'));
James Walker's avatar
James Walker committed
78 79

        // PuSH actions
Brion Vibber's avatar
Brion Vibber committed
80
        $m->connect('main/push/hub', array('action' => 'pushhub'));
81

Brion Vibber's avatar
Brion Vibber committed
82 83
        $m->connect('main/push/callback/:feed',
                    array('action' => 'pushcallback'),
84
                    array('feed' => '[0-9]+'));
James Walker's avatar
James Walker committed
85 86

        // Salmon endpoint
87
        $m->connect('main/salmon/user/:id',
88
                    array('action' => 'usersalmon'),
James Walker's avatar
James Walker committed
89
                    array('id' => '[0-9]+'));
90
        $m->connect('main/salmon/group/:id',
91
                    array('action' => 'groupsalmon'),
92
                    array('id' => '[0-9]+'));
Shashi Gowda's avatar
Shashi Gowda committed
93 94 95
        $m->connect('main/salmon/peopletag/:id',
                    array('action' => 'peopletagsalmon'),
                    array('id' => '[0-9]+'));
96 97 98
        return true;
    }

99 100 101 102 103 104 105
    /**
     * Set up queue handlers for outgoing hub pushes
     * @param QueueManager $qm
     * @return boolean hook return
     */
    function onEndInitializeQueueManager(QueueManager $qm)
    {
106 107 108
        // Prepare outgoing distributions after notice save.
        $qm->connect('ostatus', 'OStatusQueueHandler');

Brion Vibber's avatar
Brion Vibber committed
109
        // Outgoing from our internal PuSH hub
110
        $qm->connect('hubconf', 'HubConfQueueHandler');
111 112
        $qm->connect('hubprep', 'HubPrepQueueHandler');

113
        $qm->connect('hubout', 'HubOutQueueHandler');
Brion Vibber's avatar
Brion Vibber committed
114

115
        // Outgoing Salmon replies (when we don't need a return value)
116
        $qm->connect('salmon', 'SalmonQueueHandler');
117

Brion Vibber's avatar
Brion Vibber committed
118
        // Incoming from a foreign PuSH hub
119
        $qm->connect('pushin', 'PushInQueueHandler');
120 121 122 123 124 125 126 127
        return true;
    }

    /**
     * Put saved notices into the queue for pubsub distribution.
     */
    function onStartEnqueueNotice($notice, &$transports)
    {
128 129 130
        // FIXME: we don't do privacy-controlled OStatus updates yet.
        // once that happens, finer grain of control here.
        if ($notice->isLocal() && $notice->inScope(null)) {
131 132 133
            // put our transport first, in case there's any conflict (like OMB)
            array_unshift($transports, 'ostatus');
        }
134 135 136
        return true;
    }

137 138 139 140 141 142 143
    /**
     * Add a link header for LRDD Discovery
     */
    function onStartShowHTML($action)
    {
        if ($action instanceof ShowstreamAction) {
            $acct = 'acct:'. $action->profile->nickname .'@'. common_config('site', 'server');
James Walker's avatar
James Walker committed
144
            $url = common_local_url('userxrd');
145
            $url.= '?uri='. $acct;
146

147 148 149
            header('Link: <'.$url.'>; rel="'. Discovery::LRDD_REL.'"; type="application/xrd+xml"');
        }
    }
150

151 152
    /**
     * Set up a PuSH hub link to our internal link for canonical timeline
153
     * Atom feeds for users and groups.
154
     */
Brion Vibber's avatar
Brion Vibber committed
155
    function onStartApiAtom($feed)
156
    {
157 158 159
        $id = null;

        if ($feed instanceof AtomUserNoticeFeed) {
160 161 162 163
            $salmonAction = 'usersalmon';
            $user = $feed->getUser();
            $id   = $user->id;
            $profile = $user->getProfile();
164
        } else if ($feed instanceof AtomGroupNoticeFeed) {
165 166 167
            $salmonAction = 'groupsalmon';
            $group = $feed->getGroup();
            $id = $group->id;
Shashi Gowda's avatar
Shashi Gowda committed
168 169 170 171
        } else if ($feed instanceof AtomListNoticeFeed) {
            $salmonAction = 'peopletagsalmon';
            $peopletag = $feed->getList();
            $id = $peopletag->id;
172
        } else {
173
            return true;
174
        }
Brion Vibber's avatar
Brion Vibber committed
175

176
        if (!empty($id)) {
177 178 179 180
            $hub = common_config('ostatus', 'hub');
            if (empty($hub)) {
                // Updates will be handled through our internal PuSH hub.
                $hub = common_local_url('pushhub');
181
            }
182
            $feed->addLink($hub, array('rel' => 'hub'));
183 184 185

            // Also, we'll add in the salmon link
            $salmon = common_local_url($salmonAction, array('id' => $id));
186 187 188
            $feed->addLink($salmon, array('rel' => Salmon::REL_SALMON));

            // XXX: these are deprecated
189 190
            $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
            $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
191
        }
192 193

        return true;
194
    }
195

196 197 198 199 200 201 202 203 204 205 206 207
    /**
     * Automatically load the actions and libraries used by the plugin
     *
     * @param Class $cls the class
     *
     * @return boolean hook return
     *
     */
    function onAutoload($cls)
    {
        $base = dirname(__FILE__);
        $lower = strtolower($cls);
Brion Vibber's avatar
Brion Vibber committed
208 209 210 211 212 213
        $map = array('activityverb' => 'activity',
                     'activityobject' => 'activity',
                     'activityutils' => 'activity');
        if (isset($map[$lower])) {
            $lower = $map[$lower];
        }
214 215
        $files = array("$base/classes/$cls.php",
                       "$base/lib/$lower.php");
216 217 218 219 220 221 222 223 224 225 226 227
        if (substr($lower, -6) == 'action') {
            $files[] = "$base/actions/" . substr($lower, 0, -6) . ".php";
        }
        foreach ($files as $file) {
            if (file_exists($file)) {
                include_once $file;
                return false;
            }
        }
        return true;
    }

228 229 230
    /**
     * Add in an OStatus subscribe button
     */
231
    function onStartProfileRemoteSubscribe($output, $profile)
Shashi Gowda's avatar
Shashi Gowda committed
232 233 234 235 236
    {
        $this->onStartProfileListItemActionElements($output, $profile);
        return false;
    }

237
    function onStartGroupSubscribe($widget, $group)
238 239 240 241 242
    {
        $cur = common_current_user();

        if (empty($cur)) {
            $output->elementStart('li', 'entity_subscribe');
243
            $profile = $peopletag->getTagger();
244
            $url = common_local_url('ostatusinit',
Shashi Gowda's avatar
Shashi Gowda committed
245
                                    array('group' => $group->nickname));
246
            $widget->out->element('a', array('href' => $url,
247
                                        'class' => 'entity_remote_subscribe'),
248
                                // TRANS: Link to subscribe to a remote entity.
249
                                _m('Subscribe'));
250

251
            $output->elementEnd('li');
252
            return false;
253
        }
254

Shashi Gowda's avatar
Shashi Gowda committed
255
        return true;
256 257
    }

Shashi Gowda's avatar
Shashi Gowda committed
258
    function onStartSubscribePeopletagForm($output, $peopletag)
259 260 261 262
    {
        $cur = common_current_user();

        if (empty($cur)) {
Shashi Gowda's avatar
Shashi Gowda committed
263 264
            $output->elementStart('li', 'entity_subscribe');
            $profile = $peopletag->getTagger();
265
            $url = common_local_url('ostatusinit',
Shashi Gowda's avatar
Shashi Gowda committed
266
                                    array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
267 268
            $output->element('a', array('href' => $url,
                                        'class' => 'entity_remote_subscribe'),
269
                                // TRANS: Link to subscribe to a remote entity.
Shashi Gowda's avatar
Shashi Gowda committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
                                _m('Subscribe'));

            $output->elementEnd('li');
            return false;
        }

        return true;
    }

    function onStartShowTagProfileForm($action, $profile)
    {
        $action->elementStart('form', array('method' => 'post',
                                           'id' => 'form_tag_user',
                                           'class' => 'form_settings',
                                           'name' => 'tagprofile',
                                           'action' => common_local_url('tagprofile', array('id' => @$profile->id))));

        $action->elementStart('fieldset');
288 289
        // TRANS: Fieldset legend.
        $action->element('legend', null, _m('Tag remote profile'));
Shashi Gowda's avatar
Shashi Gowda committed
290 291 292 293 294 295 296
        $action->hidden('token', common_session_token());

        $user = common_current_user();

        $action->elementStart('ul', 'form_data');
        $action->elementStart('li');

297 298 299 300
        // TRANS: Field label.
        $action->input('uri', _m('LABEL','Remote profile'), $action->trimmed('uri'),
                     // TRANS: Field title.
                     _m('OStatus user\'s address, like nickname@example.com or http://example.net/nickname.'));
Shashi Gowda's avatar
Shashi Gowda committed
301 302
        $action->elementEnd('li');
        $action->elementEnd('ul');
303 304
        // TRANS: Button text to fetch remote profile.
        $action->submit('fetch', _m('BUTTON','Fetch'));
Shashi Gowda's avatar
Shashi Gowda committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
        $action->elementEnd('fieldset');
        $action->elementEnd('form');
    }

    function onStartTagProfileAction($action, $profile)
    {
        $err = null;
        $uri = $action->trimmed('uri');

        if (!$profile && $uri) {
            try {
                if (Validate::email($uri)) {
                    $oprofile = Ostatus_profile::ensureWebfinger($uri);
                } else if (Validate::uri($uri)) {
                    $oprofile = Ostatus_profile::ensureProfileURL($uri);
                } else {
321 322
                    // TRANS: Exception in OStatus when invalid URI was entered.
                    throw new Exception(_m('Invalid URI.'));
Shashi Gowda's avatar
Shashi Gowda committed
323 324 325 326 327 328 329
                }

                // redirect to the new profile.
                common_redirect(common_local_url('tagprofile', array('id' => $oprofile->profile_id)), 303);
                return false;

            } catch (Exception $e) {
330 331
                // TRANS: Error message in OStatus plugin.
                $err = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
Shashi Gowda's avatar
Shashi Gowda committed
332 333 334 335
            }

            $action->showForm($err);
            return false;
336
        }
Shashi Gowda's avatar
Shashi Gowda committed
337 338
        return true;
    }
339

Shashi Gowda's avatar
Shashi Gowda committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    /*
     * If the field being looked for is URI look for the profile
     */
    function onStartProfileCompletionSearch($action, $profile, $search_engine) {
        if ($action->field == 'uri') {
            $user = new User();
            $profile->joinAdd($user);
            $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
            $profile->query();

            if ($profile->N == 0) {
                try {
                    if (Validate::email($q)) {
                        $oprofile = Ostatus_profile::ensureWebfinger($q);
                    } else if (Validate::uri($q)) {
                        $oprofile = Ostatus_profile::ensureProfileURL($q);
                    } else {
357 358
                        // TRANS: Exception in OStatus when invalid URI was entered.
                        throw new Exception(_m('Invalid URI.'));
Shashi Gowda's avatar
Shashi Gowda committed
359 360 361 362
                    }
                    return $this->filter(array($oprofile->localProfile()));

                } catch (Exception $e) {
363 364
                    // TRANS: Error message in OStatus plugin.
                    $this->msg = _m("Sorry, we could not reach that address. Please make sure that the OStatus address is like nickname@example.com or http://example.net/nickname.");
Shashi Gowda's avatar
Shashi Gowda committed
365 366 367 368 369
                    return array();
                }
            }
            return false;
        }
370
        return true;
371 372
    }

373
    /**
374 375 376 377 378 379 380
     * Find any explicit remote mentions. Accepted forms:
     *   Webfinger: @user@example.com
     *   Profile link: @example.com/mublog/user
     * @param Profile $sender (os user?)
     * @param string $text input markup text
     * @param array &$mention in/out param: set of found mentions
     * @return boolean hook return value
381
     */
382
    function onEndFindMentions($sender, $text, &$mentions)
383
    {
384 385 386
        $matches = array();

        // Webfinger matches: @user@example.com
387
        if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+@(?:\w+\-?\w+\.)*\w+(?:\w+\-\w+)*\.\w+)!',
388 389
                       $text,
                       $wmatches,
390 391 392 393
                       PREG_OFFSET_CAPTURE)) {
            foreach ($wmatches[1] as $wmatch) {
                list($target, $pos) = $wmatch;
                $this->log(LOG_INFO, "Checking webfinger '$target'");
394 395
                try {
                    $oprofile = Ostatus_profile::ensureWebfinger($target);
396 397 398 399 400 401 402
                    if ($oprofile && !$oprofile->isGroup()) {
                        $profile = $oprofile->localProfile();
                        $matches[$pos] = array('mentioned' => array($profile),
                                               'text' => $target,
                                               'position' => $pos,
                                               'url' => $profile->profileurl);
                    }
403 404 405
                } catch (Exception $e) {
                    $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
                }
406 407 408 409 410 411 412 413 414 415 416
            }
        }

        // Profile matches: @example.com/mublog/user
        if (preg_match_all('!(?:^|\s+)@((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)!',
                       $text,
                       $wmatches,
                       PREG_OFFSET_CAPTURE)) {
            foreach ($wmatches[1] as $wmatch) {
                list($target, $pos) = $wmatch;
                $schemes = array('http', 'https');
417 418 419 420
                foreach ($schemes as $scheme) {
                    $url = "$scheme://$target";
                    $this->log(LOG_INFO, "Checking profile address '$url'");
                    try {
421
                        $oprofile = Ostatus_profile::ensureProfileURL($url);
422 423 424 425 426 427 428
                        if ($oprofile && !$oprofile->isGroup()) {
                            $profile = $oprofile->localProfile();
                            $matches[$pos] = array('mentioned' => array($profile),
                                                   'text' => $target,
                                                   'position' => $pos,
                                                   'url' => $profile->profileurl);
                            break;
429 430 431 432 433 434
                        }
                    } catch (Exception $e) {
                        $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
                    }
                }
            }
435
        }
436

437 438 439 440 441 442
        foreach ($mentions as $i => $other) {
            // If we share a common prefix with a local user, override it!
            $pos = $other['position'];
            if (isset($matches[$pos])) {
                $mentions[$i] = $matches[$pos];
                unset($matches[$pos]);
James Walker's avatar
James Walker committed
443 444
            }
        }
445 446 447
        foreach ($matches as $mention) {
            $mentions[] = $mention;
        }
448

449 450 451
        return true;
    }

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    /**
     * Allow remote profile references to be used in commands:
     *   sub update@status.net
     *   whois evan@identi.ca
     *   reply http://identi.ca/evan hey what's up
     *
     * @param Command $command
     * @param string $arg
     * @param Profile &$profile
     * @return hook return code
     */
    function onStartCommandGetProfile($command, $arg, &$profile)
    {
        $oprofile = $this->pullRemoteProfile($arg);
        if ($oprofile && !$oprofile->isGroup()) {
            $profile = $oprofile->localProfile();
            return false;
        } else {
            return true;
        }
    }

    /**
     * Allow remote group references to be used in commands:
     *   join group+statusnet@identi.ca
     *   join http://identi.ca/group/statusnet
     *   drop identi.ca/group/statusnet
     *
     * @param Command $command
     * @param string $arg
     * @param User_group &$group
     * @return hook return code
     */
    function onStartCommandGetGroup($command, $arg, &$group)
    {
        $oprofile = $this->pullRemoteProfile($arg);
        if ($oprofile && $oprofile->isGroup()) {
            $group = $oprofile->localGroup();
            return false;
        } else {
            return true;
        }
    }

    protected function pullRemoteProfile($arg)
    {
        $oprofile = null;
        if (preg_match('!^((?:\w+\.)*\w+@(?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+)$!', $arg)) {
            // webfinger lookup
            try {
                return Ostatus_profile::ensureWebfinger($arg);
            } catch (Exception $e) {
                common_log(LOG_ERR, 'Webfinger lookup failed for ' .
                                    $arg . ': ' . $e->getMessage());
            }
        }

        // Look for profile URLs, with or without scheme:
        $urls = array();
        if (preg_match('!^https?://((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
            $urls[] = $arg;
        }
        if (preg_match('!^((?:\w+\.)*\w+(?:\w+\-\w+)*\.\w+(?:/\w+)+)$!', $arg)) {
            $schemes = array('http', 'https');
            foreach ($schemes as $scheme) {
                $urls[] = "$scheme://$arg";
            }
        }

        foreach ($urls as $url) {
            try {
523
                return Ostatus_profile::ensureProfileURL($url);
524 525 526 527 528 529 530 531
            } catch (Exception $e) {
                common_log(LOG_ERR, 'Profile lookup failed for ' .
                                    $arg . ': ' . $e->getMessage());
            }
        }
        return null;
    }

532 533 534
    /**
     * Make sure necessary tables are filled out.
     */
535 536
    function onCheckSchema() {
        $schema = Schema::get();
537
        $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
538
        $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
539
        $schema->ensureTable('feedsub', FeedSub::schemaDef());
540
        $schema->ensureTable('hubsub', HubSub::schemaDef());
541
        $schema->ensureTable('magicsig', Magicsig::schemaDef());
542
        return true;
543
    }
544 545

    function onEndShowStatusNetStyles($action) {
Evan Prodromou's avatar
Evan Prodromou committed
546
        $action->cssLink($this->path('theme/base/css/ostatus.css'));
547 548
        return true;
    }
549 550

    function onEndShowStatusNetScripts($action) {
Evan Prodromou's avatar
Evan Prodromou committed
551
        $action->script($this->path('js/ostatus.js'));
552 553
        return true;
    }
554

Brion Vibber's avatar
Brion Vibber committed
555 556 557 558 559 560 561 562 563 564
    /**
     * Override the "from ostatus" bit in notice lists to link to the
     * original post and show the domain it came from.
     *
     * @param Notice in $notice
     * @param string out &$name
     * @param string out &$url
     * @param string out &$title
     * @return mixed hook return code
     */
565 566 567
    function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
    {
        if ($notice->source == 'ostatus') {
568 569 570 571 572 573 574 575
            if ($notice->url) {
                $bits = parse_url($notice->url);
                $domain = $bits['host'];
                if (substr($domain, 0, 4) == 'www.') {
                    $name = substr($domain, 4);
                } else {
                    $name = $domain;
                }
576

577
                $url = $notice->url;
578 579 580
                // TRANS: Title.
                // TRANS: %s is a domain name.
                $title = sprintf(_m('Sent from %s via OStatus'), $domain);
581 582
                return false;
            }
583
        }
584
    return true;
585
    }
586 587 588 589 590 591 592 593 594 595 596 597

    /**
     * Send incoming PuSH feeds for OStatus endpoints in for processing.
     *
     * @param FeedSub $feedsub
     * @param DOMDocument $feed
     * @return mixed hook return code
     */
    function onStartFeedSubReceive($feedsub, $feed)
    {
        $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
        if ($oprofile) {
598
            $oprofile->processFeed($feed, 'push');
599 600
        } else {
            common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
601 602
        }
    }
603

604 605 606 607
    /**
     * Tell the FeedSub infrastructure whether we have any active OStatus
     * usage for the feed; if not it'll be able to garbage-collect the
     * feed subscription.
608
     *
609 610 611 612 613 614 615 616 617 618 619 620 621
     * @param FeedSub $feedsub
     * @param integer $count in/out
     * @return mixed hook return code
     */
    function onFeedSubSubscriberCount($feedsub, &$count)
    {
        $oprofile = Ostatus_profile::staticGet('feeduri', $feedsub->uri);
        if ($oprofile) {
            $count += $oprofile->subscriberCount();
        }
        return true;
    }

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
    /**
     * When about to subscribe to a remote user, start a server-to-server
     * PuSH subscription if needed. If we can't establish that, abort.
     *
     * @fixme If something else aborts later, we could end up with a stray
     *        PuSH subscription. This is relatively harmless, though.
     *
     * @param Profile $subscriber
     * @param Profile $other
     *
     * @return hook return code
     *
     * @throws Exception
     */
    function onStartSubscribe($subscriber, $other)
    {
        $user = User::staticGet('id', $subscriber->id);

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

        $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);

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

        if (!$oprofile->subscribe()) {
651
            // TRANS: Exception thrown when setup of remote subscription fails.
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
            throw new Exception(_m('Could not set up remote subscription.'));
        }
    }

    /**
     * Having established a remote subscription, send a notification to the
     * remote OStatus profile's endpoint.
     *
     * @param Profile $subscriber
     * @param Profile $other
     *
     * @return hook return code
     *
     * @throws Exception
     */
667 668 669 670 671 672 673 674 675 676 677 678 679 680
    function onEndSubscribe($subscriber, $other)
    {
        $user = User::staticGet('id', $subscriber->id);

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

        $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);

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

681 682
        $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
                                           'subscribed' => $other->id));
683

684
        $act = $sub->asActivity();
685

686
        $oprofile->notifyActivity($act, $subscriber);
687 688 689 690

        return true;
    }

691 692
    /**
     * Notify remote server and garbage collect unused feeds on unsubscribe.
693
     * @todo FIXME: Send these operations to background queues
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
     *
     * @param User $user
     * @param Profile $other
     * @return hook return value
     */
    function onEndUnsubscribe($profile, $other)
    {
        $user = User::staticGet('id', $profile->id);

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

        $oprofile = Ostatus_profile::staticGet('profile_id', $other->id);

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

        // Drop the PuSH subscription if there are no other subscribers.
        $oprofile->garbageCollect();

        $act = new Activity();

        $act->verb = ActivityVerb::UNFOLLOW;

        $act->id   = TagURI::mint('unfollow:%d:%d:%s',
                                  $profile->id,
                                  $other->id,
                                  common_date_iso8601(time()));

        $act->time    = time();
726 727
        // TRANS: Title for unfollowing a remote profile.
        $act->title   = _m('TITLE','Unfollow');
728 729
        // TRANS: Success message for unsubscribe from user attempt through OStatus.
        // TRANS: %1$s is the unsubscriber's name, %2$s is the unsubscribed user's name.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
730
        $act->content = sprintf(_m('%1$s stopped following %2$s.'),
731 732 733 734 735 736
                               $profile->getBestName(),
                               $other->getBestName());

        $act->actor   = ActivityObject::fromProfile($profile);
        $act->object  = ActivityObject::fromProfile($other);

737
        $oprofile->notifyActivity($act, $profile);
738 739 740 741

        return true;
    }

742 743 744 745 746 747 748 749 750 751 752 753 754 755
    /**
     * When one of our local users tries to join a remote group,
     * notify the remote server. If the notification is rejected,
     * deny the join.
     *
     * @param User_group $group
     * @param User $user
     *
     * @return mixed hook return value
     */
    function onStartJoinGroup($group, $user)
    {
        $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
        if ($oprofile) {
756
            if (!$oprofile->subscribe()) {
757
                // TRANS: Exception thrown when setup of remote group membership fails.
758 759 760
                throw new Exception(_m('Could not set up remote group membership.'));
            }

761 762 763
            // NOTE: we don't use Group_member::asActivity() since that record
            // has not yet been created.

764 765 766 767 768 769 770 771 772 773 774 775 776
            $member = Profile::staticGet($user->id);

            $act = new Activity();
            $act->id = TagURI::mint('join:%d:%d:%s',
                                    $member->id,
                                    $group->id,
                                    common_date_iso8601(time()));

            $act->actor = ActivityObject::fromProfile($member);
            $act->verb = ActivityVerb::JOIN;
            $act->object = $oprofile->asActivityObject();

            $act->time = time();
777 778
            // TRANS: Title to join a remote group.
            $act->title = _m('TITLE','Join');
779 780
            // TRANS: Success message for subscribe to group attempt through OStatus.
            // TRANS: %1$s is the member name, %2$s is the subscribed group's name.
781
            $act->content = sprintf(_m('%1$s has joined group %2$s.'),
782 783 784
                                    $member->getBestName(),
                                    $oprofile->getBestName());

785
            if ($oprofile->notifyActivity($act, $member)) {
786 787
                return true;
            } else {
788
                $oprofile->garbageCollect();
789 790
                // TRANS: Exception thrown when joining a remote group fails.
                throw new Exception(_m('Failed joining remote group.'));
791 792 793 794 795 796 797 798 799 800 801 802 803 804
            }
        }
    }

    /**
     * When one of our local users leaves a remote group, notify the remote
     * server.
     *
     * @fixme Might be good to schedule a resend of the leave notification
     * if it failed due to a transitory error. We've canceled the local
     * membership already anyway, but if the remote server comes back up
     * it'll be left with a stray membership record.
     *
     * @param User_group $group
805
     * @param Profile $user
806 807 808 809 810 811 812 813
     *
     * @return mixed hook return value
     */
    function onEndLeaveGroup($group, $user)
    {
        $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
        if ($oprofile) {
            // Drop the PuSH subscription if there are no other subscribers.
814
            $oprofile->garbageCollect();
815

816 817 818 819 820 821 822 823 824 825 826 827 828
            $member = Profile::staticGet($user->id);

            $act = new Activity();
            $act->id = TagURI::mint('leave:%d:%d:%s',
                                    $member->id,
                                    $group->id,
                                    common_date_iso8601(time()));

            $act->actor = ActivityObject::fromProfile($member);
            $act->verb = ActivityVerb::LEAVE;
            $act->object = $oprofile->asActivityObject();

            $act->time = time();
829 830
            // TRANS: Title for leaving a remote group.
            $act->title = _m('TITLE','Leave');
831 832
            // TRANS: Success message for unsubscribe from group attempt through OStatus.
            // TRANS: %1$s is the member name, %2$s is the unsubscribed group's name.
833
            $act->content = sprintf(_m('%1$s has left group %2$s.'),
834 835 836
                                    $member->getBestName(),
                                    $oprofile->getBestName());

837
            $oprofile->notifyActivity($act, $member);
838 839 840
        }
    }

Shashi Gowda's avatar
Shashi Gowda committed
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
    /**
     * When one of our local users tries to subscribe to a remote peopletag,
     * notify the remote server. If the notification is rejected,
     * deny the subscription.
     *
     * @param Profile_list $peopletag
     * @param User         $user
     *
     * @return mixed hook return value
     */

    function onStartSubscribePeopletag($peopletag, $user)
    {
        $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
        if ($oprofile) {
            if (!$oprofile->subscribe()) {
857
                // TRANS: Exception thrown when setup of remote list subscription fails.
858
                throw new Exception(_m('Could not set up remote list subscription.'));
Shashi Gowda's avatar
Shashi Gowda committed
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
            }

            $sub = $user->getProfile();
            $tagger = Profile::staticGet($peopletag->tagger);

            $act = new Activity();
            $act->id = TagURI::mint('subscribe_peopletag:%d:%d:%s',
                                    $sub->id,
                                    $peopletag->id,
                                    common_date_iso8601(time()));

            $act->actor = ActivityObject::fromProfile($sub);
            $act->verb = ActivityVerb::FOLLOW;
            $act->object = $oprofile->asActivityObject();

            $act->time = time();
875 876 877
            // TRANS: Title for remote follow list.
            $act->title = _m('TITLE','Follow list');
            // TRANS: Success message for remote list follow through OStatus.
878
            // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the tagger's name.
879
            $act->content = sprintf(_m("%1$s is now following people listed in %2$s by %3$s."),
Shashi Gowda's avatar
Shashi Gowda committed
880 881 882 883 884 885 886 887
                                    $sub->getBestName(),
                                    $oprofile->getBestName(),
                                    $tagger->getBestName());

            if ($oprofile->notifyActivity($act, $sub)) {
                return true;
            } else {
                $oprofile->garbageCollect();
888 889
                // TRANS: Exception thrown when subscription of remote people tag fails.
                throw new Exception(_m('Failed subscribing to remote people tag.'));
Shashi Gowda's avatar
Shashi Gowda committed
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
            }
        }
    }

    /**
     * When one of our local users unsubscribes to a remote peopletag, notify the remote
     * server.
     *
     * @param Profile_list $peopletag
     * @param User         $user
     *
     * @return mixed hook return value
     */

    function onEndUnsubscribePeopletag($peopletag, $user)
    {
        $oprofile = Ostatus_profile::staticGet('peopletag_id', $peopletag->id);
        if ($oprofile) {
            // Drop the PuSH subscription if there are no other subscribers.
            $oprofile->garbageCollect();

            $sub = Profile::staticGet($user->id);
            $tagger = Profile::staticGet($peopletag->tagger);

            $act = new Activity();
            $act->id = TagURI::mint('unsubscribe_peopletag:%d:%d:%s',
                                    $sub->id,
                                    $peopletag->id,
                                    common_date_iso8601(time()));

            $act->actor = ActivityObject::fromProfile($member);
            $act->verb = ActivityVerb::UNFOLLOW;
            $act->object = $oprofile->asActivityObject();

            $act->time = time();
925 926
            $act->title = _m('Unfollow people tag');
            $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
Shashi Gowda's avatar
Shashi Gowda committed
927 928 929 930 931 932 933 934
                                    $sub->getBestName(),
                                    $oprofile->getBestName(),
                                    $tagger->getBestName());

            $oprofile->notifyActivity($act, $user);
        }
    }

935 936 937 938 939 940 941
    /**
     * 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
     */
942
    function onEndFavorNotice(Profile $profile, Notice $notice)
943
    {
944 945 946 947
        $user = User::staticGet('id', $profile->id);

        if (empty($user)) {
            return true;
948
        }
949

950
        $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
951

952 953
        if (empty($oprofile)) {
            return true;
954
        }
955

956 957
        $fav = Fave::pkeyGet(array('user_id' => $user->id,
                                   'notice_id' => $notice->id));
958

959 960 961 962
        if (empty($fav)) {
            // That's weird.
            return true;
        }
963

964
        $act = $fav->asActivity();
965

966
        $oprofile->notifyActivity($act, $profile);
967

968
        return true;
969 970
    }

971 972 973 974 975 976 977 978
    /**
     * Notify remote user it has got a new people tag
     *   - tag verb is queued
     *   - the subscription is done immediately if not present
     *
     * @param Profile_tag $ptag the people tag that was created
     * @return hook return value
     */
Shashi Gowda's avatar
Shashi Gowda committed
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    function onEndTagProfile($ptag)
    {
        $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);

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

        $plist = $ptag->getMeta();
        if ($plist->private) {
            return true;
        }

        $act = new Activity();

        $tagger = $plist->getTagger();
        $tagged = Profile::staticGet('id', $ptag->tagged);

        $act->verb = ActivityVerb::TAG;
        $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
                                  $plist->tagger, $plist->id,
                                  common_date_iso8601(time()));
        $act->time = time();
1002
        $act->title = _m('TITLE','Tag');
1003
        $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
Shashi Gowda's avatar
Shashi Gowda committed
1004 1005 1006 1007 1008 1009 1010 1011
                                $tagger->getBestName(),
                                $tagged->getBestName(),
                                $plist->getBestName());

        $act->actor  = ActivityObject::fromProfile($tagger);
        $act->objects = array(ActivityObject::fromProfile($tagged));
        $act->target = ActivityObject::fromPeopletag($plist);

1012
        $oprofile->notifyDeferred($act, $tagger);
Shashi Gowda's avatar
Shashi Gowda committed
1013 1014 1015

        // initiate a PuSH subscription for the person being tagged
        if (!$oprofile->subscribe()) {
1016
            throw new Exception(sprintf(_m('Could not complete subscription to remote '.
Shashi Gowda's avatar
Shashi Gowda committed
1017 1018 1019 1020 1021 1022
                                          'profile\'s feed. Tag %s could not be saved.'), $ptag->tag));
            return false;
        }
        return true;
    }

1023 1024 1025 1026 1027 1028 1029 1030 1031
    /**
     * Notify remote user that a people tag has been removed
     *   - untag verb is queued
     *   - the subscription is undone immediately if not required
     *     i.e garbageCollect()'d
     *
     * @param Profile_tag $ptag the people tag that was deleted
     * @return hook return value
     */
Shashi Gowda's avatar
Shashi Gowda committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    function onEndUntagProfile($ptag)
    {
        $oprofile = Ostatus_profile::staticGet('profile_id', $ptag->tagged);

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

        $plist = $ptag->getMeta();
        if ($plist->private) {
            return true;
        }

        $act = new Activity();

        $tagger = $plist->getTagger();
        $tagged = Profile::staticGet('id', $ptag->tagged);

        $act->verb = ActivityVerb::UNTAG;
        $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
                                  $plist->tagger, $plist->id,
                                  common_date_iso8601(time()));
        $act->time = time();
1055 1056
        $act->title = _m('TITLE','Untag');
        $act->content = sprintf(_('%1$s untagged %2$s from the list %3$s.'),
Shashi Gowda's avatar
Shashi Gowda committed
1057 1058 1059 1060 1061 1062 1063 1064
                                $tagger->getBestName(),
                                $tagged->getBestName(),
                                $plist->getBestName());

        $act->actor  = ActivityObject::fromProfile($tagger);
        $act->objects = array(ActivityObject::fromProfile($tagged));
        $act->target = ActivityObject::fromPeopletag($plist);

1065
        $oprofile->notifyDeferred($act, $tagger);
Shashi Gowda's avatar
Shashi Gowda committed
1066 1067 1068 1069 1070 1071 1072

        // unsubscribe to PuSH feed if no more required
        $oprofile->garbageCollect();

        return true;
    }

1073 1074 1075
    /**
     * Notify remote users when their notices get de-favorited.
     *
1076 1077 1078
     * @param Profile $profile Profile person doing the de-faving
     * @param Notice  $notice  Notice being favored
     *
1079 1080 1081
     * @return hook return value
     */
    function onEndDisfavorNotice(Profile $profile, Notice $notice)
1082
    {
1083 1084 1085 1086 1087 1088
        $user = User::staticGet('id', $profile->id);

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

1089
        $oprofile = Ostatus_profile::staticGet('profile_id', $notice->profile_id);
1090

1091 1092
        if (empty($oprofile)) {
            return true;
1093
        }
1094

1095 1096 1097 1098 1099 1100 1101 1102
        $act = new Activity();

        $act->verb = ActivityVerb::UNFAVORITE;
        $act->id   = TagURI::mint('disfavor:%d:%d:%s',
                                  $profile->id,
                                  $notice->id,
                                  common_date_iso8601(time()));
        $act->time    = time();
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1103
        $act->title   = _m('Disfavor');
1104 1105
        // TRANS: Success message for remove a favorite notice through OStatus.
        // TRANS: %1$s is the unfavoring user's name, %2$s is URI to the no longer favored notice.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1106
        $act->content = sprintf(_m('%1$s marked notice %2$s as no longer a favorite.'),
1107 1108 1109 1110 1111 1112
                               $profile->getBestName(),
                               $notice->uri);

        $act->actor   = ActivityObject::fromProfile($profile);
        $act->object  = ActivityObject::fromNotice($notice);

1113
        $oprofile->notifyActivity($act, $profile);
1114

1115 1116
        return true;
    }
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

    function onStartGetProfileUri($profile, &$uri)
    {
        $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
        if (!empty($oprofile)) {
            $uri = $oprofile->uri;
            return false;
        }
        return true;
    }
1127

1128 1129
    function onStartUserGroupHomeUrl($group, &$url)
    {
James Walker's avatar
James Walker committed
1130
        return $this->onStartUserGroupPermalink($group, $url);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
    }

    function onStartUserGroupPermalink($group, &$url)
    {
        $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
        if ($oprofile) {
            // @fixme this should probably be in the user_group table
            // @fixme this uri not guaranteed to be a profile page
            $url = $oprofile->uri;
            return false;
        }
    }

1144 1145
    function onStartShowSubscriptionsContent($action)
    {
1146
        $this->showEntityRemoteSubscribe($action);
1147 1148 1149

        return true;
    }
1150

1151 1152
    function onStartShowUserGroupsContent($action)
    {
1153
        $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1154 1155 1156 1157

        return true;
    }

1158
    function onEndShowSubscriptionsMiniList($action)
1159 1160 1161 1162 1163 1164
    {
        $this->showEntityRemoteSubscribe($action);

        return true;
    }

1165 1166
    function onEndShowGroupsMiniList($action)
    {
1167
        $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1168 1169 1170 1171

        return true;
    }

1172
    function showEntityRemoteSubscribe($action, $target='ostatussub')
1173 1174 1175 1176 1177 1178
    {
        $user = common_current_user();
        if ($user && ($user->id == $action->profile->id)) {
            $action->elementStart('div', 'entity_actions');
            $action->elementStart('p', array('id' => 'entity_remote_subscribe',
                                             'class' => 'entity_subscribe'));
1179
            $action->element('a', array('href' => common_local_url($target),
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1180 1181 1182
                                        'class' => 'entity_remote_subscribe'),
                                // TRANS: Link text for link to remote subscribe.
                                _m('Remote'));
1183 1184 1185 1186
            $action->elementEnd('p');
            $action->elementEnd('div');
        }
    }
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220

    /**
     * Ping remote profiles with updates to this profile.
     * Salmon pings are queued for background processing.
     */
    function onEndBroadcastProfile(Profile $profile)
    {
        $user = User::staticGet('id', $profile->id);

        // Find foreign accounts I'm subscribed to that support Salmon pings.
        //
        // @fixme we could run updates through the PuSH feed too,
        // in which case we can skip Salmon pings to folks who
        // are also subscribed to me.
        $sql = "SELECT * FROM ostatus_profile " .
               "WHERE profile_id IN " .
               "(SELECT subscribed FROM subscription WHERE subscriber=%d) " .
               "OR group_id IN " .
               "(SELECT group_id FROM group_member WHERE profile_id=%d)";
        $oprofile = new Ostatus_profile();
        $oprofile->query(sprintf($sql, $profile->id, $profile->id));

        if ($oprofile->N == 0) {
            common_log(LOG_DEBUG, "No OStatus remote subscribees for $profile->nickname");
            return true;
        }

        $act = new Activity();

        $act->verb = ActivityVerb::UPDATE_PROFILE;
        $act->id   = TagURI::mint('update-profile:%d:%s',
                                  $profile->id,
                                  common_date_iso8601(time()));
        $act->time    = time();
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1221
        // TRANS: Title for activity.
1222
        $act->title   = _m("Profile update");
1223 1224