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

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

mattl's avatar
mattl committed
20
if (!defined('GNUSOCIAL')) { exit(1); }
21

22
/**
23
 * @package OStatusPlugin
mattl's avatar
mattl committed
24 25
 * @author Brion Vibber <brion@status.net>
 * @maintainer Mikael Nordfeldth <mmn@hethane.se>
26
 */
27
class Ostatus_profile extends Managed_DataObject
28
{
29
    public $__table = 'ostatus_profile';
30

31 32
    public $uri;

33
    public $profile_id;
34
    public $group_id;
Shashi Gowda's avatar
Shashi Gowda committed
35
    public $peopletag_id;
36 37

    public $feeduri;
38
    public $salmonuri;
39
    public $avatar; // remote URL of the last avatar we saved
40

41
    public $created;
42
    public $modified;
43

44
    /**
45
     * Return table definition for Schema setup and DB_DataObject usage.
46 47 48 49 50
     *
     * @return array array of column definitions
     */
    static function schemaDef()
    {
51 52
        return array(
            'fields' => array(
53
                'uri' => array('type' => 'varchar', 'length' => 191, 'not null' => true),
54 55
                'profile_id' => array('type' => 'integer'),
                'group_id' => array('type' => 'integer'),
Shashi Gowda's avatar
Shashi Gowda committed
56
                'peopletag_id' => array('type' => 'integer'),
57 58
                'feeduri' => array('type' => 'varchar', 'length' => 191),
                'salmonuri' => array('type' => 'varchar', 'length' => 191),
59 60 61 62 63 64
                'avatar' => array('type' => 'text'),
                'created' => array('type' => 'datetime', 'not null' => true),
                'modified' => array('type' => 'datetime', 'not null' => true),
            ),
            'primary key' => array('uri'),
            'unique keys' => array(
65 66 67 68
                'ostatus_profile_profile_id_key' => array('profile_id'),
                'ostatus_profile_group_id_key' => array('group_id'),
                'ostatus_profile_peopletag_id_key' => array('peopletag_id'),
                'ostatus_profile_feeduri_key' => array('feeduri'),
69 70
            ),
            'foreign keys' => array(
71 72
                'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
                'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
Shashi Gowda's avatar
Shashi Gowda committed
73
                'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
74 75
            ),
        );
76 77
    }

78 79 80 81 82
    public function getUri()
    {
        return $this->uri;
    }

83 84 85 86 87
    public function getFeedSub()
    {
        return FeedSub::getByUri($this->feeduri);
    }

mattl's avatar
mattl committed
88
    static function fromProfile(Profile $profile)
mattl's avatar
mattl committed
89
    {
mattl's avatar
mattl committed
90
        $oprofile = Ostatus_profile::getKV('profile_id', $profile->getID());
mattl's avatar
mattl committed
91
        if (!$oprofile instanceof Ostatus_profile) {
mattl's avatar
mattl committed
92
            throw new Exception('No Ostatus_profile for Profile ID: '.$profile->getID());
mattl's avatar
mattl committed
93
        }
mattl's avatar
mattl committed
94
        return $oprofile;
mattl's avatar
mattl committed
95 96
    }

97
    /**
98
     * Fetch the locally stored profile for this feed
99
     * @return Profile
100
     * @throws NoProfileException if it was not found
101
     */
102
    public function localProfile()
103
    {
104 105 106 107
        if ($this->isGroup()) {
            return $this->localGroup()->getProfile();
        }

108
        $profile = Profile::getKV('id', $this->profile_id);
109 110
        if (!$profile instanceof Profile) {
            throw new NoProfileException($this->profile_id);
111
        }
112
        return $profile;
113 114 115 116 117 118 119 120
    }

    /**
     * Fetch the StatusNet-side profile for this feed
     * @return Profile
     */
    public function localGroup()
    {
121 122 123 124
        $group = User_group::getKV('id', $this->group_id);

        if (!$group instanceof User_group) {
            throw new NoSuchGroupException(array('id'=>$this->group_id));
125
        }
126 127

        return $group;
128 129
    }

Shashi Gowda's avatar
Shashi Gowda committed
130 131 132 133 134 135 136
    /**
     * Fetch the StatusNet-side peopletag for this feed
     * @return Profile
     */
    public function localPeopletag()
    {
        if ($this->peopletag_id) {
137
            return Profile_list::getKV('id', $this->peopletag_id);
Shashi Gowda's avatar
Shashi Gowda committed
138 139 140 141
        }
        return null;
    }

142 143 144 145 146 147 148 149 150
    /**
     * Returns an ActivityObject describing this remote user or group profile.
     * Can then be used to generate Atom chunks.
     *
     * @return ActivityObject
     */
    function asActivityObject()
    {
        if ($this->isGroup()) {
151
            return ActivityObject::fromGroup($this->localGroup());
Shashi Gowda's avatar
Shashi Gowda committed
152 153
        } else if ($this->isPeopletag()) {
            return ActivityObject::fromPeopletag($this->localPeopletag());
154
        } else {
155
            return $this->localProfile()->asActivityObject();
156 157 158
        }
    }

159 160 161 162 163 164
    /**
     * Returns an XML string fragment with profile information as an
     * Activity Streams noun object with the given element type.
     *
     * Assumes that 'activity' namespace has been previously defined.
     *
165
     * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
166
     *
167 168 169 170 171 172
     * @param string $element one of 'actor', 'subject', 'object', 'target'
     * @return string
     */
    function asActivityNoun($element)
    {
        if ($this->isGroup()) {
173 174
            $noun = ActivityObject::fromGroup($this->localGroup());
            return $noun->asString('activity:' . $element);
Shashi Gowda's avatar
Shashi Gowda committed
175 176 177
        } else if ($this->isPeopletag()) {
            $noun = ActivityObject::fromPeopletag($this->localPeopletag());
            return $noun->asString('activity:' . $element);
178
        } else {
179
            $noun = $this->localProfile()->asActivityObject();
180
            return $noun->asString('activity:' . $element);
181 182 183
        }
    }

184
    /**
185
     * @return boolean true if this is a remote group
186 187 188
     */
    function isGroup()
    {
Shashi Gowda's avatar
Shashi Gowda committed
189
        if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
190
            return false;
Shashi Gowda's avatar
Shashi Gowda committed
191
        } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
192
            return true;
Shashi Gowda's avatar
Shashi Gowda committed
193 194
        } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
            // TRANS: Server exception. %s is a URI
