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