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