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