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