OStatusPlugin.php 53.9 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 22 23 24
 * OStatusPlugin implementation for GNU Social
 *
 * Depends on: WebFinger plugin
 *
25
 * @package OStatusPlugin
26 27 28
 * @maintainer Brion Vibber <brion@status.net>
 */

29
if (!defined('GNUSOCIAL')) { exit(1); }
30

31
set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/phpseclib');
32

33
class OStatusPlugin extends Plugin
34 35 36 37
{
    /**
     * Hook for RouterInitialized event.
     *
38
     * @param URLMapper $m path-to-action mapper
39 40
     * @return boolean hook return
     */
41
    public function onRouterInitialized(URLMapper $m)
42
    {
43
        // Discovery actions
44 45 46 47
        $m->connect('main/ostatustag',
                    array('action' => 'ostatustag'));
        $m->connect('main/ostatustag?nickname=:nickname',
                    array('action' => 'ostatustag'), array('nickname' => '[A-Za-z0-9_-]+'));
48
        $m->connect('main/ostatus/nickname/:nickname',
49
                  array('action' => 'ostatusinit'), array('nickname' => '[A-Za-z0-9_-]+'));
50
        $m->connect('main/ostatus/group/:group',
51
                  array('action' => 'ostatusinit'), array('group' => '[A-Za-z0-9_-]+'));
52
        $m->connect('main/ostatus/peopletag/:peopletag/tagger/:tagger',
53 54
                  array('action' => 'ostatusinit'), array('tagger' => '[A-Za-z0-9_-]+',
                                                          'peopletag' => '[A-Za-z0-9_-]+'));
55 56
        $m->connect('main/ostatus',
                    array('action' => 'ostatusinit'));
57 58

        // Remote subscription actions
59
        $m->connect('main/ostatussub',
60
                    array('action' => 'ostatussub'));
61 62
        $m->connect('main/ostatusgroup',
                    array('action' => 'ostatusgroup'));
63 64
        $m->connect('main/ostatuspeopletag',
                    array('action' => 'ostatuspeopletag'));
65 66

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

Brion Vibber's avatar
Brion Vibber committed
69 70
        $m->connect('main/push/callback/:feed',
                    array('action' => 'pushcallback'),
71
                    array('feed' => '[0-9]+'));
72 73

        // Salmon endpoint
74
        $m->connect('main/salmon/user/:id',
75
                    array('action' => 'usersalmon'),
76
                    array('id' => '[0-9]+'));
77
        $m->connect('main/salmon/group/:id',
78
                    array('action' => 'groupsalmon'),
79
                    array('id' => '[0-9]+'));
80 81 82
        $m->connect('main/salmon/peopletag/:id',
                    array('action' => 'peopletagsalmon'),
                    array('id' => '[0-9]+'));
83 84 85
        return true;
    }

86 87 88 89 90 91 92 93 94 95 96 97 98 99
    public function onAutoload($cls)
    {
        switch ($cls) {
        case 'Crypt_AES':
        case 'Crypt_RSA':
            // Crypt_AES becomes Crypt/AES.php which is found in extlib/phpseclib/
            // which has been added to our include_path before
            require_once str_replace('_', '/', $cls) . '.php';
            return false;
        }

        return parent::onAutoload($cls);
    }

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

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

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

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

Brion Vibber's avatar
Brion Vibber committed
119
        // Incoming from a foreign PuSH hub
120
        $qm->connect('pushin', 'PushInQueueHandler');
Stephen Paul Weber's avatar
Stephen Paul Weber committed
121 122 123

        // Re-subscribe feeds that need renewal
        $qm->connect('pushrenew', 'PushRenewQueueHandler');
124 125 126 127 128 129 130 131
        return true;
    }

    /**
     * Put saved notices into the queue for pubsub distribution.
     */
    function onStartEnqueueNotice($notice, &$transports)
    {
132 133 134 135
        if ($notice->inScope(null)) {
            // put our transport first, in case there's any conflict (like OMB)
            array_unshift($transports, 'ostatus');
            $this->log(LOG_INFO, "Notice {$notice->id} queued for OStatus processing");
136
        } else {
137 138 139
            // FIXME: we don't do privacy-controlled OStatus updates yet.
            // once that happens, finer grain of control here.
            $this->log(LOG_NOTICE, "Not queueing notice {$notice->id} for OStatus because of privacy; scope = {$notice->scope}");
140
        }
141 142 143 144 145
        return true;
    }

    /**
     * Set up a PuSH hub link to our internal link for canonical timeline
146
     * Atom feeds for users and groups.
147
     */
148
    function onStartApiAtom($feed)
149
    {
150 151 152
        $id = null;

        if ($feed instanceof AtomUserNoticeFeed) {
153 154 155 156
            $salmonAction = 'usersalmon';
            $user = $feed->getUser();
            $id   = $user->id;
            $profile = $user->getProfile();
157
        } else if ($feed instanceof AtomGroupNoticeFeed) {
158 159 160
            $salmonAction = 'groupsalmon';
            $group = $feed->getGroup();
            $id = $group->id;
161 162 163 164
        } else if ($feed instanceof AtomListNoticeFeed) {
            $salmonAction = 'peopletagsalmon';
            $peopletag = $feed->getList();
            $id = $peopletag->id;
165
        } else {
166
            return true;
167
        }
Brion Vibber's avatar
Brion Vibber committed
168

169
        if (!empty($id)) {
170 171 172 173
            $hub = common_config('ostatus', 'hub');
            if (empty($hub)) {
                // Updates will be handled through our internal PuSH hub.
                $hub = common_local_url('pushhub');
174
            }
175
            $feed->addLink($hub, array('rel' => 'hub'));
176 177 178

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

181
            // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
182 183
            $feed->addLink($salmon, array('rel' => Salmon::NS_REPLIES));
            $feed->addLink($salmon, array('rel' => Salmon::NS_MENTIONS));
184
        }
185 186

        return true;
187
    }
