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