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