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