188

189 190 191
    /**
     * Add in an OStatus subscribe button
     */
192
    function onStartProfileRemoteSubscribe($output, $profile)
193 194 195 196 197
    {
        $this->onStartProfileListItemActionElements($output, $profile);
        return false;
    }

198
    function onStartGroupSubscribe($widget, $group)
199 200 201 202
    {
        $cur = common_current_user();

        if (empty($cur)) {
203
            $widget->out->elementStart('li', 'entity_subscribe');
204

205
            $url = common_local_url('ostatusinit',
206
                                    array('group' => $group->nickname));
207
            $widget->out->element('a', array('href' => $url,
208
                                             'class' => 'entity_remote_subscribe'),
209
                                // TRANS: Link to subscribe to a remote entity.
210
                                _m('Subscribe'));
211

212
            $widget->out->elementEnd('li');
213
            return false;
214
        }
215

216
        return true;
217 218
    }

219
    function onStartSubscribePeopletagForm($output, $peopletag)
220 221 222 223
    {
        $cur = common_current_user();

        if (empty($cur)) {
224 225
            $output->elementStart('li', 'entity_subscribe');
            $profile = $peopletag->getTagger();
226
            $url = common_local_url('ostatusinit',
227
                                    array('tagger' => $profile->nickname, 'peopletag' => $peopletag->tag));
228 229
            $output->element('a', array('href' => $url,
                                        'class' => 'entity_remote_subscribe'),
230
                                // TRANS: Link to subscribe to a remote entity.
231 232 233 234 235 236 237 238 239 240 241 242 243 244
                                _m('Subscribe'));

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

        return true;
    }

    /*
     * If the field being looked for is URI look for the profile
     */
    function onStartProfileCompletionSearch($action, $profile, $search_engine) {
        if ($action->field == 'uri') {
245
            $profile->joinAdd(array('id', 'user:id'));
246 247 248
            $profile->whereAdd('uri LIKE "%' . $profile->escape($q) . '%"');
            $profile->query();

249 250
            $validate = new Validate();

251 252
            if ($profile->N == 0) {
                try {
253
                    if ($validate->email($q)) {
254
                        $oprofile = Ostatus_profile::ensureWebfinger($q);
255
                    } else if ($validate->uri($q)) {
256 257
                        $oprofile = Ostatus_profile::ensureProfileURL($q);
                    } else {
258 259
                        // TRANS: Exception in OStatus when invalid URI was entered.
                        throw new Exception(_m('Invalid URI.'));
260 261 262 263
                    }
                    return $this->filter(array($oprofile->localProfile()));

                } catch (Exception $e) {
264 265
                // TRANS: Error message in OStatus plugin. Do not translate the domain names example.com
                // TRANS: and example.net, as these are official standard domain names for use in examples.
266
                    $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.");
267 268 269 270 271
                    return array();
                }
            }
            return false;
        }
272
        return true;
273 274
    }

275 276 277 278 279 280 281 282
    /**
     * Webfinger matches: @user@example.com or even @user--one.george_orwell@1984.biz
     *
     * @return  array   The matching IDs (without @ or acct:) and each respective position in the given string.
     */
    static function extractWebfingerIds($text)
    {
        $wmatches = array();
283
        $result = preg_match_all('/(?:^|\s+)@((?:\w+[\w\-\_\.]?)*(?:[\w\-\_\.]*\w+)@'.URL_REGEX_DOMAIN_NAME.')/',
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
                       $text,
                       $wmatches,
                       PREG_OFFSET_CAPTURE);
        if ($result === false) {
            common_log(LOG_ERR, __METHOD__ . ': Error parsing webfinger IDs from text (preg_last_error=='.preg_last_error().').');
        } else {
            common_debug(sprintf('Found %i matches for WebFinger IDs: %s', count($wmatches), _ve($wmatches)));
        }
        return $wmatches[1];
    }

    /**
     * Profile URL matches: @example.com/mublog/user
     *
     * @return  array   The matching URLs (without @ or acct:) and each respective position in the given string.
     */
    static function extractUrlMentions($text)
    {
        $wmatches = array();
303 304 305
        // In the regexp below we need to match / _before_ URL_REGEX_VALID_PATH_CHARS because it otherwise gets merged
        // with the TLD before (but / is in URL_REGEX_VALID_PATH_CHARS anyway, it's just its positioning that is important)
        $result = preg_match_all('/(?:^|\s+)@('.URL_REGEX_DOMAIN_NAME.'(?:\/['.URL_REGEX_VALID_PATH_CHARS.']*)*)/',
306 307 308 309 310 311 312 313 314 315 316
                       $text,
                       $wmatches,
                       PREG_OFFSET_CAPTURE);
        if ($result === false) {
            common_log(LOG_ERR, __METHOD__ . ': Error parsing profile URL mentions from text (preg_last_error=='.preg_last_error().').');
        } else {
            common_debug(sprintf('Found %i matches for profile URL mentions: %s', count($wmatches), _ve($wmatches)));
        }
        return $wmatches[1];
    }

317
    /**
318 319 320
     * Find any explicit remote mentions. Accepted forms:
     *   Webfinger: @user@example.com
     *   Profile link: @example.com/mublog/user
321
     * @param Profile $sender
322 323 324
     * @param string $text input markup text
     * @param array &$mention in/out param: set of found mentions
     * @return boolean hook return value
325
     */
326
    function onEndFindMentions(Profile $sender, $text, &$mentions)
327
    {
328 329
        $matches = array();

330 331 332 333 334 335 336
        foreach (self::extractWebfingerIds($text) as $wmatch) {
            list($target, $pos) = $wmatch;
            $this->log(LOG_INFO, "Checking webfinger '$target'");
            $profile = null;
            try {
                $oprofile = Ostatus_profile::ensureWebfinger($target);
                if (!$oprofile instanceof Ostatus_profile || !$oprofile->isPerson()) {
337
                    continue;
338
                }
339 340 341 342 343 344 345 346
                $profile = $oprofile->localProfile();
            } catch (OStatusShadowException $e) {
                // This means we got a local user in the webfinger lookup
                $profile = $e->profile;
            } catch (Exception $e) {
                $this->log(LOG_ERR, "Webfinger check failed: " . $e->getMessage());
                continue;
            }
347

348
            assert($profile instanceof Profile);
349

350 351 352 353 354 355
            $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target)
                    ? $profile->getNickname()   // TODO: we could do getBestName() or getFullname() here
                    : $target;
            $url = $profile->getUri();
            if (!common_valid_http_url($url)) {
                $url = $profile->getUrl();
356
            }
357 358 359 360 361 362
            $matches[$pos] = array('mentioned' => array($profile),
                                   'type' => 'mention',
                                   'text' => $text,
                                   'position' => $pos,
                                   'length' => mb_strlen($target),
                                   'url' => $url);
363 364
        }

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
        foreach (self::extractUrlMentions($text) as $wmatch) {
            list($target, $pos) = $wmatch;
            $schemes = array('http', 'https');
            foreach ($schemes as $scheme) {
                $url = "$scheme://$target";
                $this->log(LOG_INFO, "Checking profile address '$url'");
                try {
                    $oprofile = Ostatus_profile::ensureProfileURL($url);
                    if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
                        $profile = $oprofile->localProfile();
                        $text = !empty($profile->nickname) && mb_strlen($profile->nickname) < mb_strlen($target) ?
                                $profile->nickname : $target;
                        $matches[$pos] = array('mentioned' => array($profile),
                                               'type' => 'mention',
                                               'text' => $text,
                                               'position' => $pos,
                                               'length' => mb_strlen($target),
                                               'url' => $profile->getUrl());
                        break;
384
                    }
385 386
                } catch (Exception $e) {
                    $this->log(LOG_ERR, "Profile check failed: " . $e->getMessage());
387 388
                }
            }
389
        }
