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

Ostatus_profile.php 58.9 KB
Newer Older
1 2
<?php
/*
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * 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/>.
 */

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

25
class Ostatus_profile extends Memcached_DataObject
26
{
27
    public $__table = 'ostatus_profile';
28

29 30
    public $uri;

31
    public $profile_id;
32
    public $group_id;
33 34

    public $feeduri;
35
    public $salmonuri;
36
    public $avatar; // remote URL of the last avatar we saved
37

38
    public $created;
39
    public $modified;
40 41 42 43 44 45

    public /*static*/ function staticGet($k, $v=null)
    {
        return parent::staticGet(__CLASS__, $k, $v);
    }

46 47 48 49 50 51 52 53 54 55 56
    /**
     * return table definition for DB_DataObject
     *
     * DB_DataObject needs to know something about the table to manipulate
     * instances. This method provides all the DB_DataObject needs to know.
     *
     * @return array array of column definitions
     */

    function table()
    {
57
        return array('uri' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
58 59
                     'profile_id' => DB_DATAOBJECT_INT,
                     'group_id' => DB_DATAOBJECT_INT,
60
                     'feeduri' => DB_DATAOBJECT_STR,
61
                     'salmonuri' =>  DB_DATAOBJECT_STR,
62
                     'avatar' =>  DB_DATAOBJECT_STR,
63
                     'created' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL,
64
                     'modified' => DB_DATAOBJECT_STR + DB_DATAOBJECT_DATE + DB_DATAOBJECT_TIME + DB_DATAOBJECT_NOTNULL);
65
    }
66

67 68
    static function schemaDef()
    {
69 70
        return array(new ColumnDef('uri', 'varchar',
                                   255, false, 'PRI'),
71
                     new ColumnDef('profile_id', 'integer',
72
                                   null, true, 'UNI'),
73
                     new ColumnDef('group_id', 'integer',
74
                                   null, true, 'UNI'),
75
                     new ColumnDef('feeduri', 'varchar',
76
                                   255, true, 'UNI'),
77 78
                     new ColumnDef('salmonuri', 'text',
                                   null, true),
79 80
                     new ColumnDef('avatar', 'text',
                                   null, true),
81 82
                     new ColumnDef('created', 'datetime',
                                   null, false),
83
                     new ColumnDef('modified', 'datetime',
84 85 86 87 88 89 90 91 92 93 94 95 96 97
                                   null, false));
    }

    /**
     * return key definitions for DB_DataObject
     *
     * DB_DataObject needs to know about keys that the table has; this function
     * defines them.
     *
     * @return array key definitions
     */

    function keys()
    {
98
        return array_keys($this->keyTypes());
99 100 101 102 103 104 105 106 107 108 109 110
    }

    /**
     * return key definitions for Memcached_DataObject
     *
     * Our caching system uses the same key definitions, but uses a different
     * method to get them.
     *
     * @return array key definitions
     */

    function keyTypes()
111
    {
112
        return array('uri' => 'K', 'profile_id' => 'U', 'group_id' => 'U', 'feeduri' => 'U');
113 114 115 116
    }

    function sequenceKey()
    {
117
        return array(false, false, false);
118 119
    }

120 121 122 123
    /**
     * Fetch the StatusNet-side profile for this feed
     * @return Profile
     */
124
    public function localProfile()
125
    {
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        if ($this->profile_id) {
            return Profile::staticGet('id', $this->profile_id);
        }
        return null;
    }

    /**
     * Fetch the StatusNet-side profile for this feed
     * @return Profile
     */
    public function localGroup()
    {
        if ($this->group_id) {
            return User_group::staticGet('id', $this->group_id);
        }
        return null;
142 143
    }

144 145 146 147 148 149 150 151 152
    /**
     * 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()) {
153
            return ActivityObject::fromGroup($this->localGroup());
154 155 156 157 158
        } else {
            return ActivityObject::fromProfile($this->localProfile());
        }
    }

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 166
     * @fixme replace with wrappers on asActivityObject when it's got everything.
     *
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);
175
        } else {
176 177
            $noun = ActivityObject::fromProfile($this->localProfile());
            return $noun->asString('activity:' . $element);
178 179 180
        }
    }

181
    /**
182
     * @return boolean true if this is a remote group
183 184 185
     */
    function isGroup()
    {
186 187 188 189 190 191 192 193 194
        if ($this->profile_id && !$this->group_id) {
            return false;
        } else if ($this->group_id && !$this->profile_id) {
            return true;
        } else if ($this->group_id && $this->profile_id) {
            throw new ServerException("Invalid ostatus_profile state: both group and profile IDs set for $this->uri");
        } else {
            throw new ServerException("Invalid ostatus_profile state: both group and profile IDs empty for $this->uri");
        }
195 196
    }

197
    /**
198 199
     * Send a subscription request to the hub for this feed.
     * The hub will later send us a confirmation POST to /main/push/callback.
200
     *
201 202
     * @return bool true on success, false on failure
     * @throws ServerException if feed state is not valid
203
     */
204
    public function subscribe()
205
    {
206
        $feedsub = FeedSub::ensureFeed($this->feeduri);
207 208
        if ($feedsub->sub_state == 'active') {
            // Active subscription, we don't need to do anything.
209
            return true;
210 211 212
        } else {
            // Inactive or we got left in an inconsistent state.
            // Run a subscription request to make sure we're current!
213
            return $feedsub->subscribe();
214 215 216 217
        }
    }

    /**
218 219 220 221 222
     * Send a PuSH unsubscription request to the hub for this feed.
     * The hub will later send us a confirmation POST to /main/push/callback.
     *
     * @return bool true on success, false on failure
     * @throws ServerException if feed state is not valid
223
     */
224 225
    public function unsubscribe() {
        $feedsub = FeedSub::staticGet('uri', $this->feeduri);
226 227
        if (!$feedsub || $feedsub->sub_state == '' || $feedsub->sub_state == 'inactive') {
            // No active PuSH subscription, we can just leave it be.
228
            return true;
229 230 231
        } else {
            // PuSH subscription is either active or in an indeterminate state.
            // Send an unsubscribe.
232 233
            return $feedsub->unsubscribe();
        }
234 235
    }

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    /**
     * Check if this remote profile has any active local subscriptions, and
     * if not drop the PuSH subscription feed.
     *
     * @return boolean
     */
    public function garbageCollect()
    {
        if ($this->isGroup()) {
            $members = $this->localGroup()->getMembers(0, 1);
            $count = $members->N;
        } else {
            $count = $this->localProfile()->subscriberCount();
        }
        if ($count == 0) {
251
            common_log(LOG_INFO, "Unsubscribing from now-unused remote feed $this->feeduri");
252 253 254 255 256 257 258
            $this->unsubscribe();
            return true;
        } else {
            return false;
        }
    }

259 260 261 262
    /**
     * Send an Activity Streams notification to the remote Salmon endpoint,
     * if so configured.
     *
263 264 265
     * @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)
266
     */
267
    public function notify($actor, $verb, $object=null)
268
    {
269 270 271 272 273 274 275
        if (!($actor instanceof Profile)) {
            $type = gettype($actor);
            if ($type == 'object') {
                $type = get_class($actor);
            }
            throw new ServerException("Invalid actor passed to " . __METHOD__ . ": " . $type);
        }
276
        if ($object == null) {
277
            $object = $this;
278 279
        }
        if ($this->salmonuri) {
280 281 282 283 284

            $text = 'update';
            $id = TagURI::mint('%s:%s:%s',
                               $verb,
                               $actor->getURI(),
285
                               common_date_iso8601(time()));
286

287 288 289 290 291
            // @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',
292
                                'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
293 294
                                'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
                                'xmlns:media' => 'http://purl.org/syndication/atommedia');
295

Brion Vibber's avatar
Brion Vibber committed
296
            $entry = new XMLStringer();
297
            $entry->elementStart('entry', $attributes);
298 299 300
            $entry->element('id', null, $id);
            $entry->element('title', null, $text);
            $entry->element('summary', null, $text);
301
            $entry->element('published', null, common_date_w3dtf(common_sql_now()));
302 303

            $entry->element('activity:verb', null, $verb);
Brion Vibber's avatar
Brion Vibber committed
304 305
            $entry->raw($actor->asAtomAuthor());
            $entry->raw($actor->asActivityActor());
306
            $entry->raw($object->asActivityNoun('object'));
Brion Vibber's avatar
Brion Vibber committed
307
            $entry->elementEnd('entry');
308

309
            $xml = $entry->getString();
310
            common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
311 312

            $salmon = new Salmon(); // ?
313
            return $salmon->post($this->salmonuri, $xml, $actor);
314
        }
315
        return false;
316 317
    }

