]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Ostatus_profile.php
More Exceptions for FeedSub doSubscribe and related functions
[quix0rs-gnu-social.git] / plugins / OStatus / classes / Ostatus_profile.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009-2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 /**
25  * @package OStatusPlugin
26  * @maintainer Brion Vibber <brion@status.net>
27  */
28 class Ostatus_profile extends Managed_DataObject
29 {
30     public $__table = 'ostatus_profile';
31
32     public $uri;
33
34     public $profile_id;
35     public $group_id;
36     public $peopletag_id;
37
38     public $feeduri;
39     public $salmonuri;
40     public $avatar; // remote URL of the last avatar we saved
41
42     public $created;
43     public $modified;
44
45     /**
46      * Return table definition for Schema setup and DB_DataObject usage.
47      *
48      * @return array array of column definitions
49      */
50     static function schemaDef()
51     {
52         return array(
53             'fields' => array(
54                 'uri' => array('type' => 'varchar', 'length' => 255, 'not null' => true),
55                 'profile_id' => array('type' => 'integer'),
56                 'group_id' => array('type' => 'integer'),
57                 'peopletag_id' => array('type' => 'integer'),
58                 'feeduri' => array('type' => 'varchar', 'length' => 255),
59                 'salmonuri' => array('type' => 'varchar', 'length' => 255),
60                 'avatar' => array('type' => 'text'),
61                 'created' => array('type' => 'datetime', 'not null' => true),
62                 'modified' => array('type' => 'datetime', 'not null' => true),
63             ),
64             'primary key' => array('uri'),
65             'unique keys' => array(
66                 'ostatus_profile_profile_id_idx' => array('profile_id'),
67                 'ostatus_profile_group_id_idx' => array('group_id'),
68                 'ostatus_profile_peopletag_id_idx' => array('peopletag_id'),
69                 'ostatus_profile_feeduri_idx' => array('feeduri'),
70             ),
71             'foreign keys' => array(
72                 'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
73                 'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
74                 'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
75             ),
76         );
77     }
78
79     public function getUri()
80     {
81         return $this->uri;
82     }
83
84     /**
85      * Fetch the StatusNet-side profile for this feed
86      * @return Profile
87      */
88     public function localProfile()
89     {
90         if ($this->profile_id) {
91             return Profile::getKV('id', $this->profile_id);
92         }
93         return null;
94     }
95
96     /**
97      * Fetch the StatusNet-side profile for this feed
98      * @return Profile
99      */
100     public function localGroup()
101     {
102         if ($this->group_id) {
103             return User_group::getKV('id', $this->group_id);
104         }
105         return null;
106     }
107
108     /**
109      * Fetch the StatusNet-side peopletag for this feed
110      * @return Profile
111      */
112     public function localPeopletag()
113     {
114         if ($this->peopletag_id) {
115             return Profile_list::getKV('id', $this->peopletag_id);
116         }
117         return null;
118     }
119
120     /**
121      * Returns an ActivityObject describing this remote user or group profile.
122      * Can then be used to generate Atom chunks.
123      *
124      * @return ActivityObject
125      */
126     function asActivityObject()
127     {
128         if ($this->isGroup()) {
129             return ActivityObject::fromGroup($this->localGroup());
130         } else if ($this->isPeopletag()) {
131             return ActivityObject::fromPeopletag($this->localPeopletag());
132         } else {
133             return ActivityObject::fromProfile($this->localProfile());
134         }
135     }
136
137     /**
138      * Returns an XML string fragment with profile information as an
139      * Activity Streams noun object with the given element type.
140      *
141      * Assumes that 'activity' namespace has been previously defined.
142      *
143      * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
144      *
145      * @param string $element one of 'actor', 'subject', 'object', 'target'
146      * @return string
147      */
148     function asActivityNoun($element)
149     {
150         if ($this->isGroup()) {
151             $noun = ActivityObject::fromGroup($this->localGroup());
152             return $noun->asString('activity:' . $element);
153         } else if ($this->isPeopletag()) {
154             $noun = ActivityObject::fromPeopletag($this->localPeopletag());
155             return $noun->asString('activity:' . $element);
156         } else {
157             $noun = ActivityObject::fromProfile($this->localProfile());
158             return $noun->asString('activity:' . $element);
159         }
160     }
161
162     /**
163      * @return boolean true if this is a remote group
164      */
165     function isGroup()
166     {
167         if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
168             return false;
169         } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
170             return true;
171         } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
172             // TRANS: Server exception. %s is a URI
173             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
174         } else {
175             // TRANS: Server exception. %s is a URI
176             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
177         }
178     }
179
180     /**
181      * @return boolean true if this is a remote peopletag
182      */
183     function isPeopletag()
184     {
185         if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
186             return false;
187         } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
188             return true;
189         } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
190             // TRANS: Server exception. %s is a URI
191             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
192         } else {
193             // TRANS: Server exception. %s is a URI
194             throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
195         }
196     }
197
198     /**
199      * Send a subscription request to the hub for this feed.
200      * The hub will later send us a confirmation POST to /main/push/callback.
201      *
202      * @return void
203      * @throws ServerException if feed state is not valid or subscription fails.
204      */
205     public function subscribe()
206     {
207         $feedsub = FeedSub::ensureFeed($this->feeduri);
208         if ($feedsub->sub_state == 'active') {
209             // Active subscription, we don't need to do anything.
210             return;
211         }
212
213         // Inactive or we got left in an inconsistent state.
214         // Run a subscription request to make sure we're current!
215         return $feedsub->subscribe();
216     }
217
218     /**
219      * Check if this remote profile has any active local subscriptions, and
220      * if not drop the PuSH subscription feed.
221      *
222      * @return boolean true if subscription is removed, false if there are still subscribers to the feed
223      * @throws Exception of various kinds on failure.
224      */
225     public function unsubscribe() {
226         return $this->garbageCollect();
227     }
228
229     /**
230      * Check if this remote profile has any active local subscriptions, and
231      * if not drop the PuSH subscription feed.
232      *
233      * @return boolean true if subscription is removed, false if there are still subscribers to the feed
234      * @throws Exception of various kinds on failure.
235      */
236     public function garbageCollect()
237     {
238         $feedsub = FeedSub::getKV('uri', $this->feeduri);
239         return $feedsub->garbageCollect();
240     }
241
242     /**
243      * Check if this remote profile has any active local subscriptions, so the
244      * PuSH subscription layer can decide if it can drop the feed.
245      *
246      * This gets called via the FeedSubSubscriberCount event when running
247      * FeedSub::garbageCollect().
248      *
249      * @return int
250      */
251     public function subscriberCount()
252     {
253         if ($this->isGroup()) {
254             $members = $this->localGroup()->getMembers(0, 1);
255             $count = $members->N;
256         } else if ($this->isPeopletag()) {
257             $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
258             $count = $subscribers->N;
259         } else {
260             $profile = $this->localProfile();
261             $count = $profile->subscriberCount();
262             if ($profile->hasLocalTags()) {
263                 $count = 1;
264             }
265         }
266         common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
267
268         // Other plugins may be piggybacking on OStatus without having
269         // an active group or user-to-user subscription we know about.
270         Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
271         common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
272
273         return $count;
274     }
275
276     /**
277      * Send an Activity Streams notification to the remote Salmon endpoint,
278      * if so configured.
279      *
280      * @param Profile $actor  Actor who did the activity
281      * @param string  $verb   Activity::SUBSCRIBE or Activity::JOIN
282      * @param Object  $object object of the action; must define asActivityNoun($tag)
283      */
284     public function notify($actor, $verb, $object=null, $target=null)
285     {
286         if (!($actor instanceof Profile)) {
287             $type = gettype($actor);
288             if ($type == 'object') {
289                 $type = get_class($actor);
290             }
291             // TRANS: Server exception.
292             // TRANS: %1$s is the method name the exception occured in, %2$s is the actor type.
293             throw new ServerException(sprintf(_m('Invalid actor passed to %1$s: %2$s.'),__METHOD__,$type));
294         }
295         if ($object == null) {
296             $object = $this;
297         }
298         if ($this->salmonuri) {
299             $text = 'update';
300             $id = TagURI::mint('%s:%s:%s',
301                                $verb,
302                                $actor->getURI(),
303                                common_date_iso8601(time()));
304
305             // @todo FIXME: Consolidate all these NS settings somewhere.
306             $attributes = array('xmlns' => Activity::ATOM,
307                                 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
308                                 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
309                                 'xmlns:georss' => 'http://www.georss.org/georss',
310                                 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
311                                 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
312                                 'xmlns:media' => 'http://purl.org/syndication/atommedia');
313
314             $entry = new XMLStringer();
315             $entry->elementStart('entry', $attributes);
316             $entry->element('id', null, $id);
317             $entry->element('title', null, $text);
318             $entry->element('summary', null, $text);
319             $entry->element('published', null, common_date_w3dtf(common_sql_now()));
320
321             $entry->element('activity:verb', null, $verb);
322             $entry->raw($actor->asAtomAuthor());
323             $entry->raw($actor->asActivityActor());
324             $entry->raw($object->asActivityNoun('object'));
325             if ($target != null) {
326                 $entry->raw($target->asActivityNoun('target'));
327             }
328             $entry->elementEnd('entry');
329
330             $xml = $entry->getString();
331             common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
332
333             $salmon = new Salmon(); // ?
334             return $salmon->post($this->salmonuri, $xml, $actor);
335         }
336         return false;
337     }
338
339     /**
340      * Send a Salmon notification ping immediately, and confirm that we got
341      * an acceptable response from the remote site.
342      *
343      * @param mixed $entry XML string, Notice, or Activity
344      * @param Profile $actor
345      * @return boolean success
346      */
347     public function notifyActivity($entry, Profile $actor)
348     {
349         if ($this->salmonuri) {
350             $salmon = new Salmon();
351             return $salmon->post($this->salmonuri, $this->notifyPrepXml($entry), $actor);
352         }
353         common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
354
355         return false;
356     }
357
358     /**
359      * Queue a Salmon notification for later. If queues are disabled we'll
360      * send immediately but won't get the return value.
361      *
362      * @param mixed $entry XML string, Notice, or Activity
363      * @return boolean success
364      */
365     public function notifyDeferred($entry, $actor)
366     {
367         if ($this->salmonuri) {
368             $data = array('salmonuri' => $this->salmonuri,
369                           'entry' => $this->notifyPrepXml($entry),
370                           'actor' => $actor->id);
371
372             $qm = QueueManager::get();
373             return $qm->enqueue($data, 'salmon');
374         }
375
376         return false;
377     }
378
379     protected function notifyPrepXml($entry)
380     {
381         $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
382         if (is_string($entry)) {
383             return $entry;
384         } else if ($entry instanceof Activity) {
385             return $preamble . $entry->asString(true);
386         } else if ($entry instanceof Notice) {
387             return $preamble . $entry->asAtomEntry(true, true);
388         } else {
389             // TRANS: Server exception.
390             throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
391         }
392     }
393
394     function getBestName()
395     {
396         if ($this->isGroup()) {
397             return $this->localGroup()->getBestName();
398         } else if ($this->isPeopletag()) {
399             return $this->localPeopletag()->getBestName();
400         } else {
401             return $this->localProfile()->getBestName();
402         }
403     }
404
405     /**
406      * Read and post notices for updates from the feed.
407      * Currently assumes that all items in the feed are new,
408      * coming from a PuSH hub.
409      *
410      * @param DOMDocument $doc
411      * @param string $source identifier ("push")
412      */
413     public function processFeed(DOMDocument $doc, $source)
414     {
415         $feed = $doc->documentElement;
416
417         if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
418             $this->processAtomFeed($feed, $source);
419         } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
420             $this->processRssFeed($feed, $source);
421         } else {
422             // TRANS: Exception.
423             throw new Exception(_m('Unknown feed format.'));
424         }
425     }
426
427     public function processAtomFeed(DOMElement $feed, $source)
428     {
429         $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
430         if ($entries->length == 0) {
431             common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
432             return;
433         }
434
435         for ($i = 0; $i < $entries->length; $i++) {
436             $entry = $entries->item($i);
437             $this->processEntry($entry, $feed, $source);
438         }
439     }
440
441     public function processRssFeed(DOMElement $rss, $source)
442     {
443         $channels = $rss->getElementsByTagName('channel');
444
445         if ($channels->length == 0) {
446             // TRANS: Exception.
447             throw new Exception(_m('RSS feed without a channel.'));
448         } else if ($channels->length > 1) {
449             common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
450         }
451
452         $channel = $channels->item(0);
453
454         $items = $channel->getElementsByTagName('item');
455
456         for ($i = 0; $i < $items->length; $i++) {
457             $item = $items->item($i);
458             $this->processEntry($item, $channel, $source);
459         }
460     }
461
462     /**
463      * Process a posted entry from this feed source.
464      *
465      * @param DOMElement $entry
466      * @param DOMElement $feed for context
467      * @param string $source identifier ("push" or "salmon")
468      *
469      * @return Notice Notice representing the new (or existing) activity
470      */
471     public function processEntry($entry, $feed, $source)
472     {
473         $activity = new Activity($entry, $feed);
474         return $this->processActivity($activity, $source);
475     }
476
477     // TODO: Make this throw an exception
478     public function processActivity($activity, $source)
479     {
480         $notice = null;
481
482         // The "WithProfile" events were added later.
483
484         if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this, &$notice)) &&
485             Event::handle('StartHandleFeedEntry', array($activity))) {
486
487             switch ($activity->verb) {
488             case ActivityVerb::POST:
489                 // @todo process all activity objects
490                 switch ($activity->objects[0]->type) {
491                 case ActivityObject::ARTICLE:
492                 case ActivityObject::BLOGENTRY:
493                 case ActivityObject::NOTE:
494                 case ActivityObject::STATUS:
495                 case ActivityObject::COMMENT:
496                 case null:
497                     $notice = $this->processPost($activity, $source);
498                     break;
499                 default:
500                     // TRANS: Client exception.
501                     throw new ClientException(_m('Cannot handle that kind of post.'));
502                 }
503                 break;
504             case ActivityVerb::SHARE:
505                 $notice = $this->processShare($activity, $source);
506                 break;
507             default:
508                 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
509             }
510
511             Event::handle('EndHandleFeedEntry', array($activity));
512             Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
513         }
514
515         return $notice;
516     }
517
518     public function processShare($activity, $method)
519     {
520         $notice = null;
521
522         $oprofile = $this->checkAuthorship($activity);
523
524         if (!$oprofile instanceof Ostatus_profile) {
525             common_log(LOG_INFO, "No author matched share activity");
526             return null;
527         }
528
529         // The id URI will be used as a unique identifier for the notice,
530         // protecting against duplicate saves. It isn't required to be a URL;
531         // tag: URIs for instance are found in Google Buzz feeds.
532         $dupe = Notice::getKV('uri', $activity->id);
533         if ($dupe instanceof Notice) {
534             common_log(LOG_INFO, "OStatus: ignoring duplicate post: {$activity->id}");
535             return $dupe;
536         }
537
538         if (count($activity->objects) != 1) {
539             // TRANS: Client exception thrown when trying to share multiple activities at once.
540             throw new ClientException(_m('Can only handle share activities with exactly one object.'));
541         }
542
543         $shared = $activity->objects[0];
544
545         if (!$shared instanceof Activity) {
546             // TRANS: Client exception thrown when trying to share a non-activity object.
547             throw new ClientException(_m('Can only handle shared activities.'));
548         }
549
550         $sharedId = $shared->id;
551         if (!empty($shared->objects[0]->id)) {
552             // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
553             // fucks up federation, because the URI is no longer recognised by the origin.
554             // So we set it to the object ID if it exists, otherwise we trust $shared->id
555             $sharedId = $shared->objects[0]->id;
556         }
557         if (empty($sharedId)) {
558             throw new ClientException(_m('Shared activity does not have an id'));
559         }
560
561         // First check if we have the shared activity. This has to be done first, because
562         // we can't use these functions to "ensureActivityObjectProfile" of a local user,
563         // who might be the creator of the shared activity in question.
564         $sharedNotice = Notice::getKV('uri', $sharedId);
565         if (!$sharedNotice instanceof Notice) {
566             // If no locally stored notice is found, process it!
567             // TODO: Remember to check Deleted_notice!
568             // TODO: If a post is shared that we can't retrieve - what to do?
569             try {
570                 $other = self::ensureActivityObjectProfile($shared->actor);
571                 $sharedNotice = $other->processActivity($shared, $method);
572                 if (!$sharedNotice instanceof Notice) {
573                     // And if we apparently can't get the shared notice, we'll abort the whole thing.
574                     // TRANS: Client exception thrown when saving an activity share fails.
575                     // TRANS: %s is a share ID.
576                     throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedId));
577                 }
578             } catch (FeedSubException $e) {
579                 // Remote feed could not be found or verified, should we
580                 // transform this into an "RT @user Blah, blah, blah..."?
581                 common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
582                 return null;
583             }
584         }
585
586         // We'll want to save a web link to the original notice, if provided.
587
588         $sourceUrl = null;
589         if ($activity->link) {
590             $sourceUrl = $activity->link;
591         } else if ($activity->link) {
592             $sourceUrl = $activity->link;
593         } else if (preg_match('!^https?://!', $activity->id)) {
594             $sourceUrl = $activity->id;
595         }
596
597         // Use summary as fallback for content
598
599         if (!empty($activity->content)) {
600             $sourceContent = $activity->content;
601         } else if (!empty($activity->summary)) {
602             $sourceContent = $activity->summary;
603         } else if (!empty($activity->title)) {
604             $sourceContent = $activity->title;
605         } else {
606             // @todo FIXME: Fetch from $sourceUrl?
607             // TRANS: Client exception. %s is a source URI.
608             throw new ClientException(sprintf(_m('No content for notice %s.'), $activity->id));
609         }
610
611         // Get (safe!) HTML and text versions of the content
612
613         $rendered = $this->purify($sourceContent);
614         $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
615
616         $shortened = common_shorten_links($content);
617
618         // If it's too long, try using the summary, and make the
619         // HTML an attachment.
620
621         $attachment = null;
622
623         if (Notice::contentTooLong($shortened)) {
624             $attachment = $this->saveHTMLFile($activity->title, $rendered);
625             $summary = html_entity_decode(strip_tags($activity->summary), ENT_QUOTES, 'UTF-8');
626             if (empty($summary)) {
627                 $summary = $content;
628             }
629             $shortSummary = common_shorten_links($summary);
630             if (Notice::contentTooLong($shortSummary)) {
631                 $url = common_shorten_url($sourceUrl);
632                 $shortSummary = substr($shortSummary,
633                                        0,
634                                        Notice::maxContent() - (mb_strlen($url) + 2));
635                 $content = $shortSummary . ' ' . $url;
636
637                 // We mark up the attachment link specially for the HTML output
638                 // so we can fold-out the full version inline.
639
640                 // @todo FIXME i18n: This tooltip will be saved with the site's default language
641                 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
642                 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
643                 $showMoreText = _m('Show more');
644                 $attachUrl = common_local_url('attachment',
645                                               array('attachment' => $attachment->id));
646                 $rendered = common_render_text($shortSummary) .
647                             '<a href="' . htmlspecialchars($attachUrl) .'"'.
648                             ' class="attachment more"' .
649                             ' title="'. htmlspecialchars($showMoreText) . '">' .
650                             '&#8230;' .
651                             '</a>';
652             }
653         }
654
655         $options = array('is_local' => Notice::REMOTE,
656                          'url' => $sourceUrl,
657                          'uri' => $activity->id,
658                          'rendered' => $rendered,
659                          'replies' => array(),
660                          'groups' => array(),
661                          'peopletags' => array(),
662                          'tags' => array(),
663                          'urls' => array(),
664                          'repeat_of' => $sharedNotice->id,
665                          'scope' => $sharedNotice->scope);
666
667         // Check for optional attributes...
668
669         if (!empty($activity->time)) {
670             $options['created'] = common_sql_date($activity->time);
671         }
672
673         if ($activity->context) {
674             // TODO: context->attention
675             list($options['groups'], $options['replies'])
676                 = $this->filterAttention($oprofile, $activity->context->attention);
677
678             // Maintain direct reply associations
679             // @todo FIXME: What about conversation ID?
680             if (!empty($activity->context->replyToID)) {
681                 $orig = Notice::getKV('uri',
682                                           $activity->context->replyToID);
683                 if ($orig instanceof Notice) {
684                     $options['reply_to'] = $orig->id;
685                 }
686             }
687
688             $location = $activity->context->location;
689             if ($location) {
690                 $options['lat'] = $location->lat;
691                 $options['lon'] = $location->lon;
692                 if ($location->location_id) {
693                     $options['location_ns'] = $location->location_ns;
694                     $options['location_id'] = $location->location_id;
695                 }
696             }
697         }
698
699         if ($this->isPeopletag()) {
700             $options['peopletags'][] = $this->localPeopletag();
701         }
702
703         // Atom categories <-> hashtags
704         foreach ($activity->categories as $cat) {
705             if ($cat->term) {
706                 $term = common_canonical_tag($cat->term);
707                 if ($term) {
708                     $options['tags'][] = $term;
709                 }
710             }
711         }
712
713         // Atom enclosures -> attachment URLs
714         foreach ($activity->enclosures as $href) {
715             // @todo FIXME: Save these locally or....?
716             $options['urls'][] = $href;
717         }
718
719         $notice = Notice::saveNew($oprofile->profile_id,
720                                   $content,
721                                   'ostatus',
722                                   $options);
723
724         return $notice;
725     }
726
727     /**
728      * Process an incoming post activity from this remote feed.
729      * @param Activity $activity
730      * @param string $method 'push' or 'salmon'
731      * @return mixed saved Notice or false
732      * @todo FIXME: Break up this function, it's getting nasty long
733      */
734     public function processPost($activity, $method)
735     {
736         $notice = null;
737
738         $oprofile = $this->checkAuthorship($activity);
739
740         if (!$oprofile instanceof Ostatus_profile) {
741             return null;
742         }
743
744         // It's not always an ActivityObject::NOTE, but... let's just say it is.
745
746         $note = $activity->objects[0];
747
748         // The id URI will be used as a unique identifier for the notice,
749         // protecting against duplicate saves. It isn't required to be a URL;
750         // tag: URIs for instance are found in Google Buzz feeds.
751         $sourceUri = $note->id;
752         $dupe = Notice::getKV('uri', $sourceUri);
753         if ($dupe instanceof Notice) {
754             common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
755             return $dupe;
756         }
757
758         // We'll also want to save a web link to the original notice, if provided.
759         $sourceUrl = null;
760         if ($note->link) {
761             $sourceUrl = $note->link;
762         } else if ($activity->link) {
763             $sourceUrl = $activity->link;
764         } else if (preg_match('!^https?://!', $note->id)) {
765             $sourceUrl = $note->id;
766         }
767
768         // Use summary as fallback for content
769
770         if (!empty($note->content)) {
771             $sourceContent = $note->content;
772         } else if (!empty($note->summary)) {
773             $sourceContent = $note->summary;
774         } else if (!empty($note->title)) {
775             $sourceContent = $note->title;
776         } else {
777             // @todo FIXME: Fetch from $sourceUrl?
778             // TRANS: Client exception. %s is a source URI.
779             throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
780         }
781
782         // Get (safe!) HTML and text versions of the content
783
784         $rendered = $this->purify($sourceContent);
785         $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
786
787         $shortened = common_shorten_links($content);
788
789         // If it's too long, try using the summary, and make the
790         // HTML an attachment.
791
792         $attachment = null;
793
794         if (Notice::contentTooLong($shortened)) {
795             $attachment = $this->saveHTMLFile($note->title, $rendered);
796             $summary = html_entity_decode(strip_tags($note->summary), ENT_QUOTES, 'UTF-8');
797             if (empty($summary)) {
798                 $summary = $content;
799             }
800             $shortSummary = common_shorten_links($summary);
801             if (Notice::contentTooLong($shortSummary)) {
802                 $url = common_shorten_url($sourceUrl);
803                 $shortSummary = substr($shortSummary,
804                                        0,
805                                        Notice::maxContent() - (mb_strlen($url) + 2));
806                 $content = $shortSummary . ' ' . $url;
807
808                 // We mark up the attachment link specially for the HTML output
809                 // so we can fold-out the full version inline.
810
811                 // @todo FIXME i18n: This tooltip will be saved with the site's default language
812                 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
813                 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
814                 $showMoreText = _m('Show more');
815                 $attachUrl = common_local_url('attachment',
816                                               array('attachment' => $attachment->id));
817                 $rendered = common_render_text($shortSummary) .
818                             '<a href="' . htmlspecialchars($attachUrl) .'"'.
819                             ' class="attachment more"' .
820                             ' title="'. htmlspecialchars($showMoreText) . '">' .
821                             '&#8230;' .
822                             '</a>';
823             }
824         }
825
826         $options = array('is_local' => Notice::REMOTE,
827                         'url' => $sourceUrl,
828                         'uri' => $sourceUri,
829                         'rendered' => $rendered,
830                         'replies' => array(),
831                         'groups' => array(),
832                         'peopletags' => array(),
833                         'tags' => array(),
834                         'urls' => array());
835
836         // Check for optional attributes...
837
838         if (!empty($activity->time)) {
839             $options['created'] = common_sql_date($activity->time);
840         }
841
842         if ($activity->context) {
843             // TODO: context->attention
844             list($options['groups'], $options['replies'])
845                 = $this->filterAttention($oprofile, $activity->context->attention);
846
847             // Maintain direct reply associations
848             // @todo FIXME: What about conversation ID?
849             if (!empty($activity->context->replyToID)) {
850                 $orig = Notice::getKV('uri', $activity->context->replyToID);
851                 if ($orig instanceof Notice) {
852                     $options['reply_to'] = $orig->id;
853                 }
854             }
855
856             $location = $activity->context->location;
857             if ($location) {
858                 $options['lat'] = $location->lat;
859                 $options['lon'] = $location->lon;
860                 if ($location->location_id) {
861                     $options['location_ns'] = $location->location_ns;
862                     $options['location_id'] = $location->location_id;
863                 }
864             }
865         }
866
867         if ($this->isPeopletag()) {
868             $options['peopletags'][] = $this->localPeopletag();
869         }
870
871         // Atom categories <-> hashtags
872         foreach ($activity->categories as $cat) {
873             if ($cat->term) {
874                 $term = common_canonical_tag($cat->term);
875                 if ($term) {
876                     $options['tags'][] = $term;
877                 }
878             }
879         }
880
881         // Atom enclosures -> attachment URLs
882         foreach ($activity->enclosures as $href) {
883             // @todo FIXME: Save these locally or....?
884             $options['urls'][] = $href;
885         }
886
887         try {
888             $saved = Notice::saveNew($oprofile->profile_id,
889                                      $content,
890                                      'ostatus',
891                                      $options);
892             if ($saved instanceof Notice) {
893                 Ostatus_source::saveNew($saved, $this, $method);
894                 if (!empty($attachment)) {
895                     File_to_post::processNew($attachment->id, $saved->id);
896                 }
897             }
898         } catch (Exception $e) {
899             common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
900             throw $e;
901         }
902         common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
903         return $saved;
904     }
905
906     /**
907      * Clean up HTML
908      */
909     protected function purify($html)
910     {
911         require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
912         $config = array('safe' => 1,
913                         'deny_attribute' => 'id,style,on*');
914         return htmLawed($html, $config);
915     }
916
917     /**
918      * Filters a list of recipient ID URIs to just those for local delivery.
919      * @param Ostatus_profile local profile of sender
920      * @param array in/out &$attention_uris set of URIs, will be pruned on output
921      * @return array of group IDs
922      */
923     protected function filterAttention($sender, array $attention)
924     {
925         common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
926         $groups = array();
927         $replies = array();
928         foreach ($attention as $recipient=>$type) {
929             // Is the recipient a local user?
930             $user = User::getKV('uri', $recipient);
931             if ($user instanceof User) {
932                 // @todo FIXME: Sender verification, spam etc?
933                 $replies[] = $recipient;
934                 continue;
935             }
936
937             // Is the recipient a local group?
938             // TODO: $group = User_group::getKV('uri', $recipient);
939             $id = OStatusPlugin::localGroupFromUrl($recipient);
940             if ($id) {
941                 $group = User_group::getKV('id', $id);
942                 if ($group instanceof User_group) {
943                     // Deliver to all members of this local group if allowed.
944                     $profile = $sender->localProfile();
945                     if ($profile->isMember($group)) {
946                         $groups[] = $group->id;
947                     } else {
948                         common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
949                     }
950                     continue;
951                 } else {
952                     common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
953                 }
954             }
955
956             // Is the recipient a remote user or group?
957             try {
958                 $oprofile = self::ensureProfileURI($recipient);
959                 if ($oprofile->isGroup()) {
960                     // Deliver to local members of this remote group.
961                     // @todo FIXME: Sender verification?
962                     $groups[] = $oprofile->group_id;
963                 } else {
964                     // may be canonicalized or something
965                     $replies[] = $oprofile->getUri();
966                 }
967                 continue;
968             } catch (Exception $e) {
969                 // Neither a recognizable local nor remote user!
970                 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
971             }
972
973         }
974         common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
975         common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
976         return array($groups, $replies);
977     }
978
979     /**
980      * Look up and if necessary create an Ostatus_profile for the remote entity
981      * with the given profile page URL. This should never return null -- you
982      * will either get an object or an exception will be thrown.
983      *
984      * @param string $profile_url
985      * @return Ostatus_profile
986      * @throws Exception on various error conditions
987      * @throws OStatusShadowException if this reference would obscure a local user/group
988      */
989     public static function ensureProfileURL($profile_url, $hints=array())
990     {
991         $oprofile = self::getFromProfileURL($profile_url);
992
993         if ($oprofile instanceof Ostatus_profile) {
994             return $oprofile;
995         }
996
997         $hints['profileurl'] = $profile_url;
998
999         // Fetch the URL
1000         // XXX: HTTP caching
1001
1002         $client = new HTTPClient();
1003         $client->setHeader('Accept', 'text/html,application/xhtml+xml');
1004         $response = $client->get($profile_url);
1005
1006         if (!$response->isOk()) {
1007             // TRANS: Exception. %s is a profile URL.
1008             throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
1009         }
1010
1011         // Check if we have a non-canonical URL
1012
1013         $finalUrl = $response->getUrl();
1014
1015         if ($finalUrl != $profile_url) {
1016
1017             $hints['profileurl'] = $finalUrl;
1018
1019             $oprofile = self::getFromProfileURL($finalUrl);
1020
1021             if ($oprofile instanceof Ostatus_profile) {
1022                 return $oprofile;
1023             }
1024         }
1025
1026         // Try to get some hCard data
1027
1028         $body = $response->getBody();
1029
1030         $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1031
1032         if (!empty($hcardHints)) {
1033             $hints = array_merge($hints, $hcardHints);
1034         }
1035
1036         // Check if they've got an LRDD header
1037
1038         $lrdd = LinkHeader::getLink($response, 'lrdd');
1039         try {
1040             $xrd = new XML_XRD();
1041             $xrd->loadFile($lrdd);
1042             $xrdHints = DiscoveryHints::fromXRD($xrd);
1043             $hints = array_merge($hints, $xrdHints);
1044         } catch (Exception $e) {
1045             // No hints available from XRD
1046         }
1047
1048         // If discovery found a feedurl (probably from LRDD), use it.
1049
1050         if (array_key_exists('feedurl', $hints)) {
1051             return self::ensureFeedURL($hints['feedurl'], $hints);
1052         }
1053
1054         // Get the feed URL from HTML
1055
1056         $discover = new FeedDiscovery();
1057
1058         $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1059
1060         if (!empty($feedurl)) {
1061             $hints['feedurl'] = $feedurl;
1062             return self::ensureFeedURL($feedurl, $hints);
1063         }
1064
1065         // TRANS: Exception. %s is a URL.
1066         throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1067     }
1068
1069     /**
1070      * Look up the Ostatus_profile, if present, for a remote entity with the
1071      * given profile page URL. Will return null for both unknown and invalid
1072      * remote profiles.
1073      *
1074      * @return mixed Ostatus_profile or null
1075      * @throws OStatusShadowException for local profiles
1076      */
1077     static function getFromProfileURL($profile_url)
1078     {
1079         $profile = Profile::getKV('profileurl', $profile_url);
1080         if (!$profile instanceof Profile) {
1081             return null;
1082         }
1083
1084         // Is it a known Ostatus profile?
1085         $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1086         if ($oprofile instanceof Ostatus_profile) {
1087             return $oprofile;
1088         }
1089
1090         // Is it a local user?
1091         $user = User::getKV('id', $profile->id);
1092         if ($user instanceof User) {
1093             // @todo i18n FIXME: use sprintf and add i18n (?)
1094             throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1095         }
1096
1097         // Continue discovery; it's a remote profile
1098         // for OMB or some other protocol, may also
1099         // support OStatus
1100
1101         return null;
1102     }
1103
1104     /**
1105      * Look up and if necessary create an Ostatus_profile for remote entity
1106      * with the given update feed. This should never return null -- you will
1107      * either get an object or an exception will be thrown.
1108      *
1109      * @return Ostatus_profile
1110      * @throws Exception
1111      */
1112     public static function ensureFeedURL($feed_url, $hints=array())
1113     {
1114         $discover = new FeedDiscovery();
1115
1116         $feeduri = $discover->discoverFromFeedURL($feed_url);
1117         $hints['feedurl'] = $feeduri;
1118
1119         $huburi = $discover->getHubLink();
1120         $hints['hub'] = $huburi;
1121
1122         // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1123         $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1124                         ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1125         $hints['salmon'] = $salmonuri;
1126
1127         if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1128             // We can only deal with folks with a PuSH hub
1129             throw new FeedSubNoHubException();
1130         }
1131
1132         $feedEl = $discover->root;
1133
1134         if ($feedEl->tagName == 'feed') {
1135             return self::ensureAtomFeed($feedEl, $hints);
1136         } else if ($feedEl->tagName == 'channel') {
1137             return self::ensureRssChannel($feedEl, $hints);
1138         } else {
1139             throw new FeedSubBadXmlException($feeduri);
1140         }
1141     }
1142
1143     /**
1144      * Look up and, if necessary, create an Ostatus_profile for the remote
1145      * profile with the given Atom feed - actually loaded from the feed.
1146      * This should never return null -- you will either get an object or
1147      * an exception will be thrown.
1148      *
1149      * @param DOMElement $feedEl root element of a loaded Atom feed
1150      * @param array $hints additional discovery information passed from higher levels
1151      * @todo FIXME: Should this be marked public?
1152      * @return Ostatus_profile
1153      * @throws Exception
1154      */
1155     public static function ensureAtomFeed($feedEl, $hints)
1156     {
1157         $author = ActivityUtils::getFeedAuthor($feedEl);
1158
1159         if (empty($author)) {
1160             // XXX: make some educated guesses here
1161             // TRANS: Feed sub exception.
1162             throw new FeedSubException(_m('Cannot find enough profile '.
1163                                           'information to make a feed.'));
1164         }
1165
1166         return self::ensureActivityObjectProfile($author, $hints);
1167     }
1168
1169     /**
1170      * Look up and, if necessary, create an Ostatus_profile for the remote
1171      * profile with the given RSS feed - actually loaded from the feed.
1172      * This should never return null -- you will either get an object or
1173      * an exception will be thrown.
1174      *
1175      * @param DOMElement $feedEl root element of a loaded RSS feed
1176      * @param array $hints additional discovery information passed from higher levels
1177      * @todo FIXME: Should this be marked public?
1178      * @return Ostatus_profile
1179      * @throws Exception
1180      */
1181     public static function ensureRssChannel($feedEl, $hints)
1182     {
1183         // Special-case for Posterous. They have some nice metadata in their
1184         // posterous:author elements. We should use them instead of the channel.
1185
1186         $items = $feedEl->getElementsByTagName('item');
1187
1188         if ($items->length > 0) {
1189             $item = $items->item(0);
1190             $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1191             if (!empty($authorEl)) {
1192                 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1193                 // Posterous has multiple authors per feed, and multiple feeds
1194                 // per author. We check if this is the "main" feed for this author.
1195                 if (array_key_exists('profileurl', $hints) &&
1196                     !empty($obj->poco) &&
1197                     common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1198                     return self::ensureActivityObjectProfile($obj, $hints);
1199                 }
1200             }
1201         }
1202
1203         // @todo FIXME: We should check whether this feed has elements
1204         // with different <author> or <dc:creator> elements, and... I dunno.
1205         // Do something about that.
1206
1207         $obj = ActivityObject::fromRssChannel($feedEl);
1208
1209         return self::ensureActivityObjectProfile($obj, $hints);
1210     }
1211
1212     /**
1213      * Download and update given avatar image
1214      *
1215      * @param string $url
1216      * @throws Exception in various failure cases
1217      */
1218     protected function updateAvatar($url)
1219     {
1220         if ($url == $this->avatar) {
1221             // We've already got this one.
1222             return;
1223         }
1224         if (!common_valid_http_url($url)) {
1225             // TRANS: Server exception. %s is a URL.
1226             throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1227         }
1228
1229         if ($this->isGroup()) {
1230             $self = $this->localGroup();
1231         } else {
1232             $self = $this->localProfile();
1233         }
1234         if (!$self) {
1235             throw new ServerException(sprintf(
1236                 // TRANS: Server exception. %s is a URI.
1237                 _m('Tried to update avatar for unsaved remote profile %s.'),
1238                 $this->getUri()));
1239         }
1240
1241         // @todo FIXME: This should be better encapsulated
1242         // ripped from oauthstore.php (for old OMB client)
1243         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1244         try {
1245             if (!copy($url, $temp_filename)) {
1246                 // TRANS: Server exception. %s is a URL.
1247                 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1248             }
1249
1250             if ($this->isGroup()) {
1251                 $id = $this->group_id;
1252             } else {
1253                 $id = $this->profile_id;
1254             }
1255             // @todo FIXME: Should we be using different ids?
1256             $imagefile = new ImageFile($id, $temp_filename);
1257             $filename = Avatar::filename($id,
1258                                          image_type_to_extension($imagefile->type),
1259                                          null,
1260                                          common_timestamp());
1261             rename($temp_filename, Avatar::path($filename));
1262         } catch (Exception $e) {
1263             unlink($temp_filename);
1264             throw $e;
1265         }
1266         // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1267         // keep from accidentally saving images from command-line (queues)
1268         // that can't be read from web server, which causes hard-to-notice
1269         // problems later on:
1270         //
1271         // http://status.net/open-source/issues/2663
1272         chmod(Avatar::path($filename), 0644);
1273
1274         $self->setOriginal($filename);
1275
1276         $orig = clone($this);
1277         $this->avatar = $url;
1278         $this->update($orig);
1279     }
1280
1281     /**
1282      * Pull avatar URL from ActivityObject or profile hints
1283      *
1284      * @param ActivityObject $object
1285      * @param array $hints
1286      * @return mixed URL string or false
1287      */
1288     public static function getActivityObjectAvatar($object, $hints=array())
1289     {
1290         if ($object->avatarLinks) {
1291             $best = false;
1292             // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1293             foreach ($object->avatarLinks as $avatar) {
1294                 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1295                     // Exact match!
1296                     $best = $avatar;
1297                     break;
1298                 }
1299                 if (!$best || $avatar->width > $best->width) {
1300                     $best = $avatar;
1301                 }
1302             }
1303             return $best->url;
1304         } else if (array_key_exists('avatar', $hints)) {
1305             return $hints['avatar'];
1306         }
1307         return false;
1308     }
1309
1310     /**
1311      * Get an appropriate avatar image source URL, if available.
1312      *
1313      * @param ActivityObject $actor
1314      * @param DOMElement $feed
1315      * @return string
1316      */
1317     protected static function getAvatar($actor, $feed)
1318     {
1319         $url = '';
1320         $icon = '';
1321         if ($actor->avatar) {
1322             $url = trim($actor->avatar);
1323         }
1324         if (!$url) {
1325             // Check <atom:logo> and <atom:icon> on the feed
1326             $els = $feed->childNodes();
1327             if ($els && $els->length) {
1328                 for ($i = 0; $i < $els->length; $i++) {
1329                     $el = $els->item($i);
1330                     if ($el->namespaceURI == Activity::ATOM) {
1331                         if (empty($url) && $el->localName == 'logo') {
1332                             $url = trim($el->textContent);
1333                             break;
1334                         }
1335                         if (empty($icon) && $el->localName == 'icon') {
1336                             // Use as a fallback
1337                             $icon = trim($el->textContent);
1338                         }
1339                     }
1340                 }
1341             }
1342             if ($icon && !$url) {
1343                 $url = $icon;
1344             }
1345         }
1346         if ($url) {
1347             $opts = array('allowed_schemes' => array('http', 'https'));
1348             if (common_valid_http_url($url)) {
1349                 return $url;
1350             }
1351         }
1352
1353         return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1354     }
1355
1356     /**
1357      * Fetch, or build if necessary, an Ostatus_profile for the actor
1358      * in a given Activity Streams activity.
1359      * This should never return null -- you will either get an object or
1360      * an exception will be thrown.
1361      *
1362      * @param Activity $activity
1363      * @param string $feeduri if we already know the canonical feed URI!
1364      * @param string $salmonuri if we already know the salmon return channel URI
1365      * @return Ostatus_profile
1366      * @throws Exception
1367      */
1368     public static function ensureActorProfile($activity, $hints=array())
1369     {
1370         return self::ensureActivityObjectProfile($activity->actor, $hints);
1371     }
1372
1373     /**
1374      * Fetch, or build if necessary, an Ostatus_profile for the profile
1375      * in a given Activity Streams object (can be subject, actor, or object).
1376      * This should never return null -- you will either get an object or
1377      * an exception will be thrown.
1378      *
1379      * @param ActivityObject $object
1380      * @param array $hints additional discovery information passed from higher levels
1381      * @return Ostatus_profile
1382      * @throws Exception
1383      */
1384     public static function ensureActivityObjectProfile($object, $hints=array())
1385     {
1386         $profile = self::getActivityObjectProfile($object);
1387         if ($profile) {
1388             $profile->updateFromActivityObject($object, $hints);
1389         } else {
1390             $profile = self::createActivityObjectProfile($object, $hints);
1391         }
1392         return $profile;
1393     }
1394
1395     /**
1396      * @param Activity $activity
1397      * @return mixed matching Ostatus_profile or false if none known
1398      * @throws ServerException if feed info invalid
1399      */
1400     public static function getActorProfile($activity)
1401     {
1402         return self::getActivityObjectProfile($activity->actor);
1403     }
1404
1405     /**
1406      * @param ActivityObject $activity
1407      * @return mixed matching Ostatus_profile or false if none known
1408      * @throws ServerException if feed info invalid
1409      */
1410     protected static function getActivityObjectProfile($object)
1411     {
1412         $uri = self::getActivityObjectProfileURI($object);
1413         return Ostatus_profile::getKV('uri', $uri);
1414     }
1415
1416     /**
1417      * Get the identifier URI for the remote entity described
1418      * by this ActivityObject. This URI is *not* guaranteed to be
1419      * a resolvable HTTP/HTTPS URL.
1420      *
1421      * @param ActivityObject $object
1422      * @return string
1423      * @throws ServerException if feed info invalid
1424      */
1425     protected static function getActivityObjectProfileURI($object)
1426     {
1427         if ($object->id) {
1428             if (ActivityUtils::validateUri($object->id)) {
1429                 return $object->id;
1430             }
1431         }
1432
1433         // If the id is missing or invalid (we've seen feeds mistakenly listing
1434         // things like local usernames in that field) then we'll use the profile
1435         // page link, if valid.
1436         if ($object->link && common_valid_http_url($object->link)) {
1437             return $object->link;
1438         }
1439         // TRANS: Server exception.
1440         throw new ServerException(_m('No author ID URI found.'));
1441     }
1442
1443     /**
1444      * @todo FIXME: Validate stuff somewhere.
1445      */
1446
1447     /**
1448      * Create local ostatus_profile and profile/user_group entries for
1449      * the provided remote user or group.
1450      * This should never return null -- you will either get an object or
1451      * an exception will be thrown.
1452      *
1453      * @param ActivityObject $object
1454      * @param array $hints
1455      *
1456      * @return Ostatus_profile
1457      */
1458     protected static function createActivityObjectProfile($object, $hints=array())
1459     {
1460         $homeuri = $object->id;
1461         $discover = false;
1462
1463         if (!$homeuri) {
1464             common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1465             // TRANS: Exception.
1466             throw new Exception(_m('No profile URI.'));
1467         }
1468
1469         $user = User::getKV('uri', $homeuri);
1470         if ($user instanceof User) {
1471             // TRANS: Exception.
1472             throw new Exception(_m('Local user cannot be referenced as remote.'));
1473         }
1474
1475         if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1476             // TRANS: Exception.
1477             throw new Exception(_m('Local group cannot be referenced as remote.'));
1478         }
1479
1480         $ptag = Profile_list::getKV('uri', $homeuri);
1481         if ($ptag instanceof Profile_list) {
1482             $local_user = User::getKV('id', $ptag->tagger);
1483             if ($local_user instanceof User) {
1484                 // TRANS: Exception.
1485                 throw new Exception(_m('Local list cannot be referenced as remote.'));
1486             }
1487         }
1488
1489         if (array_key_exists('feedurl', $hints)) {
1490             $feeduri = $hints['feedurl'];
1491         } else {
1492             $discover = new FeedDiscovery();
1493             $feeduri = $discover->discoverFromURL($homeuri);
1494         }
1495
1496         if (array_key_exists('salmon', $hints)) {
1497             $salmonuri = $hints['salmon'];
1498         } else {
1499             if (!$discover) {
1500                 $discover = new FeedDiscovery();
1501                 $discover->discoverFromFeedURL($hints['feedurl']);
1502             }
1503             // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1504             $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1505                             ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1506         }
1507
1508         if (array_key_exists('hub', $hints)) {
1509             $huburi = $hints['hub'];
1510         } else {
1511             if (!$discover) {
1512                 $discover = new FeedDiscovery();
1513                 $discover->discoverFromFeedURL($hints['feedurl']);
1514             }
1515             $huburi = $discover->getHubLink();
1516         }
1517
1518         if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1519             // We can only deal with folks with a PuSH hub
1520             throw new FeedSubNoHubException();
1521         }
1522
1523         $oprofile = new Ostatus_profile();
1524
1525         $oprofile->uri        = $homeuri;
1526         $oprofile->feeduri    = $feeduri;
1527         $oprofile->salmonuri  = $salmonuri;
1528
1529         $oprofile->created    = common_sql_now();
1530         $oprofile->modified   = common_sql_now();
1531
1532         if ($object->type == ActivityObject::PERSON) {
1533             $profile = new Profile();
1534             $profile->created = common_sql_now();
1535             self::updateProfile($profile, $object, $hints);
1536
1537             $oprofile->profile_id = $profile->insert();
1538             if ($oprofile->profile_id === false) {
1539                 // TRANS: Server exception.
1540                 throw new ServerException(_m('Cannot save local profile.'));
1541             }
1542         } else if ($object->type == ActivityObject::GROUP) {
1543             $profile = new Profile();
1544             $profile->query('BEGIN');
1545
1546             $group = new User_group();
1547             $group->uri = $homeuri;
1548             $group->created = common_sql_now();
1549             self::updateGroup($group, $object, $hints);
1550
1551             // TODO: We should do this directly in User_group->insert()!
1552             // currently it's duplicated in User_group->update()
1553             // AND User_group->register()!!!
1554             $fields = array(/*group field => profile field*/
1555                         'nickname'      => 'nickname',
1556                         'fullname'      => 'fullname',
1557                         'mainpage'      => 'profileurl',
1558                         'homepage'      => 'homepage',
1559                         'description'   => 'bio',
1560                         'location'      => 'location',
1561                         'created'       => 'created',
1562                         'modified'      => 'modified',
1563                         );
1564             foreach ($fields as $gf=>$pf) {
1565                 $profile->$pf = $group->$gf;
1566             }
1567             $profile_id = $profile->insert();
1568             if ($profile_id === false) {
1569                 $profile->query('ROLLBACK');
1570                 throw new ServerException(_('Profile insertion failed.'));
1571             }
1572
1573             $group->profile_id = $profile_id;
1574
1575             $oprofile->group_id = $group->insert();
1576             if ($oprofile->group_id === false) {
1577                 $profile->query('ROLLBACK');
1578                 // TRANS: Server exception.
1579                 throw new ServerException(_m('Cannot save local profile.'));
1580             }
1581
1582             $profile->query('COMMIT');
1583         } else if ($object->type == ActivityObject::_LIST) {
1584             $ptag = new Profile_list();
1585             $ptag->uri = $homeuri;
1586             $ptag->created = common_sql_now();
1587             self::updatePeopletag($ptag, $object, $hints);
1588
1589             $oprofile->peopletag_id = $ptag->insert();
1590             if ($oprofile->peopletag_id === false) {
1591                 // TRANS: Server exception.
1592                 throw new ServerException(_m('Cannot save local list.'));
1593             }
1594         }
1595
1596         $ok = $oprofile->insert();
1597
1598         if ($ok === false) {
1599             // TRANS: Server exception.
1600             throw new ServerException(_m('Cannot save OStatus profile.'));
1601         }
1602
1603         $avatar = self::getActivityObjectAvatar($object, $hints);
1604
1605         if ($avatar) {
1606             try {
1607                 $oprofile->updateAvatar($avatar);
1608             } catch (Exception $ex) {
1609                 // Profile is saved, but Avatar is messed up. We're
1610                 // just going to continue.
1611                 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1612             }
1613         }
1614
1615         return $oprofile;
1616     }
1617
1618     /**
1619      * Save any updated profile information to our local copy.
1620      * @param ActivityObject $object
1621      * @param array $hints
1622      */
1623     public function updateFromActivityObject($object, $hints=array())
1624     {
1625         if ($this->isGroup()) {
1626             $group = $this->localGroup();
1627             self::updateGroup($group, $object, $hints);
1628         } else if ($this->isPeopletag()) {
1629             $ptag = $this->localPeopletag();
1630             self::updatePeopletag($ptag, $object, $hints);
1631         } else {
1632             $profile = $this->localProfile();
1633             self::updateProfile($profile, $object, $hints);
1634         }
1635
1636         $avatar = self::getActivityObjectAvatar($object, $hints);
1637         if ($avatar && !isset($ptag)) {
1638             try {
1639                 $this->updateAvatar($avatar);
1640             } catch (Exception $ex) {
1641                 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1642             }
1643         }
1644     }
1645
1646     public static function updateProfile($profile, $object, $hints=array())
1647     {
1648         $orig = clone($profile);
1649
1650         // Existing nickname is better than nothing.
1651
1652         if (!array_key_exists('nickname', $hints)) {
1653             $hints['nickname'] = $profile->nickname;
1654         }
1655
1656         $nickname = self::getActivityObjectNickname($object, $hints);
1657
1658         if (!empty($nickname)) {
1659             $profile->nickname = $nickname;
1660         }
1661
1662         if (!empty($object->title)) {
1663             $profile->fullname = $object->title;
1664         } else if (array_key_exists('fullname', $hints)) {
1665             $profile->fullname = $hints['fullname'];
1666         }
1667
1668         if (!empty($object->link)) {
1669             $profile->profileurl = $object->link;
1670         } else if (array_key_exists('profileurl', $hints)) {
1671             $profile->profileurl = $hints['profileurl'];
1672         } else if (common_valid_http_url($object->id)) {
1673             $profile->profileurl = $object->id;
1674         }
1675
1676         $bio = self::getActivityObjectBio($object, $hints);
1677
1678         if (!empty($bio)) {
1679             $profile->bio = $bio;
1680         }
1681
1682         $location = self::getActivityObjectLocation($object, $hints);
1683
1684         if (!empty($location)) {
1685             $profile->location = $location;
1686         }
1687
1688         $homepage = self::getActivityObjectHomepage($object, $hints);
1689
1690         if (!empty($homepage)) {
1691             $profile->homepage = $homepage;
1692         }
1693
1694         if (!empty($object->geopoint)) {
1695             $location = ActivityContext::locationFromPoint($object->geopoint);
1696             if (!empty($location)) {
1697                 $profile->lat = $location->lat;
1698                 $profile->lon = $location->lon;
1699             }
1700         }
1701
1702         // @todo FIXME: tags/categories
1703         // @todo tags from categories
1704
1705         if ($profile->id) {
1706             common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1707             $profile->update($orig);
1708         }
1709     }
1710
1711     protected static function updateGroup(User_group $group, $object, $hints=array())
1712     {
1713         $orig = clone($group);
1714
1715         $group->nickname = self::getActivityObjectNickname($object, $hints);
1716         $group->fullname = $object->title;
1717
1718         if (!empty($object->link)) {
1719             $group->mainpage = $object->link;
1720         } else if (array_key_exists('profileurl', $hints)) {
1721             $group->mainpage = $hints['profileurl'];
1722         }
1723
1724         // @todo tags from categories
1725         $group->description = self::getActivityObjectBio($object, $hints);
1726         $group->location = self::getActivityObjectLocation($object, $hints);
1727         $group->homepage = self::getActivityObjectHomepage($object, $hints);
1728
1729         if ($group->id) {   // If no id, we haven't called insert() yet, so don't run update()
1730             common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1731             $group->update($orig);
1732         }
1733     }
1734
1735     protected static function updatePeopletag($tag, $object, $hints=array()) {
1736         $orig = clone($tag);
1737
1738         $tag->tag = $object->title;
1739
1740         if (!empty($object->link)) {
1741             $tag->mainpage = $object->link;
1742         } else if (array_key_exists('profileurl', $hints)) {
1743             $tag->mainpage = $hints['profileurl'];
1744         }
1745
1746         $tag->description = $object->summary;
1747         $tagger = self::ensureActivityObjectProfile($object->owner);
1748         $tag->tagger = $tagger->profile_id;
1749
1750         if ($tag->id) {
1751             common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1752             $tag->update($orig);
1753         }
1754     }
1755
1756     protected static function getActivityObjectHomepage($object, $hints=array())
1757     {
1758         $homepage = null;
1759         $poco     = $object->poco;
1760
1761         if (!empty($poco)) {
1762             $url = $poco->getPrimaryURL();
1763             if ($url && $url->type == 'homepage') {
1764                 $homepage = $url->value;
1765             }
1766         }
1767
1768         // @todo Try for a another PoCo URL?
1769
1770         return $homepage;
1771     }
1772
1773     protected static function getActivityObjectLocation($object, $hints=array())
1774     {
1775         $location = null;
1776
1777         if (!empty($object->poco) &&
1778             isset($object->poco->address->formatted)) {
1779             $location = $object->poco->address->formatted;
1780         } else if (array_key_exists('location', $hints)) {
1781             $location = $hints['location'];
1782         }
1783
1784         if (!empty($location)) {
1785             if (mb_strlen($location) > 255) {
1786                 $location = mb_substr($note, 0, 255 - 3) . ' â€¦ ';
1787             }
1788         }
1789
1790         // @todo Try to find location some othe way? Via goerss point?
1791
1792         return $location;
1793     }
1794
1795     protected static function getActivityObjectBio($object, $hints=array())
1796     {
1797         $bio  = null;
1798
1799         if (!empty($object->poco)) {
1800             $note = $object->poco->note;
1801         } else if (array_key_exists('bio', $hints)) {
1802             $note = $hints['bio'];
1803         }
1804
1805         if (!empty($note)) {
1806             if (Profile::bioTooLong($note)) {
1807                 // XXX: truncate ok?
1808                 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' â€¦ ';
1809             } else {
1810                 $bio = $note;
1811             }
1812         }
1813
1814         // @todo Try to get bio info some other way?
1815
1816         return $bio;
1817     }
1818
1819     public static function getActivityObjectNickname($object, $hints=array())
1820     {
1821         if ($object->poco) {
1822             if (!empty($object->poco->preferredUsername)) {
1823                 return common_nicknamize($object->poco->preferredUsername);
1824             }
1825         }
1826
1827         if (!empty($object->nickname)) {
1828             return common_nicknamize($object->nickname);
1829         }
1830
1831         if (array_key_exists('nickname', $hints)) {
1832             return $hints['nickname'];
1833         }
1834
1835         // Try the profile url (like foo.example.com or example.com/user/foo)
1836         if (!empty($object->link)) {
1837             $profileUrl = $object->link;
1838         } else if (!empty($hints['profileurl'])) {
1839             $profileUrl = $hints['profileurl'];
1840         }
1841
1842         if (!empty($profileUrl)) {
1843             $nickname = self::nicknameFromURI($profileUrl);
1844         }
1845
1846         // Try the URI (may be a tag:, http:, acct:, ...
1847
1848         if (empty($nickname)) {
1849             $nickname = self::nicknameFromURI($object->id);
1850         }
1851
1852         // Try a Webfinger if one was passed (way) down
1853
1854         if (empty($nickname)) {
1855             if (array_key_exists('webfinger', $hints)) {
1856                 $nickname = self::nicknameFromURI($hints['webfinger']);
1857             }
1858         }
1859
1860         // Try the name
1861
1862         if (empty($nickname)) {
1863             $nickname = common_nicknamize($object->title);
1864         }
1865
1866         return $nickname;
1867     }
1868
1869     protected static function nicknameFromURI($uri)
1870     {
1871         if (preg_match('/(\w+):/', $uri, $matches)) {
1872             $protocol = $matches[1];
1873         } else {
1874             return null;
1875         }
1876
1877         switch ($protocol) {
1878         case 'acct':
1879         case 'mailto':
1880             if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1881                 return common_canonical_nickname($matches[1]);
1882             }
1883             return null;
1884         case 'http':
1885             return common_url_to_nickname($uri);
1886             break;
1887         default:
1888             return null;
1889         }
1890     }
1891
1892     /**
1893      * Look up, and if necessary create, an Ostatus_profile for the remote
1894      * entity with the given webfinger address.
1895      * This should never return null -- you will either get an object or
1896      * an exception will be thrown.
1897      *
1898      * @param string $addr webfinger address
1899      * @return Ostatus_profile
1900      * @throws Exception on error conditions
1901      * @throws OStatusShadowException if this reference would obscure a local user/group
1902      */
1903     public static function ensureWebfinger($addr)
1904     {
1905         // First, try the cache
1906
1907         $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1908
1909         if ($uri !== false) {
1910             if (is_null($uri)) {
1911                 // Negative cache entry
1912                 // TRANS: Exception.
1913                 throw new Exception(_m('Not a valid webfinger address.'));
1914             }
1915             $oprofile = Ostatus_profile::getKV('uri', $uri);
1916             if ($oprofile instanceof Ostatus_profile) {
1917                 return $oprofile;
1918             }
1919         }
1920
1921         // Try looking it up
1922         $oprofile = Ostatus_profile::getKV('uri', 'acct:'.$addr);
1923
1924         if ($oprofile instanceof Ostatus_profile) {
1925             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1926             return $oprofile;
1927         }
1928
1929         // Now, try some discovery
1930
1931         $disco = new Discovery();
1932
1933         try {
1934             $xrd = $disco->lookup($addr);
1935         } catch (Exception $e) {
1936             // Save negative cache entry so we don't waste time looking it up again.
1937             // @todo FIXME: Distinguish temporary failures?
1938             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1939             // TRANS: Exception.
1940             throw new Exception(_m('Not a valid webfinger address.'));
1941         }
1942
1943         $hints = array('webfinger' => $addr);
1944
1945         $dhints = DiscoveryHints::fromXRD($xrd);
1946
1947         $hints = array_merge($hints, $dhints);
1948
1949         // If there's an Hcard, let's grab its info
1950         if (array_key_exists('hcard', $hints)) {
1951             if (!array_key_exists('profileurl', $hints) ||
1952                 $hints['hcard'] != $hints['profileurl']) {
1953                 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1954                 $hints = array_merge($hcardHints, $hints);
1955             }
1956         }
1957
1958         // If we got a feed URL, try that
1959         if (array_key_exists('feedurl', $hints)) {
1960             try {
1961                 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1962                 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1963                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1964                 return $oprofile;
1965             } catch (Exception $e) {
1966                 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1967                 // keep looking
1968             }
1969         }
1970
1971         // If we got a profile page, try that!
1972         if (array_key_exists('profileurl', $hints)) {
1973             try {
1974                 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1975                 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1976                 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1977                 return $oprofile;
1978             } catch (OStatusShadowException $e) {
1979                 // We've ended up with a remote reference to a local user or group.
1980                 // @todo FIXME: Ideally we should be able to say who it was so we can
1981                 // go back and refer to it the regular way
1982                 throw $e;
1983             } catch (Exception $e) {
1984                 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1985                 // keep looking
1986                 //
1987                 // @todo FIXME: This means an error discovering from profile page
1988                 // may give us a corrupt entry using the webfinger URI, which
1989                 // will obscure the correct page-keyed profile later on.
1990             }
1991         }
1992
1993         // XXX: try hcard
1994         // XXX: try FOAF
1995
1996         if (array_key_exists('salmon', $hints)) {
1997             $salmonEndpoint = $hints['salmon'];
1998
1999             // An account URL, a salmon endpoint, and a dream? Not much to go
2000             // on, but let's give it a try
2001
2002             $uri = 'acct:'.$addr;
2003
2004             $profile = new Profile();
2005
2006             $profile->nickname = self::nicknameFromUri($uri);
2007             $profile->created  = common_sql_now();
2008
2009             if (isset($profileUrl)) {
2010                 $profile->profileurl = $profileUrl;
2011             }
2012
2013             $profile_id = $profile->insert();
2014
2015             if ($profile_id === false) {
2016                 common_log_db_error($profile, 'INSERT', __FILE__);
2017                 // TRANS: Exception. %s is a webfinger address.
2018                 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2019             }
2020
2021             $oprofile = new Ostatus_profile();
2022
2023             $oprofile->uri        = $uri;
2024             $oprofile->salmonuri  = $salmonEndpoint;
2025             $oprofile->profile_id = $profile_id;
2026             $oprofile->created    = common_sql_now();
2027
2028             if (isset($feedUrl)) {
2029                 $profile->feeduri = $feedUrl;
2030             }
2031
2032             $result = $oprofile->insert();
2033
2034             if ($result === false) {
2035                 common_log_db_error($oprofile, 'INSERT', __FILE__);
2036                 // TRANS: Exception. %s is a webfinger address.
2037                 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2038             }
2039
2040             self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
2041             return $oprofile;
2042         }
2043
2044         // TRANS: Exception. %s is a webfinger address.
2045         throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2046     }
2047
2048     /**
2049      * Store the full-length scrubbed HTML of a remote notice to an attachment
2050      * file on our server. We'll link to this at the end of the cropped version.
2051      *
2052      * @param string $title plaintext for HTML page's title
2053      * @param string $rendered HTML fragment for HTML page's body
2054      * @return File
2055      */
2056     function saveHTMLFile($title, $rendered)
2057     {
2058         $final = sprintf("<!DOCTYPE html>\n" .
2059                          '<html><head>' .
2060                          '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2061                          '<title>%s</title>' .
2062                          '</head>' .
2063                          '<body>%s</body></html>',
2064                          htmlspecialchars($title),
2065                          $rendered);
2066
2067         $filename = File::filename($this->localProfile(),
2068                                    'ostatus', // ignored?
2069                                    'text/html');
2070
2071         $filepath = File::path($filename);
2072
2073         file_put_contents($filepath, $final);
2074
2075         $file = new File;
2076
2077         $file->filename = $filename;
2078         $file->url      = File::url($filename);
2079         $file->size     = filesize($filepath);
2080         $file->date     = time();
2081         $file->mimetype = 'text/html';
2082
2083         $file_id = $file->insert();
2084
2085         if ($file_id === false) {
2086             common_log_db_error($file, "INSERT", __FILE__);
2087             // TRANS: Server exception.
2088             throw new ServerException(_m('Could not store HTML content of long post as file.'));
2089         }
2090
2091         return $file;
2092     }
2093
2094     static function ensureProfileURI($uri)
2095     {
2096         $oprofile = null;
2097
2098         // First, try to query it
2099
2100         $oprofile = Ostatus_profile::getKV('uri', $uri);
2101
2102         if ($oprofile instanceof Ostatus_profile) {
2103             return $oprofile;
2104         }
2105
2106         // If unfound, do discovery stuff
2107         if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2108             $protocol = $match[1];
2109             switch ($protocol) {
2110             case 'http':
2111             case 'https':
2112                 $oprofile = self::ensureProfileURL($uri);
2113                 break;
2114             case 'acct':
2115             case 'mailto':
2116                 $rest = $match[2];
2117                 $oprofile = self::ensureWebfinger($rest);
2118                 break;
2119             default:
2120                 // TRANS: Server exception.
2121                 // TRANS: %1$s is a protocol, %2$s is a URI.
2122                 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2123                                                   $protocol,
2124                                                   $uri));
2125                 break;
2126             }
2127         } else {
2128             // TRANS: Server exception. %s is a URI.
2129             throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2130         }
2131
2132         return $oprofile;
2133     }
2134
2135     function checkAuthorship($activity)
2136     {
2137         if ($this->isGroup() || $this->isPeopletag()) {
2138             // A group or propletag feed will contain posts from multiple authors.
2139             $oprofile = self::ensureActorProfile($activity);
2140             if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2141                 // Groups can't post notices in StatusNet.
2142                 common_log(LOG_WARNING,
2143                     "OStatus: skipping post with group listed ".
2144                     "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
2145                 return false;
2146             }
2147         } else {
2148             $actor = $activity->actor;
2149
2150             if (empty($actor)) {
2151                 // OK here! assume the default
2152             } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
2153                 $this->updateFromActivityObject($actor);
2154             } else if ($actor->id) {
2155                 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2156                 // This isn't what we expect from mainline OStatus person feeds!
2157                 // Group feeds go down another path, with different validation...
2158                 // Most likely this is a plain ol' blog feed of some kind which
2159                 // doesn't match our expectations. We'll take the entry, but ignore
2160                 // the <author> info.
2161                 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
2162             } else {
2163                 // Plain <author> without ActivityStreams actor info.
2164                 // We'll just ignore this info for now and save the update under the feed's identity.
2165             }
2166
2167             $oprofile = $this;
2168         }
2169
2170         return $oprofile;
2171     }
2172 }
2173
2174 /**
2175  * Exception indicating we've got a remote reference to a local user,
2176  * not a remote user!
2177  *
2178  * If we can ue a local profile after all, it's available as $e->profile.
2179  */
2180 class OStatusShadowException extends Exception
2181 {
2182     public $profile;
2183
2184     /**
2185      * @param Profile $profile
2186      * @param string $message
2187      */
2188     function __construct($profile, $message) {
2189         $this->profile = $profile;
2190         parent::__construct($message);
2191     }
2192 }