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