195
            throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
196
        } else {
Shashi Gowda's avatar
Shashi Gowda committed
197
            // TRANS: Server exception. %s is a URI
198
            throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
Shashi Gowda's avatar
Shashi Gowda committed
199 200 201
        }
    }

202 203 204 205 206
    public function isPerson()
    {
        return $this->localProfile()->isPerson();
    }

Shashi Gowda's avatar
Shashi Gowda committed
207 208 209 210 211 212 213 214 215 216 217
    /**
     * @return boolean true if this is a remote peopletag
     */
    function isPeopletag()
    {
        if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
            return false;
        } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
            return true;
        } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
            // TRANS: Server exception. %s is a URI
218
            throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
Shashi Gowda's avatar
Shashi Gowda committed
219 220
        } else {
            // TRANS: Server exception. %s is a URI
221
            throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
222
        }
223 224
    }

225
    /**
226 227
     * Send a subscription request to the hub for this feed.
     * The hub will later send us a confirmation POST to /main/push/callback.
228
     *
229 230
     * @return void
     * @throws ServerException if feed state is not valid or subscription fails.
231
     */
232
    public function subscribe()
233
    {
234
        $feedsub = FeedSub::ensureFeed($this->feeduri);
235 236
        if ($feedsub->sub_state == 'active') {
            // Active subscription, we don't need to do anything.
237
            return;
238
        }
239 240 241 242

        // Inactive or we got left in an inconsistent state.
        // Run a subscription request to make sure we're current!
        return $feedsub->subscribe();
243 244 245
    }

    /**
246
     * Check if this remote profile has any active local subscriptions, and
mattl's avatar
mattl committed
247
     * if not drop the WebSub subscription feed.
248
     *
249 250
     * @return boolean true if subscription is removed, false if there are still subscribers to the feed
     * @throws Exception of various kinds on failure.
251
     */
252
    public function unsubscribe() {
253
        return $this->garbageCollect();
254 255
    }

256 257
    /**
     * Check if this remote profile has any active local subscriptions, and
mattl's avatar
mattl committed
258
     * if not drop the WebSub subscription feed.
259
     *
260 261
     * @return boolean true if subscription is removed, false if there are still subscribers to the feed
     * @throws Exception of various kinds on failure.
262 263
     */
    public function garbageCollect()