318 319 320 321 322 323 324
    /**
     * 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
     * @return boolean success
     */
325
    public function notifyActivity($entry, $actor)
326 327
    {
        if ($this->salmonuri) {
328
            $salmon = new Salmon();
329
            return $salmon->post($this->salmonuri, $this->notifyPrepXml($entry), $actor);
330
        }
331

332 333
        return false;
    }
334

335 336 337 338 339 340 341
    /**
     * 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
     */
342
    public function notifyDeferred($entry, $actor)
343 344 345
    {
        if ($this->salmonuri) {
            $data = array('salmonuri' => $this->salmonuri,
346 347
                          'entry' => $this->notifyPrepXml($entry),
                          'actor' => $actor->id);
348

349 350
            $qm = QueueManager::get();
            return $qm->enqueue($data, 'salmon');
351 352
        }

353
        return false;
354 355
    }

356 357 358 359 360 361 362 363 364 365 366 367 368 369
    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 {
            throw new ServerException("Invalid type passed to Ostatus_profile::notify; must be XML string or Activity entry");
        }
    }

370 371 372 373 374 375 376 377 378
    function getBestName()
    {
        if ($this->isGroup()) {
            return $this->localGroup()->getBestName();
        } else {
            return $this->localProfile()->getBestName();
        }
    }