390

391 392 393 394 395 396
        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]);
397 398
            }
        }
399 400 401
        foreach ($matches as $mention) {
            $mentions[] = $mention;
        }
402

403 404 405
        return true;
    }

406 407 408 409 410 411 412 413 414 415 416 417 418 419
    /**
     * 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);
420
        if ($oprofile instanceof Ostatus_profile && !$oprofile->isGroup()) {
421 422 423 424 425 426
            try {
                $profile = $oprofile->localProfile();
            } catch (NoProfileException $e) {
                // No locally stored profile found for remote profile
                return true;
            }
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
            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);
447
        if ($oprofile instanceof Ostatus_profile && $oprofile->isGroup()) {
448 449 450 451 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
            $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 {
482
                return Ostatus_profile::ensureProfileURL($url);
483 484 485 486 487 488 489 490
            } catch (Exception $e) {
                common_log(LOG_ERR, 'Profile lookup failed for ' .
                                    $arg . ': ' . $e->getMessage());
            }
        }
        return null;
    }

491 492 493 494 495 496 497 498 499 500 501
    function onEndProfileSettingsActions($out) {
        $siteName = common_config('site', 'name');
        $js = 'navigator.registerContentHandler("application/vnd.mozilla.maybe.feed", "'.addslashes(common_local_url('ostatussub', null, array('profile' => '%s'))).'", "'.addslashes($siteName).'")';
        $out->elementStart('li');
        $out->element('a',
                      array('href' => 'javascript:'.$js),
                      // TRANS: Option in profile settings to add this instance to Firefox as a feedreader
                      _('Add to Firefox as feedreader'));
        $out->elementEnd('li');
    }

502 503 504
    /**
     * Make sure necessary tables are filled out.
     */
505 506
    function onCheckSchema() {
        $schema = Schema::get();
507
        $schema->ensureTable('ostatus_profile', Ostatus_profile::schemaDef());
508
        $schema->ensureTable('ostatus_source', Ostatus_source::schemaDef());
509
        $schema->ensureTable('feedsub', FeedSub::schemaDef());
510
        $schema->ensureTable('hubsub', HubSub::schemaDef());
511
        $schema->ensureTable('magicsig', Magicsig::schemaDef());
512
        return true;
513
    }