264
    {
265
        $feedsub = FeedSub::getKV('uri', $this->feeduri);
266 267 268 269 270
        if ($feedsub instanceof FeedSub) {
            return $feedsub->garbageCollect();
        }
        // Since there's no FeedSub we can assume it's already garbage collected
        return true;
271 272 273 274
    }

    /**
     * Check if this remote profile has any active local subscriptions, so the
mattl's avatar
mattl committed
275
     * WebSub subscription layer can decide if it can drop the feed.
276 277 278 279 280
     *
     * This gets called via the FeedSubSubscriberCount event when running
     * FeedSub::garbageCollect().
     *
     * @return int
281
     * @throws NoProfileException if there is no local profile for the object
282 283
     */
    public function subscriberCount()
284 285 286 287
    {
        if ($this->isGroup()) {
            $members = $this->localGroup()->getMembers(0, 1);
            $count = $members->N;
Shashi Gowda's avatar
Shashi Gowda committed
288 289 290
        } else if ($this->isPeopletag()) {
            $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
            $count = $subscribers->N;
291
        } else {
Shashi Gowda's avatar
Shashi Gowda committed
292 293 294
            $profile = $this->localProfile();
            if ($profile->hasLocalTags()) {
                $count = 1;
295 296
            } else {
                $count = $profile->subscriberCount();
Shashi Gowda's avatar
Shashi Gowda committed
297
            }
298
        }
299 300 301 302 303 304 305 306
        common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");

        // Other plugins may be piggybacking on OStatus without having
        // an active group or user-to-user subscription we know about.
        Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
        common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");

        return $count;
307 308
    }

309 310 311 312
    /**
     * Send an Activity Streams notification to the remote Salmon endpoint,
     * if so configured.
     *
313 314 315
     * @param Profile $actor  Actor who did the activity
     * @param string  $verb   Activity::SUBSCRIBE or Activity::JOIN
     * @param Object  $object object of the action; must define asActivityNoun($tag)
316
     */
317
    public function notify(Profile $actor, $verb, $object=null, $target=null)
318 319
    {
        if ($object == null) {
320
            $object = $this;
321
        }
322 323 324 325 326 327 328 329
        if (empty($this->salmonuri)) {
            return false;
        }
        $text = 'update';
        $id = TagURI::mint('%s:%s:%s',
                           $verb,
                           $actor->getURI(),
                           common_date_iso8601(time()));
330

331 332 333 334 335 336 337 338
        // @todo FIXME: Consolidate all these NS settings somewhere.
        $attributes = array('xmlns' => Activity::ATOM,
                            'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
                            'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
                            'xmlns:georss' => 'http://www.georss.org/georss',
                            'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
                            'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
                            'xmlns:media' => 'http://purl.org/syndication/atommedia');
339

340 341 342 343 344 345
        $entry = new XMLStringer();
        $entry->elementStart('entry', $attributes);
        $entry->element('id', null, $id);
        $entry->element('title', null, $text);
        $entry->element('summary', null, $text);
        $entry->element('published', null, common_date_w3dtf(common_sql_now()));
346

347 348 349 350 351 352 353 354
        $entry->element('activity:verb', null, $verb);
        $entry->raw($actor->asAtomAuthor());
        $entry->raw($actor->asActivityActor());
        $entry->raw($object->asActivityNoun('object'));
        if ($target != null) {
            $entry->raw($target->asActivityNoun('target'));
        }
        $entry->elementEnd('entry');
355

356 357
        $xml = $entry->getString();
        common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
358

mattl's avatar
mattl committed
359
        Salmon::post($this->salmonuri, $xml, $actor);
360 361
    }

362 363 364 365 366
    /**
     * Send a Salmon notification ping immediately, and confirm that we got
     * an acceptable response from the remote site.
     *
     * @param mixed $entry XML string, Notice, or Activity
367
     * @param Profile $actor
368 369
     * @return boolean success
     */
370
    public function notifyActivity($entry, Profile $actor)
371 372
    {
        if ($this->salmonuri) {
mattl's avatar
mattl committed
373
            return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor, $this->localProfile());
374
        }
mattl's avatar
mattl committed
375
        common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '._ve($this->getUri()));
376

377 378
        return false;
    }
379

