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