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