380 381 382 383 384 385 386
    /**
     * Queue a Salmon notification for later. If queues are disabled we'll
     * send immediately but won't get the return value.
     *
     * @param mixed $entry XML string, Notice, or Activity
     * @return boolean success
     */
387
    public function notifyDeferred($entry, $actor)
388 389
    {
        if ($this->salmonuri) {
mattl's avatar
mattl committed
390 391 392 393 394 395 396 397 398 399 400 401 402
            try {
                common_debug("OSTATUS: user {$actor->getNickname()} ({$actor->getID()}) wants to ping {$this->localProfile()->getNickname()} on {$this->salmonuri}");
                $data = array('salmonuri' => $this->salmonuri,
                              'entry' => $this->notifyPrepXml($entry),
                              'actor' => $actor->getID(),
                              'target' => $this->localProfile()->getID());

                $qm = QueueManager::get();
                return $qm->enqueue($data, 'salmon');
            } catch (Exception $e) {
                common_log(LOG_ERR, 'OSTATUS: Something went wrong when creating a Salmon slap: '._ve($e->getMessage()));
                return false;
            }
403 404
        }

405
        return false;
406 407
    }

408 409
    protected function notifyPrepXml($entry)
    {
410
        $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . ">\n";
411 412 413 414 415 416 417
        if (is_string($entry)) {
            return $entry;
        } else if ($entry instanceof Activity) {
            return $preamble . $entry->asString(true);
        } else if ($entry instanceof Notice) {
            return $preamble . $entry->asAtomEntry(true, true);
        } else {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
418 419
            // TRANS: Server exception.
            throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
420 421 422
        }
    }

423 424 425 426
    function getBestName()
    {
        if ($this->isGroup()) {
            return $this->localGroup()->getBestName();
Shashi Gowda's avatar
Shashi Gowda committed
427 428
        } else if ($this->isPeopletag()) {
            return $this->localPeopletag()->getBestName();
429 430 431 432 433
        } else {
            return $this->localProfile()->getBestName();
        }
    }

434 435 436
    /**
     * Read and post notices for updates from the feed.
     * Currently assumes that all items in the feed are new,
mattl's avatar
mattl committed
437
     * coming from a WebSub hub.
438
     *
439 440
     * @param DOMDocument $doc
     * @param string $source identifier ("push")
441
     */
442
    public function processFeed(DOMDocument $doc, $source)
443
    {
444 445
        $feed = $doc->documentElement;

446 447
        if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
            $this->processAtomFeed($feed, $source);
448
        } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
449 450
            $this->processRssFeed($feed, $source);
        } else {
451
            // TRANS: Exception.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
452
            throw new Exception(_m('Unknown feed format.'));
453
        }
454
    }
455

456 457
    public function processAtomFeed(DOMElement $feed, $source)
    {
458 459 460 461 462 463
        $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
        if ($entries->length == 0) {
            common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
            return;
        }

464
        $this->processEntries($entries, $feed, $source);
465 466
    }

467 468 469 470 471
    public function processRssFeed(DOMElement $rss, $source)
    {
        $channels = $rss->getElementsByTagName('channel');

        if ($channels->length == 0) {
472
            // TRANS: Exception.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
473
            throw new Exception(_m('RSS feed without a channel.'));
474 475 476 477 478 479 480 481
        } else if ($channels->length > 1) {
            common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
        }

        $channel = $channels->item(0);

        $items = $channel->getElementsByTagName('item');

482 483 484 485 486 487 488 489 490 491 492
        $this->processEntries($items, $channel, $source);
    }

    public function processEntries(DOMNodeList $entries, DOMElement $feed, $source)
    {
        for ($i = 0; $i < $entries->length; $i++) {
            $entry = $entries->item($i);
            try {
                $this->processEntry($entry, $feed, $source);
            } catch (AlreadyFulfilledException $e) {
                common_debug('We already had this entry: '.$e->getMessage());
493 494 495
            } catch (ServerException $e) {
                // FIXME: This should be UnknownUriException and the ActivityUtils:: findLocalObject should only test one URI
                common_log(LOG_ERR, 'Entry threw exception while processing a feed from '.$source.': '.$e->getMessage());
496
            }
497 498 499
        }
    }

500 501 502 503 504
    /**
     * Process a posted entry from this feed source.
     *
     * @param DOMElement $entry
     * @param DOMElement $feed for context
505
     * @param string $source identifier ("push" or "salmon")
506 507
     *
     * @return Notice Notice representing the new (or existing) activity
508
     */