379 380 381 382 383
    /**
     * Read and post notices for updates from the feed.
     * Currently assumes that all items in the feed are new,
     * coming from a PuSH hub.
     *
384 385
     * @param DOMDocument $doc
     * @param string $source identifier ("push")
386
     */
387
    public function processFeed(DOMDocument $doc, $source)
388
    {
389 390
        $feed = $doc->documentElement;

391 392 393 394 395 396
        if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
            $this->processAtomFeed($feed, $source);
        } else if ($feed->localName == 'rss') { // @fixme check namespace
            $this->processRssFeed($feed, $source);
        } else {
            throw new Exception("Unknown feed format.");
397
        }
398
    }
399

400 401
    public function processAtomFeed(DOMElement $feed, $source)
    {
402 403 404 405 406 407 408 409
        $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
        if ($entries->length == 0) {
            common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
            return;
        }

        for ($i = 0; $i < $entries->length; $i++) {
            $entry = $entries->item($i);
410
            $this->processEntry($entry, $feed, $source);
411 412 413
        }
    }

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
    public function processRssFeed(DOMElement $rss, $source)
    {
        $channels = $rss->getElementsByTagName('channel');

        if ($channels->length == 0) {
            throw new Exception("RSS feed without a channel.");
        } 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');

        for ($i = 0; $i < $items->length; $i++) {
            $item = $items->item($i);
            $this->processEntry($item, $channel, $source);
        }
    }

434 435 436 437 438
    /**
     * Process a posted entry from this feed source.
     *
     * @param DOMElement $entry
     * @param DOMElement $feed for context
439
     * @param string $source identifier ("push" or "salmon")
440
     */
441
    public function processEntry($entry, $feed, $source)