514

515
    public function onEndShowStylesheets(Action $action) {
516
        $action->cssLink($this->path('theme/base/css/ostatus.css'));
517 518
        return true;
    }
519 520

    function onEndShowStatusNetScripts($action) {
521
        $action->script($this->path('js/ostatus.js'));
522 523
        return true;
    }
524

525 526 527 528 529 530 531 532 533 534
    /**
     * 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
     */
535 536
    function onStartNoticeSourceLink($notice, &$name, &$url, &$title)
    {
537
        // If we don't handle this, keep the event handler going
mmn's avatar
mmn committed
538
        if (!in_array($notice->source, array('ostatus', 'share'))) {
539 540
            return true;
        }
541

542 543 544 545 546 547 548 549 550 551
        try {
            $url = $notice->getUrl();
            // If getUrl() throws exception, $url is never set
            
            $bits = parse_url($url);
            $domain = $bits['host'];
            if (substr($domain, 0, 4) == 'www.') {
                $name = substr($domain, 4);
            } else {
                $name = $domain;
552
            }
553 554 555 556 557 558 559 560 561

            // TRANS: Title. %s is a domain name.
            $title = sprintf(_m('Sent from %s via OStatus'), $domain);

            // Abort event handler, we have a name and URL!
            return false;
        } catch (InvalidUrlException $e) {
            // This just means we don't have the notice source data
            return true;
562 563
        }
    }
564 565 566 567 568 569 570 571 572 573

    /**
     * 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)
    {
574
        $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
575
        if ($oprofile instanceof Ostatus_profile) {
576
            $oprofile->processFeed($feed, 'push');
577 578
        } else {
            common_log(LOG_DEBUG, "No ostatus profile for incoming feed $feedsub->uri");
579 580
        }
    }
581

582 583 584 585
    /**
     * 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.
586
     *
587 588 589 590 591 592
     * @param FeedSub $feedsub
     * @param integer $count in/out
     * @return mixed hook return code
     */
    function onFeedSubSubscriberCount($feedsub, &$count)
    {
593
        $oprofile = Ostatus_profile::getKV('feeduri', $feedsub->uri);
594
        if ($oprofile instanceof Ostatus_profile) {
595 596 597 598 599
            $count += $oprofile->subscriberCount();
        }
        return true;
    }

600 601 602 603 604 605 606
    /**
     * 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.
     *
607 608
     * @param Profile $profile  subscriber
     * @param Profile $other    subscribee
609 610 611 612 613
     *
     * @return hook return code
     *
     * @throws Exception
     */
614
    function onStartSubscribe(Profile $profile, Profile $other)
615
    {
616
        if (!$profile->isLocal()) {
617 618 619
            return true;
        }

620
        $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
621
        if (!$oprofile instanceof Ostatus_profile) {
622 623 624
            return true;
        }

625
        $oprofile->subscribe();
626 627 628 629 630 631
    }

    /**
     * Having established a remote subscription, send a notification to the
     * remote OStatus profile's endpoint.
     *
632 633
     * @param Profile $profile  subscriber
     * @param Profile $other    subscribee
634 635 636 637 638
     *
     * @return hook return code
     *
     * @throws Exception
     */
639
    function onEndSubscribe(Profile $profile, Profile $other)
640
    {
641
        if (!$profile->isLocal()) {
642 643 644
            return true;
        }

645
        $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
646
        if (!$oprofile instanceof Ostatus_profile) {
647 648 649
            return true;
        }

650
        $sub = Subscription::pkeyGet(array('subscriber' => $profile->id,
651
                                           'subscribed' => $other->id));
652

653
        $act = $sub->asActivity();
654

655
        $oprofile->notifyActivity($act, $profile);
656 657 658 659

        return true;
    }

660 661
    /**
     * Notify remote server and garbage collect unused feeds on unsubscribe.
662
     * @todo FIXME: Send these operations to background queues
663 664 665 666 667
     *
     * @param User $user
     * @param Profile $other
     * @return hook return value
     */
668
    function onEndUnsubscribe(Profile $profile, Profile $other)