509
    public function processEntry(DOMElement $entry, DOMElement $feed, $source)
510 511
    {
        $activity = new Activity($entry, $feed);
512
        return $this->processActivity($activity, $source);
Evan Prodromou's avatar
Evan Prodromou committed
513 514
    }

515
    // TODO: Make this throw an exception
516
    public function processActivity(Activity $activity, $source)
Evan Prodromou's avatar
Evan Prodromou committed
517
    {
518 519
        $notice = null;

Evan Prodromou's avatar
Evan Prodromou committed
520
        // The "WithProfile" events were added later.
521

522
        if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
Evan Prodromou's avatar
Evan Prodromou committed
523
            Event::handle('StartHandleFeedEntry', array($activity))) {
Evan Prodromou's avatar
Evan Prodromou committed
524

525
            common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
526

527
            Event::handle('EndHandleFeedEntry', array($activity));
528
            Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
529
        }
530

531
        return $notice;
532 533 534 535 536
    }

    /**
     * Process an incoming post activity from this remote feed.
     * @param Activity $activity
537 538
     * @param string $method 'push' or 'salmon'
     * @return mixed saved Notice or false
539
     */
540
    public function processPost($activity, $method)
541
    {
542
        $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
543

544
        $options = array('is_local' => Notice::REMOTE);
545

546
        try {
547
            $stored = Notice::saveActivity($activity, $actor, $options);
548
        } catch (Exception $e) {
549 550
            common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
            throw $e;
551
        }
552
        return $stored;
553
    }
554

555 556
    /**
     * Filters a list of recipient ID URIs to just those for local delivery.
557
     * @param Profile local profile of sender
558 559 560
     * @param array in/out &$attention_uris set of URIs, will be pruned on output
     * @return array of group IDs
     */
561
    static public function filterAttention(Profile $sender, array $attention)
562
    {
563
        common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
564 565
        $groups = array();
        $replies = array();
566
        foreach ($attention as $recipient=>$type) {
567
            // Is the recipient a local user?
568
            $user = User::getKV('uri', $recipient);
569
            if ($user instanceof User) {
570
                // @todo FIXME: Sender verification, spam etc?
571 572 573 574 575
                $replies[] = $recipient;
                continue;
            }

            // Is the recipient a local group?
576
            // TODO: $group = User_group::getKV('uri', $recipient);
577 578
            $id = OStatusPlugin::localGroupFromUrl($recipient);
            if ($id) {
579
                $group = User_group::getKV('id', $id);
580
                if ($group instanceof User_group) {
581 582 583 584 585
                    // Deliver to all members of this local group if allowed.
                    if ($sender->isMember($group)) {
                        $groups[] = $group->id;
                    } else {
                        common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
586 587
                    }
                    continue;
588 589
                } else {
                    common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
590 591
                }
            }
592

593 594
            // Is the recipient a remote user or group?
            try {
595
                $oprofile = self::ensureProfileURI($recipient);
596 597
                if ($oprofile->isGroup()) {
                    // Deliver to local members of this remote group.
598
                    // @todo FIXME: Sender verification?
599 600 601
                    $groups[] = $oprofile->group_id;
                } else {
                    // may be canonicalized or something
602
                    $replies[] = $oprofile->getUri();
603 604 605 606 607 608
                }
                continue;
            } catch (Exception $e) {
                // Neither a recognizable local nor remote user!
                common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
            }
609

610
        }
611 612
        common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
        common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
613
        return array($groups, $replies);
614 615
    }

616
    /**
Brion Vibber's avatar
Brion Vibber committed
617 618 619 620
     * Look up and if necessary create an Ostatus_profile for the remote entity
     * with the given profile page URL. This should never return null -- you
     * will either get an object or an exception will be thrown.
     *
621 622
     * @param string $profile_url
     * @return Ostatus_profile
623 624
     * @throws Exception on various error conditions
     * @throws OStatusShadowException if this reference would obscure a local user/group
625
     */
mattl's avatar
mattl committed
626
    public static function ensureProfileURL($profile_url, array $hints=array())