442 443 444
    {
        $activity = new Activity($entry, $feed);

445 446
        // @todo process all activity objects
        switch ($activity->objects[0]->type) {
447 448 449 450 451 452 453 454 455 456
        case ActivityObject::ARTICLE:
        case ActivityObject::BLOGENTRY:
        case ActivityObject::NOTE:
        case ActivityObject::STATUS:
        case ActivityObject::COMMENT:
            break;
        default:
            throw new ClientException("Can't handle that kind of post.");
        }

457
        if ($activity->verb == ActivityVerb::POST) {
458
            $this->processPost($activity, $source);
459 460 461 462 463 464 465 466
        } else {
            common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
        }
    }

    /**
     * Process an incoming post activity from this remote feed.
     * @param Activity $activity
467 468
     * @param string $method 'push' or 'salmon'
     * @return mixed saved Notice or false
469
     * @fixme break up this function, it's getting nasty long
470
     */
471
    public function processPost($activity, $method)
472
    {
473
        if ($this->isGroup()) {
474
            // A group feed will contain posts from multiple authors.
475
            // @fixme validate these profiles in some way!
476
            $oprofile = self::ensureActorProfile($activity);
477 478 479 480 481
            if ($oprofile->isGroup()) {
                // Groups can't post notices in StatusNet.
                common_log(LOG_WARNING, "OStatus: skipping post with group listed as author: $oprofile->uri in feed from $this->uri");
                return false;
            }
482
        } else {
483 484 485 486 487 488
            $actor = $activity->actor;

            if (empty($actor)) {
                // OK here! assume the default
            } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
                $this->updateFromActivityObject($actor);
489
            } else {
490
                throw new Exception("Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
491
            }
492

493
            $oprofile = $this;
494
        }
495

496 497
        // It's not always an ActivityObject::NOTE, but... let's just say it is.

Zach Copley's avatar
Zach Copley committed
498
        $note = $activity->objects[0];
499

500 501 502
        // The id URI will be used as a unique identifier for for the notice,
        // protecting against duplicate saves. It isn't required to be a URL;
        // tag: URIs for instance are found in Google Buzz feeds.
503
        $sourceUri = $note->id;
504 505
        $dupe = Notice::staticGet('uri', $sourceUri);
        if ($dupe) {
506
            common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
507
            return false;
508
        }
509

510
        // We'll also want to save a web link to the original notice, if provided.
511
        $sourceUrl = null;
512 513
        if ($note->link) {
            $sourceUrl = $note->link;
514 515
        } else if ($activity->link) {
            $sourceUrl = $activity->link;
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        } else if (preg_match('!^https?://!', $note->id)) {
            $sourceUrl = $note->id;
        }

        // Use summary as fallback for content

        if (!empty($note->content)) {
            $sourceContent = $note->content;
        } else if (!empty($note->summary)) {
            $sourceContent = $note->summary;
        } else if (!empty($note->title)) {
            $sourceContent = $note->title;
        } else {
            // @fixme fetch from $sourceUrl?
            throw new ClientException("No content for notice {$sourceUri}");
531 532
        }

533
        // Get (safe!) HTML and text versions of the content
534 535

        $rendered = $this->purify($sourceContent);
536
        $content = html_entity_decode(strip_tags($rendered));
537

Evan Prodromou's avatar
Evan Prodromou committed
538
        $shortened = common_shorten_links($content);
539 540 541 542 543 544 545

        // If it's too long, try using the summary, and make the
        // HTML an attachment.

        $attachment = null;

        if (Notice::contentTooLong($shortened)) {
546 547
            $attachment = $this->saveHTMLFile($note->title, $rendered);
            $summary = html_entity_decode(strip_tags($note->summary));
548 549 550
            if (empty($summary)) {
                $summary = $content;
            }
Evan Prodromou's avatar
Evan Prodromou committed
551
            $shortSummary = common_shorten_links($summary);
552
            if (Notice::contentTooLong($shortSummary)) {
553
                $url = common_shorten_url($sourceUrl);
554 555 556
                $shortSummary = substr($shortSummary,
                                       0,
                                       Notice::maxContent() - (mb_strlen($url) + 2));
557 558 559 560 561 562 563
                $content = $shortSummary . ' ' . $url;

                // We mark up the attachment link specially for the HTML output
                // so we can fold-out the full version inline.
                $attachUrl = common_local_url('attachment',
                                              array('attachment' => $attachment->id));
                $rendered = common_render_text($shortSummary) .
564 565 566 567
                            '<a href="' . htmlspecialchars($attachUrl) .'"'.
                            ' class="attachment more"' .
                            ' title="'. htmlspecialchars(_m('Show more')) . '">' .
                            '&#8230;' .
568
                            '</a>';
569 570 571
            }
        }

572
        $options = array('is_local' => Notice::REMOTE_OMB,
573
                        'url' => $sourceUrl,
574
                        'uri' => $sourceUri,
575 576
                        'rendered' => $rendered,
                        'replies' => array(),
577
                        'groups' => array(),
578 579
                        'tags' => array(),
                        'urls' => array());
580

581
        // Check for optional attributes...
582

583 584
        if (!empty($activity->time)) {
            $options['created'] = common_sql_date($activity->time);
585 586
        }

587
        if ($activity->context) {
588 589 590 591 592 593 594 595 596 597 598 599
            // Any individual or group attn: targets?
            $replies = $activity->context->attention;
            $options['groups'] = $this->filterReplies($oprofile, $replies);
            $options['replies'] = $replies;

            // Maintain direct reply associations
            // @fixme what about conversation ID?
            if (!empty($activity->context->replyToID)) {
                $orig = Notice::staticGet('uri',
                                          $activity->context->replyToID);
                if (!empty($orig)) {
                    $options['reply_to'] = $orig->id;
600
                }
601 602 603 604 605 606 607 608 609
            }

            $location = $activity->context->location;
            if ($location) {
                $options['lat'] = $location->lat;
                $options['lon'] = $location->lon;
                if ($location->location_id) {
                    $options['location_ns'] = $location->location_ns;
                    $options['location_id'] = $location->location_id;
610 611 612
                }
            }
        }
613

614 615 616 617 618 619 620 621 622 623
        // Atom categories <-> hashtags
        foreach ($activity->categories as $cat) {
            if ($cat->term) {
                $term = common_canonical_tag($cat->term);
                if ($term) {
                    $options['tags'][] = $term;
                }
            }
        }

624 625 626 627 628 629
        // Atom enclosures -> attachment URLs
        foreach ($activity->enclosures as $href) {
            // @fixme save these locally or....?
            $options['urls'][] = $href;
        }

630
        try {
631
            $saved = Notice::saveNew($oprofile->profile_id,
632 633
                                     $content,
                                     'ostatus',
634 635 636
                                     $options);
            if ($saved) {
                Ostatus_source::saveNew($saved, $this, $method);
637 638 639
                if (!empty($attachment)) {
                    File_to_post::processNew($attachment->id, $saved->id);
                }
640
            }
641
        } catch (Exception $e) {
642 643
            common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
            throw $e;
644
        }
645 646 647
        common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
        return $saved;
    }