669
    {
670
        if (!$profile->isLocal()) {
671 672 673
            return true;
        }

674
        $oprofile = Ostatus_profile::getKV('profile_id', $other->id);
675
        if (!$oprofile instanceof Ostatus_profile) {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
            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();
692 693
        // TRANS: Title for unfollowing a remote profile.
        $act->title   = _m('TITLE','Unfollow');
694 695
        // 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
696
        $act->content = sprintf(_m('%1$s stopped following %2$s.'),
697 698 699
                               $profile->getBestName(),
                               $other->getBestName());

700
        $act->actor   = $profile->asActivityObject();
mmn's avatar
mmn committed
701
        $act->objects[] = $other->asActivityObject();
702

703
        $oprofile->notifyActivity($act, $profile);
704 705 706 707

        return true;
    }

708 709 710 711 712 713
    /**
     * 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
714
     * @param Profile    $profile
715 716
     *
     * @return mixed hook return value
717
     * @throws Exception of various kinds, some from $oprofile->subscribe();
718
     */
719
    function onStartJoinGroup($group, $profile)
720
    {
721
        $oprofile = Ostatus_profile::getKV('group_id', $group->id);
722 723 724
        if (!$oprofile instanceof Ostatus_profile) {
            return true;
        }
725

726
        $oprofile->subscribe();
727 728 729 730 731 732 733 734 735 736

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

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

737
        $act->actor = $profile->asActivityObject();
738
        $act->verb = ActivityVerb::JOIN;
mmn's avatar
mmn committed
739
        $act->objects[] = $oprofile->asActivityObject();
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755

        $act->time = time();
        // TRANS: Title for joining a remote groep.
        $act->title = _m('TITLE','Join');
        // 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.
        $act->content = sprintf(_m('%1$s has joined group %2$s.'),
                                $profile->getBestName(),
                                $oprofile->getBestName());

        if ($oprofile->notifyActivity($act, $profile)) {
            return true;
        } else {
            $oprofile->garbageCollect();
            // TRANS: Exception thrown when joining a remote group fails.
            throw new Exception(_m('Failed joining remote group.'));
756 757 758 759 760 761 762 763 764 765 766 767 768
        }
    }

    /**
     * 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
769
     * @param Profile $profile
770 771 772
     *
     * @return mixed hook return value
     */
773
    function onEndLeaveGroup($group, $profile)
774
    {
775
        $oprofile = Ostatus_profile::getKV('group_id', $group->id);
776 777 778
        if (!$oprofile instanceof Ostatus_profile) {
            return true;
        }
779

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

783
        $member = $profile;
784

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

791
        $act->actor = $member->asActivityObject();
792
        $act->verb = ActivityVerb::LEAVE;
mmn's avatar
mmn committed
793
        $act->objects[] = $oprofile->asActivityObject();
794

795 796 797 798 799 800 801 802 803 804
        $act->time = time();
        // TRANS: Title for leaving a remote group.
        $act->title = _m('TITLE','Leave');
        // 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.
        $act->content = sprintf(_m('%1$s has left group %2$s.'),
                                $member->getBestName(),
                                $oprofile->getBestName());

        $oprofile->notifyActivity($act, $member);
805 806
    }

807 808 809 810 811 812 813 814 815
    /**
     * 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
816
     * @throws Exception of various kinds, some from $oprofile->subscribe();
817 818 819 820
     */

    function onStartSubscribePeopletag($peopletag, $user)
    {
821
        $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
822 823 824
        if (!$oprofile instanceof Ostatus_profile) {
            return true;
        }
825

826
        $oprofile->subscribe();
827 828 829 830 831 832 833 834 835 836

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

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

837
        $act->actor = $sub->asActivityObject();
838
        $act->verb = ActivityVerb::FOLLOW;
mmn's avatar
mmn committed
839
        $act->objects[] = $oprofile->asActivityObject();
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856

        $act->time = time();
        // TRANS: Title for following a remote list.
        $act->title = _m('TITLE','Follow list');
        // TRANS: Success message for remote list follow through OStatus.
        // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
        $act->content = sprintf(_m('%1$s is now following people listed in %2$s by %3$s.'),
                                $sub->getBestName(),
                                $oprofile->getBestName(),
                                $tagger->getBestName());

        if ($oprofile->notifyActivity($act, $sub)) {
            return true;
        } else {
            $oprofile->garbageCollect();
            // TRANS: Exception thrown when subscription to remote list fails.
            throw new Exception(_m('Failed subscribing to remote list.'));
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
        }
    }

    /**
     * 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)
    {
872
        $oprofile = Ostatus_profile::getKV('peopletag_id', $peopletag->id);
873 874
        if (!$oprofile instanceof Ostatus_profile) {
            return true;
875
        }
876 877 878 879 880 881 882 883 884 885 886 887 888

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

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

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

889
        $act->actor = $member->asActivityObject();
890
        $act->verb = ActivityVerb::UNFOLLOW;
mmn's avatar
mmn committed
891
        $act->objects[] = $oprofile->asActivityObject();
892 893 894 895 896 897 898 899 900 901 902 903

        $act->time = time();
        // TRANS: Title for unfollowing a remote list.
        $act->title = _m('Unfollow list');
        // TRANS: Success message for remote list unfollow through OStatus.
        // TRANS: %1$s is the subscriber name, %2$s is the list, %3$s is the lister's name.
        $act->content = sprintf(_m('%1$s stopped following the list %2$s by %3$s.'),
                                $sub->getBestName(),
                                $oprofile->getBestName(),
                                $tagger->getBestName());

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

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 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
     */
    function onEndFavorNotice(Profile $profile, Notice $notice)
    {
        // Only distribute local users' favor actions, remote users
        // will have already distributed theirs.
        if (!$profile->isLocal()) {
            return true;
        }

        $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
        if (!$oprofile instanceof Ostatus_profile) {
            return true;
        }

        $fav = Fave::pkeyGet(array('user_id' => $profile->id,
                                   'notice_id' => $notice->id));

        if (!$fav instanceof Fave) {
            // That's weird.
            // TODO: Make pkeyGet throw exception, since this is a critical failure.
            return true;
        }

        $act = $fav->asActivity();

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

        return true;
    }

942 943 944 945 946 947 948
    /**
     * 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
949
     * @throws Exception of various kinds, some from $oprofile->subscribe();
950
     */
951 952
    function onEndTagProfile($ptag)
    {
953
        $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
954
        if (!$oprofile instanceof Ostatus_profile) {
955 956 957 958 959 960 961 962 963 964 965
            return true;
        }

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

        $act = new Activity();

        $tagger = $plist->getTagger();
966
        $tagged = Profile::getKV('id', $ptag->tagged);
967 968 969 970 971 972

        $act->verb = ActivityVerb::TAG;
        $act->id   = TagURI::mint('tag_profile:%d:%d:%s',
                                  $plist->tagger, $plist->id,
                                  common_date_iso8601(time()));
        $act->time = time();
Siebrand Mazeland's avatar
Siebrand Mazeland committed
973 974 975 976
        // TRANS: Title for listing a remote profile.
        $act->title = _m('TITLE','List');
        // TRANS: Success message for remote list addition through OStatus.
        // TRANS: %1$s is the list creator's name, %2$s is the added list member, %3$s is the list name.
977
        $act->content = sprintf(_m('%1$s listed %2$s in the list %3$s.'),
978 979 980 981
                                $tagger->getBestName(),
                                $tagged->getBestName(),
                                $plist->getBestName());

982 983
        $act->actor  = $tagger->asActivityObject();
        $act->objects = array($tagged->asActivityObject());
984 985
        $act->target = ActivityObject::fromPeopletag($plist);

986
        $oprofile->notifyDeferred($act, $tagger);
987 988

        // initiate a PuSH subscription for the person being tagged
989
        $oprofile->subscribe();
990 991 992
        return true;
    }

993 994 995 996 997 998 999 1000 1001
    /**
     * 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
     */
1002 1003
    function onEndUntagProfile($ptag)
    {
1004
        $oprofile = Ostatus_profile::getKV('profile_id', $ptag->tagged);
1005
        if (!$oprofile instanceof Ostatus_profile) {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
            return true;
        }

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

        $act = new Activity();

        $tagger = $plist->getTagger();
1017
        $tagged = Profile::getKV('id', $ptag->tagged);
1018 1019 1020 1021 1022 1023

        $act->verb = ActivityVerb::UNTAG;
        $act->id   = TagURI::mint('untag_profile:%d:%d:%s',
                                  $plist->tagger, $plist->id,
                                  common_date_iso8601(time()));
        $act->time = time();
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1024 1025 1026 1027 1028
        // TRANS: Title for unlisting a remote profile.
        $act->title = _m('TITLE','Unlist');
        // TRANS: Success message for remote list removal through OStatus.
        // TRANS: %1$s is the list creator's name, %2$s is the removed list member, %3$s is the list name.
        $act->content = sprintf(_m('%1$s removed %2$s from the list %3$s.'),
1029 1030 1031 1032
                                $tagger->getBestName(),
                                $tagged->getBestName(),
                                $plist->getBestName());

1033 1034
        $act->actor  = $tagger->asActivityObject();
        $act->objects = array($tagged->asActivityObject());
1035 1036
        $act->target = ActivityObject::fromPeopletag($plist);

1037
        $oprofile->notifyDeferred($act, $tagger);
1038 1039 1040 1041 1042 1043 1044

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

        return true;
    }

1045 1046 1047
    /**
     * Notify remote users when their notices get de-favorited.
     *
1048 1049 1050
     * @param Profile $profile Profile person doing the de-faving
     * @param Notice  $notice  Notice being favored
     *
1051 1052 1053
     * @return hook return value
     */
    function onEndDisfavorNotice(Profile $profile, Notice $notice)
1054
    {
1055 1056 1057
        // Only distribute local users' disfavor actions, remote users
        // will have already distributed theirs.
        if (!$profile->isLocal()) {
1058 1059 1060
            return true;
        }

1061
        $oprofile = Ostatus_profile::getKV('profile_id', $notice->profile_id);
1062
        if (!$oprofile instanceof Ostatus_profile) {
1063
            return true;
1064
        }
1065

1066 1067 1068 1069 1070 1071 1072 1073
        $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
1074 1075
        // TRANS: Title for unliking a remote notice.
        $act->title   = _m('Unlike');
1076 1077
        // 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
1078
        $act->content = sprintf(_m('%1$s no longer likes %2$s.'),
1079
                               $profile->getBestName(),
1080
                               $notice->getUrl());
1081

1082
        $act->actor   = $profile->asActivityObject();
mmn's avatar
mmn committed
1083
        $act->objects[]  = $notice->asActivityObject();
1084

1085
        $oprofile->notifyActivity($act, $profile);
1086

1087 1088
        return true;
    }
1089 1090 1091

    function onStartGetProfileUri($profile, &$uri)
    {
1092
        $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1093
        if ($oprofile instanceof Ostatus_profile) {
1094 1095 1096 1097 1098
            $uri = $oprofile->uri;
            return false;
        }
        return true;
    }
1099

1100 1101
    function onStartUserGroupHomeUrl($group, &$url)
    {
1102
        return $this->onStartUserGroupPermalink($group, $url);
1103 1104 1105 1106
    }

    function onStartUserGroupPermalink($group, &$url)
    {
1107
        $oprofile = Ostatus_profile::getKV('group_id', $group->id);
1108
        if ($oprofile instanceof Ostatus_profile) {
1109 1110 1111 1112 1113 1114 1115
            // @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;
        }
    }

1116 1117
    function onStartShowSubscriptionsContent($action)
    {
1118
        $this->showEntityRemoteSubscribe($action);
1119 1120 1121

        return true;
    }
1122

1123 1124
    function onStartShowUserGroupsContent($action)
    {
1125
        $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1126 1127 1128 1129

        return true;
    }

1130
    function onEndShowSubscriptionsMiniList($action)
1131 1132 1133 1134 1135 1136
    {
        $this->showEntityRemoteSubscribe($action);

        return true;
    }

1137 1138
    function onEndShowGroupsMiniList($action)
    {
1139
        $this->showEntityRemoteSubscribe($action, 'ostatusgroup');
1140 1141 1142 1143

        return true;
    }

1144
    function showEntityRemoteSubscribe($action, $target='ostatussub')
1145
    {
mmn's avatar
mmn committed
1146 1147 1148 1149 1150 1151
        if (!$action->getScoped() instanceof Profile) {
            // early return if we're not logged in
            return true;
        }

        if ($action->getScoped()->sameAs($action->getTarget())) {
1152 1153 1154
            $action->elementStart('div', 'entity_actions');
            $action->elementStart('p', array('id' => 'entity_remote_subscribe',
                                             'class' => 'entity_subscribe'));
1155
            $action->element('a', array('href' => common_local_url($target),
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1156 1157 1158
                                        'class' => 'entity_remote_subscribe'),
                                // TRANS: Link text for link to remote subscribe.
                                _m('Remote'));
1159 1160 1161 1162
            $action->elementEnd('p');
            $action->elementEnd('div');
        }
    }
1163 1164 1165 1166 1167 1168 1169

    /**
     * Ping remote profiles with updates to this profile.
     * Salmon pings are queued for background processing.
     */
    function onEndBroadcastProfile(Profile $profile)
    {
1170
        $user = User::getKV('id', $profile->id);
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196

        // 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
1197
        // TRANS: Title for activity.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1198
        $act->title   = _m('Profile update');
1199 1200
        // TRANS: Ping text for remote profile update through OStatus.
        // TRANS: %s is user that updated their profile.
1201
        $act->content = sprintf(_m('%s has updated their profile page.'),
1202 1203
                               $profile->getBestName());

1204
        $act->actor   = $profile->asActivityObject();
mmn's avatar
mmn committed
1205
        $act->objects[]  = $act->actor;
1206 1207

        while ($oprofile->fetch()) {
1208
            $oprofile->notifyDeferred($act, $profile);
1209 1210 1211 1212
        }

        return true;
    }
1213

mmn's avatar
mmn committed
1214 1215
    // FIXME: This one can accept both an Action and a Widget. Confusing! Refactor to (HTMLOutputter $out, Profile $target)!
    function onStartProfileListItemActionElements($item)
1216
    {
mmn's avatar
mmn committed
1217 1218 1219 1220 1221 1222 1223
        if (common_logged_in()) {
            // only non-logged in users get to see the "remote subscribe" form
            return true;
        } elseif (!$item->getTarget()->isLocal()) {
            // we can (for now) only provide remote subscribe forms for local users
            return true;
        }
1224

mmn's avatar
mmn committed
1225 1226 1227 1228 1229 1230 1231
        if ($item instanceof ProfileAction) {
            $output = $item;
        } elseif ($item instanceof Widget) {
            $output = $item->out;
        } else {
            // Bad $item class, don't know how to use this for outputting!
            throw new ServerException('Bad item type for onStartProfileListItemActionElements');
1232 1233
        }

mmn's avatar
mmn committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
        // Add an OStatus subscribe
        $output->elementStart('li', 'entity_subscribe');
        $url = common_local_url('ostatusinit',
                                array('nickname' => $item->getTarget()->getNickname()));
        $output->element('a', array('href' => $url,
                                    'class' => 'entity_remote_subscribe'),
                          // TRANS: Link text for a user to subscribe to an OStatus user.
                         _m('Subscribe'));
        $output->elementEnd('li');

        $output->elementStart('li', 'entity_tag');
        $url = common_local_url('ostatustag',
                                array('nickname' => $item->getTarget()->getNickname()));
        $output->element('a', array('href' => $url,
                                    'class' => 'entity_remote_tag'),
                          // TRANS: Link text for a user to list an OStatus user.
                         _m('List'));
        $output->elementEnd('li');

1253 1254
        return true;
    }
1255

1256
    function onPluginVersion(array &$versions)
1257 1258
    {
        $versions[] = array('name' => 'OStatus',
1259
                            'version' => GNUSOCIAL_VERSION,
1260 1261
                            'author' => 'Evan Prodromou, James Walker, Brion Vibber, Zach Copley',
                            'homepage' => 'http://status.net/wiki/Plugin:OStatus',
Siebrand Mazeland's avatar
Siebrand Mazeland committed
1262 1263 1264
                            // TRANS: Plugin description.
                            'rawdescription' => _m('Follow people across social networks that implement '.
                               '<a href="http://ostatus.org/">OStatus</a>.'));
1265 1266 1267

        return true;
    }
1268 1269

    /**
1270
     * Utility function to check if the given URI is a canonical group profile
1271 1272 1273 1274 1275 1276 1277
     * page, and if so return the ID number.
     *
     * @param string $url
     * @return mixed int or false
     */
    public static function localGroupFromUrl($url)
    {
1278
        $group = User_group::getKV('uri', $url);
mmn's avatar
mmn committed
1279 1280
        if ($group instanceof User_group) {
            if ($group->isLocal()) {
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
                return $group->id;
            }
        } else {
            // To find local groups which haven't had their uri fields filled out...
            // If the domain has changed since a subscriber got the URI, it'll
            // be broken.
            $template = common_local_url('groupbyid', array('id' => '31337'));
            $template = preg_quote($template, '/');
            $template = str_replace('31337', '(\d+)', $template);
            if (preg_match("/$template/", $url, $matches)) {
                return intval($matches[1]);
            }
1293 1294 1295
        }
        return false;
    }
1296 1297 1298

    public function onStartProfileGetAtomFeed($profile, &$feed)
    {
1299
        $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1300

1301
        if (!$oprofile instanceof Ostatus_profile) {
1302 1303 1304 1305 1306 1307
            return true;
        }

        $feed = $oprofile->feeduri;
        return false;
    }
1308

1309 1310 1311
    function onStartGetProfileFromURI($uri, &$profile)
    {
        // Don't want to do Web-based discovery on our own server,
1312 1313 1314
        // so we check locally first. This duplicates the functionality
        // in the Profile class, since the plugin always runs before
        // that local lookup, but since we return false it won't run double.
1315

1316
        $user = User::getKV('uri', $uri);
1317
        if ($user instanceof User) {
1318 1319
            $profile = $user->getProfile();
            return false;
1320 1321 1322 1323 1324 1325
        } else {
            $group = User_group::getKV('uri', $uri);
            if ($group instanceof User_group) {
                $profile = $group->getProfile();
                return false;
            }
1326
        }
1327

1328
        // Now, check remotely
1329 1330
        try {
            $oprofile = Ostatus_profile::ensureProfileURI($uri);
1331
            $profile = $oprofile->localProfile();
1332 1333 1334
            return !($profile instanceof Profile);  // localProfile won't throw exception but can return null
        } catch (Exception $e) {
            return true; // It's not an OStatus profile as far as we know, continue event handling
1335 1336
        }
    }
1337

1338 1339 1340
    function onEndWebFingerNoticeLinks(XML_XRD $xrd, Notice $target)
    {
        $author = $target->getProfile();
1341 1342
        $profiletype = $this->profileTypeString($author);
        $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $author->id));