627
    {
628 629
        $oprofile = self::getFromProfileURL($profile_url);

630
        if ($oprofile instanceof Ostatus_profile) {
631 632 633 634 635 636 637 638 639 640 641 642 643
            return $oprofile;
        }

        $hints['profileurl'] = $profile_url;

        // Fetch the URL
        // XXX: HTTP caching

        $client = new HTTPClient();
        $client->setHeader('Accept', 'text/html,application/xhtml+xml');
        $response = $client->get($profile_url);

        if (!$response->isOk()) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
644 645
            // TRANS: Exception. %s is a profile URL.
            throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
646 647 648 649
        }

        // Check if we have a non-canonical URL

650
        $finalUrl = $response->getEffectiveUrl();
651 652 653 654 655 656 657

        if ($finalUrl != $profile_url) {

            $hints['profileurl'] = $finalUrl;

            $oprofile = self::getFromProfileURL($finalUrl);

658
            if ($oprofile instanceof Ostatus_profile) {
659 660 661 662
                return $oprofile;
            }
        }

663 664 665 666
        if (in_array(
            preg_replace('/\s*;.*$/', '', $response->getHeader('Content-Type')),
            array('application/rss+xml', 'application/atom+xml', 'application/xml', 'text/xml'))
        ) {
667
            $hints['feedurl'] = $response->getEffectiveUrl();
668 669
        } else {
            // Try to get some hCard data
670

671
            $body = $response->getBody();
672

673
            $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
674

675 676 677
            if (!empty($hcardHints)) {
                $hints = array_merge($hints, $hcardHints);
            }
678 679 680 681
        }

        // Check if they've got an LRDD header

682 683 684 685
        $lrdd = LinkHeader::getLink($response, 'lrdd');
        try {
            $xrd = new XML_XRD();
            $xrd->loadFile($lrdd);
686 687
            $xrdHints = DiscoveryHints::fromXRD($xrd);
            $hints = array_merge($hints, $xrdHints);
688 689
        } catch (Exception $e) {
            // No hints available from XRD
690 691 692 693 694 695 696 697 698 699
        }

        // If discovery found a feedurl (probably from LRDD), use it.

        if (array_key_exists('feedurl', $hints)) {
            return self::ensureFeedURL($hints['feedurl'], $hints);
        }

        // Get the feed URL from HTML

700
        $discover = new FeedDiscovery();
701 702 703 704 705 706 707

        $feedurl = $discover->discoverFromHTML($finalUrl, $body);

        if (!empty($feedurl)) {
            $hints['feedurl'] = $feedurl;
            return self::ensureFeedURL($feedurl, $hints);
        }
Brion Vibber's avatar
Brion Vibber committed
708

709
        // TRANS: Exception. %s is a URL.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
710
        throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
711 712
    }

Brion Vibber's avatar
Brion Vibber committed
713 714 715 716 717 718
    /**
     * Look up the Ostatus_profile, if present, for a remote entity with the
     * given profile page URL. Will return null for both unknown and invalid
     * remote profiles.
     *
     * @return mixed Ostatus_profile or null
719
     * @throws OStatusShadowException for local profiles
Brion Vibber's avatar
Brion Vibber committed
720
     */
721 722
    static function getFromProfileURL($profile_url)
    {
723
        $profile = Profile::getKV('profileurl', $profile_url);
724
        if (!$profile instanceof Profile) {
725 726 727
            return null;
        }

728 729 730
        try {
            $oprofile = self::getFromProfile($profile);
            // We found the profile, return it!
731
            return $oprofile;
732 733 734 735 736 737 738
        } catch (NoResultException $e) {
            // Could not find an OStatus profile, is it instead a local user?
            $user = User::getKV('id', $profile->id);
            if ($user instanceof User) {
                // @todo i18n FIXME: use sprintf and add i18n (?)
                throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
            }
739 740 741 742 743 744 745 746 747
        }

        // Continue discovery; it's a remote profile
        // for OMB or some other protocol, may also
        // support OStatus

        return null;
    }

748 749 750 751 752 753 754 755 756 757
    static function getFromProfile(Profile $profile)
    {
        $oprofile = new Ostatus_profile();
        $oprofile->profile_id = $profile->id;
        if (!$oprofile->find(true)) {
            throw new NoResultException($oprofile);
        }
        return $oprofile;
    }

Brion Vibber's avatar
Brion Vibber committed
758 759 760 761 762 763 764 765
    /**
     * Look up and if necessary create an Ostatus_profile for remote entity
     * with the given update feed. This should never return null -- you will
     * either get an object or an exception will be thrown.
     *
     * @return Ostatus_profile
     * @throws Exception
     */