648

649 650 651 652 653
    /**
     * Clean up HTML
     */
    protected function purify($html)
    {
654
        require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
655 656
        $config = array('safe' => 1,
                        'deny_attribute' => 'id,style,on*');
657
        return htmLawed($html, $config);
658 659 660 661 662 663 664 665 666 667
    }

    /**
     * Filters a list of recipient ID URIs to just those for local delivery.
     * @param Ostatus_profile local profile of sender
     * @param array in/out &$attention_uris set of URIs, will be pruned on output
     * @return array of group IDs
     */
    protected function filterReplies($sender, &$attention_uris)
    {
668
        common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', $attention_uris));
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
        $groups = array();
        $replies = array();
        foreach ($attention_uris as $recipient) {
            // Is the recipient a local user?
            $user = User::staticGet('uri', $recipient);
            if ($user) {
                // @fixme sender verification, spam etc?
                $replies[] = $recipient;
                continue;
            }

            // Is the recipient a remote group?
            $oprofile = Ostatus_profile::staticGet('uri', $recipient);
            if ($oprofile) {
                if ($oprofile->isGroup()) {
                    // Deliver to local members of this remote group.
                    // @fixme sender verification?
                    $groups[] = $oprofile->group_id;
687 688
                } else {
                    common_log(LOG_DEBUG, "Skipping reply to remote profile $recipient");
689 690 691 692 693
                }
                continue;
            }

            // Is the recipient a local group?
694
            // @fixme uri on user_group isn't reliable yet
695
            // $group = User_group::staticGet('uri', $recipient);
696 697
            $id = OStatusPlugin::localGroupFromUrl($recipient);
            if ($id) {
698 699 700
                $group = User_group::staticGet('id', $id);
                if ($group) {
                    // Deliver to all members of this local group if allowed.
701 702
                    $profile = $sender->localProfile();
                    if ($profile->isMember($group)) {
703
                        $groups[] = $group->id;
704 705
                    } else {
                        common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
706 707
                    }
                    continue;
708 709
                } else {
                    common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
710 711
                }
            }
712 713 714

            common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient");

715
        }
716
        $attention_uris = $replies;
717 718
        common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
        common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
719
        return $groups;
720 721
    }

