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