mattl's avatar
mattl committed
766
    public static function ensureFeedURL($feed_url, array $hints=array())
767
    {
768 769 770 771 772
        $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
        if ($oprofile instanceof Ostatus_profile) {
            return $oprofile;
        }

773 774 775 776 777
        $discover = new FeedDiscovery();

        $feeduri = $discover->discoverFromFeedURL($feed_url);
        $hints['feedurl'] = $feeduri;

778
        $huburi = $discover->getHubLink();
779
        $hints['hub'] = $huburi;
780 781 782 783

        // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
        $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
                        ?: $discover->getAtomLink(Salmon::NS_REPLIES);
784
        $hints['salmon'] = $salmonuri;
785

786
        if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
mattl's avatar
mattl committed
787
            // We can only deal with folks with a WebSub hub
788
            // unless we have something similar available locally.
789 790 791
            throw new FeedSubNoHubException();
        }

Evan Prodromou's avatar
Evan Prodromou committed
792 793 794 795 796 797 798 799 800 801
        $feedEl = $discover->root;

        if ($feedEl->tagName == 'feed') {
            return self::ensureAtomFeed($feedEl, $hints);
        } else if ($feedEl->tagName == 'channel') {
            return self::ensureRssChannel($feedEl, $hints);
        } else {
            throw new FeedSubBadXmlException($feeduri);
        }
    }
802

Brion Vibber's avatar
Brion Vibber committed
803 804 805 806 807 808 809 810
    /**
     * Look up and, if necessary, create an Ostatus_profile for the remote
     * profile with the given Atom feed - actually loaded from the feed.
     * This should never return null -- you will either get an object or
     * an exception will be thrown.
     *
     * @param DOMElement $feedEl root element of a loaded Atom feed
     * @param array $hints additional discovery information passed from higher levels
811
     * @todo FIXME: Should this be marked public?
Brion Vibber's avatar
Brion Vibber committed
812 813 814
     * @return Ostatus_profile
     * @throws Exception
     */
mattl's avatar
mattl committed
815
    public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
Evan Prodromou's avatar
Evan Prodromou committed
816
    {
817
        $author = ActivityUtils::getFeedAuthor($feedEl);
818

819 820 821
        if (empty($author)) {
            // XXX: make some educated guesses here
            // TRANS: Feed sub exception.
822
            throw new FeedSubException(_m('Cannot find enough profile '.
823
                                          'information to make a feed.'));
824
        }
825

826
        return self::ensureActivityObjectProfile($author, $hints);
827 828
    }

Brion Vibber's avatar
Brion Vibber committed
829 830 831 832 833 834 835 836
    /**
     * Look up and, if necessary, create an Ostatus_profile for the remote
     * profile with the given RSS feed - actually loaded from the feed.
     * This should never return null -- you will either get an object or
     * an exception will be thrown.
     *
     * @param DOMElement $feedEl root element of a loaded RSS feed
     * @param array $hints additional discovery information passed from higher levels
837
     * @todo FIXME: Should this be marked public?
Brion Vibber's avatar
Brion Vibber committed
838 839 840
     * @return Ostatus_profile
     * @throws Exception
     */
mattl's avatar
mattl committed
841
    public static function ensureRssChannel(DOMElement $feedEl, array $hints)
Evan Prodromou's avatar
Evan Prodromou committed
842
    {
843 844 845 846 847 848 849 850 851 852
        // Special-case for Posterous. They have some nice metadata in their
        // posterous:author elements. We should use them instead of the channel.

        $items = $feedEl->getElementsByTagName('item');

        if ($items->length > 0) {
            $item = $items->item(0);
            $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
            if (!empty($authorEl)) {
                $obj = ActivityObject::fromPosterousAuthor($authorEl);
853 854 855 856 857 858 859
                // Posterous has multiple authors per feed, and multiple feeds
                // per author. We check if this is the "main" feed for this author.
                if (array_key_exists('profileurl', $hints) &&
                    !empty($obj->poco) &&
                    common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
                    return self::ensureActivityObjectProfile($obj, $hints);
                }
860 861 862
            }
        }

863 864
        $obj = ActivityUtils::getFeedAuthor($feedEl);

865
        // @todo FIXME: We should check whether this feed has elements