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