1343 1344 1345 1346
        $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
        return true;
    }

1347
    function onEndWebFingerProfileLinks(XML_XRD $xrd, Profile $target)
1348
    {
1349 1350 1351
        if ($target->getObjectType() === ActivityObject::PERSON) {
            $this->addWebFingerPersonLinks($xrd, $target);
        }
1352

1353 1354 1355
        // Salmon
        $profiletype = $this->profileTypeString($target);
        $salmon_url = common_local_url("{$profiletype}salmon", array('id' => $target->id));
1356

1357
        $xrd->links[] = new XML_XRD_Element_Link(Salmon::REL_SALMON, $salmon_url);
1358 1359

        // XXX: these are deprecated, but StatusNet only looks for NS_REPLIES
1360 1361
        $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_REPLIES, $salmon_url);
        $xrd->links[] = new XML_XRD_Element_Link(Salmon::NS_MENTIONS, $salmon_url);
1362

1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
        // TODO - finalize where the redirect should go on the publisher
        $xrd->links[] = new XML_XRD_Element_Link('http://ostatus.org/schema/1.0/subscribe',
                              common_local_url('ostatussub') . '?profile={uri}',
                              null, // type not set
                              true); // isTemplate

        return true;
    }

    protected function profileTypeString(Profile $target)
    {
        // This is just used to have a definitive string response to "USERsalmon" or "GROUPsalmon"
        switch ($target->getObjectType()) {
        case ActivityObject::PERSON:
            return 'user';
        case ActivityObject::GROUP:
            return 'group';
        default:
            throw new ServerException('Unknown profile type for WebFinger profile links');
        }
    }

    protected function addWebFingerPersonLinks(XML_XRD $xrd, Profile $target)
    {
        $xrd->links[] = new XML_XRD_Element_Link(Discovery::UPDATESFROM,
                            common_local_url('ApiTimelineUser',
                                array('id' => $target->id, 'format' => 'atom')),
                            'application/atom+xml');

1392 1393 1394
        // Get this profile's keypair
        $magicsig = Magicsig::getKV('user_id', $target->id);
        if (!$magicsig instanceof Magicsig && $target->isLocal()) {
mmn's avatar
mmn committed
1395
            $magicsig = Magicsig::generate($target->getUser());
1396 1397
        }

1398 1399 1400 1401
        if (!$magicsig instanceof Magicsig) {
            return false;   // value doesn't mean anything, just figured I'd indicate this function didn't do anything
        }
        if (Event::handle('StartAttachPubkeyToUserXRD', array($magicsig, $xrd, $target))) {
1402
            $xrd->links[] = new XML_XRD_Element_Link(Magicsig::PUBLICKEYREL,
1403
                                'data:application/magic-public-key,'. $magicsig->toString());
1404 1405
            // The following event handles plugins like Diaspora which add their own version of the Magicsig pubkey
            Event::handle('EndAttachPubkeyToUserXRD', array($magicsig, $xrd, $target));
1406
        }
1407
    }
1408 1409 1410

    public function onGetLocalAttentions(Profile $actor, array $attention_uris, array &$mentions, array &$groups)
    {
1411
        list($groups, $mentions) = Ostatus_profile::filterAttention($actor, $attention_uris);