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('GNUSOCIAL')) { exit(1); }
23 * @package OStatusPlugin
24 * @author Brion Vibber <brion@status.net>
25 * @maintainer Mikael Nordfeldth <mmn@hethane.se>
27 class Ostatus_profile extends Managed_DataObject
29 public $__table = 'ostatus_profile';
39 public $avatar; // remote URL of the last avatar we saved
45 * Return table definition for Schema setup and DB_DataObject usage.
47 * @return array array of column definitions
49 static function schemaDef()
53 'uri' => array('type' => 'varchar', 'length' => 191, 'not null' => true),
54 'profile_id' => array('type' => 'integer'),
55 'group_id' => array('type' => 'integer'),
56 'peopletag_id' => array('type' => 'integer'),
57 'feeduri' => array('type' => 'varchar', 'length' => 191),
58 'salmonuri' => array('type' => 'varchar', 'length' => 191),
59 'avatar' => array('type' => 'text'),
60 'created' => array('type' => 'datetime', 'not null' => true),
61 'modified' => array('type' => 'datetime', 'not null' => true),
63 'primary key' => array('uri'),
64 'unique keys' => array(
65 'ostatus_profile_profile_id_key' => array('profile_id'),
66 'ostatus_profile_group_id_key' => array('group_id'),
67 'ostatus_profile_peopletag_id_key' => array('peopletag_id'),
68 'ostatus_profile_feeduri_key' => array('feeduri'),
70 'foreign keys' => array(
71 'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
72 'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
73 'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
78 public function getUri()
83 public function getFeedSub()
85 return FeedSub::getByUri($this->feeduri);
88 static function fromProfile(Profile $profile)
90 $oprofile = Ostatus_profile::getKV('profile_id', $profile->getID());
91 if (!$oprofile instanceof Ostatus_profile) {
92 throw new Exception('No Ostatus_profile for Profile ID: '.$profile->getID());
98 * Fetch the locally stored profile for this feed
100 * @throws NoProfileException if it was not found
102 public function localProfile()
104 if ($this->isGroup()) {
105 return $this->localGroup()->getProfile();
108 $profile = Profile::getKV('id', $this->profile_id);
109 if (!$profile instanceof Profile) {
110 throw new NoProfileException($this->profile_id);
116 * Fetch the StatusNet-side profile for this feed
119 public function localGroup()
121 $group = User_group::getKV('id', $this->group_id);
123 if (!$group instanceof User_group) {
124 throw new NoSuchGroupException(array('id'=>$this->group_id));
131 * Fetch the StatusNet-side peopletag for this feed
134 public function localPeopletag()
136 if ($this->peopletag_id) {
137 return Profile_list::getKV('id', $this->peopletag_id);
143 * Returns an ActivityObject describing this remote user or group profile.
144 * Can then be used to generate Atom chunks.
146 * @return ActivityObject
148 function asActivityObject()
150 if ($this->isGroup()) {
151 return ActivityObject::fromGroup($this->localGroup());
152 } else if ($this->isPeopletag()) {
153 return ActivityObject::fromPeopletag($this->localPeopletag());
155 return $this->localProfile()->asActivityObject();
160 * Returns an XML string fragment with profile information as an
161 * Activity Streams noun object with the given element type.
163 * Assumes that 'activity' namespace has been previously defined.
165 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
167 * @param string $element one of 'actor', 'subject', 'object', 'target'
170 function asActivityNoun($element)
172 if ($this->isGroup()) {
173 $noun = ActivityObject::fromGroup($this->localGroup());
174 return $noun->asString('activity:' . $element);
175 } else if ($this->isPeopletag()) {
176 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
177 return $noun->asString('activity:' . $element);
179 $noun = $this->localProfile()->asActivityObject();
180 return $noun->asString('activity:' . $element);
185 * @return boolean true if this is a remote group
189 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
191 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
193 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
194 // TRANS: Server exception. %s is a URI
195 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
197 // TRANS: Server exception. %s is a URI
198 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
202 public function isPerson()
204 return $this->localProfile()->isPerson();
208 * @return boolean true if this is a remote peopletag
210 function isPeopletag()
212 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
214 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
216 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
217 // TRANS: Server exception. %s is a URI
218 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
220 // TRANS: Server exception. %s is a URI
221 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
226 * Send a subscription request to the hub for this feed.
227 * The hub will later send us a confirmation POST to /main/push/callback.
230 * @throws ServerException if feed state is not valid or subscription fails.
232 public function subscribe()
234 $feedsub = FeedSub::ensureFeed($this->feeduri);
235 if ($feedsub->sub_state == 'active') {
236 // Active subscription, we don't need to do anything.
240 // Inactive or we got left in an inconsistent state.
241 // Run a subscription request to make sure we're current!
242 return $feedsub->subscribe();
246 * Check if this remote profile has any active local subscriptions, and
247 * if not drop the WebSub subscription feed.
249 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
250 * @throws Exception of various kinds on failure.
252 public function unsubscribe() {
253 return $this->garbageCollect();
257 * Check if this remote profile has any active local subscriptions, and
258 * if not drop the WebSub subscription feed.
260 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
261 * @throws Exception of various kinds on failure.
263 public function garbageCollect()
265 $feedsub = FeedSub::getKV('uri', $this->feeduri);
266 if ($feedsub instanceof FeedSub) {
267 return $feedsub->garbageCollect();
269 // Since there's no FeedSub we can assume it's already garbage collected
274 * Check if this remote profile has any active local subscriptions, so the
275 * WebSub subscription layer can decide if it can drop the feed.
277 * This gets called via the FeedSubSubscriberCount event when running
278 * FeedSub::garbageCollect().
281 * @throws NoProfileException if there is no local profile for the object
283 public function subscriberCount()
285 if ($this->isGroup()) {
286 $members = $this->localGroup()->getMembers(0, 1);
287 $count = $members->N;
288 } else if ($this->isPeopletag()) {
289 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
290 $count = $subscribers->N;
292 $profile = $this->localProfile();
293 if ($profile->hasLocalTags()) {
296 $count = $profile->subscriberCount();
299 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
301 // Other plugins may be piggybacking on OStatus without having
302 // an active group or user-to-user subscription we know about.
303 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
304 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
310 * Send an Activity Streams notification to the remote Salmon endpoint,
313 * @param Profile $actor Actor who did the activity
314 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
315 * @param Object $object object of the action; must define asActivityNoun($tag)
317 public function notify(Profile $actor, $verb, $object=null, $target=null)
319 if ($object == null) {
322 if (empty($this->salmonuri)) {
326 $id = TagURI::mint('%s:%s:%s',
329 common_date_iso8601(time()));
331 // @todo FIXME: Consolidate all these NS settings somewhere.
332 $attributes = array('xmlns' => Activity::ATOM,
333 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
334 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
335 'xmlns:georss' => 'http://www.georss.org/georss',
336 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
337 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
338 'xmlns:media' => 'http://purl.org/syndication/atommedia');
340 $entry = new XMLStringer();
341 $entry->elementStart('entry', $attributes);
342 $entry->element('id', null, $id);
343 $entry->element('title', null, $text);
344 $entry->element('summary', null, $text);
345 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
347 $entry->element('activity:verb', null, $verb);
348 $entry->raw($actor->asAtomAuthor());
349 $entry->raw($actor->asActivityActor());
350 $entry->raw($object->asActivityNoun('object'));
351 if ($target != null) {
352 $entry->raw($target->asActivityNoun('target'));
354 $entry->elementEnd('entry');
356 $xml = $entry->getString();
357 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
359 Salmon::post($this->salmonuri, $xml, $actor);
363 * Send a Salmon notification ping immediately, and confirm that we got
364 * an acceptable response from the remote site.
366 * @param mixed $entry XML string, Notice, or Activity
367 * @param Profile $actor
368 * @return boolean success
370 public function notifyActivity($entry, Profile $actor)
372 if ($this->salmonuri) {
373 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor, $this->localProfile());
375 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '._ve($this->getUri()));
381 * Queue a Salmon notification for later. If queues are disabled we'll
382 * send immediately but won't get the return value.
384 * @param mixed $entry XML string, Notice, or Activity
385 * @return boolean success
387 public function notifyDeferred($entry, $actor)
389 if ($this->salmonuri) {
391 common_debug("OSTATUS: user {$actor->getNickname()} ({$actor->getID()}) wants to ping {$this->localProfile()->getNickname()} on {$this->salmonuri}");
392 $data = array('salmonuri' => $this->salmonuri,
393 'entry' => $this->notifyPrepXml($entry),
394 'actor' => $actor->getID(),
395 'target' => $this->localProfile()->getID());
397 $qm = QueueManager::get();
398 return $qm->enqueue($data, 'salmon');
399 } catch (Exception $e) {
400 common_log(LOG_ERR, 'OSTATUS: Something went wrong when creating a Salmon slap: '._ve($e->getMessage()));
408 protected function notifyPrepXml($entry)
410 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . ">\n";
411 if (is_string($entry)) {
413 } else if ($entry instanceof Activity) {
414 return $preamble . $entry->asString(true);
415 } else if ($entry instanceof Notice) {
416 return $preamble . $entry->asAtomEntry(true, true);
418 // TRANS: Server exception.
419 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
423 function getBestName()
425 if ($this->isGroup()) {
426 return $this->localGroup()->getBestName();
427 } else if ($this->isPeopletag()) {
428 return $this->localPeopletag()->getBestName();
430 return $this->localProfile()->getBestName();
435 * Read and post notices for updates from the feed.
436 * Currently assumes that all items in the feed are new,
437 * coming from a WebSub hub.
439 * @param DOMDocument $doc
440 * @param string $source identifier ("push")
442 public function processFeed(DOMDocument $doc, $source)
444 $feed = $doc->documentElement;
446 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
447 $this->processAtomFeed($feed, $source);
448 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
449 $this->processRssFeed($feed, $source);
452 throw new Exception(_m('Unknown feed format.'));
456 public function processAtomFeed(DOMElement $feed, $source)
458 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
459 if ($entries->length == 0) {
460 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
464 $this->processEntries($entries, $feed, $source);
467 public function processRssFeed(DOMElement $rss, $source)
469 $channels = $rss->getElementsByTagName('channel');
471 if ($channels->length == 0) {
473 throw new Exception(_m('RSS feed without a channel.'));
474 } else if ($channels->length > 1) {
475 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
478 $channel = $channels->item(0);
480 $items = $channel->getElementsByTagName('item');
482 $this->processEntries($items, $channel, $source);
485 public function processEntries(DOMNodeList $entries, DOMElement $feed, $source)
487 for ($i = 0; $i < $entries->length; $i++) {
488 $entry = $entries->item($i);
490 $this->processEntry($entry, $feed, $source);
491 } catch (AlreadyFulfilledException $e) {
492 common_debug('We already had this entry: '.$e->getMessage());
493 } catch (ServerException $e) {
494 // FIXME: This should be UnknownUriException and the ActivityUtils:: findLocalObject should only test one URI
495 common_log(LOG_ERR, 'Entry threw exception while processing a feed from '.$source.': '.$e->getMessage());
501 * Process a posted entry from this feed source.
503 * @param DOMElement $entry
504 * @param DOMElement $feed for context
505 * @param string $source identifier ("push" or "salmon")
507 * @return Notice Notice representing the new (or existing) activity
509 public function processEntry(DOMElement $entry, DOMElement $feed, $source)
511 $activity = new Activity($entry, $feed);
512 return $this->processActivity($activity, $source);
515 // TODO: Make this throw an exception
516 public function processActivity(Activity $activity, $source)
520 // The "WithProfile" events were added later.
522 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
523 Event::handle('StartHandleFeedEntry', array($activity))) {
525 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
527 Event::handle('EndHandleFeedEntry', array($activity));
528 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
535 * Process an incoming post activity from this remote feed.
536 * @param Activity $activity
537 * @param string $method 'push' or 'salmon'
538 * @return mixed saved Notice or false
540 public function processPost($activity, $method)
542 $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
544 $options = array('is_local' => Notice::REMOTE);
547 $stored = Notice::saveActivity($activity, $actor, $options);
548 } catch (Exception $e) {
549 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
556 * Filters a list of recipient ID URIs to just those for local delivery.
557 * @param Profile local profile of sender
558 * @param array in/out &$attention_uris set of URIs, will be pruned on output
559 * @return array of group IDs
561 static public function filterAttention(Profile $sender, array $attention)
563 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
566 foreach ($attention as $recipient=>$type) {
567 // Is the recipient a local user?
568 $user = User::getKV('uri', $recipient);
569 if ($user instanceof User) {
570 // @todo FIXME: Sender verification, spam etc?
571 $replies[] = $recipient;
575 // Is the recipient a local group?
576 // TODO: $group = User_group::getKV('uri', $recipient);
577 $id = OStatusPlugin::localGroupFromUrl($recipient);
579 $group = User_group::getKV('id', $id);
580 if ($group instanceof User_group) {
581 // Deliver to all members of this local group if allowed.
582 if ($sender->isMember($group)) {
583 $groups[] = $group->id;
585 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
589 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
593 // Is the recipient a remote user or group?
595 $oprofile = self::ensureProfileURI($recipient);
596 if ($oprofile->isGroup()) {
597 // Deliver to local members of this remote group.
598 // @todo FIXME: Sender verification?
599 $groups[] = $oprofile->group_id;
601 // may be canonicalized or something
602 $replies[] = $oprofile->getUri();
605 } catch (Exception $e) {
606 // Neither a recognizable local nor remote user!
607 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
611 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
612 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
613 return array($groups, $replies);
617 * Look up and if necessary create an Ostatus_profile for the remote entity
618 * with the given profile page URL. This should never return null -- you
619 * will either get an object or an exception will be thrown.
621 * @param string $profile_url
622 * @return Ostatus_profile
623 * @throws Exception on various error conditions
624 * @throws OStatusShadowException if this reference would obscure a local user/group
626 public static function ensureProfileURL($profile_url, array $hints=array())
628 $oprofile = self::getFromProfileURL($profile_url);
630 if ($oprofile instanceof Ostatus_profile) {
634 $hints['profileurl'] = $profile_url;
639 $client = new HTTPClient();
640 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
641 $response = $client->get($profile_url);
643 if (!$response->isOk()) {
644 // TRANS: Exception. %s is a profile URL.
645 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
648 // Check if we have a non-canonical URL
650 $finalUrl = $response->getEffectiveUrl();
652 if ($finalUrl != $profile_url) {
654 $hints['profileurl'] = $finalUrl;
656 $oprofile = self::getFromProfileURL($finalUrl);
658 if ($oprofile instanceof Ostatus_profile) {
664 preg_replace('/\s*;.*$/', '', $response->getHeader('Content-Type')),
665 array('application/rss+xml', 'application/atom+xml', 'application/xml', 'text/xml'))
667 $hints['feedurl'] = $response->getEffectiveUrl();
669 // Try to get some hCard data
671 $body = $response->getBody();
673 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
675 if (!empty($hcardHints)) {
676 $hints = array_merge($hints, $hcardHints);
680 // Check if they've got an LRDD header
682 $lrdd = LinkHeader::getLink($response, 'lrdd');
684 $xrd = new XML_XRD();
685 $xrd->loadFile($lrdd);
686 $xrdHints = DiscoveryHints::fromXRD($xrd);
687 $hints = array_merge($hints, $xrdHints);
688 } catch (Exception $e) {
689 // No hints available from XRD
692 // If discovery found a feedurl (probably from LRDD), use it.
694 if (array_key_exists('feedurl', $hints)) {
695 return self::ensureFeedURL($hints['feedurl'], $hints);
698 // Get the feed URL from HTML
700 $discover = new FeedDiscovery();
702 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
704 if (!empty($feedurl)) {
705 $hints['feedurl'] = $feedurl;
706 return self::ensureFeedURL($feedurl, $hints);
709 // TRANS: Exception. %s is a URL.
710 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
714 * Look up the Ostatus_profile, if present, for a remote entity with the
715 * given profile page URL. Will return null for both unknown and invalid
718 * @return mixed Ostatus_profile or null
719 * @throws OStatusShadowException for local profiles
721 static function getFromProfileURL($profile_url)
723 $profile = Profile::getKV('profileurl', $profile_url);
724 if (!$profile instanceof Profile) {
729 $oprofile = self::getFromProfile($profile);
730 // We found the profile, return it!
732 } catch (NoResultException $e) {
733 // Could not find an OStatus profile, is it instead a local user?
734 $user = User::getKV('id', $profile->id);
735 if ($user instanceof User) {
736 // @todo i18n FIXME: use sprintf and add i18n (?)
737 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
741 // Continue discovery; it's a remote profile
742 // for OMB or some other protocol, may also
748 static function getFromProfile(Profile $profile)
750 $oprofile = new Ostatus_profile();
751 $oprofile->profile_id = $profile->id;
752 if (!$oprofile->find(true)) {
753 throw new NoResultException($oprofile);
759 * Look up and if necessary create an Ostatus_profile for remote entity
760 * with the given update feed. This should never return null -- you will
761 * either get an object or an exception will be thrown.
763 * @return Ostatus_profile
766 public static function ensureFeedURL($feed_url, array $hints=array())
768 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
769 if ($oprofile instanceof Ostatus_profile) {
773 $discover = new FeedDiscovery();
775 $feeduri = $discover->discoverFromFeedURL($feed_url);
776 $hints['feedurl'] = $feeduri;
778 $huburi = $discover->getHubLink();
779 $hints['hub'] = $huburi;
781 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
782 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
783 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
784 $hints['salmon'] = $salmonuri;
786 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
787 // We can only deal with folks with a WebSub hub
788 // unless we have something similar available locally.
789 throw new FeedSubNoHubException();
792 $feedEl = $discover->root;
794 if ($feedEl->tagName == 'feed') {
795 return self::ensureAtomFeed($feedEl, $hints);
796 } else if ($feedEl->tagName == 'channel') {
797 return self::ensureRssChannel($feedEl, $hints);
799 throw new FeedSubBadXmlException($feeduri);
804 * Look up and, if necessary, create an Ostatus_profile for the remote
805 * profile with the given Atom feed - actually loaded from the feed.
806 * This should never return null -- you will either get an object or
807 * an exception will be thrown.
809 * @param DOMElement $feedEl root element of a loaded Atom feed
810 * @param array $hints additional discovery information passed from higher levels
811 * @todo FIXME: Should this be marked public?
812 * @return Ostatus_profile
815 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
817 $author = ActivityUtils::getFeedAuthor($feedEl);
819 if (empty($author)) {
820 // XXX: make some educated guesses here
821 // TRANS: Feed sub exception.
822 throw new FeedSubException(_m('Cannot find enough profile '.
823 'information to make a feed.'));
826 return self::ensureActivityObjectProfile($author, $hints);
830 * Look up and, if necessary, create an Ostatus_profile for the remote
831 * profile with the given RSS feed - actually loaded from the feed.
832 * This should never return null -- you will either get an object or
833 * an exception will be thrown.
835 * @param DOMElement $feedEl root element of a loaded RSS feed
836 * @param array $hints additional discovery information passed from higher levels
837 * @todo FIXME: Should this be marked public?
838 * @return Ostatus_profile
841 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
843 // Special-case for Posterous. They have some nice metadata in their
844 // posterous:author elements. We should use them instead of the channel.
846 $items = $feedEl->getElementsByTagName('item');
848 if ($items->length > 0) {
849 $item = $items->item(0);
850 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
851 if (!empty($authorEl)) {
852 $obj = ActivityObject::fromPosterousAuthor($authorEl);
853 // Posterous has multiple authors per feed, and multiple feeds
854 // per author. We check if this is the "main" feed for this author.
855 if (array_key_exists('profileurl', $hints) &&
856 !empty($obj->poco) &&
857 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
858 return self::ensureActivityObjectProfile($obj, $hints);
863 $obj = ActivityUtils::getFeedAuthor($feedEl);
865 // @todo FIXME: We should check whether this feed has elements
866 // with different <author> or <dc:creator> elements, and... I dunno.
867 // Do something about that.
869 if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
871 return self::ensureActivityObjectProfile($obj, $hints);
875 * Download and update given avatar image
878 * @return Avatar The Avatar we have on disk. (seldom used)
879 * @throws Exception in various failure cases
881 public function updateAvatar($url, $force=false)
884 // If avatar URL differs: update. If URLs were identical but we're forced: update.
885 if ($url == $this->avatar && !$force) {
886 // If there's no locally stored avatar, throw an exception and continue fetching below.
887 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
890 } catch (NoAvatarException $e) {
891 // No avatar available, let's fetch it.
894 if (!common_valid_http_url($url)) {
895 // TRANS: Server exception. %s is a URL.
896 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
899 $self = $this->localProfile();
901 // @todo FIXME: This should be better encapsulated
902 // ripped from oauthstore.php (for old OMB client)
903 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
905 $imgData = HTTPClient::quickGet($url);
906 // Make sure it's at least an image file. ImageFile can do the rest.
907 if (false === getimagesizefromstring($imgData)) {
908 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
910 file_put_contents($temp_filename, $imgData);
911 unset($imgData); // No need to carry this in memory.
913 if ($this->isGroup()) {
914 $id = $this->group_id;
916 $id = $this->profile_id;
918 $imagefile = new ImageFile(null, $temp_filename);
919 $filename = Avatar::filename($id,
920 image_type_to_extension($imagefile->type),
923 rename($temp_filename, Avatar::path($filename));
924 } catch (Exception $e) {
925 unlink($temp_filename);
928 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
929 // keep from accidentally saving images from command-line (queues)
930 // that can't be read from web server, which causes hard-to-notice
931 // problems later on:
933 // http://status.net/open-source/issues/2663
934 chmod(Avatar::path($filename), 0644);
936 $self->setOriginal($filename);
938 $orig = clone($this);
939 $this->avatar = $url;
940 $this->update($orig);
942 return Avatar::getUploaded($self);
946 * Pull avatar URL from ActivityObject or profile hints
948 * @param ActivityObject $object
949 * @param array $hints
950 * @return mixed URL string or false
952 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
954 if ($object->avatarLinks) {
956 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
957 foreach ($object->avatarLinks as $avatar) {
958 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
963 if (!$best || $avatar->width > $best->width) {
968 } else if (array_key_exists('avatar', $hints)) {
969 return $hints['avatar'];
975 * Get an appropriate avatar image source URL, if available.
977 * @param ActivityObject $actor
978 * @param DOMElement $feed
981 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
985 if ($actor->avatar) {
986 $url = trim($actor->avatar);
989 // Check <atom:logo> and <atom:icon> on the feed
990 $els = $feed->childNodes();
991 if ($els && $els->length) {
992 for ($i = 0; $i < $els->length; $i++) {
993 $el = $els->item($i);
994 if ($el->namespaceURI == Activity::ATOM) {
995 if (empty($url) && $el->localName == 'logo') {
996 $url = trim($el->textContent);
999 if (empty($icon) && $el->localName == 'icon') {
1000 // Use as a fallback
1001 $icon = trim($el->textContent);
1006 if ($icon && !$url) {
1011 $opts = array('allowed_schemes' => array('http', 'https'));
1012 if (common_valid_http_url($url)) {
1017 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1021 * Fetch, or build if necessary, an Ostatus_profile for the actor
1022 * in a given Activity Streams activity.
1023 * This should never return null -- you will either get an object or
1024 * an exception will be thrown.
1026 * @param Activity $activity
1027 * @param string $feeduri if we already know the canonical feed URI!
1028 * @param string $salmonuri if we already know the salmon return channel URI
1029 * @return Ostatus_profile
1032 public static function ensureActorProfile(Activity $activity, array $hints=array())
1034 return self::ensureActivityObjectProfile($activity->actor, $hints);
1038 * Fetch, or build if necessary, an Ostatus_profile for the profile
1039 * in a given Activity Streams object (can be subject, actor, or object).
1040 * This should never return null -- you will either get an object or
1041 * an exception will be thrown.
1043 * @param ActivityObject $object
1044 * @param array $hints additional discovery information passed from higher levels
1045 * @return Ostatus_profile
1048 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1050 $profile = self::getActivityObjectProfile($object);
1051 if ($profile instanceof Ostatus_profile) {
1052 $profile->updateFromActivityObject($object, $hints);
1054 $profile = self::createActivityObjectProfile($object, $hints);
1060 * @param Activity $activity
1061 * @return mixed matching Ostatus_profile or false if none known
1062 * @throws ServerException if feed info invalid
1064 public static function getActorProfile(Activity $activity)
1066 return self::getActivityObjectProfile($activity->actor);
1070 * @param ActivityObject $activity
1071 * @return mixed matching Ostatus_profile or false if none known
1072 * @throws ServerException if feed info invalid
1074 protected static function getActivityObjectProfile(ActivityObject $object)
1076 $uri = self::getActivityObjectProfileURI($object);
1077 return Ostatus_profile::getKV('uri', $uri);
1081 * Get the identifier URI for the remote entity described
1082 * by this ActivityObject. This URI is *not* guaranteed to be
1083 * a resolvable HTTP/HTTPS URL.
1085 * @param ActivityObject $object
1087 * @throws ServerException if feed info invalid
1089 protected static function getActivityObjectProfileURI(ActivityObject $object)
1092 if (ActivityUtils::validateUri($object->id)) {
1097 // If the id is missing or invalid (we've seen feeds mistakenly listing
1098 // things like local usernames in that field) then we'll use the profile
1099 // page link, if valid.
1100 if ($object->link && common_valid_http_url($object->link)) {
1101 return $object->link;
1103 // TRANS: Server exception.
1104 throw new ServerException(_m('No author ID URI found.'));
1108 * @todo FIXME: Validate stuff somewhere.
1112 * Create local ostatus_profile and profile/user_group entries for
1113 * the provided remote user or group.
1114 * This should never return null -- you will either get an object or
1115 * an exception will be thrown.
1117 * @param ActivityObject $object
1118 * @param array $hints
1120 * @return Ostatus_profile
1122 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1124 common_debug('Attempting to create an Ostatus_profile from an ActivityObject with ID: '._ve($object->id));
1126 $homeuri = $object->id;
1130 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1131 // TRANS: Exception.
1132 throw new Exception(_m('No profile URI.'));
1135 $user = User::getKV('uri', $homeuri);
1136 if ($user instanceof User) {
1137 // TRANS: Exception.
1138 throw new Exception(_m('Local user cannot be referenced as remote.'));
1141 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1142 // TRANS: Exception.
1143 throw new Exception(_m('Local group cannot be referenced as remote.'));
1146 $ptag = Profile_list::getKV('uri', $homeuri);
1147 if ($ptag instanceof Profile_list) {
1148 $local_user = User::getKV('id', $ptag->tagger);
1149 if ($local_user instanceof User) {
1150 // TRANS: Exception.
1151 throw new Exception(_m('Local list cannot be referenced as remote.'));
1155 if (!array_key_exists('feedurl', $hints)) {
1156 $discover = new FeedDiscovery();
1157 $hints['feedurl'] = $discover->discoverFromURL($homeuri);
1158 common_debug(__METHOD__.' did not have a "feedurl" hint, FeedDiscovery found '._ve($hints['feedurl']));
1160 $feeduri = $hints['feedurl'];
1162 if (array_key_exists('salmon', $hints)) {
1163 $salmonuri = $hints['salmon'];
1166 $discover = new FeedDiscovery();
1167 $discover->discoverFromFeedURL($hints['feedurl']);
1169 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1170 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1171 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1174 if (array_key_exists('hub', $hints)) {
1175 $huburi = $hints['hub'];
1178 $discover = new FeedDiscovery();
1179 $discover->discoverFromFeedURL($hints['feedurl']);
1181 $huburi = $discover->getHubLink();
1184 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1185 // We can only deal with folks with a WebSub hub
1186 throw new FeedSubNoHubException();
1189 $oprofile = new Ostatus_profile();
1191 $oprofile->uri = $homeuri;
1192 $oprofile->feeduri = $feeduri;
1193 $oprofile->salmonuri = $salmonuri;
1195 $oprofile->created = common_sql_now();
1196 $oprofile->modified = common_sql_now();
1198 if ($object->type == ActivityObject::PERSON) {
1199 $profile = new Profile();
1200 $profile->created = common_sql_now();
1201 self::updateProfile($profile, $object, $hints);
1203 $oprofile->profile_id = $profile->insert();
1204 if ($oprofile->profile_id === false) {
1205 // TRANS: Server exception.
1206 throw new ServerException(_m('Cannot save local profile.'));
1208 } else if ($object->type == ActivityObject::GROUP) {
1209 $profile = new Profile();
1210 $profile->query('BEGIN');
1212 $group = new User_group();
1213 $group->uri = $homeuri;
1214 $group->created = common_sql_now();
1215 self::updateGroup($group, $object, $hints);
1217 // TODO: We should do this directly in User_group->insert()!
1218 // currently it's duplicated in User_group->update()
1219 // AND User_group->register()!!!
1220 $fields = array(/*group field => profile field*/
1221 'nickname' => 'nickname',
1222 'fullname' => 'fullname',
1223 'mainpage' => 'profileurl',
1224 'homepage' => 'homepage',
1225 'description' => 'bio',
1226 'location' => 'location',
1227 'created' => 'created',
1228 'modified' => 'modified',
1230 foreach ($fields as $gf=>$pf) {
1231 $profile->$pf = $group->$gf;
1233 $profile_id = $profile->insert();
1234 if ($profile_id === false) {
1235 $profile->query('ROLLBACK');
1236 throw new ServerException(_('Profile insertion failed.'));
1239 $group->profile_id = $profile_id;
1241 $oprofile->group_id = $group->insert();
1242 if ($oprofile->group_id === false) {
1243 $profile->query('ROLLBACK');
1244 // TRANS: Server exception.
1245 throw new ServerException(_m('Cannot save local profile.'));
1248 $profile->query('COMMIT');
1249 } else if ($object->type == ActivityObject::_LIST) {
1250 $ptag = new Profile_list();
1251 $ptag->uri = $homeuri;
1252 $ptag->created = common_sql_now();
1253 self::updatePeopletag($ptag, $object, $hints);
1255 $oprofile->peopletag_id = $ptag->insert();
1256 if ($oprofile->peopletag_id === false) {
1257 // TRANS: Server exception.
1258 throw new ServerException(_m('Cannot save local list.'));
1262 $ok = $oprofile->insert();
1264 if ($ok === false) {
1265 // TRANS: Server exception.
1266 throw new ServerException(_m('Cannot save OStatus profile.'));
1269 $avatar = self::getActivityObjectAvatar($object, $hints);
1273 $oprofile->updateAvatar($avatar);
1274 } catch (Exception $ex) {
1275 // Profile is saved, but Avatar is messed up. We're
1276 // just going to continue.
1277 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1285 * Save any updated profile information to our local copy.
1286 * @param ActivityObject $object
1287 * @param array $hints
1289 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1291 if (self::getActivityObjectProfileURI($object) !== $this->getUri()) {
1292 common_log(LOG_ERR, 'Trying to update profile with URI '._ve($this->getUri()).' from ActivityObject with URI: '._ve(self::getActivityObjectProfileURI($object)));
1293 // FIXME: Maybe not AuthorizationException?
1294 throw new AuthorizationException('Trying to update profile from ActivityObject with different URI.');
1297 common_debug('Updating Ostatus_profile with URI '._ve($this->getUri()).' from ActivityObject');
1299 if ($this->isGroup()) {
1300 $group = $this->localGroup();
1301 self::updateGroup($group, $object, $hints);
1302 } else if ($this->isPeopletag()) {
1303 $ptag = $this->localPeopletag();
1304 self::updatePeopletag($ptag, $object, $hints);
1306 $profile = $this->localProfile();
1307 self::updateProfile($profile, $object, $hints);
1310 $avatar = self::getActivityObjectAvatar($object, $hints);
1311 if ($avatar && !isset($ptag)) {
1313 $this->updateAvatar($avatar);
1314 } catch (Exception $e) {
1315 common_log(LOG_WARNING, 'Exception ('.get_class($e).') updating OStatus profile avatar: ' . $e->getMessage());
1320 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1322 $orig = clone($profile);
1324 // Existing nickname is better than nothing.
1326 if (!array_key_exists('nickname', $hints)) {
1327 $hints['nickname'] = $profile->nickname;
1330 $nickname = self::getActivityObjectNickname($object, $hints);
1332 if (!empty($nickname)) {
1333 $profile->nickname = $nickname;
1336 if (!empty($object->title)) {
1337 $profile->fullname = $object->title;
1338 } else if (array_key_exists('fullname', $hints)) {
1339 $profile->fullname = $hints['fullname'];
1342 if (!empty($object->link)) {
1343 $profile->profileurl = $object->link;
1344 } else if (array_key_exists('profileurl', $hints)) {
1345 $profile->profileurl = $hints['profileurl'];
1346 } else if (common_valid_http_url($object->id)) {
1347 $profile->profileurl = $object->id;
1350 $bio = self::getActivityObjectBio($object, $hints);
1353 $profile->bio = $bio;
1356 $location = self::getActivityObjectLocation($object, $hints);
1358 if (!empty($location)) {
1359 $profile->location = $location;
1362 $homepage = self::getActivityObjectHomepage($object, $hints);
1364 if (!empty($homepage)) {
1365 $profile->homepage = $homepage;
1368 if (!empty($object->geopoint)) {
1369 $location = ActivityContext::locationFromPoint($object->geopoint);
1370 if (!empty($location)) {
1371 $profile->lat = $location->lat;
1372 $profile->lon = $location->lon;
1376 // @todo FIXME: tags/categories
1377 // @todo tags from categories
1380 //common_debug('Updating OStatus profile '._ve($profile->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1381 common_debug('Updating OStatus profile '._ve($profile->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1382 $profile->update($orig);
1386 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1388 $orig = clone($group);
1390 $group->nickname = self::getActivityObjectNickname($object, $hints);
1391 $group->fullname = $object->title;
1393 if (!empty($object->link)) {
1394 $group->mainpage = $object->link;
1395 } else if (array_key_exists('profileurl', $hints)) {
1396 $group->mainpage = $hints['profileurl'];
1399 // @todo tags from categories
1400 $group->description = self::getActivityObjectBio($object, $hints);
1401 $group->location = self::getActivityObjectLocation($object, $hints);
1402 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1404 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1405 //common_debug('Updating OStatus group '._ve($group->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1406 common_debug('Updating OStatus group '._ve($group->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1407 $group->update($orig);
1411 protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array()) {
1412 $orig = clone($tag);
1414 $tag->tag = $object->title;
1416 if (!empty($object->link)) {
1417 $tag->mainpage = $object->link;
1418 } else if (array_key_exists('profileurl', $hints)) {
1419 $tag->mainpage = $hints['profileurl'];
1422 $tag->description = $object->summary;
1423 $tagger = self::ensureActivityObjectProfile($object->owner);
1424 $tag->tagger = $tagger->profile_id;
1427 //common_debug('Updating OStatus peopletag '._ve($tag->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1428 common_debug('Updating OStatus peopletag '._ve($tag->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1429 $tag->update($orig);
1433 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1436 $poco = $object->poco;
1438 if (!empty($poco)) {
1439 $url = $poco->getPrimaryURL();
1440 if ($url && $url->type == 'homepage') {
1441 $homepage = $url->value;
1445 // @todo Try for a another PoCo URL?
1450 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1454 if (!empty($object->poco) &&
1455 isset($object->poco->address->formatted)) {
1456 $location = $object->poco->address->formatted;
1457 } else if (array_key_exists('location', $hints)) {
1458 $location = $hints['location'];
1461 if (!empty($location)) {
1462 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1463 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1467 // @todo Try to find location some othe way? Via goerss point?
1472 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1476 if (!empty($object->poco)) {
1477 $note = $object->poco->note;
1478 } else if (array_key_exists('bio', $hints)) {
1479 $note = $hints['bio'];
1482 if (!empty($note)) {
1483 if (Profile::bioTooLong($note)) {
1484 // XXX: truncate ok?
1485 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1491 // @todo Try to get bio info some other way?
1496 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1498 if ($object->poco) {
1499 if (!empty($object->poco->preferredUsername)) {
1500 return common_nicknamize($object->poco->preferredUsername);
1504 if (!empty($object->nickname)) {
1505 return common_nicknamize($object->nickname);
1508 if (array_key_exists('nickname', $hints)) {
1509 return $hints['nickname'];
1512 // Try the profile url (like foo.example.com or example.com/user/foo)
1513 if (!empty($object->link)) {
1514 $profileUrl = $object->link;
1515 } else if (!empty($hints['profileurl'])) {
1516 $profileUrl = $hints['profileurl'];
1519 if (!empty($profileUrl)) {
1520 $nickname = self::nicknameFromURI($profileUrl);
1523 // Try the URI (may be a tag:, http:, acct:, ...
1525 if (empty($nickname)) {
1526 $nickname = self::nicknameFromURI($object->id);
1529 // Try a Webfinger if one was passed (way) down
1531 if (empty($nickname)) {
1532 if (array_key_exists('webfinger', $hints)) {
1533 $nickname = self::nicknameFromURI($hints['webfinger']);
1539 if (empty($nickname)) {
1540 $nickname = common_nicknamize($object->title);
1546 protected static function nicknameFromURI($uri)
1548 if (preg_match('/(\w+):/', $uri, $matches)) {
1549 $protocol = $matches[1];
1554 switch ($protocol) {
1557 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1558 return common_canonical_nickname($matches[1]);
1562 return common_url_to_nickname($uri);
1570 * Look up, and if necessary create, an Ostatus_profile for the remote
1571 * entity with the given webfinger address.
1572 * This should never return null -- you will either get an object or
1573 * an exception will be thrown.
1575 * @param string $addr webfinger address
1576 * @return Ostatus_profile
1577 * @throws Exception on error conditions
1578 * @throws OStatusShadowException if this reference would obscure a local user/group
1580 public static function ensureWebfinger($addr)
1582 // Normalize $addr, i.e. add 'acct:' if missing
1583 $addr = Discovery::normalize($addr);
1586 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1588 if ($uri !== false) {
1589 if (is_null($uri)) {
1590 // Negative cache entry
1591 // TRANS: Exception.
1592 throw new Exception(_m('Not a valid webfinger address (via cache).'));
1594 $oprofile = Ostatus_profile::getKV('uri', $uri);
1595 if ($oprofile instanceof Ostatus_profile) {
1598 common_log(LOG_ERR, sprintf(__METHOD__ . ': Webfinger address cache inconsistent with database, did not find Ostatus_profile uri==%s', $uri));
1599 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), false);
1602 // Try looking it up
1603 $oprofile = Ostatus_profile::getKV('uri', $addr);
1605 if ($oprofile instanceof Ostatus_profile) {
1606 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1610 // Now, try some discovery
1612 $disco = new Discovery();
1615 $xrd = $disco->lookup($addr);
1616 } catch (Exception $e) {
1617 // Save negative cache entry so we don't waste time looking it up again.
1618 // @todo FIXME: Distinguish temporary failures?
1619 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1620 // TRANS: Exception.
1621 throw new Exception(_m('Not a valid webfinger address.'));
1624 $hints = array_merge(array('webfinger' => $addr),
1625 DiscoveryHints::fromXRD($xrd));
1627 // If there's an Hcard, let's grab its info
1628 if (array_key_exists('hcard', $hints)) {
1629 if (!array_key_exists('profileurl', $hints) ||
1630 $hints['hcard'] != $hints['profileurl']) {
1631 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1632 $hints = array_merge($hcardHints, $hints);
1636 // If we got a feed URL, try that
1638 if (array_key_exists('feedurl', $hints)) {
1639 $feedUrl = $hints['feedurl'];
1641 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1642 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1643 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1645 } catch (Exception $e) {
1646 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1651 // If we got a profile page, try that!
1653 if (array_key_exists('profileurl', $hints)) {
1654 $profileUrl = $hints['profileurl'];
1656 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1657 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1658 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1660 } catch (OStatusShadowException $e) {
1661 // We've ended up with a remote reference to a local user or group.
1662 // @todo FIXME: Ideally we should be able to say who it was so we can
1663 // go back and refer to it the regular way
1665 } catch (Exception $e) {
1666 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1669 // @todo FIXME: This means an error discovering from profile page
1670 // may give us a corrupt entry using the webfinger URI, which
1671 // will obscure the correct page-keyed profile later on.
1678 if (array_key_exists('salmon', $hints)) {
1679 $salmonEndpoint = $hints['salmon'];
1681 // An account URL, a salmon endpoint, and a dream? Not much to go
1682 // on, but let's give it a try
1684 $uri = 'acct:'.$addr;
1686 $profile = new Profile();
1688 $profile->nickname = self::nicknameFromUri($uri);
1689 $profile->created = common_sql_now();
1691 if (!is_null($profileUrl)) {
1692 $profile->profileurl = $profileUrl;
1695 $profile_id = $profile->insert();
1697 if ($profile_id === false) {
1698 common_log_db_error($profile, 'INSERT', __FILE__);
1699 // TRANS: Exception. %s is a webfinger address.
1700 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1703 $oprofile = new Ostatus_profile();
1705 $oprofile->uri = $uri;
1706 $oprofile->salmonuri = $salmonEndpoint;
1707 $oprofile->profile_id = $profile_id;
1708 $oprofile->created = common_sql_now();
1710 if (!is_null($feedUrl)) {
1711 $oprofile->feeduri = $feedUrl;
1714 $result = $oprofile->insert();
1716 if ($result === false) {
1718 common_log_db_error($oprofile, 'INSERT', __FILE__);
1719 // TRANS: Exception. %s is a webfinger address.
1720 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1723 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1727 // TRANS: Exception. %s is a webfinger address.
1728 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1732 * Store the full-length scrubbed HTML of a remote notice to an attachment
1733 * file on our server. We'll link to this at the end of the cropped version.
1735 * @param string $title plaintext for HTML page's title
1736 * @param string $rendered HTML fragment for HTML page's body
1739 function saveHTMLFile($title, $rendered)
1741 $final = sprintf("<!DOCTYPE html>\n" .
1743 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1744 '<title>%s</title>' .
1746 '<body>%s</body></html>',
1747 htmlspecialchars($title),
1750 $filename = File::filename($this->localProfile(),
1751 'ostatus', // ignored?
1754 $filepath = File::path($filename);
1755 $fileurl = File::url($filename);
1757 file_put_contents($filepath, $final);
1761 $file->filename = $filename;
1762 $file->urlhash = File::hashurl($fileurl);
1763 $file->url = $fileurl;
1764 $file->size = filesize($filepath);
1765 $file->date = time();
1766 $file->mimetype = 'text/html';
1768 $file_id = $file->insert();
1770 if ($file_id === false) {
1771 common_log_db_error($file, "INSERT", __FILE__);
1772 // TRANS: Server exception.
1773 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1779 static function ensureProfileURI($uri)
1783 // First, try to query it
1785 $oprofile = Ostatus_profile::getKV('uri', $uri);
1787 if ($oprofile instanceof Ostatus_profile) {
1791 // If unfound, do discovery stuff
1792 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1793 $protocol = $match[1];
1794 switch ($protocol) {
1797 $oprofile = self::ensureProfileURL($uri);
1802 $oprofile = self::ensureWebfinger($rest);
1805 // TRANS: Server exception.
1806 // TRANS: %1$s is a protocol, %2$s is a URI.
1807 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1812 // TRANS: Server exception. %s is a URI.
1813 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1819 public function checkAuthorship(Activity $activity)
1821 if ($this->isGroup() || $this->isPeopletag()) {
1822 // A group or propletag feed will contain posts from multiple authors.
1823 $oprofile = self::ensureActorProfile($activity);
1824 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1825 // Groups can't post notices in StatusNet.
1826 common_log(LOG_WARNING,
1827 "OStatus: skipping post with group listed ".
1828 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1829 throw new ServerException('Activity author is a non-actor');
1832 $actor = $activity->actor;
1834 if (empty($actor)) {
1835 // OK here! assume the default
1836 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1837 $this->updateFromActivityObject($actor);
1838 } else if ($actor->id) {
1839 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1840 // This isn't what we expect from mainline OStatus person feeds!
1841 // Group feeds go down another path, with different validation...
1842 // Most likely this is a plain ol' blog feed of some kind which
1843 // doesn't match our expectations. We'll take the entry, but ignore
1844 // the <author> info.
1845 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1847 // Plain <author> without ActivityStreams actor info.
1848 // We'll just ignore this info for now and save the update under the feed's identity.
1854 return $oprofile->localProfile();
1857 public function updateUriKeys($profile_uri, array $hints=array())
1859 $orig = clone($this);
1861 common_debug('URIFIX These identities both say they are each other: '._ve($orig->uri).' and '._ve($profile_uri));
1862 $this->uri = $profile_uri;
1864 if (array_key_exists('feedurl', $hints) && common_valid_http_url($hints['feedurl'])) {
1866 $feedsub = $this->getFeedSub();
1867 common_debug('URIFIX Changing FeedSub id==['._ve($feedsub->id).'] feeduri '._ve($feedsub->uri).' to '._ve($hints['feedurl']));
1868 $feedorig = clone($feedsub);
1869 $feedsub->uri = $hints['feedurl'];
1870 $feedsub->updateWithKeys($feedorig);
1871 } catch (EmptyPkeyValueException $e) {
1872 common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring new feedurl: '._ve($hints['feedurl']));
1873 FeedSub::ensureFeed($hints['feedurl']);
1874 } catch (NoResultException $e) {
1875 common_debug('URIFIX Missing FeedSub entry for the Ostatus_profile, ensuring new feedurl: '._ve($hints['feedurl']));
1876 FeedSub::ensureFeed($hints['feedurl']);
1878 $this->feeduri = $hints['feedurl'];
1879 } elseif (array_key_exists('feedurl')) {
1880 common_log(LOG_WARN, 'The feedurl hint we got was not a valid HTTP URL: '._ve($hints['feedurl']));
1883 if (array_key_exists('salmon', $hints)) {
1884 common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
1885 $this->salmonuri = $hints['salmon'];
1888 common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
1889 $this->updateWithKeys($orig); // Will use the PID column(s) in the 'UPDATE ... WHERE [unique selector]'
1891 common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);