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 * @param Profile $actor Acting profile
376 * @return boolean success
378 public function notifyDeferred($entry, Profile $actor)
380 if ($this->salmonuri) {
381 $data = array('salmonuri' => $this->salmonuri,
382 'entry' => $this->notifyPrepXml($entry),
383 'actor' => $actor->id);
385 $qm = QueueManager::get();
386 return $qm->enqueue($data, 'salmon');
392 protected function notifyPrepXml($entry)
394 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
395 if (is_string($entry)) {
397 } else if ($entry instanceof Activity) {
398 return $preamble . $entry->asString(true);
399 } else if ($entry instanceof Notice) {
400 return $preamble . $entry->asAtomEntry(true, true);
402 // TRANS: Server exception.
403 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
407 function getBestName()
409 if ($this->isGroup()) {
410 return $this->localGroup()->getBestName();
411 } else if ($this->isPeopletag()) {
412 return $this->localPeopletag()->getBestName();
414 return $this->localProfile()->getBestName();
419 * Read and post notices for updates from the feed.
420 * Currently assumes that all items in the feed are new,
421 * coming from a PuSH hub.
423 * @param DOMDocument $doc
424 * @param string $source identifier ("push")
426 public function processFeed(DOMDocument $doc, $source)
428 $feed = $doc->documentElement;
430 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
431 $this->processAtomFeed($feed, $source);
432 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
433 $this->processRssFeed($feed, $source);
436 throw new Exception(_m('Unknown feed format.'));
440 public function processAtomFeed(DOMElement $feed, $source)
442 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
443 if ($entries->length == 0) {
444 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
448 for ($i = 0; $i < $entries->length; $i++) {
449 $entry = $entries->item($i);
450 $this->processEntry($entry, $feed, $source);
454 public function processRssFeed(DOMElement $rss, $source)
456 $channels = $rss->getElementsByTagName('channel');
458 if ($channels->length == 0) {
460 throw new Exception(_m('RSS feed without a channel.'));
461 } else if ($channels->length > 1) {
462 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
465 $channel = $channels->item(0);
467 $items = $channel->getElementsByTagName('item');
469 for ($i = 0; $i < $items->length; $i++) {
470 $item = $items->item($i);
471 $this->processEntry($item, $channel, $source);
476 * Process a posted entry from this feed source.
478 * @param DOMElement $entry
479 * @param DOMElement $feed for context
480 * @param string $source identifier ("push" or "salmon")
482 * @return Notice Notice representing the new (or existing) activity
484 public function processEntry(DOMElement $entry, DOMElement $feed, $source)
486 $activity = new Activity($entry, $feed);
487 return $this->processActivity($activity, $source);
490 // TODO: Make this throw an exception
491 public function processActivity(Activity $activity, $source)
495 // The "WithProfile" events were added later.
497 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
498 Event::handle('StartHandleFeedEntry', array($activity))) {
500 switch ($activity->verb) {
501 case ActivityVerb::POST:
502 // @todo process all activity objects
503 switch ($activity->objects[0]->type) {
504 case ActivityObject::ARTICLE:
505 case ActivityObject::BLOGENTRY:
506 case ActivityObject::NOTE:
507 case ActivityObject::STATUS:
508 case ActivityObject::COMMENT:
510 $notice = $this->processPost($activity, $source);
513 // TRANS: Client exception.
514 throw new ClientException(_m('Cannot handle that kind of post.'));
518 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
521 Event::handle('EndHandleFeedEntry', array($activity));
522 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
529 * Process an incoming post activity from this remote feed.
530 * @param Activity $activity
531 * @param string $method 'push' or 'salmon'
532 * @return mixed saved Notice or false
533 * @todo FIXME: Break up this function, it's getting nasty long
535 public function processPost(Activity $activity, $method)
539 $profile = ActivityUtils::checkAuthorship($activity, $this->localProfile());
541 // It's not always an ActivityObject::NOTE, but... let's just say it is.
543 $note = $activity->objects[0];
545 // The id URI will be used as a unique identifier for the notice,
546 // protecting against duplicate saves. It isn't required to be a URL;
547 // tag: URIs for instance are found in Google Buzz feeds.
548 $sourceUri = $note->id;
549 $dupe = Notice::getKV('uri', $sourceUri);
550 if ($dupe instanceof Notice) {
551 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
555 // We'll also want to save a web link to the original notice, if provided.
558 $sourceUrl = $note->link;
559 } else if ($activity->link) {
560 $sourceUrl = $activity->link;
561 } else if (preg_match('!^https?://!', $note->id)) {
562 $sourceUrl = $note->id;
565 // Use summary as fallback for content
567 if (!empty($note->content)) {
568 $sourceContent = $note->content;
569 } else if (!empty($note->summary)) {
570 $sourceContent = $note->summary;
571 } else if (!empty($note->title)) {
572 $sourceContent = $note->title;
574 // @todo FIXME: Fetch from $sourceUrl?
575 // TRANS: Client exception. %s is a source URI.
576 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
579 // Get (safe!) HTML and text versions of the content
581 $rendered = common_purify($sourceContent);
582 $content = common_strip_html($rendered);
584 $shortened = common_shorten_links($content);
586 // If it's too long, try using the summary, and make the
587 // HTML an attachment.
591 if (Notice::contentTooLong($shortened)) {
592 $attachment = $this->saveHTMLFile($note->title, $rendered);
593 $summary = common_strip_html($note->summary);
594 if (empty($summary)) {
597 $shortSummary = common_shorten_links($summary);
598 if (Notice::contentTooLong($shortSummary)) {
599 $url = common_shorten_url($sourceUrl);
600 $shortSummary = substr($shortSummary,
602 Notice::maxContent() - (mb_strlen($url) + 2));
603 $content = $shortSummary . ' ' . $url;
605 // We mark up the attachment link specially for the HTML output
606 // so we can fold-out the full version inline.
608 // @todo FIXME i18n: This tooltip will be saved with the site's default language
609 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
610 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
611 $showMoreText = _m('Show more');
612 $attachUrl = common_local_url('attachment',
613 array('attachment' => $attachment->id));
614 $rendered = common_render_text($shortSummary) .
615 '<a href="' . htmlspecialchars($attachUrl) .'"'.
616 ' class="attachment more"' .
617 ' title="'. htmlspecialchars($showMoreText) . '">' .
623 $options = array('is_local' => Notice::REMOTE,
626 'rendered' => $rendered,
627 'replies' => array(),
629 'peopletags' => array(),
633 // Check for optional attributes...
635 if (!empty($activity->time)) {
636 $options['created'] = common_sql_date($activity->time);
639 if ($activity->context) {
640 // TODO: context->attention
641 list($options['groups'], $options['replies'])
642 = self::filterAttention($profile, $activity->context->attention);
644 // Maintain direct reply associations
645 // @todo FIXME: What about conversation ID?
646 if (!empty($activity->context->replyToID)) {
647 $orig = Notice::getKV('uri', $activity->context->replyToID);
648 if ($orig instanceof Notice) {
649 $options['reply_to'] = $orig->id;
652 if (!empty($activity->context->conversation)) {
653 // we store the URI here, Notice class can look it up later
654 $options['conversation'] = $activity->context->conversation;
657 $location = $activity->context->location;
659 $options['lat'] = $location->lat;
660 $options['lon'] = $location->lon;
661 if ($location->location_id) {
662 $options['location_ns'] = $location->location_ns;
663 $options['location_id'] = $location->location_id;
668 if ($this->isPeopletag()) {
669 $options['peopletags'][] = $this->localPeopletag();
672 // Atom categories <-> hashtags
673 foreach ($activity->categories as $cat) {
675 $term = common_canonical_tag($cat->term);
677 $options['tags'][] = $term;
682 // Atom enclosures -> attachment URLs
683 foreach ($activity->enclosures as $href) {
684 // @todo FIXME: Save these locally or....?
685 $options['urls'][] = $href;
689 $saved = Notice::saveNew($profile->id,
693 if ($saved instanceof Notice) {
694 Ostatus_source::saveNew($saved, $this, $method);
695 if (!empty($attachment)) {
696 File_to_post::processNew($attachment->id, $saved->id);
699 } catch (Exception $e) {
700 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
703 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
708 * Filters a list of recipient ID URIs to just those for local delivery.
709 * @param Profile local profile of sender
710 * @param array in/out &$attention_uris set of URIs, will be pruned on output
711 * @return array of group IDs
713 static public function filterAttention(Profile $sender, array $attention)
715 common_debug("Original reply recipients: " . implode(', ', array_keys($attention)));
718 foreach ($attention as $recipient=>$type) {
719 // Is the recipient a local user?
720 $user = User::getKV('uri', $recipient);
721 if ($user instanceof User) {
722 // @todo FIXME: Sender verification, spam etc?
723 $replies[] = $recipient;
727 // Is the recipient a local group?
728 // TODO: $group = User_group::getKV('uri', $recipient);
729 $id = OStatusPlugin::localGroupFromUrl($recipient);
731 $group = User_group::getKV('id', $id);
732 if ($group instanceof User_group) {
733 // Deliver to all members of this local group if allowed.
734 if ($sender->isMember($group)) {
735 $groups[] = $group->id;
737 common_debug(sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
741 common_debug("Skipping reply to bogus group $recipient");
745 // Is the recipient a remote user or group?
747 $oprofile = self::ensureProfileURI($recipient);
748 if ($oprofile->isGroup()) {
749 // Deliver to local members of this remote group.
750 // @todo FIXME: Sender verification?
751 $groups[] = $oprofile->group_id;
753 // may be canonicalized or something
754 $replies[] = $oprofile->getUri();
757 } catch (Exception $e) {
758 // Neither a recognizable local nor remote user!
759 common_debug("Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
763 common_debug("Local reply recipients: " . implode(', ', $replies));
764 common_debug("Local group recipients: " . implode(', ', $groups));
765 return array($groups, $replies);
769 * Look up and if necessary create an Ostatus_profile for the remote entity
770 * with the given profile page URL. This should never return null -- you
771 * will either get an object or an exception will be thrown.
773 * @param string $profile_url
774 * @return Ostatus_profile
775 * @throws Exception on various error conditions
776 * @throws OStatusShadowException if this reference would obscure a local user/group
778 public static function ensureProfileURL($profile_url, array $hints=array())
780 $oprofile = self::getFromProfileURL($profile_url);
782 if ($oprofile instanceof Ostatus_profile) {
786 $hints['profileurl'] = $profile_url;
791 $client = new HTTPClient();
792 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
793 $response = $client->get($profile_url);
795 if (!$response->isOk()) {
796 // TRANS: Exception. %s is a profile URL.
797 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
800 // Check if we have a non-canonical URL
802 $finalUrl = $response->getUrl();
804 if ($finalUrl != $profile_url) {
806 $hints['profileurl'] = $finalUrl;
808 $oprofile = self::getFromProfileURL($finalUrl);
810 if ($oprofile instanceof Ostatus_profile) {
815 // Try to get some hCard data
817 $body = $response->getBody();
819 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
821 if (!empty($hcardHints)) {
822 $hints = array_merge($hints, $hcardHints);
825 // Check if they've got an LRDD header
827 $lrdd = LinkHeader::getLink($response, 'lrdd');
829 $xrd = new XML_XRD();
830 $xrd->loadFile($lrdd);
831 $xrdHints = DiscoveryHints::fromXRD($xrd);
832 $hints = array_merge($hints, $xrdHints);
833 } catch (Exception $e) {
834 // No hints available from XRD
837 // If discovery found a feedurl (probably from LRDD), use it.
839 if (array_key_exists('feedurl', $hints)) {
840 return self::ensureFeedURL($hints['feedurl'], $hints);
843 // Get the feed URL from HTML
845 $discover = new FeedDiscovery();
847 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
849 if (!empty($feedurl)) {
850 $hints['feedurl'] = $feedurl;
851 return self::ensureFeedURL($feedurl, $hints);
854 // TRANS: Exception. %s is a URL.
855 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
859 * Look up the Ostatus_profile, if present, for a remote entity with the
860 * given profile page URL. Will return null for both unknown and invalid
863 * @return mixed Ostatus_profile or null
864 * @throws OStatusShadowException for local profiles
866 static function getFromProfileURL($profile_url)
868 $profile = Profile::getKV('profileurl', $profile_url);
869 if (!$profile instanceof Profile) {
874 $oprofile = self::getFromProfile($profile);
875 // We found the profile, return it!
877 } catch (NoResultException $e) {
878 // Could not find an OStatus profile, is it instead a local user?
879 $user = User::getKV('id', $profile->id);
880 if ($user instanceof User) {
881 // @todo i18n FIXME: use sprintf and add i18n (?)
882 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
886 // Continue discovery; it's a remote profile
887 // for OMB or some other protocol, may also
893 static function getFromProfile(Profile $profile)
895 $oprofile = new Ostatus_profile();
896 $oprofile->profile_id = $profile->id;
897 if (!$oprofile->find(true)) {
898 throw new NoResultException($oprofile);
904 * Look up and if necessary create an Ostatus_profile for remote entity
905 * with the given update feed. This should never return null -- you will
906 * either get an object or an exception will be thrown.
908 * @return Ostatus_profile
911 public static function ensureFeedURL($feed_url, array $hints=array())
913 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
914 if ($oprofile instanceof Ostatus_profile) {
918 $discover = new FeedDiscovery();
920 $feeduri = $discover->discoverFromFeedURL($feed_url);
921 $hints['feedurl'] = $feeduri;
923 $huburi = $discover->getHubLink();
924 $hints['hub'] = $huburi;
926 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
927 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
928 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
929 $hints['salmon'] = $salmonuri;
931 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
932 // We can only deal with folks with a PuSH hub
933 // unless we have something similar available locally.
934 throw new FeedSubNoHubException();
937 $feedEl = $discover->root;
939 if ($feedEl->tagName == 'feed') {
940 return self::ensureAtomFeed($feedEl, $hints);
941 } else if ($feedEl->tagName == 'channel') {
942 return self::ensureRssChannel($feedEl, $hints);
944 throw new FeedSubBadXmlException($feeduri);
949 * Look up and, if necessary, create an Ostatus_profile for the remote
950 * profile with the given Atom feed - actually loaded from the feed.
951 * This should never return null -- you will either get an object or
952 * an exception will be thrown.
954 * @param DOMElement $feedEl root element of a loaded Atom feed
955 * @param array $hints additional discovery information passed from higher levels
956 * @todo FIXME: Should this be marked public?
957 * @return Ostatus_profile
960 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
962 $author = ActivityUtils::getFeedAuthor($feedEl);
964 if (empty($author)) {
965 // XXX: make some educated guesses here
966 // TRANS: Feed sub exception.
967 throw new FeedSubException(_m('Cannot find enough profile '.
968 'information to make a feed.'));
971 return self::ensureActivityObjectProfile($author, $hints);
975 * Look up and, if necessary, create an Ostatus_profile for the remote
976 * profile with the given RSS feed - actually loaded from the feed.
977 * This should never return null -- you will either get an object or
978 * an exception will be thrown.
980 * @param DOMElement $feedEl root element of a loaded RSS feed
981 * @param array $hints additional discovery information passed from higher levels
982 * @todo FIXME: Should this be marked public?
983 * @return Ostatus_profile
986 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
988 // Special-case for Posterous. They have some nice metadata in their
989 // posterous:author elements. We should use them instead of the channel.
991 $items = $feedEl->getElementsByTagName('item');
993 if ($items->length > 0) {
994 $item = $items->item(0);
995 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
996 if (!empty($authorEl)) {
997 $obj = ActivityObject::fromPosterousAuthor($authorEl);
998 // Posterous has multiple authors per feed, and multiple feeds
999 // per author. We check if this is the "main" feed for this author.
1000 if (array_key_exists('profileurl', $hints) &&
1001 !empty($obj->poco) &&
1002 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1003 return self::ensureActivityObjectProfile($obj, $hints);
1008 // @todo FIXME: We should check whether this feed has elements
1009 // with different <author> or <dc:creator> elements, and... I dunno.
1010 // Do something about that.
1012 $obj = ActivityObject::fromRssChannel($feedEl);
1014 return self::ensureActivityObjectProfile($obj, $hints);
1018 * Download and update given avatar image
1020 * @param string $url
1021 * @return Avatar The Avatar we have on disk. (seldom used)
1022 * @throws Exception in various failure cases
1024 public function updateAvatar($url, $force=false)
1027 // If avatar URL differs: update. If URLs were identical but we're forced: update.
1028 if ($url == $this->avatar && !$force) {
1029 // If there's no locally stored avatar, throw an exception and continue fetching below.
1030 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
1033 } catch (NoAvatarException $e) {
1034 // No avatar available, let's fetch it.
1037 if (!common_valid_http_url($url)) {
1038 // TRANS: Server exception. %s is a URL.
1039 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1042 $self = $this->localProfile();
1044 // @todo FIXME: This should be better encapsulated
1045 // ripped from oauthstore.php (for old OMB client)
1046 $temp_filename = tempnam(common_get_temp_dir(), 'listener_avatar');
1048 $imgData = HTTPClient::quickGet($url);
1049 // Make sure it's at least an image file. ImageFile can do the rest.
1050 if (false === getimagesizefromstring($imgData)) {
1051 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
1053 file_put_contents($temp_filename, $imgData);
1054 unset($imgData); // No need to carry this in memory.
1056 if ($this->isGroup()) {
1057 $id = $this->group_id;
1059 $id = $this->profile_id;
1061 $imagefile = new ImageFile(null, $temp_filename);
1062 $filename = Avatar::filename($id,
1063 image_type_to_extension($imagefile->type),
1065 common_timestamp());
1066 rename($temp_filename, Avatar::path($filename));
1067 } catch (Exception $e) {
1068 unlink($temp_filename);
1071 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1072 // keep from accidentally saving images from command-line (queues)
1073 // that can't be read from web server, which causes hard-to-notice
1074 // problems later on:
1076 // http://status.net/open-source/issues/2663
1077 chmod(Avatar::path($filename), 0644);
1079 $self->setOriginal($filename);
1081 $orig = clone($this);
1082 $this->avatar = $url;
1083 $this->update($orig);
1085 return Avatar::getUploaded($self);
1089 * Pull avatar URL from ActivityObject or profile hints
1091 * @param ActivityObject $object
1092 * @param array $hints
1093 * @return mixed URL string or false
1095 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
1097 if ($object->avatarLinks) {
1099 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1100 foreach ($object->avatarLinks as $avatar) {
1101 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1106 if (!$best || $avatar->width > $best->width) {
1111 } else if (array_key_exists('avatar', $hints)) {
1112 return $hints['avatar'];
1118 * Get an appropriate avatar image source URL, if available.
1120 * @param ActivityObject $actor
1121 * @param DOMElement $feed
1124 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
1128 if ($actor->avatar) {
1129 $url = trim($actor->avatar);
1132 // Check <atom:logo> and <atom:icon> on the feed
1133 $els = $feed->childNodes();
1134 if ($els && $els->length) {
1135 for ($i = 0; $i < $els->length; $i++) {
1136 $el = $els->item($i);
1137 if ($el->namespaceURI == Activity::ATOM) {
1138 if (empty($url) && $el->localName == 'logo') {
1139 $url = trim($el->textContent);
1142 if (empty($icon) && $el->localName == 'icon') {
1143 // Use as a fallback
1144 $icon = trim($el->textContent);
1149 if ($icon && !$url) {
1154 $opts = array('allowed_schemes' => array('http', 'https'));
1155 if (common_valid_http_url($url)) {
1160 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1164 * Fetch, or build if necessary, an Ostatus_profile for the actor
1165 * in a given Activity Streams activity.
1166 * This should never return null -- you will either get an object or
1167 * an exception will be thrown.
1169 * @param Activity $activity
1170 * @param string $feeduri if we already know the canonical feed URI!
1171 * @param string $salmonuri if we already know the salmon return channel URI
1172 * @return Ostatus_profile
1175 public static function ensureActorProfile(Activity $activity, array $hints=array())
1177 return self::ensureActivityObjectProfile($activity->actor, $hints);
1181 * Fetch, or build if necessary, an Ostatus_profile for the profile
1182 * in a given Activity Streams object (can be subject, actor, or object).
1183 * This should never return null -- you will either get an object or
1184 * an exception will be thrown.
1186 * @param ActivityObject $object
1187 * @param array $hints additional discovery information passed from higher levels
1188 * @return Ostatus_profile
1191 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1193 $profile = self::getActivityObjectProfile($object);
1194 if ($profile instanceof Ostatus_profile) {
1195 $profile->updateFromActivityObject($object, $hints);
1197 $profile = self::createActivityObjectProfile($object, $hints);
1203 * @param Activity $activity
1204 * @return mixed matching Ostatus_profile or false if none known
1205 * @throws ServerException if feed info invalid
1207 public static function getActorProfile(Activity $activity)
1209 return self::getActivityObjectProfile($activity->actor);
1213 * @param ActivityObject $activity
1214 * @return mixed matching Ostatus_profile or false if none known
1215 * @throws ServerException if feed info invalid
1217 protected static function getActivityObjectProfile(ActivityObject $object)
1219 $uri = self::getActivityObjectProfileURI($object);
1220 return Ostatus_profile::getKV('uri', $uri);
1224 * Get the identifier URI for the remote entity described
1225 * by this ActivityObject. This URI is *not* guaranteed to be
1226 * a resolvable HTTP/HTTPS URL.
1228 * @param ActivityObject $object
1230 * @throws ServerException if feed info invalid
1232 protected static function getActivityObjectProfileURI(ActivityObject $object)
1235 if (ActivityUtils::validateUri($object->id)) {
1240 // If the id is missing or invalid (we've seen feeds mistakenly listing
1241 // things like local usernames in that field) then we'll use the profile
1242 // page link, if valid.
1243 if ($object->link && common_valid_http_url($object->link)) {
1244 return $object->link;
1246 // TRANS: Server exception.
1247 throw new ServerException(_m('No author ID URI found.'));
1251 * @todo FIXME: Validate stuff somewhere.
1255 * Create local ostatus_profile and profile/user_group entries for
1256 * the provided remote user or group.
1257 * This should never return null -- you will either get an object or
1258 * an exception will be thrown.
1260 * @param ActivityObject $object
1261 * @param array $hints
1263 * @return Ostatus_profile
1265 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1267 $homeuri = $object->id;
1271 common_debug(__METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1272 // TRANS: Exception.
1273 throw new Exception(_m('No profile URI.'));
1276 $user = User::getKV('uri', $homeuri);
1277 if ($user instanceof User) {
1278 // TRANS: Exception.
1279 throw new Exception(_m('Local user cannot be referenced as remote.'));
1282 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1283 // TRANS: Exception.
1284 throw new Exception(_m('Local group cannot be referenced as remote.'));
1287 $ptag = Profile_list::getKV('uri', $homeuri);
1288 if ($ptag instanceof Profile_list) {
1289 $local_user = User::getKV('id', $ptag->tagger);
1290 if ($local_user instanceof User) {
1291 // TRANS: Exception.
1292 throw new Exception(_m('Local list cannot be referenced as remote.'));
1296 if (array_key_exists('feedurl', $hints)) {
1297 $feeduri = $hints['feedurl'];
1299 $discover = new FeedDiscovery();
1300 $feeduri = $discover->discoverFromURL($homeuri);
1303 if (array_key_exists('salmon', $hints)) {
1304 $salmonuri = $hints['salmon'];
1307 $discover = new FeedDiscovery();
1308 $discover->discoverFromFeedURL($hints['feedurl']);
1310 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1311 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1312 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1315 if (array_key_exists('hub', $hints)) {
1316 $huburi = $hints['hub'];
1319 $discover = new FeedDiscovery();
1320 $discover->discoverFromFeedURL($hints['feedurl']);
1322 $huburi = $discover->getHubLink();
1325 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1326 // We can only deal with folks with a PuSH hub
1327 throw new FeedSubNoHubException();
1330 $oprofile = new Ostatus_profile();
1332 $oprofile->uri = $homeuri;
1333 $oprofile->feeduri = $feeduri;
1334 $oprofile->salmonuri = $salmonuri;
1336 $oprofile->created = common_sql_now();
1337 $oprofile->modified = common_sql_now();
1339 if ($object->type == ActivityObject::PERSON) {
1340 $profile = new Profile();
1341 $profile->created = common_sql_now();
1342 self::updateProfile($profile, $object, $hints);
1344 $oprofile->profile_id = $profile->insert();
1345 if ($oprofile->profile_id === false) {
1346 // TRANS: Server exception.
1347 throw new ServerException(_m('Cannot save local profile.'));
1349 } else if ($object->type == ActivityObject::GROUP) {
1350 $profile = new Profile();
1351 $profile->query('BEGIN');
1353 $group = new User_group();
1354 $group->uri = $homeuri;
1355 $group->created = common_sql_now();
1356 self::updateGroup($group, $object, $hints);
1358 // TODO: We should do this directly in User_group->insert()!
1359 // currently it's duplicated in User_group->update()
1360 // AND User_group->register()!!!
1361 $fields = array(/*group field => profile field*/
1362 'nickname' => 'nickname',
1363 'fullname' => 'fullname',
1364 'mainpage' => 'profileurl',
1365 'homepage' => 'homepage',
1366 'description' => 'bio',
1367 'location' => 'location',
1368 'created' => 'created',
1369 'modified' => 'modified',
1371 foreach ($fields as $gf=>$pf) {
1372 $profile->$pf = $group->$gf;
1374 $profile_id = $profile->insert();
1375 if ($profile_id === false) {
1376 $profile->query('ROLLBACK');
1377 throw new ServerException(_('Profile insertion failed.'));
1380 $group->profile_id = $profile_id;
1382 $oprofile->group_id = $group->insert();
1383 if ($oprofile->group_id === false) {
1384 $profile->query('ROLLBACK');
1385 // TRANS: Server exception.
1386 throw new ServerException(_m('Cannot save local profile.'));
1389 $profile->query('COMMIT');
1390 } else if ($object->type == ActivityObject::_LIST) {
1391 $ptag = new Profile_list();
1392 $ptag->uri = $homeuri;
1393 $ptag->created = common_sql_now();
1394 self::updatePeopletag($ptag, $object, $hints);
1396 $oprofile->peopletag_id = $ptag->insert();
1397 if ($oprofile->peopletag_id === false) {
1398 // TRANS: Server exception.
1399 throw new ServerException(_m('Cannot save local list.'));
1403 $ok = $oprofile->insert();
1405 if ($ok === false) {
1406 // TRANS: Server exception.
1407 throw new ServerException(_m('Cannot save OStatus profile.'));
1410 $avatar = self::getActivityObjectAvatar($object, $hints);
1414 $oprofile->updateAvatar($avatar);
1415 } catch (Exception $ex) {
1416 // Profile is saved, but Avatar is messed up. We're
1417 // just going to continue.
1418 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1426 * Save any updated profile information to our local copy.
1427 * @param ActivityObject $object
1428 * @param array $hints
1430 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1432 if ($this->isGroup()) {
1433 $group = $this->localGroup();
1434 self::updateGroup($group, $object, $hints);
1435 } else if ($this->isPeopletag()) {
1436 $ptag = $this->localPeopletag();
1437 self::updatePeopletag($ptag, $object, $hints);
1439 $profile = $this->localProfile();
1440 self::updateProfile($profile, $object, $hints);
1443 $avatar = self::getActivityObjectAvatar($object, $hints);
1444 if ($avatar && !isset($ptag)) {
1446 $this->updateAvatar($avatar);
1447 } catch (Exception $ex) {
1448 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1453 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1455 $orig = clone($profile);
1457 // Existing nickname is better than nothing.
1459 if (!array_key_exists('nickname', $hints)) {
1460 $hints['nickname'] = $profile->nickname;
1463 $nickname = self::getActivityObjectNickname($object, $hints);
1465 if (!empty($nickname)) {
1466 $profile->nickname = $nickname;
1469 if (!empty($object->title)) {
1470 $profile->fullname = $object->title;
1471 } else if (array_key_exists('fullname', $hints)) {
1472 $profile->fullname = $hints['fullname'];
1475 if (!empty($object->link)) {
1476 $profile->profileurl = $object->link;
1477 } else if (array_key_exists('profileurl', $hints)) {
1478 $profile->profileurl = $hints['profileurl'];
1479 } else if (common_valid_http_url($object->id)) {
1480 $profile->profileurl = $object->id;
1483 $bio = self::getActivityObjectBio($object, $hints);
1486 $profile->bio = $bio;
1489 $location = self::getActivityObjectLocation($object, $hints);
1491 if (!empty($location)) {
1492 $profile->location = $location;
1495 $homepage = self::getActivityObjectHomepage($object, $hints);
1497 if (!empty($homepage)) {
1498 $profile->homepage = $homepage;
1501 if (!empty($object->geopoint)) {
1502 $location = ActivityContext::locationFromPoint($object->geopoint);
1503 if (!empty($location)) {
1504 $profile->lat = $location->lat;
1505 $profile->lon = $location->lon;
1509 // @todo FIXME: tags/categories
1510 // @todo tags from categories
1513 common_debug("Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1514 $profile->update($orig);
1518 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1520 $orig = clone($group);
1522 $group->nickname = self::getActivityObjectNickname($object, $hints);
1523 $group->fullname = $object->title;
1525 if (!empty($object->link)) {
1526 $group->mainpage = $object->link;
1527 } else if (array_key_exists('profileurl', $hints)) {
1528 $group->mainpage = $hints['profileurl'];
1531 // @todo tags from categories
1532 $group->description = self::getActivityObjectBio($object, $hints);
1533 $group->location = self::getActivityObjectLocation($object, $hints);
1534 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1536 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1537 common_debug("Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1538 $group->update($orig);
1542 protected static function updatePeopletag(Peopletag $tag, ActivityObject $object, array $hints=array()) {
1543 $orig = clone($tag);
1545 $tag->tag = $object->title;
1547 if (!empty($object->link)) {
1548 $tag->mainpage = $object->link;
1549 } else if (array_key_exists('profileurl', $hints)) {
1550 $tag->mainpage = $hints['profileurl'];
1553 $tag->description = $object->summary;
1554 $tagger = self::ensureActivityObjectProfile($object->owner);
1555 $tag->tagger = $tagger->profile_id;
1558 common_debug("Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1559 $tag->update($orig);
1563 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1566 $poco = $object->poco;
1568 if (!empty($poco)) {
1569 $url = $poco->getPrimaryURL();
1570 if ($url && $url->type == 'homepage') {
1571 $homepage = $url->value;
1575 // @todo Try for a another PoCo URL?
1580 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1584 if (!empty($object->poco) &&
1585 isset($object->poco->address->formatted)) {
1586 $location = $object->poco->address->formatted;
1587 } else if (array_key_exists('location', $hints)) {
1588 $location = $hints['location'];
1591 if (!empty($location)) {
1592 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1593 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1597 // @todo Try to find location some othe way? Via goerss point?
1602 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1606 if (!empty($object->poco)) {
1607 $note = $object->poco->note;
1608 } else if (array_key_exists('bio', $hints)) {
1609 $note = $hints['bio'];
1612 if (!empty($note)) {
1613 if (Profile::bioTooLong($note)) {
1614 // XXX: truncate ok?
1615 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1621 // @todo Try to get bio info some other way?
1626 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1628 if ($object->poco) {
1629 if (!empty($object->poco->preferredUsername)) {
1630 return common_nicknamize($object->poco->preferredUsername);
1634 if (!empty($object->nickname)) {
1635 return common_nicknamize($object->nickname);
1638 if (array_key_exists('nickname', $hints)) {
1639 return $hints['nickname'];
1642 // Try the profile url (like foo.example.com or example.com/user/foo)
1643 if (!empty($object->link)) {
1644 $profileUrl = $object->link;
1645 } else if (!empty($hints['profileurl'])) {
1646 $profileUrl = $hints['profileurl'];
1649 if (!empty($profileUrl)) {
1650 $nickname = self::nicknameFromURI($profileUrl);
1653 // Try the URI (may be a tag:, http:, acct:, ...
1655 if (empty($nickname)) {
1656 $nickname = self::nicknameFromURI($object->id);
1659 // Try a Webfinger if one was passed (way) down
1661 if (empty($nickname)) {
1662 if (array_key_exists('webfinger', $hints)) {
1663 $nickname = self::nicknameFromURI($hints['webfinger']);
1669 if (empty($nickname)) {
1670 $nickname = common_nicknamize($object->title);
1676 protected static function nicknameFromURI($uri)
1678 if (preg_match('/(\w+):/', $uri, $matches)) {
1679 $protocol = $matches[1];
1684 switch ($protocol) {
1687 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1688 return common_canonical_nickname($matches[1]);
1692 return common_url_to_nickname($uri);
1700 * Look up, and if necessary create, an Ostatus_profile for the remote
1701 * entity with the given webfinger address.
1702 * This should never return null -- you will either get an object or
1703 * an exception will be thrown.
1705 * @param string $addr webfinger address
1706 * @return Ostatus_profile
1707 * @throws Exception on error conditions
1708 * @throws OStatusShadowException if this reference would obscure a local user/group
1710 public static function ensureWebfinger($addr)
1712 // First, try the cache
1714 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1716 if ($uri !== false) {
1717 if (is_null($uri)) {
1718 // Negative cache entry
1719 // TRANS: Exception.
1720 throw new Exception(_m('Not a valid webfinger address.'));
1722 $oprofile = Ostatus_profile::getKV('uri', $uri);
1723 if ($oprofile instanceof Ostatus_profile) {
1728 // Try looking it up
1729 $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1731 if ($oprofile instanceof Ostatus_profile) {
1732 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1736 // Now, try some discovery
1738 $disco = new Discovery();
1741 $xrd = $disco->lookup($addr);
1742 } catch (Exception $e) {
1743 // Save negative cache entry so we don't waste time looking it up again.
1744 // @todo FIXME: Distinguish temporary failures?
1745 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1746 // TRANS: Exception.
1747 throw new Exception(_m('Not a valid webfinger address.'));
1750 $hints = array('webfinger' => $addr);
1752 $dhints = DiscoveryHints::fromXRD($xrd);
1754 $hints = array_merge($hints, $dhints);
1756 // If there's an Hcard, let's grab its info
1757 if (array_key_exists('hcard', $hints)) {
1758 if (!array_key_exists('profileurl', $hints) ||
1759 $hints['hcard'] != $hints['profileurl']) {
1760 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1761 $hints = array_merge($hcardHints, $hints);
1765 // If we got a feed URL, try that
1767 if (array_key_exists('feedurl', $hints)) {
1768 $feedUrl = $hints['feedurl'];
1770 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1771 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1772 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1774 } catch (Exception $e) {
1775 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1780 // If we got a profile page, try that!
1782 if (array_key_exists('profileurl', $hints)) {
1783 $profileUrl = $hints['profileurl'];
1785 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1786 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1787 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1789 } catch (OStatusShadowException $e) {
1790 // We've ended up with a remote reference to a local user or group.
1791 // @todo FIXME: Ideally we should be able to say who it was so we can
1792 // go back and refer to it the regular way
1794 } catch (Exception $e) {
1795 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1798 // @todo FIXME: This means an error discovering from profile page
1799 // may give us a corrupt entry using the webfinger URI, which
1800 // will obscure the correct page-keyed profile later on.
1807 if (array_key_exists('salmon', $hints)) {
1808 $salmonEndpoint = $hints['salmon'];
1810 // An account URL, a salmon endpoint, and a dream? Not much to go
1811 // on, but let's give it a try
1813 $uri = 'acct:'.$addr;
1815 $profile = new Profile();
1817 $profile->nickname = self::nicknameFromUri($uri);
1818 $profile->created = common_sql_now();
1820 if (!is_null($profileUrl)) {
1821 $profile->profileurl = $profileUrl;
1824 $profile_id = $profile->insert();
1826 if ($profile_id === false) {
1827 common_log_db_error($profile, 'INSERT', __FILE__);
1828 // TRANS: Exception. %s is a webfinger address.
1829 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1832 $oprofile = new Ostatus_profile();
1834 $oprofile->uri = $uri;
1835 $oprofile->salmonuri = $salmonEndpoint;
1836 $oprofile->profile_id = $profile_id;
1837 $oprofile->created = common_sql_now();
1839 if (!is_null($feedUrl)) {
1840 $oprofile->feeduri = $feedUrl;
1843 $result = $oprofile->insert();
1845 if ($result === false) {
1847 common_log_db_error($oprofile, 'INSERT', __FILE__);
1848 // TRANS: Exception. %s is a webfinger address.
1849 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1852 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1856 // TRANS: Exception. %s is a webfinger address.
1857 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1861 * Store the full-length scrubbed HTML of a remote notice to an attachment
1862 * file on our server. We'll link to this at the end of the cropped version.
1864 * @param string $title plaintext for HTML page's title
1865 * @param string $rendered HTML fragment for HTML page's body
1868 function saveHTMLFile($title, $rendered)
1870 $final = sprintf("<!DOCTYPE html>\n" .
1872 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1873 '<title>%s</title>' .
1875 '<body>%s</body></html>',
1876 htmlspecialchars($title),
1879 $filename = File::filename($this->localProfile(),
1880 'ostatus', // ignored?
1883 $filepath = File::path($filename);
1884 $fileurl = File::url($filename);
1886 file_put_contents($filepath, $final);
1890 $file->filename = $filename;
1891 $file->urlhash = File::hashurl($fileurl);
1892 $file->url = $fileurl;
1893 $file->size = filesize($filepath);
1894 $file->date = time();
1895 $file->mimetype = 'text/html';
1897 $file_id = $file->insert();
1899 if ($file_id === false) {
1900 common_log_db_error($file, "INSERT", __FILE__);
1901 // TRANS: Server exception.
1902 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1908 static function ensureProfileURI($uri)
1912 // First, try to query it
1914 $oprofile = Ostatus_profile::getKV('uri', $uri);
1916 if ($oprofile instanceof Ostatus_profile) {
1920 // If unfound, do discovery stuff
1921 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1922 $protocol = $match[1];
1923 switch ($protocol) {
1926 $oprofile = self::ensureProfileURL($uri);
1931 $oprofile = self::ensureWebfinger($rest);
1934 // TRANS: Server exception.
1935 // TRANS: %1$s is a protocol, %2$s is a URI.
1936 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1941 // TRANS: Server exception. %s is a URI.
1942 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1948 public function checkAuthorship(Activity $activity)
1950 if ($this->isGroup() || $this->isPeopletag()) {
1951 // A group or propletag feed will contain posts from multiple authors.
1952 $oprofile = self::ensureActorProfile($activity);
1953 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1954 // Groups can't post notices in StatusNet.
1955 common_log(LOG_WARNING,
1956 "OStatus: skipping post with group listed ".
1957 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1958 throw new ServerException('Activity author is a non-actor');
1961 $actor = $activity->actor;
1963 if (!$actor instanceof Profile) {
1964 // OK here! assume the default
1965 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1966 $this->updateFromActivityObject($actor);
1967 } else if ($actor->id) {
1968 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1969 // This isn't what we expect from mainline OStatus person feeds!
1970 // Group feeds go down another path, with different validation...
1971 // Most likely this is a plain ol' blog feed of some kind which
1972 // doesn't match our expectations. We'll take the entry, but ignore
1973 // the <author> info.
1974 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1976 // Plain <author> without ActivityStreams actor info.
1977 // We'll just ignore this info for now and save the update under the feed's identity.
1983 return $oprofile->localProfile();
1988 * Exception indicating we've got a remote reference to a local user,
1989 * not a remote user!
1991 * If we can ue a local profile after all, it's available as $e->profile.
1993 class OStatusShadowException extends Exception
1998 * @param Profile $profile
1999 * @param string $message
2001 function __construct($profile, $message) {
2002 $this->profile = $profile;
2003 parent::__construct($message);