722
    /**
Brion Vibber's avatar
Brion Vibber committed
723 724 725 726
     * 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.
     *
727 728
     * @param string $profile_url
     * @return Ostatus_profile
729 730
     * @throws Exception on various error conditions
     * @throws OStatusShadowException if this reference would obscure a local user/group
731
     */
732 733

    public static function ensureProfileURL($profile_url, $hints=array())
734
    {
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
        $oprofile = self::getFromProfileURL($profile_url);

        if (!empty($oprofile)) {
            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()) {
Brion Vibber's avatar
Brion Vibber committed
751
            throw new Exception("Could not reach profile page: " . $profile_url);
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
        }

        // Check if we have a non-canonical URL

        $finalUrl = $response->getUrl();

        if ($finalUrl != $profile_url) {

            $hints['profileurl'] = $finalUrl;

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

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

        // Try to get some hCard data

        $body = $response->getBody();

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

        if (!empty($hcardHints)) {
            $hints = array_merge($hints, $hcardHints);
        }

        // Check if they've got an LRDD header

        $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');

        if (!empty($lrdd)) {

            $xrd = Discovery::fetchXrd($lrdd);
            $xrdHints = DiscoveryHints::fromXRD($xrd);

            $hints = array_merge($hints, $xrdHints);
        }

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

799
        $discover = new FeedDiscovery();
800 801 802 803 804 805 806

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

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

        throw new Exception("Could not find a feed URL for profile page " . $finalUrl);
809 810
    }

Brion Vibber's avatar
Brion Vibber committed
811 812 813 814 815 816
    /**
     * 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
817
     * @throws OStatusShadowException for local profiles
Brion Vibber's avatar
Brion Vibber committed
818
     */
819 820 821 822 823 824 825 826 827 828 829 830 831 832
    static function getFromProfileURL($profile_url)
    {
        $profile = Profile::staticGet('profileurl', $profile_url);

        if (empty($profile)) {
            return null;
        }

        // Is it a known Ostatus profile?

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

        if (!empty($oprofile)) {
            return $oprofile;
833
        }
834

835 836 837 838 839
        // Is it a local user?

        $user = User::staticGet('id', $profile->id);

        if (!empty($user)) {
840
            throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
841 842 843 844 845 846 847 848 849
        }

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

        return null;
    }

Brion Vibber's avatar
Brion Vibber committed
850 851 852 853 854 855 856 857
    /**
     * 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
     */
858 859 860 861 862 863 864
    public static function ensureFeedURL($feed_url, $hints=array())
    {
        $discover = new FeedDiscovery();

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

865
        $huburi = $discover->getAtomLink('hub');
866
        $hints['hub'] = $huburi;
867
        $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
868
        $hints['salmon'] = $salmonuri;
869 870 871 872 873 874

        if (!$huburi) {
            // We can only deal with folks with a PuSH hub
            throw new FeedSubNoHubException();
        }

Evan Prodromou's avatar
Evan Prodromou committed
875 876 877 878 879 880 881 882 883 884
        $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);
        }
    }
