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