3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009-2010, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET')) {
25 * @package OStatusPlugin
26 * @maintainer Brion Vibber <brion@status.net>
28 class Ostatus_profile extends Managed_DataObject
30 public $__table = 'ostatus_profile';
40 public $avatar; // remote URL of the last avatar we saved
46 * Return table definition for Schema setup and DB_DataObject usage.
48 * @return array array of column definitions
50 static function schemaDef()
54 'uri' => array('type' => 'varchar', 'length' => 191, 'not null' => true),
55 'profile_id' => array('type' => 'integer'),
56 'group_id' => array('type' => 'integer'),
57 'peopletag_id' => array('type' => 'integer'),
58 'feeduri' => array('type' => 'varchar', 'length' => 191),
59 'salmonuri' => array('type' => 'varchar', 'length' => 191),
60 'avatar' => array('type' => 'text'),
61 'created' => array('type' => 'datetime', 'not null' => true),
62 'modified' => array('type' => 'datetime', 'not null' => true),
64 'primary key' => array('uri'),
65 'unique keys' => array(
66 'ostatus_profile_profile_id_key' => array('profile_id'),
67 'ostatus_profile_group_id_key' => array('group_id'),
68 'ostatus_profile_peopletag_id_key' => array('peopletag_id'),
69 'ostatus_profile_feeduri_key' => array('feeduri'),
71 'foreign keys' => array(
72 'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
73 'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
74 'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
79 public function getUri()
84 public function fromProfile(Profile $profile)
86 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
87 if (!$oprofile instanceof Ostatus_profile) {
88 throw new Exception('No Ostatus_profile for Profile ID: '.$profile->id);
93 * Fetch the locally stored profile for this feed
95 * @throws NoProfileException if it was not found
97 public function localProfile()
99 if ($this->isGroup()) {
100 return $this->localGroup()->getProfile();
103 $profile = Profile::getKV('id', $this->profile_id);
104 if (!$profile instanceof Profile) {
105 throw new NoProfileException($this->profile_id);
111 * Fetch the StatusNet-side profile for this feed
114 public function localGroup()
116 $group = User_group::getKV('id', $this->group_id);
118 if (!$group instanceof User_group) {
119 throw new NoSuchGroupException(array('id'=>$this->group_id));
126 * Fetch the StatusNet-side peopletag for this feed
129 public function localPeopletag()
131 if ($this->peopletag_id) {
132 return Profile_list::getKV('id', $this->peopletag_id);
138 * Returns an ActivityObject describing this remote user or group profile.
139 * Can then be used to generate Atom chunks.
141 * @return ActivityObject
143 function asActivityObject()
145 if ($this->isGroup()) {
146 return ActivityObject::fromGroup($this->localGroup());
147 } else if ($this->isPeopletag()) {
148 return ActivityObject::fromPeopletag($this->localPeopletag());
150 return $this->localProfile()->asActivityObject();
155 * Returns an XML string fragment with profile information as an
156 * Activity Streams noun object with the given element type.
158 * Assumes that 'activity' namespace has been previously defined.
160 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
162 * @param string $element one of 'actor', 'subject', 'object', 'target'
165 function asActivityNoun($element)
167 if ($this->isGroup()) {
168 $noun = ActivityObject::fromGroup($this->localGroup());
169 return $noun->asString('activity:' . $element);
170 } else if ($this->isPeopletag()) {
171 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
172 return $noun->asString('activity:' . $element);
174 $noun = $this->localProfile()->asActivityObject();
175 return $noun->asString('activity:' . $element);
180 * @return boolean true if this is a remote group
184 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
186 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
188 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
189 // TRANS: Server exception. %s is a URI
190 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
192 // TRANS: Server exception. %s is a URI
193 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
198 * @return boolean true if this is a remote peopletag
200 function isPeopletag()
202 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
204 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
206 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
207 // TRANS: Server exception. %s is a URI
208 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
210 // TRANS: Server exception. %s is a URI
211 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
216 * Send a subscription request to the hub for this feed.
217 * The hub will later send us a confirmation POST to /main/push/callback.
220 * @throws ServerException if feed state is not valid or subscription fails.
222 public function subscribe()
224 $feedsub = FeedSub::ensureFeed($this->feeduri);
225 if ($feedsub->sub_state == 'active') {
226 // Active subscription, we don't need to do anything.
230 // Inactive or we got left in an inconsistent state.
231 // Run a subscription request to make sure we're current!
232 return $feedsub->subscribe();
236 * Check if this remote profile has any active local subscriptions, and
237 * if not drop the PuSH subscription feed.
239 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
240 * @throws Exception of various kinds on failure.
242 public function unsubscribe() {
243 return $this->garbageCollect();
247 * Check if this remote profile has any active local subscriptions, and
248 * if not drop the PuSH subscription feed.
250 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
251 * @throws Exception of various kinds on failure.
253 public function garbageCollect()
255 $feedsub = FeedSub::getKV('uri', $this->feeduri);
256 if ($feedsub instanceof FeedSub) {
257 return $feedsub->garbageCollect();
259 // Since there's no FeedSub we can assume it's already garbage collected
264 * Check if this remote profile has any active local subscriptions, so the
265 * PuSH subscription layer can decide if it can drop the feed.
267 * This gets called via the FeedSubSubscriberCount event when running
268 * FeedSub::garbageCollect().
271 * @throws NoProfileException if there is no local profile for the object
273 public function subscriberCount()
275 if ($this->isGroup()) {
276 $members = $this->localGroup()->getMembers(0, 1);
277 $count = $members->N;
278 } else if ($this->isPeopletag()) {
279 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
280 $count = $subscribers->N;
282 $profile = $this->localProfile();
283 if ($profile->hasLocalTags()) {
286 $count = $profile->subscriberCount();
289 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
291 // Other plugins may be piggybacking on OStatus without having
292 // an active group or user-to-user subscription we know about.
293 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
294 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
300 * Send an Activity Streams notification to the remote Salmon endpoint,
303 * @param Profile $actor Actor who did the activity
304 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
305 * @param Object $object object of the action; must define asActivityNoun($tag)
307 public function notify(Profile $actor, $verb, $object=null, $target=null)
309 if ($object == null) {
312 if (empty($this->salmonuri)) {
316 $id = TagURI::mint('%s:%s:%s',
319 common_date_iso8601(time()));
321 // @todo FIXME: Consolidate all these NS settings somewhere.
322 $attributes = array('xmlns' => Activity::ATOM,
323 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
324 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
325 'xmlns:georss' => 'http://www.georss.org/georss',
326 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
327 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
328 'xmlns:media' => 'http://purl.org/syndication/atommedia');
330 $entry = new XMLStringer();
331 $entry->elementStart('entry', $attributes);
332 $entry->element('id', null, $id);
333 $entry->element('title', null, $text);
334 $entry->element('summary', null, $text);
335 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
337 $entry->element('activity:verb', null, $verb);
338 $entry->raw($actor->asAtomAuthor());
339 $entry->raw($actor->asActivityActor());
340 $entry->raw($object->asActivityNoun('object'));
341 if ($target != null) {
342 $entry->raw($target->asActivityNoun('target'));
344 $entry->elementEnd('entry');
346 $xml = $entry->getString();
347 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
349 Salmon::post($this->salmonuri, $xml, $actor->getUser());
353 * Send a Salmon notification ping immediately, and confirm that we got
354 * an acceptable response from the remote site.
356 * @param mixed $entry XML string, Notice, or Activity
357 * @param Profile $actor
358 * @return boolean success
360 public function notifyActivity($entry, Profile $actor)
362 if ($this->salmonuri) {
363 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor->getUser());
365 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
371 * Queue a Salmon notification for later. If queues are disabled we'll
372 * send immediately but won't get the return value.
374 * @param mixed $entry XML string, Notice, or Activity
375 * @return boolean success
377 public function notifyDeferred($entry, $actor)
379 if ($this->salmonuri) {
380 $data = array('salmonuri' => $this->salmonuri,
381 'entry' => $this->notifyPrepXml($entry),
382 'actor' => $actor->id);
384 $qm = QueueManager::get();
385 return $qm->enqueue($data, 'salmon');
391 protected function notifyPrepXml($entry)
393 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
394 if (is_string($entry)) {
396 } else if ($entry instanceof Activity) {
397 return $preamble . $entry->asString(true);
398 } else if ($entry instanceof Notice) {
399 return $preamble . $entry->asAtomEntry(true, true);
401 // TRANS: Server exception.
402 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
406 function getBestName()
408 if ($this->isGroup()) {
409 return $this->localGroup()->getBestName();
410 } else if ($this->isPeopletag()) {
411 return $this->localPeopletag()->getBestName();
413 return $this->localProfile()->getBestName();
418 * Read and post notices for updates from the feed.
419 * Currently assumes that all items in the feed are new,
420 * coming from a PuSH hub.
422 * @param DOMDocument $doc
423 * @param string $source identifier ("push")
425 public function processFeed(DOMDocument $doc, $source)
427 $feed = $doc->documentElement;
429 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
430 $this->processAtomFeed($feed, $source);
431 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
432 $this->processRssFeed($feed, $source);
435 throw new Exception(_m('Unknown feed format.'));
439 public function processAtomFeed(DOMElement $feed, $source)
441 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
442 if ($entries->length == 0) {
443 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
447 for ($i = 0; $i < $entries->length; $i++) {
448 $entry = $entries->item($i);
449 $this->processEntry($entry, $feed, $source);
453 public function processRssFeed(DOMElement $rss, $source)
455 $channels = $rss->getElementsByTagName('channel');
457 if ($channels->length == 0) {
459 throw new Exception(_m('RSS feed without a channel.'));
460 } else if ($channels->length > 1) {
461 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
464 $channel = $channels->item(0);
466 $items = $channel->getElementsByTagName('item');
468 for ($i = 0; $i < $items->length; $i++) {
469 $item = $items->item($i);
470 $this->processEntry($item, $channel, $source);
475 * Process a posted entry from this feed source.
477 * @param DOMElement $entry
478 * @param DOMElement $feed for context
479 * @param string $source identifier ("push" or "salmon")
481 * @return Notice Notice representing the new (or existing) activity
483 public function processEntry($entry, $feed, $source)
485 $activity = new Activity($entry, $feed);
486 return $this->processActivity($activity, $source);
489 // TODO: Make this throw an exception
490 public function processActivity($activity, $source)
494 // The "WithProfile" events were added later.
496 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
497 Event::handle('StartHandleFeedEntry', array($activity))) {
499 switch ($activity->verb) {
500 case ActivityVerb::POST:
501 // @todo process all activity objects
502 switch ($activity->objects[0]->type) {
503 case ActivityObject::ARTICLE:
504 case ActivityObject::BLOGENTRY:
505 case ActivityObject::NOTE:
506 case ActivityObject::STATUS:
507 case ActivityObject::COMMENT:
509 $notice = $this->processPost($activity, $source);
512 // TRANS: Client exception.
513 throw new ClientException(_m('Cannot handle that kind of post.'));
517 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
520 Event::handle('EndHandleFeedEntry', array($activity));
521 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
528 * Process an incoming post activity from this remote feed.
529 * @param Activity $activity
530 * @param string $method 'push' or 'salmon'
531 * @return mixed saved Notice or false
532 * @todo FIXME: Break up this function, it's getting nasty long
534 public function processPost($activity, $method)
538 $profile = ActivityUtils::checkAuthorship($activity, $this->localProfile());
540 // It's not always an ActivityObject::NOTE, but... let's just say it is.
542 $note = $activity->objects[0];
544 // The id URI will be used as a unique identifier for the notice,
545 // protecting against duplicate saves. It isn't required to be a URL;
546 // tag: URIs for instance are found in Google Buzz feeds.
547 $sourceUri = $note->id;
548 $dupe = Notice::getKV('uri', $sourceUri);
549 if ($dupe instanceof Notice) {
550 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
554 // We'll also want to save a web link to the original notice, if provided.
557 $sourceUrl = $note->link;
558 } else if ($activity->link) {
559 $sourceUrl = $activity->link;
560 } else if (preg_match('!^https?://!', $note->id)) {
561 $sourceUrl = $note->id;
564 // Use summary as fallback for content
566 if (!empty($note->content)) {
567 $sourceContent = $note->content;
568 } else if (!empty($note->summary)) {
569 $sourceContent = $note->summary;
570 } else if (!empty($note->title)) {
571 $sourceContent = $note->title;
573 // @todo FIXME: Fetch from $sourceUrl?
574 // TRANS: Client exception. %s is a source URI.
575 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
578 // Get (safe!) HTML and text versions of the content
580 $rendered = common_purify($sourceContent);
581 $content = common_strip_html($rendered);
583 $shortened = common_shorten_links($content);
585 // If it's too long, try using the summary, and make the
586 // HTML an attachment.
590 if (Notice::contentTooLong($shortened)) {
591 $attachment = $this->saveHTMLFile($note->title, $rendered);
592 $summary = common_strip_html($note->summary);
593 if (empty($summary)) {
596 $shortSummary = common_shorten_links($summary);
597 if (Notice::contentTooLong($shortSummary)) {
598 $url = common_shorten_url($sourceUrl);
599 $shortSummary = substr($shortSummary,
601 Notice::maxContent() - (mb_strlen($url) + 2));
602 $content = $shortSummary . ' ' . $url;
604 // We mark up the attachment link specially for the HTML output
605 // so we can fold-out the full version inline.
607 // @todo FIXME i18n: This tooltip will be saved with the site's default language
608 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
609 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
610 $showMoreText = _m('Show more');
611 $attachUrl = common_local_url('attachment',
612 array('attachment' => $attachment->id));
613 $rendered = common_render_text($shortSummary) .
614 '<a href="' . htmlspecialchars($attachUrl) .'"'.
615 ' class="attachment more"' .
616 ' title="'. htmlspecialchars($showMoreText) . '">' .
622 $options = array('is_local' => Notice::REMOTE,
625 'rendered' => $rendered,
626 'replies' => array(),
628 'peopletags' => array(),
632 // Check for optional attributes...
634 if (!empty($activity->time)) {
635 $options['created'] = common_sql_date($activity->time);
638 if ($activity->context) {
639 // TODO: context->attention
640 list($options['groups'], $options['replies'])
641 = self::filterAttention($profile, $activity->context->attention);
643 // Maintain direct reply associations
644 // @todo FIXME: What about conversation ID?
645 if (!empty($activity->context->replyToID)) {
646 $orig = Notice::getKV('uri', $activity->context->replyToID);
647 if ($orig instanceof Notice) {
648 $options['reply_to'] = $orig->id;
651 if (!empty($activity->context->conversation)) {
652 // we store the URI here, Notice class can look it up later
653 $options['conversation'] = $activity->context->conversation;
656 $location = $activity->context->location;
658 $options['lat'] = $location->lat;
659 $options['lon'] = $location->lon;
660 if ($location->location_id) {
661 $options['location_ns'] = $location->location_ns;
662 $options['location_id'] = $location->location_id;
667 if ($this->isPeopletag()) {
668 $options['peopletags'][] = $this->localPeopletag();
671 // Atom categories <-> hashtags
672 foreach ($activity->categories as $cat) {
674 $term = common_canonical_tag($cat->term);
676 $options['tags'][] = $term;
681 // Atom enclosures -> attachment URLs
682 foreach ($activity->enclosures as $href) {
683 // @todo FIXME: Save these locally or....?
684 $options['urls'][] = $href;
688 $saved = Notice::saveNew($profile->id,
692 if ($saved instanceof Notice) {
693 Ostatus_source::saveNew($saved, $this, $method);
694 if (!empty($attachment)) {
695 File_to_post::processNew($attachment->id, $saved->id);
698 } catch (Exception $e) {
699 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
702 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
707 * Filters a list of recipient ID URIs to just those for local delivery.
708 * @param Profile local profile of sender
709 * @param array in/out &$attention_uris set of URIs, will be pruned on output
710 * @return array of group IDs
712 static public function filterAttention(Profile $sender, array $attention)
714 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
717 foreach ($attention as $recipient=>$type) {
718 // Is the recipient a local user?
719 $user = User::getKV('uri', $recipient);
720 if ($user instanceof User) {
721 // @todo FIXME: Sender verification, spam etc?
722 $replies[] = $recipient;
726 // Is the recipient a local group?
727 // TODO: $group = User_group::getKV('uri', $recipient);
728 $id = OStatusPlugin::localGroupFromUrl($recipient);
730 $group = User_group::getKV('id', $id);
731 if ($group instanceof User_group) {
732 // Deliver to all members of this local group if allowed.
733 if ($sender->isMember($group)) {
734 $groups[] = $group->id;
736 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
740 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
744 // Is the recipient a remote user or group?
746 $oprofile = self::ensureProfileURI($recipient);
747 if ($oprofile->isGroup()) {
748 // Deliver to local members of this remote group.
749 // @todo FIXME: Sender verification?
750 $groups[] = $oprofile->group_id;
752 // may be canonicalized or something
753 $replies[] = $oprofile->getUri();
756 } catch (Exception $e) {
757 // Neither a recognizable local nor remote user!
758 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
762 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
763 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
764 return array($groups, $replies);
768 * Look up and if necessary create an Ostatus_profile for the remote entity
769 * with the given profile page URL. This should never return null -- you
770 * will either get an object or an exception will be thrown.
772 * @param string $profile_url
773 * @return Ostatus_profile
774 * @throws Exception on various error conditions
775 * @throws OStatusShadowException if this reference would obscure a local user/group
777 public static function ensureProfileURL($profile_url, array $hints=array())
779 $oprofile = self::getFromProfileURL($profile_url);
781 if ($oprofile instanceof Ostatus_profile) {
785 $hints['profileurl'] = $profile_url;
790 $client = new HTTPClient();
791 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
792 $response = $client->get($profile_url);
794 if (!$response->isOk()) {
795 // TRANS: Exception. %s is a profile URL.
796 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
799 // Check if we have a non-canonical URL
801 $finalUrl = $response->getUrl();
803 if ($finalUrl != $profile_url) {
805 $hints['profileurl'] = $finalUrl;
807 $oprofile = self::getFromProfileURL($finalUrl);
809 if ($oprofile instanceof Ostatus_profile) {
814 // Try to get some hCard data
816 $body = $response->getBody();
818 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
820 if (!empty($hcardHints)) {
821 $hints = array_merge($hints, $hcardHints);
824 // Check if they've got an LRDD header
826 $lrdd = LinkHeader::getLink($response, 'lrdd');
828 $xrd = new XML_XRD();
829 $xrd->loadFile($lrdd);
830 $xrdHints = DiscoveryHints::fromXRD($xrd);
831 $hints = array_merge($hints, $xrdHints);
832 } catch (Exception $e) {
833 // No hints available from XRD
836 // If discovery found a feedurl (probably from LRDD), use it.
838 if (array_key_exists('feedurl', $hints)) {
839 return self::ensureFeedURL($hints['feedurl'], $hints);
842 // Get the feed URL from HTML
844 $discover = new FeedDiscovery();
846 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
848 if (!empty($feedurl)) {
849 $hints['feedurl'] = $feedurl;
850 return self::ensureFeedURL($feedurl, $hints);
853 // TRANS: Exception. %s is a URL.
854 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
858 * Look up the Ostatus_profile, if present, for a remote entity with the
859 * given profile page URL. Will return null for both unknown and invalid
862 * @return mixed Ostatus_profile or null
863 * @throws OStatusShadowException for local profiles
865 static function getFromProfileURL($profile_url)
867 $profile = Profile::getKV('profileurl', $profile_url);
868 if (!$profile instanceof Profile) {
873 $oprofile = self::getFromProfile($profile);
874 // We found the profile, return it!
876 } catch (NoResultException $e) {
877 // Could not find an OStatus profile, is it instead a local user?
878 $user = User::getKV('id', $profile->id);
879 if ($user instanceof User) {
880 // @todo i18n FIXME: use sprintf and add i18n (?)
881 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
885 // Continue discovery; it's a remote profile
886 // for OMB or some other protocol, may also
892 static function getFromProfile(Profile $profile)
894 $oprofile = new Ostatus_profile();
895 $oprofile->profile_id = $profile->id;
896 if (!$oprofile->find(true)) {
897 throw new NoResultException($oprofile);
903 * Look up and if necessary create an Ostatus_profile for remote entity
904 * with the given update feed. This should never return null -- you will
905 * either get an object or an exception will be thrown.
907 * @return Ostatus_profile
910 public static function ensureFeedURL($feed_url, array $hints=array())
912 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
913 if ($oprofile instanceof Ostatus_profile) {
917 $discover = new FeedDiscovery();
919 $feeduri = $discover->discoverFromFeedURL($feed_url);
920 $hints['feedurl'] = $feeduri;
922 $huburi = $discover->getHubLink();
923 $hints['hub'] = $huburi;
925 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
926 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
927 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
928 $hints['salmon'] = $salmonuri;
930 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
931 // We can only deal with folks with a PuSH hub
932 // unless we have something similar available locally.
933 throw new FeedSubNoHubException();
936 $feedEl = $discover->root;
938 if ($feedEl->tagName == 'feed') {
939 return self::ensureAtomFeed($feedEl, $hints);
940 } else if ($feedEl->tagName == 'channel') {
941 return self::ensureRssChannel($feedEl, $hints);
943 throw new FeedSubBadXmlException($feeduri);
948 * Look up and, if necessary, create an Ostatus_profile for the remote
949 * profile with the given Atom feed - actually loaded from the feed.
950 * This should never return null -- you will either get an object or
951 * an exception will be thrown.
953 * @param DOMElement $feedEl root element of a loaded Atom feed
954 * @param array $hints additional discovery information passed from higher levels
955 * @todo FIXME: Should this be marked public?
956 * @return Ostatus_profile
959 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
961 $author = ActivityUtils::getFeedAuthor($feedEl);
963 if (empty($author)) {
964 // XXX: make some educated guesses here
965 // TRANS: Feed sub exception.
966 throw new FeedSubException(_m('Cannot find enough profile '.
967 'information to make a feed.'));
970 return self::ensureActivityObjectProfile($author, $hints);
974 * Look up and, if necessary, create an Ostatus_profile for the remote
975 * profile with the given RSS feed - actually loaded from the feed.
976 * This should never return null -- you will either get an object or
977 * an exception will be thrown.
979 * @param DOMElement $feedEl root element of a loaded RSS feed
980 * @param array $hints additional discovery information passed from higher levels
981 * @todo FIXME: Should this be marked public?
982 * @return Ostatus_profile
985 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
987 // Special-case for Posterous. They have some nice metadata in their
988 // posterous:author elements. We should use them instead of the channel.
990 $items = $feedEl->getElementsByTagName('item');
992 if ($items->length > 0) {
993 $item = $items->item(0);
994 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
995 if (!empty($authorEl)) {
996 $obj = ActivityObject::fromPosterousAuthor($authorEl);
997 // Posterous has multiple authors per feed, and multiple feeds
998 // per author. We check if this is the "main" feed for this author.
999 if (array_key_exists('profileurl', $hints) &&
1000 !empty($obj->poco) &&
1001 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1002 return self::ensureActivityObjectProfile($obj, $hints);
1007 // @todo FIXME: We should check whether this feed has elements
1008 // with different <author> or <dc:creator> elements, and... I dunno.
1009 // Do something about that.
1011 $obj = ActivityObject::fromRssChannel($feedEl);
1013 return self::ensureActivityObjectProfile($obj, $hints);
1017 * Download and update given avatar image
1019 * @param string $url
1020 * @return Avatar The Avatar we have on disk. (seldom used)
1021 * @throws Exception in various failure cases
1023 public function updateAvatar($url, $force=false)
1026 // If avatar URL differs: update. If URLs were identical but we're forced: update.
1027 if ($url == $this->avatar && !$force) {
1028 // If there's no locally stored avatar, throw an exception and continue fetching below.
1029 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
1032 } catch (NoAvatarException $e) {
1033 // No avatar available, let's fetch it.
1036 if (!common_valid_http_url($url)) {
1037 // TRANS: Server exception. %s is a URL.
1038 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1041 $self = $this->localProfile();
1043 // @todo FIXME: This should be better encapsulated
1044 // ripped from oauthstore.php (for old OMB client)
1045 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1047 $imgData = HTTPClient::quickGet($url);
1048 // Make sure it's at least an image file. ImageFile can do the rest.
1049 if (false === getimagesizefromstring($imgData)) {
1050 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
1052 file_put_contents($temp_filename, $imgData);
1053 unset($imgData); // No need to carry this in memory.
1055 if ($this->isGroup()) {
1056 $id = $this->group_id;
1058 $id = $this->profile_id;
1060 $imagefile = new ImageFile(null, $temp_filename);
1061 $filename = Avatar::filename($id,
1062 image_type_to_extension($imagefile->type),
1064 common_timestamp());
1065 rename($temp_filename, Avatar::path($filename));
1066 } catch (Exception $e) {
1067 unlink($temp_filename);
1070 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1071 // keep from accidentally saving images from command-line (queues)
1072 // that can't be read from web server, which causes hard-to-notice
1073 // problems later on:
1075 // http://status.net/open-source/issues/2663
1076 chmod(Avatar::path($filename), 0644);
1078 $self->setOriginal($filename);
1080 $orig = clone($this);
1081 $this->avatar = $url;
1082 $this->update($orig);
1084 return Avatar::getUploaded($self);
1088 * Pull avatar URL from ActivityObject or profile hints
1090 * @param ActivityObject $object
1091 * @param array $hints
1092 * @return mixed URL string or false
1094 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
1096 if ($object->avatarLinks) {
1098 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1099 foreach ($object->avatarLinks as $avatar) {
1100 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1105 if (!$best || $avatar->width > $best->width) {
1110 } else if (array_key_exists('avatar', $hints)) {
1111 return $hints['avatar'];
1117 * Get an appropriate avatar image source URL, if available.
1119 * @param ActivityObject $actor
1120 * @param DOMElement $feed
1123 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
1127 if ($actor->avatar) {
1128 $url = trim($actor->avatar);
1131 // Check <atom:logo> and <atom:icon> on the feed
1132 $els = $feed->childNodes();
1133 if ($els && $els->length) {
1134 for ($i = 0; $i < $els->length; $i++) {
1135 $el = $els->item($i);
1136 if ($el->namespaceURI == Activity::ATOM) {
1137 if (empty($url) && $el->localName == 'logo') {
1138 $url = trim($el->textContent);
1141 if (empty($icon) && $el->localName == 'icon') {
1142 // Use as a fallback
1143 $icon = trim($el->textContent);
1148 if ($icon && !$url) {
1153 $opts = array('allowed_schemes' => array('http', 'https'));
1154 if (common_valid_http_url($url)) {
1159 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1163 * Fetch, or build if necessary, an Ostatus_profile for the actor
1164 * in a given Activity Streams activity.
1165 * This should never return null -- you will either get an object or
1166 * an exception will be thrown.
1168 * @param Activity $activity
1169 * @param string $feeduri if we already know the canonical feed URI!
1170 * @param string $salmonuri if we already know the salmon return channel URI
1171 * @return Ostatus_profile
1174 public static function ensureActorProfile(Activity $activity, array $hints=array())
1176 return self::ensureActivityObjectProfile($activity->actor, $hints);
1180 * Fetch, or build if necessary, an Ostatus_profile for the profile
1181 * in a given Activity Streams object (can be subject, actor, or object).
1182 * This should never return null -- you will either get an object or
1183 * an exception will be thrown.
1185 * @param ActivityObject $object
1186 * @param array $hints additional discovery information passed from higher levels
1187 * @return Ostatus_profile
1190 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1192 $profile = self::getActivityObjectProfile($object);
1193 if ($profile instanceof Ostatus_profile) {
1194 $profile->updateFromActivityObject($object, $hints);
1196 $profile = self::createActivityObjectProfile($object, $hints);
1202 * @param Activity $activity
1203 * @return mixed matching Ostatus_profile or false if none known
1204 * @throws ServerException if feed info invalid
1206 public static function getActorProfile(Activity $activity)
1208 return self::getActivityObjectProfile($activity->actor);
1212 * @param ActivityObject $activity
1213 * @return mixed matching Ostatus_profile or false if none known
1214 * @throws ServerException if feed info invalid
1216 protected static function getActivityObjectProfile(ActivityObject $object)
1218 $uri = self::getActivityObjectProfileURI($object);
1219 return Ostatus_profile::getKV('uri', $uri);
1223 * Get the identifier URI for the remote entity described
1224 * by this ActivityObject. This URI is *not* guaranteed to be
1225 * a resolvable HTTP/HTTPS URL.
1227 * @param ActivityObject $object
1229 * @throws ServerException if feed info invalid
1231 protected static function getActivityObjectProfileURI(ActivityObject $object)
1234 if (ActivityUtils::validateUri($object->id)) {
1239 // If the id is missing or invalid (we've seen feeds mistakenly listing
1240 // things like local usernames in that field) then we'll use the profile
1241 // page link, if valid.
1242 if ($object->link && common_valid_http_url($object->link)) {
1243 return $object->link;
1245 // TRANS: Server exception.
1246 throw new ServerException(_m('No author ID URI found.'));
1250 * @todo FIXME: Validate stuff somewhere.
1254 * Create local ostatus_profile and profile/user_group entries for
1255 * the provided remote user or group.
1256 * This should never return null -- you will either get an object or
1257 * an exception will be thrown.
1259 * @param ActivityObject $object
1260 * @param array $hints
1262 * @return Ostatus_profile
1264 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1266 $homeuri = $object->id;
1270 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1271 // TRANS: Exception.
1272 throw new Exception(_m('No profile URI.'));
1275 $user = User::getKV('uri', $homeuri);
1276 if ($user instanceof User) {
1277 // TRANS: Exception.
1278 throw new Exception(_m('Local user cannot be referenced as remote.'));
1281 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1282 // TRANS: Exception.
1283 throw new Exception(_m('Local group cannot be referenced as remote.'));
1286 $ptag = Profile_list::getKV('uri', $homeuri);
1287 if ($ptag instanceof Profile_list) {
1288 $local_user = User::getKV('id', $ptag->tagger);
1289 if ($local_user instanceof User) {
1290 // TRANS: Exception.
1291 throw new Exception(_m('Local list cannot be referenced as remote.'));
1295 if (array_key_exists('feedurl', $hints)) {
1296 $feeduri = $hints['feedurl'];
1298 $discover = new FeedDiscovery();
1299 $feeduri = $discover->discoverFromURL($homeuri);
1302 if (array_key_exists('salmon', $hints)) {
1303 $salmonuri = $hints['salmon'];
1306 $discover = new FeedDiscovery();
1307 $discover->discoverFromFeedURL($hints['feedurl']);
1309 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1310 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1311 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1314 if (array_key_exists('hub', $hints)) {
1315 $huburi = $hints['hub'];
1318 $discover = new FeedDiscovery();
1319 $discover->discoverFromFeedURL($hints['feedurl']);
1321 $huburi = $discover->getHubLink();
1324 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1325 // We can only deal with folks with a PuSH hub
1326 throw new FeedSubNoHubException();
1329 $oprofile = new Ostatus_profile();
1331 $oprofile->uri = $homeuri;
1332 $oprofile->feeduri = $feeduri;
1333 $oprofile->salmonuri = $salmonuri;
1335 $oprofile->created = common_sql_now();
1336 $oprofile->modified = common_sql_now();
1338 if ($object->type == ActivityObject::PERSON) {
1339 $profile = new Profile();
1340 $profile->created = common_sql_now();
1341 self::updateProfile($profile, $object, $hints);
1343 $oprofile->profile_id = $profile->insert();
1344 if ($oprofile->profile_id === false) {
1345 // TRANS: Server exception.
1346 throw new ServerException(_m('Cannot save local profile.'));
1348 } else if ($object->type == ActivityObject::GROUP) {
1349 $profile = new Profile();
1350 $profile->query('BEGIN');
1352 $group = new User_group();
1353 $group->uri = $homeuri;
1354 $group->created = common_sql_now();
1355 self::updateGroup($group, $object, $hints);
1357 // TODO: We should do this directly in User_group->insert()!
1358 // currently it's duplicated in User_group->update()
1359 // AND User_group->register()!!!
1360 $fields = array(/*group field => profile field*/
1361 'nickname' => 'nickname',
1362 'fullname' => 'fullname',
1363 'mainpage' => 'profileurl',
1364 'homepage' => 'homepage',
1365 'description' => 'bio',
1366 'location' => 'location',
1367 'created' => 'created',
1368 'modified' => 'modified',
1370 foreach ($fields as $gf=>$pf) {
1371 $profile->$pf = $group->$gf;
1373 $profile_id = $profile->insert();
1374 if ($profile_id === false) {
1375 $profile->query('ROLLBACK');
1376 throw new ServerException(_('Profile insertion failed.'));
1379 $group->profile_id = $profile_id;
1381 $oprofile->group_id = $group->insert();
1382 if ($oprofile->group_id === false) {
1383 $profile->query('ROLLBACK');
1384 // TRANS: Server exception.
1385 throw new ServerException(_m('Cannot save local profile.'));
1388 $profile->query('COMMIT');
1389 } else if ($object->type == ActivityObject::_LIST) {
1390 $ptag = new Profile_list();
1391 $ptag->uri = $homeuri;
1392 $ptag->created = common_sql_now();
1393 self::updatePeopletag($ptag, $object, $hints);
1395 $oprofile->peopletag_id = $ptag->insert();
1396 if ($oprofile->peopletag_id === false) {
1397 // TRANS: Server exception.
1398 throw new ServerException(_m('Cannot save local list.'));
1402 $ok = $oprofile->insert();
1404 if ($ok === false) {
1405 // TRANS: Server exception.
1406 throw new ServerException(_m('Cannot save OStatus profile.'));
1409 $avatar = self::getActivityObjectAvatar($object, $hints);
1413 $oprofile->updateAvatar($avatar);
1414 } catch (Exception $ex) {
1415 // Profile is saved, but Avatar is messed up. We're
1416 // just going to continue.
1417 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1425 * Save any updated profile information to our local copy.
1426 * @param ActivityObject $object
1427 * @param array $hints
1429 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1431 if ($this->isGroup()) {
1432 $group = $this->localGroup();
1433 self::updateGroup($group, $object, $hints);
1434 } else if ($this->isPeopletag()) {
1435 $ptag = $this->localPeopletag();
1436 self::updatePeopletag($ptag, $object, $hints);
1438 $profile = $this->localProfile();
1439 self::updateProfile($profile, $object, $hints);
1442 $avatar = self::getActivityObjectAvatar($object, $hints);
1443 if ($avatar && !isset($ptag)) {
1445 $this->updateAvatar($avatar);
1446 } catch (Exception $ex) {
1447 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1452 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1454 $orig = clone($profile);
1456 // Existing nickname is better than nothing.
1458 if (!array_key_exists('nickname', $hints)) {
1459 $hints['nickname'] = $profile->nickname;
1462 $nickname = self::getActivityObjectNickname($object, $hints);
1464 if (!empty($nickname)) {
1465 $profile->nickname = $nickname;
1468 if (!empty($object->title)) {
1469 $profile->fullname = $object->title;
1470 } else if (array_key_exists('fullname', $hints)) {
1471 $profile->fullname = $hints['fullname'];
1474 if (!empty($object->link)) {
1475 $profile->profileurl = $object->link;
1476 } else if (array_key_exists('profileurl', $hints)) {
1477 $profile->profileurl = $hints['profileurl'];
1478 } else if (common_valid_http_url($object->id)) {
1479 $profile->profileurl = $object->id;
1482 $bio = self::getActivityObjectBio($object, $hints);
1485 $profile->bio = $bio;
1488 $location = self::getActivityObjectLocation($object, $hints);
1490 if (!empty($location)) {
1491 $profile->location = $location;
1494 $homepage = self::getActivityObjectHomepage($object, $hints);
1496 if (!empty($homepage)) {
1497 $profile->homepage = $homepage;
1500 if (!empty($object->geopoint)) {
1501 $location = ActivityContext::locationFromPoint($object->geopoint);
1502 if (!empty($location)) {
1503 $profile->lat = $location->lat;
1504 $profile->lon = $location->lon;
1508 // @todo FIXME: tags/categories
1509 // @todo tags from categories
1512 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1513 $profile->update($orig);
1517 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1519 $orig = clone($group);
1521 $group->nickname = self::getActivityObjectNickname($object, $hints);
1522 $group->fullname = $object->title;
1524 if (!empty($object->link)) {
1525 $group->mainpage = $object->link;
1526 } else if (array_key_exists('profileurl', $hints)) {
1527 $group->mainpage = $hints['profileurl'];
1530 // @todo tags from categories
1531 $group->description = self::getActivityObjectBio($object, $hints);
1532 $group->location = self::getActivityObjectLocation($object, $hints);
1533 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1535 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1536 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1537 $group->update($orig);
1541 protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array()) {
1542 $orig = clone($tag);
1544 $tag->tag = $object->title;
1546 if (!empty($object->link)) {
1547 $tag->mainpage = $object->link;
1548 } else if (array_key_exists('profileurl', $hints)) {
1549 $tag->mainpage = $hints['profileurl'];
1552 $tag->description = $object->summary;
1553 $tagger = self::ensureActivityObjectProfile($object->owner);
1554 $tag->tagger = $tagger->profile_id;
1557 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1558 $tag->update($orig);
1562 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1565 $poco = $object->poco;
1567 if (!empty($poco)) {
1568 $url = $poco->getPrimaryURL();
1569 if ($url && $url->type == 'homepage') {
1570 $homepage = $url->value;
1574 // @todo Try for a another PoCo URL?
1579 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1583 if (!empty($object->poco) &&
1584 isset($object->poco->address->formatted)) {
1585 $location = $object->poco->address->formatted;
1586 } else if (array_key_exists('location', $hints)) {
1587 $location = $hints['location'];
1590 if (!empty($location)) {
1591 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1592 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1596 // @todo Try to find location some othe way? Via goerss point?
1601 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1605 if (!empty($object->poco)) {
1606 $note = $object->poco->note;
1607 } else if (array_key_exists('bio', $hints)) {
1608 $note = $hints['bio'];
1611 if (!empty($note)) {
1612 if (Profile::bioTooLong($note)) {
1613 // XXX: truncate ok?
1614 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1620 // @todo Try to get bio info some other way?
1625 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1627 if ($object->poco) {
1628 if (!empty($object->poco->preferredUsername)) {
1629 return common_nicknamize($object->poco->preferredUsername);
1633 if (!empty($object->nickname)) {
1634 return common_nicknamize($object->nickname);
1637 if (array_key_exists('nickname', $hints)) {
1638 return $hints['nickname'];
1641 // Try the profile url (like foo.example.com or example.com/user/foo)
1642 if (!empty($object->link)) {
1643 $profileUrl = $object->link;
1644 } else if (!empty($hints['profileurl'])) {
1645 $profileUrl = $hints['profileurl'];
1648 if (!empty($profileUrl)) {
1649 $nickname = self::nicknameFromURI($profileUrl);
1652 // Try the URI (may be a tag:, http:, acct:, ...
1654 if (empty($nickname)) {
1655 $nickname = self::nicknameFromURI($object->id);
1658 // Try a Webfinger if one was passed (way) down
1660 if (empty($nickname)) {
1661 if (array_key_exists('webfinger', $hints)) {
1662 $nickname = self::nicknameFromURI($hints['webfinger']);
1668 if (empty($nickname)) {
1669 $nickname = common_nicknamize($object->title);
1675 protected static function nicknameFromURI($uri)
1677 if (preg_match('/(\w+):/', $uri, $matches)) {
1678 $protocol = $matches[1];
1683 switch ($protocol) {
1686 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1687 return common_canonical_nickname($matches[1]);
1691 return common_url_to_nickname($uri);
1699 * Look up, and if necessary create, an Ostatus_profile for the remote
1700 * entity with the given webfinger address.
1701 * This should never return null -- you will either get an object or
1702 * an exception will be thrown.
1704 * @param string $addr webfinger address
1705 * @return Ostatus_profile
1706 * @throws Exception on error conditions
1707 * @throws OStatusShadowException if this reference would obscure a local user/group
1709 public static function ensureWebfinger($addr)
1711 // First, try the cache
1713 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1715 if ($uri !== false) {
1716 if (is_null($uri)) {
1717 // Negative cache entry
1718 // TRANS: Exception.
1719 throw new Exception(_m('Not a valid webfinger address.'));
1721 $oprofile = Ostatus_profile::getKV('uri', $uri);
1722 if ($oprofile instanceof Ostatus_profile) {
1727 // Try looking it up
1728 $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1730 if ($oprofile instanceof Ostatus_profile) {
1731 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1735 // Now, try some discovery
1737 $disco = new Discovery();
1740 $xrd = $disco->lookup($addr);
1741 } catch (Exception $e) {
1742 // Save negative cache entry so we don't waste time looking it up again.
1743 // @todo FIXME: Distinguish temporary failures?
1744 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1745 // TRANS: Exception.
1746 throw new Exception(_m('Not a valid webfinger address.'));
1749 $hints = array('webfinger' => $addr);
1751 $dhints = DiscoveryHints::fromXRD($xrd);
1753 $hints = array_merge($hints, $dhints);
1755 // If there's an Hcard, let's grab its info
1756 if (array_key_exists('hcard', $hints)) {
1757 if (!array_key_exists('profileurl', $hints) ||
1758 $hints['hcard'] != $hints['profileurl']) {
1759 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1760 $hints = array_merge($hcardHints, $hints);
1764 // If we got a feed URL, try that
1766 if (array_key_exists('feedurl', $hints)) {
1767 $feedUrl = $hints['feedurl'];
1769 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1770 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1771 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1773 } catch (Exception $e) {
1774 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1779 // If we got a profile page, try that!
1781 if (array_key_exists('profileurl', $hints)) {
1782 $profileUrl = $hints['profileurl'];
1784 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1785 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1786 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1788 } catch (OStatusShadowException $e) {
1789 // We've ended up with a remote reference to a local user or group.
1790 // @todo FIXME: Ideally we should be able to say who it was so we can
1791 // go back and refer to it the regular way
1793 } catch (Exception $e) {
1794 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1797 // @todo FIXME: This means an error discovering from profile page
1798 // may give us a corrupt entry using the webfinger URI, which
1799 // will obscure the correct page-keyed profile later on.
1806 if (array_key_exists('salmon', $hints)) {
1807 $salmonEndpoint = $hints['salmon'];
1809 // An account URL, a salmon endpoint, and a dream? Not much to go
1810 // on, but let's give it a try
1812 $uri = 'acct:'.$addr;
1814 $profile = new Profile();
1816 $profile->nickname = self::nicknameFromUri($uri);
1817 $profile->created = common_sql_now();
1819 if (!is_null($profileUrl)) {
1820 $profile->profileurl = $profileUrl;
1823 $profile_id = $profile->insert();
1825 if ($profile_id === false) {
1826 common_log_db_error($profile, 'INSERT', __FILE__);
1827 // TRANS: Exception. %s is a webfinger address.
1828 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1831 $oprofile = new Ostatus_profile();
1833 $oprofile->uri = $uri;
1834 $oprofile->salmonuri = $salmonEndpoint;
1835 $oprofile->profile_id = $profile_id;
1836 $oprofile->created = common_sql_now();
1838 if (!is_null($feedUrl)) {
1839 $oprofile->feeduri = $feedUrl;
1842 $result = $oprofile->insert();
1844 if ($result === false) {
1846 common_log_db_error($oprofile, 'INSERT', __FILE__);
1847 // TRANS: Exception. %s is a webfinger address.
1848 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1851 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1855 // TRANS: Exception. %s is a webfinger address.
1856 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1860 * Store the full-length scrubbed HTML of a remote notice to an attachment
1861 * file on our server. We'll link to this at the end of the cropped version.
1863 * @param string $title plaintext for HTML page's title
1864 * @param string $rendered HTML fragment for HTML page's body
1867 function saveHTMLFile($title, $rendered)
1869 $final = sprintf("<!DOCTYPE html>\n" .
1871 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1872 '<title>%s</title>' .
1874 '<body>%s</body></html>',
1875 htmlspecialchars($title),
1878 $filename = File::filename($this->localProfile(),
1879 'ostatus', // ignored?
1882 $filepath = File::path($filename);
1883 $fileurl = File::url($filename);
1885 file_put_contents($filepath, $final);
1889 $file->filename = $filename;
1890 $file->urlhash = File::hashurl($fileurl);
1891 $file->url = $fileurl;
1892 $file->size = filesize($filepath);
1893 $file->date = time();
1894 $file->mimetype = 'text/html';
1896 $file_id = $file->insert();
1898 if ($file_id === false) {
1899 common_log_db_error($file, "INSERT", __FILE__);
1900 // TRANS: Server exception.
1901 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1907 static function ensureProfileURI($uri)
1911 // First, try to query it
1913 $oprofile = Ostatus_profile::getKV('uri', $uri);
1915 if ($oprofile instanceof Ostatus_profile) {
1919 // If unfound, do discovery stuff
1920 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1921 $protocol = $match[1];
1922 switch ($protocol) {
1925 $oprofile = self::ensureProfileURL($uri);
1930 $oprofile = self::ensureWebfinger($rest);
1933 // TRANS: Server exception.
1934 // TRANS: %1$s is a protocol, %2$s is a URI.
1935 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1940 // TRANS: Server exception. %s is a URI.
1941 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1947 public function checkAuthorship(Activity $activity)
1949 if ($this->isGroup() || $this->isPeopletag()) {
1950 // A group or propletag feed will contain posts from multiple authors.
1951 $oprofile = self::ensureActorProfile($activity);
1952 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1953 // Groups can't post notices in StatusNet.
1954 common_log(LOG_WARNING,
1955 "OStatus: skipping post with group listed ".
1956 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1957 throw new ServerException('Activity author is a non-actor');
1960 $actor = $activity->actor;
1962 if (empty($actor)) {
1963 // OK here! assume the default
1964 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1965 $this->updateFromActivityObject($actor);
1966 } else if ($actor->id) {
1967 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1968 // This isn't what we expect from mainline OStatus person feeds!
1969 // Group feeds go down another path, with different validation...
1970 // Most likely this is a plain ol' blog feed of some kind which
1971 // doesn't match our expectations. We'll take the entry, but ignore
1972 // the <author> info.
1973 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1975 // Plain <author> without ActivityStreams actor info.
1976 // We'll just ignore this info for now and save the update under the feed's identity.
1982 return $oprofile->localProfile();
1987 * Exception indicating we've got a remote reference to a local user,
1988 * not a remote user!
1990 * If we can ue a local profile after all, it's available as $e->profile.
1992 class OStatusShadowException extends Exception
1997 * @param Profile $profile
1998 * @param string $message
2000 function __construct($profile, $message) {
2001 $this->profile = $profile;
2002 parent::__construct($message);