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

Ostatus_profile.php 66.5 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;
    }

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

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

103
        $profile = Profile::getKV('id', $this->profile_id);
104 105
        if (!$profile instanceof Profile) {
            throw new NoProfileException($this->profile_id);
106
        }
107
        return $profile;
108 109 110 111 112 113 114 115
    }

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

        if (!$group instanceof User_group) {
            throw new NoSuchGroupException(array('id'=>$this->group_id));
120
        }
121 122

        return $group;
123 124
    }

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

137 138 139 140 141 142 143 144 145
    /**
     * 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()) {
146
            return ActivityObject::fromGroup($this->localGroup());
Shashi Gowda's avatar
Shashi Gowda committed
147 148
        } else if ($this->isPeopletag()) {
            return ActivityObject::fromPeopletag($this->localPeopletag());
149
        } else {
150
            return $this->localProfile()->asActivityObject();
151 152 153
        }
    }

154 155 156 157 158 159
    /**
     * 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.
     *
160
     * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
161
     *
162 163 164 165 166 167
     * @param string $element one of 'actor', 'subject', 'object', 'target'
     * @return string
     */
    function asActivityNoun($element)
    {
        if ($this->isGroup()) {
168 169
            $noun = ActivityObject::fromGroup($this->localGroup());
            return $noun->asString('activity:' . $element);
Shashi Gowda's avatar
Shashi Gowda committed
170 171 172
        } else if ($this->isPeopletag()) {
            $noun = ActivityObject::fromPeopletag($this->localPeopletag());
            return $noun->asString('activity:' . $element);
173
        } else {
174
            $noun = $this->localProfile()->asActivityObject();
175
            return $noun->asString('activity:' . $element);
176 177 178
        }
    }

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

197 198 199 200 201
    public function isPerson()
    {
        return $this->localProfile()->isPerson();
    }

Shashi Gowda's avatar
Shashi Gowda committed
202 203 204 205 206 207 208 209 210 211 212
    /**
     * @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
213
            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
214 215
        } else {
            // TRANS: Server exception. %s is a URI
216
            throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
217
        }
218 219
    }

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

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

    /**
241 242
     * Check if this remote profile has any active local subscriptions, and
     * if not drop the PuSH subscription feed.
243
     *
244 245
     * @return boolean true if subscription is removed, false if there are still subscribers to the feed
     * @throws Exception of various kinds on failure.
246
     */
247
    public function unsubscribe() {
248
        return $this->garbageCollect();
249 250
    }

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

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

304 305 306 307
    /**
     * Send an Activity Streams notification to the remote Salmon endpoint,
     * if so configured.
     *
308 309 310
     * @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)
311
     */
312
    public function notify(Profile $actor, $verb, $object=null, $target=null)
313 314
    {
        if ($object == null) {
315
            $object = $this;
316
        }
317 318 319 320 321 322 323 324
        if (empty($this->salmonuri)) {
            return false;
        }
        $text = 'update';
        $id = TagURI::mint('%s:%s:%s',
                           $verb,
                           $actor->getURI(),
                           common_date_iso8601(time()));
325

326 327 328 329 330 331 332 333
        // @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');
334

335 336 337 338 339 340
        $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()));
341

342 343 344 345 346 347 348 349
        $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');
350

351 352
        $xml = $entry->getString();
        common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
353

mattl's avatar
mattl committed
354
        Salmon::post($this->salmonuri, $xml, $actor);
355 356
    }

357 358 359 360 361
    /**
     * 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
362
     * @param Profile $actor
363 364
     * @return boolean success
     */
365
    public function notifyActivity($entry, Profile $actor)
366 367
    {
        if ($this->salmonuri) {
mattl's avatar
mattl committed
368
            return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor, $this->localProfile());
369
        }
370
        common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
371

372 373
        return false;
    }
374

375 376 377 378 379 380 381
    /**
     * 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
     */
382
    public function notifyDeferred($entry, $actor)
383 384
    {
        if ($this->salmonuri) {
mattl's avatar
mattl committed
385 386 387 388 389 390 391 392 393 394 395 396 397
            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;
            }
398 399
        }

