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