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