400
        return false;
401 402
    }

403 404 405 406 407 408 409 410 411 412
    protected function notifyPrepXml($entry)
    {
        $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
        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
413 414
            // TRANS: Server exception.
            throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
415 416 417
        }
    }

418 419 420 421
    function getBestName()
    {
        if ($this->isGroup()) {
            return $this->localGroup()->getBestName();
Shashi Gowda's avatar
Shashi Gowda committed
422 423
        } else if ($this->isPeopletag()) {
            return $this->localPeopletag()->getBestName();
424 425 426 427 428
        } else {
            return $this->localProfile()->getBestName();
        }
    }

429 430 431 432 433
    /**
     * Read and post notices for updates from the feed.
     * Currently assumes that all items in the feed are new,
     * coming from a PuSH hub.
     *
434 435
     * @param DOMDocument $doc
     * @param string $source identifier ("push")
436
     */
437
    public function processFeed(DOMDocument $doc, $source)
438
    {
439 440
        $feed = $doc->documentElement;

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

451 452
    public function processAtomFeed(DOMElement $feed, $source)
    {
453 454 455 456 457 458
        $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
        if ($entries->length == 0) {
            common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
            return;
        }

459
        $this->processEntries($entries, $feed, $source);
460 461
    }

462 463 464 465 466
    public function processRssFeed(DOMElement $rss, $source)
    {
        $channels = $rss->getElementsByTagName('channel');

        if ($channels->length == 0) {
467
            // TRANS: Exception.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
468
            throw new Exception(_m('RSS feed without a channel.'));
469 470 471 472 473 474 475 476
        } 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');

477 478 479 480 481 482 483 484 485 486 487
        $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());
488 489 490
            } 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());
491
            }
492 493 494
        }
    }

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

510
    // TODO: Make this throw an exception
511
    public function processActivity(Activity $activity, $source)
Evan Prodromou's avatar
Evan Prodromou committed
512
    {
513 514
        $notice = null;

Evan Prodromou's avatar
Evan Prodromou committed
515
        // The "WithProfile" events were added later.
516

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

520
            common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
521

522
            Event::handle('EndHandleFeedEntry', array($activity));
523
            Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
524
        }
525

526
        return $notice;
527 528 529 530 531
    }

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

539
        $options = array('is_local' => Notice::REMOTE);
540

541
        try {
542
            $stored = Notice::saveActivity($activity, $actor, $options);
543
        } catch (Exception $e) {
544 545
            common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
            throw $e;
546
        }
547
        return $stored;
548
    }
549

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

            // Is the recipient a local group?
571
            // TODO: $group = User_group::getKV('uri', $recipient);
572 573
            $id = OStatusPlugin::localGroupFromUrl($recipient);
            if ($id) {
574
                $group = User_group::getKV('id', $id);
575
                if ($group instanceof User_group) {
576 577 578 579 580
                    // 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));
581 582
                    }
                    continue;
583 584
                } else {
                    common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
585 586
                }
            }
587

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

605
        }
606 607
        common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
        common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
608
        return array($groups, $replies);
609 610
    }

611
    /**
Brion Vibber's avatar
Brion Vibber committed
612 613 614 615
     * 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.
     *
616 617
     * @param string $profile_url
     * @return Ostatus_profile
618 619
     * @throws Exception on various error conditions
     * @throws OStatusShadowException if this reference would obscure a local user/group
620
     */
mattl's avatar
mattl committed
621
    public static function ensureProfileURL($profile_url, array $hints=array())
622
    {
623 624
        $oprofile = self::getFromProfileURL($profile_url);

625
        if ($oprofile instanceof Ostatus_profile) {
626 627 628 629 630 631 632 633 634 635 636 637 638
            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
639 640
            // TRANS: Exception. %s is a profile URL.
            throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
641 642 643 644
        }

        // Check if we have a non-canonical URL

645
        $finalUrl = $response->getEffectiveUrl();
646 647 648 649 650 651 652

        if ($finalUrl != $profile_url) {

            $hints['profileurl'] = $finalUrl;

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

653
            if ($oprofile instanceof Ostatus_profile) {
654 655 656 657
                return $oprofile;
            }
        }

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

666
            $body = $response->getBody();
667

668
            $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
669

670 671 672
            if (!empty($hcardHints)) {
                $hints = array_merge($hints, $hcardHints);
            }
673 674 675 676
        }

        // Check if they've got an LRDD header

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

        // 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