885

Brion Vibber's avatar
Brion Vibber committed
886 887 888 889 890 891 892 893 894 895 896 897
    /**
     * 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
     * @fixme should this be marked public?
     * @return Ostatus_profile
     * @throws Exception
     */
Evan Prodromou's avatar
Evan Prodromou committed
898 899 900
    public static function ensureAtomFeed($feedEl, $hints)
    {
        // Try to get a profile from the feed activity:subject
901 902 903 904 905

        $subject = ActivityUtils::child($feedEl, Activity::SUBJECT, Activity::SPEC);

        if (!empty($subject)) {
            $subjObject = new ActivityObject($subject);
906
            return self::ensureActivityObjectProfile($subjObject, $hints);
907 908 909 910 911 912 913 914
        }

        // Otherwise, try the feed author

        $author = ActivityUtils::child($feedEl, Activity::AUTHOR, Activity::ATOM);

        if (!empty($author)) {
            $authorObject = new ActivityObject($author);
915
            return self::ensureActivityObjectProfile($authorObject, $hints);
916 917 918 919 920
        }

        // Sheesh. Not a very nice feed! Let's try fingerpoken in the
        // entries.

Evan Prodromou's avatar
Evan Prodromou committed
921
        $entries = $feedEl->getElementsByTagNameNS(Activity::ATOM, 'entry');
922 923 924 925 926 927 928 929 930

        if (!empty($entries) && $entries->length > 0) {

            $entry = $entries->item(0);

            $actor = ActivityUtils::child($entry, Activity::ACTOR, Activity::SPEC);

            if (!empty($actor)) {
                $actorObject = new ActivityObject($actor);
931
                return self::ensureActivityObjectProfile($actorObject, $hints);
932 933 934 935 936 937 938

            }

            $author = ActivityUtils::child($entry, Activity::AUTHOR, Activity::ATOM);

            if (!empty($author)) {
                $authorObject = new ActivityObject($author);
939
                return self::ensureActivityObjectProfile($authorObject, $hints);
940
            }
941
        }
942 943 944 945

        // XXX: make some educated guesses here

        throw new FeedSubException("Can't find enough profile information to make a feed.");
946 947
    }

Brion Vibber's avatar
Brion Vibber committed
948 949 950 951 952 953 954 955 956 957 958 959
    /**
     * 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
     * @fixme should this be marked public?
     * @return Ostatus_profile
     * @throws Exception
     */
Evan Prodromou's avatar
Evan Prodromou committed
960 961
    public static function ensureRssChannel($feedEl, $hints)
    {
962 963 964 965 966 967 968 969 970 971
        // 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);
972 973 974 975 976 977 978
                // 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);
                }
979 980 981
            }
        }

Evan Prodromou's avatar
Evan Prodromou committed
982 983 984 985 986 987 988 989 990
        // @fixme we should check whether this feed has elements
        // with different <author> or <dc:creator> elements, and... I dunno.
        // Do something about that.

        $obj = ActivityObject::fromRssChannel($feedEl);

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

991 992
    /**
     * Download and update given avatar image
993
     *
994 995 996 997 998
     * @param string $url
     * @throws Exception in various failure cases
     */
    protected function updateAvatar($url)
    {
999 1000 1001 1002
        if ($url == $this->avatar) {
            // We've already got this one.
            return;
        }
1003
        if (!common_valid_http_url($url)) {
1004
            throw new ServerException(sprintf(_m("Invalid avatar URL %s"), $url));
1005
        }
1006

1007 1008 1009 1010 1011 1012