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