695
        $discover = new FeedDiscovery();
696 697 698 699 700 701 702

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

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

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

Brion Vibber's avatar
Brion Vibber committed
708 709 710 711 712 713
    /**
     * 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
714
     * @throws OStatusShadowException for local profiles
Brion Vibber's avatar
Brion Vibber committed
715
     */
716 717
    static function getFromProfileURL($profile_url)
    {
718
        $profile = Profile::getKV('profileurl', $profile_url);
719
        if (!$profile instanceof Profile) {
720 721 722
            return null;
        }

723 724 725
        try {
            $oprofile = self::getFromProfile($profile);
            // We found the profile, return it!
726
            return $oprofile;
727 728 729 730 731 732 733
        } 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}'.");
            }
734 735 736 737 738 739 740 741 742
        }

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

        return null;
    }

743 744 745 746 747 748 749 750 751 752
    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
753 754 755 756 757 758 759 760
    /**
     * 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
761
    public static function ensureFeedURL($feed_url, array $hints=array())
762
    {
763 764 765 766 767
        $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
        if ($oprofile instanceof Ostatus_profile) {
            return $oprofile;
        }

768 769 770 771 772
        $discover = new FeedDiscovery();

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

773
        $huburi = $discover->getHubLink();
774
        $hints['hub'] = $huburi;
775 776 777 778

        // 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);
779
        $hints['salmon'] = $salmonuri;
780

781
        if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
782
            // We can only deal with folks with a PuSH hub
783
            // unless we have something similar available locally.
784 785 786
            throw new FeedSubNoHubException();
        }

Evan Prodromou's avatar
Evan Prodromou committed
787 788 789 790 791 792 793 794 795 796
        $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);
        }
    }
797

Brion Vibber's avatar
Brion Vibber committed
798 799 800 801 802 803 804 805
    /**
     * 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
806
     * @todo FIXME: Should this be marked public?
Brion Vibber's avatar
Brion Vibber committed
807 808 809
     * @return Ostatus_profile
     * @throws Exception
     */
mattl's avatar
mattl committed
810
    public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
Evan Prodromou's avatar
Evan Prodromou committed
811
    {
812
        $author = ActivityUtils::getFeedAuthor($feedEl);
813

814 815 816
        if (empty($author)) {
            // XXX: make some educated guesses here
            // TRANS: Feed sub exception.
817
            throw new FeedSubException(_m('Cannot find enough profile '.
818
                                          'information to make a feed.'));
819
        }
820

821
        return self::ensureActivityObjectProfile($author, $hints);
822 823
    }

Brion Vibber's avatar
Brion Vibber committed
824 825 826 827 828 829 830 831
    /**
     * 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
832
     * @todo FIXME: Should this be marked public?
Brion Vibber's avatar
Brion Vibber committed
833 834 835
     * @return Ostatus_profile
     * @throws Exception
     */
mattl's avatar
mattl committed
836
    public static function ensureRssChannel(DOMElement $feedEl, array $hints)
Evan Prodromou's avatar
Evan Prodromou committed
837
    {
838 839 840 841 842 843 844 845 846 847
        // 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);
848 849 850 851 852 853 854
                // 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);
                }
855 856 857
            }
        }

858 859
        $obj = ActivityUtils::getFeedAuthor($feedEl);

860
        // @todo FIXME: We should check whether this feed has elements
Evan Prodromou's avatar
Evan Prodromou committed
861 862 863
        // with different <author> or <dc:creator> elements, and... I dunno.
        // Do something about that.

864
        if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
Evan Prodromou's avatar
Evan Prodromou committed
865 866 867 868

        return self::ensureActivityObjectProfile($obj, $hints);
    }

869 870
    /**
     * Download and update given avatar image
871
     *
872
     * @param string $url
873
     * @return Avatar    The Avatar we have on disk. (seldom used)