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 * @param Profile $actor Acting profile
386 * @return boolean success
388 public function notifyDeferred($entry, Profile $actor)
390 if ($this->salmonuri) {
392 common_debug("OSTATUS: user {$actor->getNickname()} ({$actor->getID()}) wants to ping {$this->localProfile()->getNickname()} on {$this->salmonuri}");
393 $data = array('salmonuri' => $this->salmonuri,
394 'entry' => $this->notifyPrepXml($entry),
395 'actor' => $actor->getID(),
396 'target' => $this->localProfile()->getID());
398 $qm = QueueManager::get();
399 return $qm->enqueue($data, 'salmon');
400 } catch (Exception $e) {
401 common_log(LOG_ERR, 'OSTATUS: Something went wrong when creating a Salmon slap: '._ve($e->getMessage()));
409 protected function notifyPrepXml($entry)
411 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . ">\n";
412 if (is_string($entry)) {
414 } else if ($entry instanceof Activity) {
415 return $preamble . $entry->asString(true);
416 } else if ($entry instanceof Notice) {
417 return $preamble . $entry->asAtomEntry(true, true);
419 // TRANS: Server exception.
420 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
424 function getBestName()
426 if ($this->isGroup()) {
427 return $this->localGroup()->getBestName();
428 } else if ($this->isPeopletag()) {
429 return $this->localPeopletag()->getBestName();
431 return $this->localProfile()->getBestName();
436 * Read and post notices for updates from the feed.
437 * Currently assumes that all items in the feed are new,
438 * coming from a WebSub hub.
440 * @param DOMDocument $doc
441 * @param string $source identifier ("push")
443 public function processFeed(DOMDocument $doc, $source)
445 $feed = $doc->documentElement;
447 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
448 $this->processAtomFeed($feed, $source);
449 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
450 $this->processRssFeed($feed, $source);
453 throw new Exception(_m('Unknown feed format.'));
457 public function processAtomFeed(DOMElement $feed, $source)
459 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
460 if ($entries->length == 0) {
461 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
465 $this->processEntries($entries, $feed, $source);
468 public function processRssFeed(DOMElement $rss, $source)
470 $channels = $rss->getElementsByTagName('channel');
472 if ($channels->length == 0) {
474 throw new Exception(_m('RSS feed without a channel.'));
475 } else if ($channels->length > 1) {
476 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
479 $channel = $channels->item(0);
481 $items = $channel->getElementsByTagName('item');
483 $this->processEntries($items, $channel, $source);
486 public function processEntries(DOMNodeList $entries, DOMElement $feed, $source)
488 for ($i = 0; $i < $entries->length; $i++) {
489 $entry = $entries->item($i);
491 $this->processEntry($entry, $feed, $source);
492 } catch (AlreadyFulfilledException $e) {
493 common_debug('We already had this entry: '.$e->getMessage());
494 } catch (ServerException $e) {
495 // FIXME: This should be UnknownUriException and the ActivityUtils:: findLocalObject should only test one URI
496 common_log(LOG_ERR, 'Entry threw exception while processing a feed from '.$source.': '.$e->getMessage());
502 * Process a posted entry from this feed source.
504 * @param DOMElement $entry
505 * @param DOMElement $feed for context
506 * @param string $source identifier ("push" or "salmon")
508 * @return Notice Notice representing the new (or existing) activity
510 public function processEntry(DOMElement $entry, DOMElement $feed, $source)
512 $activity = new Activity($entry, $feed);
513 return $this->processActivity($activity, $source);
516 // TODO: Make this throw an exception
517 public function processActivity(Activity $activity, $source)
521 // The "WithProfile" events were added later.
523 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
524 Event::handle('StartHandleFeedEntry', array($activity))) {
526 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
528 Event::handle('EndHandleFeedEntry', array($activity));
529 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
536 * Process an incoming post activity from this remote feed.
537 * @param Activity $activity
538 * @param string $method 'push' or 'salmon'
539 * @return mixed saved Notice or false
541 public function processPost(Activity $activity, $method)
543 $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
545 $options = array('is_local' => Notice::REMOTE);
548 $stored = Notice::saveActivity($activity, $actor, $options);
549 } catch (Exception $e) {
550 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
557 * Filters a list of recipient ID URIs to just those for local delivery.
558 * @param Profile local profile of sender
559 * @param array in/out &$attention_uris set of URIs, will be pruned on output
560 * @return array of group IDs
562 static public function filterAttention(Profile $sender, array $attention)
564 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
567 foreach ($attention as $recipient=>$type) {
568 // Is the recipient a local user?
569 $user = User::getKV('uri', $recipient);
570 if ($user instanceof User) {
571 // @todo FIXME: Sender verification, spam etc?
572 $replies[] = $recipient;
576 // Is the recipient a local group?
577 // TODO: $group = User_group::getKV('uri', $recipient);
578 $id = OStatusPlugin::localGroupFromUrl($recipient);
580 $group = User_group::getKV('id', $id);
581 if ($group instanceof User_group) {
582 // Deliver to all members of this local group if allowed.
583 if ($sender->isMember($group)) {
584 $groups[] = $group->id;
586 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
590 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
594 // Is the recipient a remote user or group?
596 $oprofile = self::ensureProfileURI($recipient);
597 if ($oprofile->isGroup()) {
598 // Deliver to local members of this remote group.
599 // @todo FIXME: Sender verification?
600 $groups[] = $oprofile->group_id;
602 // may be canonicalized or something
603 $replies[] = $oprofile->getUri();
606 } catch (Exception $e) {
607 // Neither a recognizable local nor remote user!
608 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
612 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
613 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
614 return array($groups, $replies);
618 * Look up and if necessary create an Ostatus_profile for the remote entity
619 * with the given profile page URL. This should never return null -- you
620 * will either get an object or an exception will be thrown.
622 * @param string $profile_url
623 * @return Ostatus_profile
624 * @throws Exception on various error conditions
625 * @throws OStatusShadowException if this reference would obscure a local user/group
627 public static function ensureProfileURL($profile_url, array $hints=array())
629 $oprofile = self::getFromProfileURL($profile_url);
631 if ($oprofile instanceof Ostatus_profile) {
635 $hints['profileurl'] = $profile_url;
640 $client = new HTTPClient();
641 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
642 $response = $client->get($profile_url);
644 if (!$response->isOk()) {
645 // TRANS: Exception. %s is a profile URL.
646 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
649 // Check if we have a non-canonical URL
651 $finalUrl = $response->getEffectiveUrl();
653 if ($finalUrl != $profile_url) {
655 $hints['profileurl'] = $finalUrl;
657 $oprofile = self::getFromProfileURL($finalUrl);
659 if ($oprofile instanceof Ostatus_profile) {
665 preg_replace('/\s*;.*$/', '', $response->getHeader('Content-Type')),
666 array('application/rss+xml', 'application/atom+xml', 'application/xml', 'text/xml'))
668 $hints['feedurl'] = $response->getEffectiveUrl();
670 // Try to get some hCard data
672 $body = $response->getBody();
674 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
676 if (!empty($hcardHints)) {
677 $hints = array_merge($hints, $hcardHints);
681 // Check if they've got an LRDD header
683 $lrdd = LinkHeader::getLink($response, 'lrdd');
685 $xrd = new XML_XRD();
686 $xrd->loadFile($lrdd);
687 $xrdHints = DiscoveryHints::fromXRD($xrd);
688 $hints = array_merge($hints, $xrdHints);
689 } catch (Exception $e) {
690 // No hints available from XRD
693 // If discovery found a feedurl (probably from LRDD), use it.
695 if (array_key_exists('feedurl', $hints)) {
696 return self::ensureFeedURL($hints['feedurl'], $hints);
699 // Get the feed URL from HTML
701 $discover = new FeedDiscovery();
703 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
705 if (!empty($feedurl)) {
706 $hints['feedurl'] = $feedurl;
707 return self::ensureFeedURL($feedurl, $hints);
710 // TRANS: Exception. %s is a URL.
711 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
715 * Look up the Ostatus_profile, if present, for a remote entity with the
716 * given profile page URL. Will return null for both unknown and invalid
719 * @return mixed Ostatus_profile or null
720 * @throws OStatusShadowException for local profiles
722 static function getFromProfileURL($profile_url)
724 $profile = Profile::getKV('profileurl', $profile_url);
725 if (!$profile instanceof Profile) {
730 $oprofile = self::getFromProfile($profile);
731 // We found the profile, return it!
733 } catch (NoResultException $e) {
734 // Could not find an OStatus profile, is it instead a local user?
735 $user = User::getKV('id', $profile->id);
736 if ($user instanceof User) {
737 // @todo i18n FIXME: use sprintf and add i18n (?)
738 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
742 // Continue discovery; it's a remote profile
743 // for OMB or some other protocol, may also
749 static function getFromProfile(Profile $profile)
751 $oprofile = new Ostatus_profile();
752 $oprofile->profile_id = $profile->id;
753 if (!$oprofile->find(true)) {
754 throw new NoResultException($oprofile);
760 * Look up and if necessary create an Ostatus_profile for remote entity
761 * with the given update feed. This should never return null -- you will
762 * either get an object or an exception will be thrown.
764 * @return Ostatus_profile
767 public static function ensureFeedURL($feed_url, array $hints=array())
769 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
770 if ($oprofile instanceof Ostatus_profile) {
774 $discover = new FeedDiscovery();
776 $feeduri = $discover->discoverFromFeedURL($feed_url);
777 $hints['feedurl'] = $feeduri;
779 $huburi = $discover->getHubLink();
780 $hints['hub'] = $huburi;
782 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
783 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
784 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
785 $hints['salmon'] = $salmonuri;
787 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
788 // We can only deal with folks with a WebSub hub
789 // unless we have something similar available locally.
790 throw new FeedSubNoHubException();
793 $feedEl = $discover->root;
795 if ($feedEl->tagName == 'feed') {
796 return self::ensureAtomFeed($feedEl, $hints);
797 } else if ($feedEl->tagName == 'channel') {
798 return self::ensureRssChannel($feedEl, $hints);
800 throw new FeedSubBadXmlException($feeduri);
805 * Look up and, if necessary, create an Ostatus_profile for the remote
806 * profile with the given Atom feed - actually loaded from the feed.
807 * This should never return null -- you will either get an object or
808 * an exception will be thrown.
810 * @param DOMElement $feedEl root element of a loaded Atom feed
811 * @param array $hints additional discovery information passed from higher levels
812 * @todo FIXME: Should this be marked public?
813 * @return Ostatus_profile
816 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
818 $author = ActivityUtils::getFeedAuthor($feedEl);
820 if (empty($author)) {
821 // XXX: make some educated guesses here
822 // TRANS: Feed sub exception.
823 throw new FeedSubException(_m('Cannot find enough profile '.
824 'information to make a feed.'));
827 return self::ensureActivityObjectProfile($author, $hints);
831 * Look up and, if necessary, create an Ostatus_profile for the remote
832 * profile with the given RSS feed - actually loaded from the feed.
833 * This should never return null -- you will either get an object or
834 * an exception will be thrown.
836 * @param DOMElement $feedEl root element of a loaded RSS feed
837 * @param array $hints additional discovery information passed from higher levels
838 * @todo FIXME: Should this be marked public?
839 * @return Ostatus_profile
842 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
844 // Special-case for Posterous. They have some nice metadata in their
845 // posterous:author elements. We should use them instead of the channel.
847 $items = $feedEl->getElementsByTagName('item');
849 if ($items->length > 0) {
850 $item = $items->item(0);
851 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
852 if (!empty($authorEl)) {
853 $obj = ActivityObject::fromPosterousAuthor($authorEl);
854 // Posterous has multiple authors per feed, and multiple feeds
855 // per author. We check if this is the "main" feed for this author.
856 if (array_key_exists('profileurl', $hints) &&
857 !empty($obj->poco) &&
858 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
859 return self::ensureActivityObjectProfile($obj, $hints);
864 $obj = ActivityUtils::getFeedAuthor($feedEl);
866 // @todo FIXME: We should check whether this feed has elements
867 // with different <author> or <dc:creator> elements, and... I dunno.
868 // Do something about that.
870 if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
872 return self::ensureActivityObjectProfile($obj, $hints);
876 * Download and update given avatar image
879 * @return Avatar The Avatar we have on disk. (seldom used)
880 * @throws Exception in various failure cases
882 public function updateAvatar($url, $force=false)
885 // If avatar URL differs: update. If URLs were identical but we're forced: update.
886 if ($url == $this->avatar && !$force) {
887 // If there's no locally stored avatar, throw an exception and continue fetching below.
888 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
891 } catch (NoAvatarException $e) {
892 // No avatar available, let's fetch it.
895 if (!common_valid_http_url($url)) {
896 // TRANS: Server exception. %s is a URL.
897 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
900 $self = $this->localProfile();
902 // @todo FIXME: This should be better encapsulated
903 // ripped from oauthstore.php (for old OMB client)
904 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
906 $imgData = HTTPClient::quickGet($url);
907 // Make sure it's at least an image file. ImageFile can do the rest.
908 if (false === getimagesizefromstring($imgData)) {
909 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
911 file_put_contents($temp_filename, $imgData);
912 unset($imgData); // No need to carry this in memory.
914 if ($this->isGroup()) {
915 $id = $this->group_id;
917 $id = $this->profile_id;
919 $imagefile = new ImageFile(null, $temp_filename);
920 $filename = Avatar::filename($id,
921 image_type_to_extension($imagefile->type),
924 rename($temp_filename, Avatar::path($filename));
925 } catch (Exception $e) {
926 unlink($temp_filename);
929 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
930 // keep from accidentally saving images from command-line (queues)
931 // that can't be read from web server, which causes hard-to-notice
932 // problems later on:
934 // http://status.net/open-source/issues/2663
935 chmod(Avatar::path($filename), 0644);
937 $self->setOriginal($filename);
939 $orig = clone($this);
940 $this->avatar = $url;
941 $this->update($orig);
943 return Avatar::getUploaded($self);
947 * Pull avatar URL from ActivityObject or profile hints
949 * @param ActivityObject $object
950 * @param array $hints
951 * @return mixed URL string or false
953 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
955 if ($object->avatarLinks) {
957 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
958 foreach ($object->avatarLinks as $avatar) {
959 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
964 if (!$best || $avatar->width > $best->width) {
969 } else if (array_key_exists('avatar', $hints)) {
970 return $hints['avatar'];
976 * Get an appropriate avatar image source URL, if available.
978 * @param ActivityObject $actor
979 * @param DOMElement $feed
982 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
986 if ($actor->avatar) {
987 $url = trim($actor->avatar);
990 // Check <atom:logo> and <atom:icon> on the feed
991 $els = $feed->childNodes();
992 if ($els && $els->length) {
993 for ($i = 0; $i < $els->length; $i++) {
994 $el = $els->item($i);
995 if ($el->namespaceURI == Activity::ATOM) {
996 if (empty($url) && $el->localName == 'logo') {
997 $url = trim($el->textContent);
1000 if (empty($icon) && $el->localName == 'icon') {
1001 // Use as a fallback
1002 $icon = trim($el->textContent);
1007 if ($icon && !$url) {
1012 $opts = array('allowed_schemes' => array('http', 'https'));
1013 if (common_valid_http_url($url)) {
1018 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1022 * Fetch, or build if necessary, an Ostatus_profile for the actor
1023 * in a given Activity Streams activity.
1024 * This should never return null -- you will either get an object or
1025 * an exception will be thrown.
1027 * @param Activity $activity
1028 * @param string $feeduri if we already know the canonical feed URI!
1029 * @param string $salmonuri if we already know the salmon return channel URI
1030 * @return Ostatus_profile
1033 public static function ensureActorProfile(Activity $activity, array $hints=array())
1035 return self::ensureActivityObjectProfile($activity->actor, $hints);
1039 * Fetch, or build if necessary, an Ostatus_profile for the profile
1040 * in a given Activity Streams object (can be subject, actor, or object).
1041 * This should never return null -- you will either get an object or
1042 * an exception will be thrown.
1044 * @param ActivityObject $object
1045 * @param array $hints additional discovery information passed from higher levels
1046 * @return Ostatus_profile
1049 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1051 $profile = self::getActivityObjectProfile($object);
1052 if ($profile instanceof Ostatus_profile) {
1053 $profile->updateFromActivityObject($object, $hints);
1055 $profile = self::createActivityObjectProfile($object, $hints);
1061 * @param Activity $activity
1062 * @return mixed matching Ostatus_profile or false if none known
1063 * @throws ServerException if feed info invalid
1065 public static function getActorProfile(Activity $activity)
1067 return self::getActivityObjectProfile($activity->actor);
1071 * @param ActivityObject $activity
1072 * @return mixed matching Ostatus_profile or false if none known
1073 * @throws ServerException if feed info invalid
1075 protected static function getActivityObjectProfile(ActivityObject $object)
1077 $uri = self::getActivityObjectProfileURI($object);
1078 return Ostatus_profile::getKV('uri', $uri);
1082 * Get the identifier URI for the remote entity described
1083 * by this ActivityObject. This URI is *not* guaranteed to be
1084 * a resolvable HTTP/HTTPS URL.
1086 * @param ActivityObject $object
1088 * @throws ServerException if feed info invalid
1090 protected static function getActivityObjectProfileURI(ActivityObject $object)
1093 if (ActivityUtils::validateUri($object->id)) {
1098 // If the id is missing or invalid (we've seen feeds mistakenly listing
1099 // things like local usernames in that field) then we'll use the profile
1100 // page link, if valid.
1101 if ($object->link && common_valid_http_url($object->link)) {
1102 return $object->link;
1104 // TRANS: Server exception.
1105 throw new ServerException(_m('No author ID URI found.'));
1109 * @todo FIXME: Validate stuff somewhere.
1113 * Create local ostatus_profile and profile/user_group entries for
1114 * the provided remote user or group.
1115 * This should never return null -- you will either get an object or
1116 * an exception will be thrown.
1118 * @param ActivityObject $object
1119 * @param array $hints
1121 * @return Ostatus_profile
1123 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1125 common_debug('Attempting to create an Ostatus_profile from an ActivityObject with ID: '._ve($object->id));
1127 $homeuri = $object->id;
1131 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1132 // TRANS: Exception.
1133 throw new Exception(_m('No profile URI.'));
1136 $user = User::getKV('uri', $homeuri);
1137 if ($user instanceof User) {
1138 // TRANS: Exception.
1139 throw new Exception(_m('Local user cannot be referenced as remote.'));
1142 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1143 // TRANS: Exception.
1144 throw new Exception(_m('Local group cannot be referenced as remote.'));
1147 $ptag = Profile_list::getKV('uri', $homeuri);
1148 if ($ptag instanceof Profile_list) {
1149 $local_user = User::getKV('id', $ptag->tagger);
1150 if ($local_user instanceof User) {
1151 // TRANS: Exception.
1152 throw new Exception(_m('Local list cannot be referenced as remote.'));
1156 if (!array_key_exists('feedurl', $hints)) {
1157 $discover = new FeedDiscovery();
1158 $hints['feedurl'] = $discover->discoverFromURL($homeuri);
1159 common_debug(__METHOD__.' did not have a "feedurl" hint, FeedDiscovery found '._ve($hints['feedurl']));
1161 $feeduri = $hints['feedurl'];
1163 if (array_key_exists('salmon', $hints)) {
1164 $salmonuri = $hints['salmon'];
1167 $discover = new FeedDiscovery();
1168 $discover->discoverFromFeedURL($hints['feedurl']);
1170 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1171 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1172 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1175 if (array_key_exists('hub', $hints)) {
1176 $huburi = $hints['hub'];
1179 $discover = new FeedDiscovery();
1180 $discover->discoverFromFeedURL($hints['feedurl']);
1182 $huburi = $discover->getHubLink();
1185 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1186 // We can only deal with folks with a WebSub hub
1187 throw new FeedSubNoHubException();
1190 $oprofile = new Ostatus_profile();
1192 $oprofile->uri = $homeuri;
1193 $oprofile->feeduri = $feeduri;
1194 $oprofile->salmonuri = $salmonuri;
1196 $oprofile->created = common_sql_now();
1197 $oprofile->modified = common_sql_now();
1199 if ($object->type == ActivityObject::PERSON) {
1200 $profile = new Profile();
1201 $profile->created = common_sql_now();
1202 self::updateProfile($profile, $object, $hints);
1204 $oprofile->profile_id = $profile->insert();
1205 if ($oprofile->profile_id === false) {
1206 // TRANS: Server exception.
1207 throw new ServerException(_m('Cannot save local profile.'));
1209 } else if ($object->type == ActivityObject::GROUP) {
1210 $profile = new Profile();
1211 $profile->query('BEGIN');
1213 $group = new User_group();
1214 $group->uri = $homeuri;
1215 $group->created = common_sql_now();
1216 self::updateGroup($group, $object, $hints);
1218 // TODO: We should do this directly in User_group->insert()!
1219 // currently it's duplicated in User_group->update()
1220 // AND User_group->register()!!!
1221 $fields = array(/*group field => profile field*/
1222 'nickname' => 'nickname',
1223 'fullname' => 'fullname',
1224 'mainpage' => 'profileurl',
1225 'homepage' => 'homepage',
1226 'description' => 'bio',
1227 'location' => 'location',
1228 'created' => 'created',
1229 'modified' => 'modified',
1231 foreach ($fields as $gf=>$pf) {
1232 $profile->$pf = $group->$gf;
1234 $profile_id = $profile->insert();
1235 if ($profile_id === false) {
1236 $profile->query('ROLLBACK');
1237 throw new ServerException(_('Profile insertion failed.'));
1240 $group->profile_id = $profile_id;
1242 $oprofile->group_id = $group->insert();
1243 if ($oprofile->group_id === false) {
1244 $profile->query('ROLLBACK');
1245 // TRANS: Server exception.
1246 throw new ServerException(_m('Cannot save local profile.'));
1249 $profile->query('COMMIT');
1250 } else if ($object->type == ActivityObject::_LIST) {
1251 $ptag = new Profile_list();
1252 $ptag->uri = $homeuri;
1253 $ptag->created = common_sql_now();
1254 self::updatePeopletag($ptag, $object, $hints);
1256 $oprofile->peopletag_id = $ptag->insert();
1257 if ($oprofile->peopletag_id === false) {
1258 // TRANS: Server exception.
1259 throw new ServerException(_m('Cannot save local list.'));
1263 $ok = $oprofile->insert();
1265 if ($ok === false) {
1266 // TRANS: Server exception.
1267 throw new ServerException(_m('Cannot save OStatus profile.'));
1270 $avatar = self::getActivityObjectAvatar($object, $hints);
1274 $oprofile->updateAvatar($avatar);
1275 } catch (Exception $ex) {
1276 // Profile is saved, but Avatar is messed up. We're
1277 // just going to continue.
1278 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1286 * Save any updated profile information to our local copy.
1287 * @param ActivityObject $object
1288 * @param array $hints
1290 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1292 if (self::getActivityObjectProfileURI($object) !== $this->getUri()) {
1293 common_log(LOG_ERR, 'Trying to update profile with URI '._ve($this->getUri()).' from ActivityObject with URI: '._ve(self::getActivityObjectProfileURI($object)));
1294 // FIXME: Maybe not AuthorizationException?
1295 throw new AuthorizationException('Trying to update profile from ActivityObject with different URI.');
1298 common_debug('Updating Ostatus_profile with URI '._ve($this->getUri()).' from ActivityObject');
1300 if ($this->isGroup()) {
1301 $group = $this->localGroup();
1302 self::updateGroup($group, $object, $hints);
1303 } else if ($this->isPeopletag()) {
1304 $ptag = $this->localPeopletag();
1305 self::updatePeopletag($ptag, $object, $hints);
1307 $profile = $this->localProfile();
1308 self::updateProfile($profile, $object, $hints);
1311 $avatar = self::getActivityObjectAvatar($object, $hints);
1312 if ($avatar && !isset($ptag)) {
1314 $this->updateAvatar($avatar);
1315 } catch (Exception $e) {
1316 common_log(LOG_WARNING, 'Exception ('.get_class($e).') updating OStatus profile avatar: ' . $e->getMessage());
1321 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1323 $orig = clone($profile);
1325 // Existing nickname is better than nothing.
1327 if (!array_key_exists('nickname', $hints)) {
1328 $hints['nickname'] = $profile->nickname;
1331 $nickname = self::getActivityObjectNickname($object, $hints);
1333 if (!empty($nickname)) {
1334 $profile->nickname = $nickname;
1337 if (!empty($object->title)) {
1338 $profile->fullname = $object->title;
1339 } else if (array_key_exists('fullname', $hints)) {
1340 $profile->fullname = $hints['fullname'];
1343 if (!empty($object->link)) {
1344 $profile->profileurl = $object->link;
1345 } else if (array_key_exists('profileurl', $hints)) {
1346 $profile->profileurl = $hints['profileurl'];
1347 } else if (common_valid_http_url($object->id)) {
1348 $profile->profileurl = $object->id;
1351 $bio = self::getActivityObjectBio($object, $hints);
1354 $profile->bio = $bio;
1357 $location = self::getActivityObjectLocation($object, $hints);
1359 if (!empty($location)) {
1360 $profile->location = $location;
1363 $homepage = self::getActivityObjectHomepage($object, $hints);
1365 if (!empty($homepage)) {
1366 $profile->homepage = $homepage;
1369 if (!empty($object->geopoint)) {
1370 $location = ActivityContext::locationFromPoint($object->geopoint);
1371 if (!empty($location)) {
1372 $profile->lat = $location->lat;
1373 $profile->lon = $location->lon;
1377 // @todo FIXME: tags/categories
1378 // @todo tags from categories
1381 //common_debug('Updating OStatus profile '._ve($profile->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1382 common_debug('Updating OStatus profile '._ve($profile->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1383 $profile->update($orig);
1387 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1389 $orig = clone($group);
1391 $group->nickname = self::getActivityObjectNickname($object, $hints);
1392 $group->fullname = $object->title;
1394 if (!empty($object->link)) {
1395 $group->mainpage = $object->link;
1396 } else if (array_key_exists('profileurl', $hints)) {
1397 $group->mainpage = $hints['profileurl'];
1400 // @todo tags from categories
1401 $group->description = self::getActivityObjectBio($object, $hints);
1402 $group->location = self::getActivityObjectLocation($object, $hints);
1403 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1405 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1406 //common_debug('Updating OStatus group '._ve($group->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1407 common_debug('Updating OStatus group '._ve($group->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1408 $group->update($orig);
1412 protected static function updatePeopletag(Peopletag $tag, ActivityObject $object, array $hints=array()) {
1413 $orig = clone($tag);
1415 $tag->tag = $object->title;
1417 if (!empty($object->link)) {
1418 $tag->mainpage = $object->link;
1419 } else if (array_key_exists('profileurl', $hints)) {
1420 $tag->mainpage = $hints['profileurl'];
1423 $tag->description = $object->summary;
1424 $tagger = self::ensureActivityObjectProfile($object->owner);
1425 $tag->tagger = $tagger->profile_id;
1428 //common_debug('Updating OStatus peopletag '._ve($tag->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1429 common_debug('Updating OStatus peopletag '._ve($tag->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1430 $tag->update($orig);
1434 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1437 $poco = $object->poco;
1439 if (!empty($poco)) {
1440 $url = $poco->getPrimaryURL();
1441 if ($url && $url->type == 'homepage') {
1442 $homepage = $url->value;
1446 // @todo Try for a another PoCo URL?
1451 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1455 if (!empty($object->poco) &&
1456 isset($object->poco->address->formatted)) {
1457 $location = $object->poco->address->formatted;
1458 } else if (array_key_exists('location', $hints)) {
1459 $location = $hints['location'];
1462 if (!empty($location)) {
1463 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1464 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1468 // @todo Try to find location some othe way? Via goerss point?
1473 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1477 if (!empty($object->poco)) {
1478 $note = $object->poco->note;
1479 } else if (array_key_exists('bio', $hints)) {
1480 $note = $hints['bio'];
1483 if (!empty($note)) {
1484 if (Profile::bioTooLong($note)) {
1485 // XXX: truncate ok?
1486 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1492 // @todo Try to get bio info some other way?
1497 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1499 if ($object->poco) {
1500 if (!empty($object->poco->preferredUsername)) {
1501 return common_nicknamize($object->poco->preferredUsername);
1505 if (!empty($object->nickname)) {
1506 return common_nicknamize($object->nickname);
1509 if (array_key_exists('nickname', $hints)) {
1510 return $hints['nickname'];
1513 // Try the profile url (like foo.example.com or example.com/user/foo)
1514 if (!empty($object->link)) {
1515 $profileUrl = $object->link;
1516 } else if (!empty($hints['profileurl'])) {
1517 $profileUrl = $hints['profileurl'];
1520 if (!empty($profileUrl)) {
1521 $nickname = self::nicknameFromURI($profileUrl);
1524 // Try the URI (may be a tag:, http:, acct:, ...
1526 if (empty($nickname)) {
1527 $nickname = self::nicknameFromURI($object->id);
1530 // Try a Webfinger if one was passed (way) down
1532 if (empty($nickname)) {
1533 if (array_key_exists('webfinger', $hints)) {
1534 $nickname = self::nicknameFromURI($hints['webfinger']);
1540 if (empty($nickname)) {
1541 $nickname = common_nicknamize($object->title);
1547 protected static function nicknameFromURI($uri)
1549 if (preg_match('/(\w+):/', $uri, $matches)) {
1550 $protocol = $matches[1];
1555 switch ($protocol) {
1558 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1559 return common_canonical_nickname($matches[1]);
1563 return common_url_to_nickname($uri);
1571 * Look up, and if necessary create, an Ostatus_profile for the remote
1572 * entity with the given webfinger address.
1573 * This should never return null -- you will either get an object or
1574 * an exception will be thrown.
1576 * @param string $addr webfinger address
1577 * @return Ostatus_profile
1578 * @throws Exception on error conditions
1579 * @throws OStatusShadowException if this reference would obscure a local user/group
1581 public static function ensureWebfinger($addr)
1583 // Normalize $addr, i.e. add 'acct:' if missing
1584 $addr = Discovery::normalize($addr);
1587 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1589 if ($uri !== false) {
1590 if (is_null($uri)) {
1591 // Negative cache entry
1592 // TRANS: Exception.
1593 throw new Exception(_m('Not a valid webfinger address (via cache).'));
1595 $oprofile = Ostatus_profile::getKV('uri', $uri);
1596 if ($oprofile instanceof Ostatus_profile) {
1599 common_log(LOG_ERR, sprintf(__METHOD__ . ': Webfinger address cache inconsistent with database, did not find Ostatus_profile uri==%s', $uri));
1600 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), false);
1603 // Try looking it up
1604 $oprofile = Ostatus_profile::getKV('uri', $addr);
1606 if ($oprofile instanceof Ostatus_profile) {
1607 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1611 // Now, try some discovery
1613 $disco = new Discovery();
1616 $xrd = $disco->lookup($addr);
1617 } catch (Exception $e) {
1618 // Save negative cache entry so we don't waste time looking it up again.
1619 // @todo FIXME: Distinguish temporary failures?
1620 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1621 // TRANS: Exception.
1622 throw new Exception(_m('Not a valid webfinger address.'));
1625 $hints = array_merge(array('webfinger' => $addr),
1626 DiscoveryHints::fromXRD($xrd));
1628 // If there's an Hcard, let's grab its info
1629 if (array_key_exists('hcard', $hints)) {
1630 if (!array_key_exists('profileurl', $hints) ||
1631 $hints['hcard'] != $hints['profileurl']) {
1632 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1633 $hints = array_merge($hcardHints, $hints);
1637 // If we got a feed URL, try that
1639 if (array_key_exists('feedurl', $hints)) {
1640 $feedUrl = $hints['feedurl'];
1642 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1643 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1644 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1646 } catch (Exception $e) {
1647 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1652 // If we got a profile page, try that!
1654 if (array_key_exists('profileurl', $hints)) {
1655 $profileUrl = $hints['profileurl'];
1657 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1658 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1659 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1661 } catch (OStatusShadowException $e) {
1662 // We've ended up with a remote reference to a local user or group.
1663 // @todo FIXME: Ideally we should be able to say who it was so we can
1664 // go back and refer to it the regular way
1666 } catch (Exception $e) {
1667 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1670 // @todo FIXME: This means an error discovering from profile page
1671 // may give us a corrupt entry using the webfinger URI, which
1672 // will obscure the correct page-keyed profile later on.
1679 if (array_key_exists('salmon', $hints)) {
1680 $salmonEndpoint = $hints['salmon'];
1682 // An account URL, a salmon endpoint, and a dream? Not much to go
1683 // on, but let's give it a try
1685 $uri = 'acct:'.$addr;
1687 $profile = new Profile();
1689 $profile->nickname = self::nicknameFromUri($uri);
1690 $profile->created = common_sql_now();
1692 if (!is_null($profileUrl)) {
1693 $profile->profileurl = $profileUrl;
1696 $profile_id = $profile->insert();
1698 if ($profile_id === false) {
1699 common_log_db_error($profile, 'INSERT', __FILE__);
1700 // TRANS: Exception. %s is a webfinger address.
1701 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1704 $oprofile = new Ostatus_profile();
1706 $oprofile->uri = $uri;
1707 $oprofile->salmonuri = $salmonEndpoint;
1708 $oprofile->profile_id = $profile_id;
1709 $oprofile->created = common_sql_now();
1711 if (!is_null($feedUrl)) {
1712 $oprofile->feeduri = $feedUrl;
1715 $result = $oprofile->insert();
1717 if ($result === false) {
1719 common_log_db_error($oprofile, 'INSERT', __FILE__);
1720 // TRANS: Exception. %s is a webfinger address.
1721 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1724 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1728 // TRANS: Exception. %s is a webfinger address.
1729 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1733 * Store the full-length scrubbed HTML of a remote notice to an attachment
1734 * file on our server. We'll link to this at the end of the cropped version.
1736 * @param string $title plaintext for HTML page's title
1737 * @param string $rendered HTML fragment for HTML page's body
1740 function saveHTMLFile($title, $rendered)
1742 $final = sprintf("<!DOCTYPE html>\n" .
1744 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1745 '<title>%s</title>' .
1747 '<body>%s</body></html>',
1748 htmlspecialchars($title),
1751 $filename = File::filename($this->localProfile(),
1752 'ostatus', // ignored?
1755 $filepath = File::path($filename);
1756 $fileurl = File::url($filename);
1758 file_put_contents($filepath, $final);
1762 $file->filename = $filename;
1763 $file->urlhash = File::hashurl($fileurl);
1764 $file->url = $fileurl;
1765 $file->size = filesize($filepath);
1766 $file->date = time();
1767 $file->mimetype = 'text/html';
1769 $file_id = $file->insert();
1771 if ($file_id === false) {
1772 common_log_db_error($file, "INSERT", __FILE__);
1773 // TRANS: Server exception.
1774 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1780 static function ensureProfileURI($uri)
1784 // First, try to query it
1786 $oprofile = Ostatus_profile::getKV('uri', $uri);
1788 if ($oprofile instanceof Ostatus_profile) {
1792 // If unfound, do discovery stuff
1793 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1794 $protocol = $match[1];
1795 switch ($protocol) {
1798 $oprofile = self::ensureProfileURL($uri);
1803 $oprofile = self::ensureWebfinger($rest);
1806 // TRANS: Server exception.
1807 // TRANS: %1$s is a protocol, %2$s is a URI.
1808 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1813 // TRANS: Server exception. %s is a URI.
1814 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1820 public function checkAuthorship(Activity $activity)
1822 if ($this->isGroup() || $this->isPeopletag()) {
1823 // A group or propletag feed will contain posts from multiple authors.
1824 $oprofile = self::ensureActorProfile($activity);
1825 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1826 // Groups can't post notices in StatusNet.
1827 common_log(LOG_WARNING,
1828 "OStatus: skipping post with group listed ".
1829 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1830 throw new ServerException('Activity author is a non-actor');
1833 $actor = $activity->actor;
1835 if (!$actor instanceof Profile) {
1836 // OK here! assume the default
1837 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1838 $this->updateFromActivityObject($actor);
1839 } else if ($actor->id) {
1840 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1841 // This isn't what we expect from mainline OStatus person feeds!
1842 // Group feeds go down another path, with different validation...
1843 // Most likely this is a plain ol' blog feed of some kind which
1844 // doesn't match our expectations. We'll take the entry, but ignore
1845 // the <author> info.
1846 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1848 // Plain <author> without ActivityStreams actor info.
1849 // We'll just ignore this info for now and save the update under the feed's identity.
1855 return $oprofile->localProfile();
1858 public function updateUriKeys($profile_uri, array $hints=array())
1860 $orig = clone($this);
1862 common_debug('URIFIX These identities both say they are each other: '._ve($orig->uri).' and '._ve($profile_uri));
1863 $this->uri = $profile_uri;
1865 if (array_key_exists('feedurl', $hints) && common_valid_http_url($hints['feedurl'])) {
1867 $feedsub = $this->getFeedSub();
1868 common_debug('URIFIX Changing FeedSub id==['._ve($feedsub->id).'] feeduri '._ve($feedsub->uri).' to '._ve($hints['feedurl']));
1869 $feedorig = clone($feedsub);
1870 $feedsub->uri = $hints['feedurl'];
1871 $feedsub->updateWithKeys($feedorig);
1872 } catch (EmptyPkeyValueException $e) {
1873 common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring new feedurl: '._ve($hints['feedurl']));
1874 FeedSub::ensureFeed($hints['feedurl']);
1875 } catch (NoResultException $e) {
1876 common_debug('URIFIX Missing FeedSub entry for the Ostatus_profile, ensuring new feedurl: '._ve($hints['feedurl']));
1877 FeedSub::ensureFeed($hints['feedurl']);
1879 $this->feeduri = $hints['feedurl'];
1880 } elseif (array_key_exists('feedurl')) {
1881 common_log(LOG_WARN, 'The feedurl hint we got was not a valid HTTP URL: '._ve($hints['feedurl']));
1884 if (array_key_exists('salmon', $hints)) {
1885 common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
1886 $this->salmonuri = $hints['salmon'];
1889 common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
1890 $this->updateWithKeys($orig); // Will use the PID column(s) in the 'UPDATE ... WHERE [unique selector]'
1892 common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);