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 fromProfile(Profile $profile)
85 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
86 if (!$oprofile instanceof Ostatus_profile) {
87 throw new Exception('No Ostatus_profile for Profile ID: '.$profile->id);
92 * Fetch the locally stored profile for this feed
94 * @throws NoProfileException if it was not found
96 public function localProfile()
98 if ($this->isGroup()) {
99 return $this->localGroup()->getProfile();
102 $profile = Profile::getKV('id', $this->profile_id);
103 if (!$profile instanceof Profile) {
104 throw new NoProfileException($this->profile_id);
110 * Fetch the StatusNet-side profile for this feed
113 public function localGroup()
115 $group = User_group::getKV('id', $this->group_id);
117 if (!$group instanceof User_group) {
118 throw new NoSuchGroupException(array('id'=>$this->group_id));
125 * Fetch the StatusNet-side peopletag for this feed
128 public function localPeopletag()
130 if ($this->peopletag_id) {
131 return Profile_list::getKV('id', $this->peopletag_id);
137 * Returns an ActivityObject describing this remote user or group profile.
138 * Can then be used to generate Atom chunks.
140 * @return ActivityObject
142 function asActivityObject()
144 if ($this->isGroup()) {
145 return ActivityObject::fromGroup($this->localGroup());
146 } else if ($this->isPeopletag()) {
147 return ActivityObject::fromPeopletag($this->localPeopletag());
149 return $this->localProfile()->asActivityObject();
154 * Returns an XML string fragment with profile information as an
155 * Activity Streams noun object with the given element type.
157 * Assumes that 'activity' namespace has been previously defined.
159 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
161 * @param string $element one of 'actor', 'subject', 'object', 'target'
164 function asActivityNoun($element)
166 if ($this->isGroup()) {
167 $noun = ActivityObject::fromGroup($this->localGroup());
168 return $noun->asString('activity:' . $element);
169 } else if ($this->isPeopletag()) {
170 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
171 return $noun->asString('activity:' . $element);
173 $noun = $this->localProfile()->asActivityObject();
174 return $noun->asString('activity:' . $element);
179 * @return boolean true if this is a remote group
183 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
185 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
187 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
188 // TRANS: Server exception. %s is a URI
189 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
191 // TRANS: Server exception. %s is a URI
192 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
197 * @return boolean true if this is a remote peopletag
199 function isPeopletag()
201 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
203 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
205 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
206 // TRANS: Server exception. %s is a URI
207 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
209 // TRANS: Server exception. %s is a URI
210 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
215 * Send a subscription request to the hub for this feed.
216 * The hub will later send us a confirmation POST to /main/push/callback.
219 * @throws ServerException if feed state is not valid or subscription fails.
221 public function subscribe()
223 $feedsub = FeedSub::ensureFeed($this->feeduri);
224 if ($feedsub->sub_state == 'active') {
225 // Active subscription, we don't need to do anything.
229 // Inactive or we got left in an inconsistent state.
230 // Run a subscription request to make sure we're current!
231 return $feedsub->subscribe();
235 * Check if this remote profile has any active local subscriptions, and
236 * if not drop the PuSH subscription feed.
238 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
239 * @throws Exception of various kinds on failure.
241 public function unsubscribe() {
242 return $this->garbageCollect();
246 * Check if this remote profile has any active local subscriptions, and
247 * if not drop the PuSH 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 garbageCollect()
254 $feedsub = FeedSub::getKV('uri', $this->feeduri);
255 if ($feedsub instanceof FeedSub) {
256 return $feedsub->garbageCollect();
258 // Since there's no FeedSub we can assume it's already garbage collected
263 * Check if this remote profile has any active local subscriptions, so the
264 * PuSH subscription layer can decide if it can drop the feed.
266 * This gets called via the FeedSubSubscriberCount event when running
267 * FeedSub::garbageCollect().
270 * @throws NoProfileException if there is no local profile for the object
272 public function subscriberCount()
274 if ($this->isGroup()) {
275 $members = $this->localGroup()->getMembers(0, 1);
276 $count = $members->N;
277 } else if ($this->isPeopletag()) {
278 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
279 $count = $subscribers->N;
281 $profile = $this->localProfile();
282 if ($profile->hasLocalTags()) {
285 $count = $profile->subscriberCount();
288 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
290 // Other plugins may be piggybacking on OStatus without having
291 // an active group or user-to-user subscription we know about.
292 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
293 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
299 * Send an Activity Streams notification to the remote Salmon endpoint,
302 * @param Profile $actor Actor who did the activity
303 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
304 * @param Object $object object of the action; must define asActivityNoun($tag)
306 public function notify(Profile $actor, $verb, $object=null, $target=null)
308 if ($object == null) {
311 if (empty($this->salmonuri)) {
315 $id = TagURI::mint('%s:%s:%s',
318 common_date_iso8601(time()));
320 // @todo FIXME: Consolidate all these NS settings somewhere.
321 $attributes = array('xmlns' => Activity::ATOM,
322 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
323 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
324 'xmlns:georss' => 'http://www.georss.org/georss',
325 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
326 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
327 'xmlns:media' => 'http://purl.org/syndication/atommedia');
329 $entry = new XMLStringer();
330 $entry->elementStart('entry', $attributes);
331 $entry->element('id', null, $id);
332 $entry->element('title', null, $text);
333 $entry->element('summary', null, $text);
334 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
336 $entry->element('activity:verb', null, $verb);
337 $entry->raw($actor->asAtomAuthor());
338 $entry->raw($actor->asActivityActor());
339 $entry->raw($object->asActivityNoun('object'));
340 if ($target != null) {
341 $entry->raw($target->asActivityNoun('target'));
343 $entry->elementEnd('entry');
345 $xml = $entry->getString();
346 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
348 Salmon::post($this->salmonuri, $xml, $actor);
352 * Send a Salmon notification ping immediately, and confirm that we got
353 * an acceptable response from the remote site.
355 * @param mixed $entry XML string, Notice, or Activity
356 * @param Profile $actor
357 * @return boolean success
359 public function notifyActivity($entry, Profile $actor)
361 if ($this->salmonuri) {
362 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor, $this->localProfile());
364 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
370 * Queue a Salmon notification for later. If queues are disabled we'll
371 * send immediately but won't get the return value.
373 * @param mixed $entry XML string, Notice, or Activity
374 * @param Profile $actor Acting profile
375 * @return boolean success
377 public function notifyDeferred($entry, Profile $actor)
379 if ($this->salmonuri) {
381 common_debug("OSTATUS: user {$actor->getNickname()} ({$actor->getID()}) wants to ping {$this->localProfile()->getNickname()} on {$this->salmonuri}");
382 $data = array('salmonuri' => $this->salmonuri,
383 'entry' => $this->notifyPrepXml($entry),
384 'actor' => $actor->getID(),
385 'target' => $this->localProfile()->getID());
387 $qm = QueueManager::get();
388 return $qm->enqueue($data, 'salmon');
389 } catch (Exception $e) {
390 common_log(LOG_ERR, 'OSTATUS: Something went wrong when creating a Salmon slap: '._ve($e->getMessage()));
398 protected function notifyPrepXml($entry)
400 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
401 if (is_string($entry)) {
403 } else if ($entry instanceof Activity) {
404 return $preamble . $entry->asString(true);
405 } else if ($entry instanceof Notice) {
406 return $preamble . $entry->asAtomEntry(true, true);
408 // TRANS: Server exception.
409 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
413 function getBestName()
415 if ($this->isGroup()) {
416 return $this->localGroup()->getBestName();
417 } else if ($this->isPeopletag()) {
418 return $this->localPeopletag()->getBestName();
420 return $this->localProfile()->getBestName();
425 * Read and post notices for updates from the feed.
426 * Currently assumes that all items in the feed are new,
427 * coming from a PuSH hub.
429 * @param DOMDocument $doc
430 * @param string $source identifier ("push")
432 public function processFeed(DOMDocument $doc, $source)
434 $feed = $doc->documentElement;
436 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
437 $this->processAtomFeed($feed, $source);
438 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
439 $this->processRssFeed($feed, $source);
442 throw new Exception(_m('Unknown feed format.'));
446 public function processAtomFeed(DOMElement $feed, $source)
448 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
449 if ($entries->length == 0) {
450 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
454 $this->processEntries($entries, $feed, $source);
457 public function processRssFeed(DOMElement $rss, $source)
459 $channels = $rss->getElementsByTagName('channel');
461 if ($channels->length == 0) {
463 throw new Exception(_m('RSS feed without a channel.'));
464 } else if ($channels->length > 1) {
465 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
468 $channel = $channels->item(0);
470 $items = $channel->getElementsByTagName('item');
472 $this->processEntries($items, $channel, $source);
475 public function processEntries(DOMNodeList $entries, DOMElement $feed, $source)
477 for ($i = 0; $i < $entries->length; $i++) {
478 $entry = $entries->item($i);
480 $this->processEntry($entry, $feed, $source);
481 } catch (AlreadyFulfilledException $e) {
482 common_debug('We already had this entry: '.$e->getMessage());
483 } catch (ServerException $e) {
484 // FIXME: This should be UnknownUriException and the ActivityUtils:: findLocalObject should only test one URI
485 common_log(LOG_ERR, 'Entry threw exception while processing a feed from '.$source.': '.$e->getMessage());
491 * Process a posted entry from this feed source.
493 * @param DOMElement $entry
494 * @param DOMElement $feed for context
495 * @param string $source identifier ("push" or "salmon")
497 * @return Notice Notice representing the new (or existing) activity
499 public function processEntry(DOMElement $entry, DOMElement $feed, $source)
501 $activity = new Activity($entry, $feed);
502 return $this->processActivity($activity, $source);
505 // TODO: Make this throw an exception
506 public function processActivity(Activity $activity, $source)
510 // The "WithProfile" events were added later.
512 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
513 Event::handle('StartHandleFeedEntry', array($activity))) {
515 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
517 Event::handle('EndHandleFeedEntry', array($activity));
518 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
525 * Process an incoming post activity from this remote feed.
526 * @param Activity $activity
527 * @param string $method 'push' or 'salmon'
528 * @return mixed saved Notice or false
530 public function processPost(Activity $activity, $method)
532 $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
534 $options = array('is_local' => Notice::REMOTE);
537 $stored = Notice::saveActivity($activity, $actor, $options);
538 Ostatus_source::saveNew($stored, $this, $method);
539 } catch (Exception $e) {
540 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
547 * Filters a list of recipient ID URIs to just those for local delivery.
548 * @param Profile local profile of sender
549 * @param array in/out &$attention_uris set of URIs, will be pruned on output
550 * @return array of group IDs
552 static public function filterAttention(Profile $sender, array $attention)
554 common_debug("Original reply recipients: " . implode(', ', array_keys($attention)));
557 foreach ($attention as $recipient=>$type) {
558 // Is the recipient a local user?
559 $user = User::getKV('uri', $recipient);
560 if ($user instanceof User) {
561 // @todo FIXME: Sender verification, spam etc?
562 $replies[] = $recipient;
566 // Is the recipient a local group?
567 // TODO: $group = User_group::getKV('uri', $recipient);
568 $id = OStatusPlugin::localGroupFromUrl($recipient);
570 $group = User_group::getKV('id', $id);
571 if ($group instanceof User_group) {
572 // Deliver to all members of this local group if allowed.
573 if ($sender->isMember($group)) {
574 $groups[] = $group->id;
576 common_debug(sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
580 common_debug("Skipping reply to bogus group $recipient");
584 // Is the recipient a remote user or group?
586 $oprofile = self::ensureProfileURI($recipient);
587 if ($oprofile->isGroup()) {
588 // Deliver to local members of this remote group.
589 // @todo FIXME: Sender verification?
590 $groups[] = $oprofile->group_id;
592 // may be canonicalized or something
593 $replies[] = $oprofile->getUri();
596 } catch (Exception $e) {
597 // Neither a recognizable local nor remote user!
598 common_debug("Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
602 common_debug("Local reply recipients: " . implode(', ', $replies));
603 common_debug("Local group recipients: " . implode(', ', $groups));
604 return array($groups, $replies);
608 * Look up and if necessary create an Ostatus_profile for the remote entity
609 * with the given profile page URL. This should never return null -- you
610 * will either get an object or an exception will be thrown.
612 * @param string $profile_url
613 * @return Ostatus_profile
614 * @throws Exception on various error conditions
615 * @throws OStatusShadowException if this reference would obscure a local user/group
617 public static function ensureProfileURL($profile_url, array $hints=array())
619 $oprofile = self::getFromProfileURL($profile_url);
621 if ($oprofile instanceof Ostatus_profile) {
625 $hints['profileurl'] = $profile_url;
630 $client = new HTTPClient();
631 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
632 $response = $client->get($profile_url);
634 if (!$response->isOk()) {
635 // TRANS: Exception. %s is a profile URL.
636 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
639 // Check if we have a non-canonical URL
641 $finalUrl = $response->getUrl();
643 if ($finalUrl != $profile_url) {
645 $hints['profileurl'] = $finalUrl;
647 $oprofile = self::getFromProfileURL($finalUrl);
649 if ($oprofile instanceof Ostatus_profile) {
655 preg_replace('/\s*;.*$/', '', $response->getHeader('Content-Type')),
656 array('application/rss+xml', 'application/atom+xml', 'application/xml', 'text/xml'))
658 $hints['feedurl'] = $response->getUrl();
660 // Try to get some hCard data
662 $body = $response->getBody();
664 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
666 if (!empty($hcardHints)) {
667 $hints = array_merge($hints, $hcardHints);
671 // Check if they've got an LRDD header
673 $lrdd = LinkHeader::getLink($response, 'lrdd');
675 $xrd = new XML_XRD();
676 $xrd->loadFile($lrdd);
677 $xrdHints = DiscoveryHints::fromXRD($xrd);
678 $hints = array_merge($hints, $xrdHints);
679 } catch (Exception $e) {
680 // No hints available from XRD
683 // If discovery found a feedurl (probably from LRDD), use it.
685 if (array_key_exists('feedurl', $hints)) {
686 return self::ensureFeedURL($hints['feedurl'], $hints);
689 // Get the feed URL from HTML
691 $discover = new FeedDiscovery();
693 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
695 if (!empty($feedurl)) {
696 $hints['feedurl'] = $feedurl;
697 return self::ensureFeedURL($feedurl, $hints);
700 // TRANS: Exception. %s is a URL.
701 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
705 * Look up the Ostatus_profile, if present, for a remote entity with the
706 * given profile page URL. Will return null for both unknown and invalid
709 * @return mixed Ostatus_profile or null
710 * @throws OStatusShadowException for local profiles
712 static function getFromProfileURL($profile_url)
714 $profile = Profile::getKV('profileurl', $profile_url);
715 if (!$profile instanceof Profile) {
720 $oprofile = self::getFromProfile($profile);
721 // We found the profile, return it!
723 } catch (NoResultException $e) {
724 // Could not find an OStatus profile, is it instead a local user?
725 $user = User::getKV('id', $profile->id);
726 if ($user instanceof User) {
727 // @todo i18n FIXME: use sprintf and add i18n (?)
728 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
732 // Continue discovery; it's a remote profile
733 // for OMB or some other protocol, may also
739 static function getFromProfile(Profile $profile)
741 $oprofile = new Ostatus_profile();
742 $oprofile->profile_id = $profile->id;
743 if (!$oprofile->find(true)) {
744 throw new NoResultException($oprofile);
750 * Look up and if necessary create an Ostatus_profile for remote entity
751 * with the given update feed. This should never return null -- you will
752 * either get an object or an exception will be thrown.
754 * @return Ostatus_profile
757 public static function ensureFeedURL($feed_url, array $hints=array())
759 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
760 if ($oprofile instanceof Ostatus_profile) {
764 $discover = new FeedDiscovery();
766 $feeduri = $discover->discoverFromFeedURL($feed_url);
767 $hints['feedurl'] = $feeduri;
769 $huburi = $discover->getHubLink();
770 $hints['hub'] = $huburi;
772 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
773 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
774 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
775 $hints['salmon'] = $salmonuri;
777 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
778 // We can only deal with folks with a PuSH hub
779 // unless we have something similar available locally.
780 throw new FeedSubNoHubException();
783 $feedEl = $discover->root;
785 if ($feedEl->tagName == 'feed') {
786 return self::ensureAtomFeed($feedEl, $hints);
787 } else if ($feedEl->tagName == 'channel') {
788 return self::ensureRssChannel($feedEl, $hints);
790 throw new FeedSubBadXmlException($feeduri);
795 * Look up and, if necessary, create an Ostatus_profile for the remote
796 * profile with the given Atom feed - actually loaded from the feed.
797 * This should never return null -- you will either get an object or
798 * an exception will be thrown.
800 * @param DOMElement $feedEl root element of a loaded Atom feed
801 * @param array $hints additional discovery information passed from higher levels
802 * @todo FIXME: Should this be marked public?
803 * @return Ostatus_profile
806 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
808 $author = ActivityUtils::getFeedAuthor($feedEl);
810 if (empty($author)) {
811 // XXX: make some educated guesses here
812 // TRANS: Feed sub exception.
813 throw new FeedSubException(_m('Cannot find enough profile '.
814 'information to make a feed.'));
817 return self::ensureActivityObjectProfile($author, $hints);
821 * Look up and, if necessary, create an Ostatus_profile for the remote
822 * profile with the given RSS feed - actually loaded from the feed.
823 * This should never return null -- you will either get an object or
824 * an exception will be thrown.
826 * @param DOMElement $feedEl root element of a loaded RSS feed
827 * @param array $hints additional discovery information passed from higher levels
828 * @todo FIXME: Should this be marked public?
829 * @return Ostatus_profile
832 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
834 // Special-case for Posterous. They have some nice metadata in their
835 // posterous:author elements. We should use them instead of the channel.
837 $items = $feedEl->getElementsByTagName('item');
839 if ($items->length > 0) {
840 $item = $items->item(0);
841 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
842 if (!empty($authorEl)) {
843 $obj = ActivityObject::fromPosterousAuthor($authorEl);
844 // Posterous has multiple authors per feed, and multiple feeds
845 // per author. We check if this is the "main" feed for this author.
846 if (array_key_exists('profileurl', $hints) &&
847 !empty($obj->poco) &&
848 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
849 return self::ensureActivityObjectProfile($obj, $hints);
854 $obj = ActivityUtils::getFeedAuthor($feedEl);
856 // @todo FIXME: We should check whether this feed has elements
857 // with different <author> or <dc:creator> elements, and... I dunno.
858 // Do something about that.
860 if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
862 return self::ensureActivityObjectProfile($obj, $hints);
866 * Download and update given avatar image
869 * @return Avatar The Avatar we have on disk. (seldom used)
870 * @throws Exception in various failure cases
872 public function updateAvatar($url, $force=false)
875 // If avatar URL differs: update. If URLs were identical but we're forced: update.
876 if ($url == $this->avatar && !$force) {
877 // If there's no locally stored avatar, throw an exception and continue fetching below.
878 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
881 } catch (NoAvatarException $e) {
882 // No avatar available, let's fetch it.
885 if (!common_valid_http_url($url)) {
886 // TRANS: Server exception. %s is a URL.
887 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
890 $self = $this->localProfile();
892 // @todo FIXME: This should be better encapsulated
893 // ripped from oauthstore.php (for old OMB client)
894 $temp_filename = tempnam(common_get_temp_dir(), 'listener_avatar');
896 $imgData = HTTPClient::quickGet($url);
897 // Make sure it's at least an image file. ImageFile can do the rest.
898 if (false === getimagesizefromstring($imgData)) {
899 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
901 file_put_contents($temp_filename, $imgData);
902 unset($imgData); // No need to carry this in memory.
904 if ($this->isGroup()) {
905 $id = $this->group_id;
907 $id = $this->profile_id;
909 $imagefile = new ImageFile(null, $temp_filename);
910 $filename = Avatar::filename($id,
911 image_type_to_extension($imagefile->type),
914 rename($temp_filename, Avatar::path($filename));
915 } catch (Exception $e) {
916 unlink($temp_filename);
919 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
920 // keep from accidentally saving images from command-line (queues)
921 // that can't be read from web server, which causes hard-to-notice
922 // problems later on:
924 // http://status.net/open-source/issues/2663
925 chmod(Avatar::path($filename), 0644);
927 $self->setOriginal($filename);
929 $orig = clone($this);
930 $this->avatar = $url;
931 $this->update($orig);
933 return Avatar::getUploaded($self);
937 * Pull avatar URL from ActivityObject or profile hints
939 * @param ActivityObject $object
940 * @param array $hints
941 * @return mixed URL string or false
943 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
945 if ($object->avatarLinks) {
947 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
948 foreach ($object->avatarLinks as $avatar) {
949 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
954 if (!$best || $avatar->width > $best->width) {
959 } else if (array_key_exists('avatar', $hints)) {
960 return $hints['avatar'];
966 * Get an appropriate avatar image source URL, if available.
968 * @param ActivityObject $actor
969 * @param DOMElement $feed
972 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
976 if ($actor->avatar) {
977 $url = trim($actor->avatar);
980 // Check <atom:logo> and <atom:icon> on the feed
981 $els = $feed->childNodes();
982 if ($els && $els->length) {
983 for ($i = 0; $i < $els->length; $i++) {
984 $el = $els->item($i);
985 if ($el->namespaceURI == Activity::ATOM) {
986 if (empty($url) && $el->localName == 'logo') {
987 $url = trim($el->textContent);
990 if (empty($icon) && $el->localName == 'icon') {
992 $icon = trim($el->textContent);
997 if ($icon && !$url) {
1002 $opts = array('allowed_schemes' => array('http', 'https'));
1003 if (common_valid_http_url($url)) {
1008 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1012 * Fetch, or build if necessary, an Ostatus_profile for the actor
1013 * in a given Activity Streams activity.
1014 * This should never return null -- you will either get an object or
1015 * an exception will be thrown.
1017 * @param Activity $activity
1018 * @param string $feeduri if we already know the canonical feed URI!
1019 * @param string $salmonuri if we already know the salmon return channel URI
1020 * @return Ostatus_profile
1023 public static function ensureActorProfile(Activity $activity, array $hints=array())
1025 return self::ensureActivityObjectProfile($activity->actor, $hints);
1029 * Fetch, or build if necessary, an Ostatus_profile for the profile
1030 * in a given Activity Streams object (can be subject, actor, or object).
1031 * This should never return null -- you will either get an object or
1032 * an exception will be thrown.
1034 * @param ActivityObject $object
1035 * @param array $hints additional discovery information passed from higher levels
1036 * @return Ostatus_profile
1039 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1041 $profile = self::getActivityObjectProfile($object);
1042 if ($profile instanceof Ostatus_profile) {
1043 $profile->updateFromActivityObject($object, $hints);
1045 $profile = self::createActivityObjectProfile($object, $hints);
1051 * @param Activity $activity
1052 * @return mixed matching Ostatus_profile or false if none known
1053 * @throws ServerException if feed info invalid
1055 public static function getActorProfile(Activity $activity)
1057 return self::getActivityObjectProfile($activity->actor);
1061 * @param ActivityObject $activity
1062 * @return mixed matching Ostatus_profile or false if none known
1063 * @throws ServerException if feed info invalid
1065 protected static function getActivityObjectProfile(ActivityObject $object)
1067 $uri = self::getActivityObjectProfileURI($object);
1068 return Ostatus_profile::getKV('uri', $uri);
1072 * Get the identifier URI for the remote entity described
1073 * by this ActivityObject. This URI is *not* guaranteed to be
1074 * a resolvable HTTP/HTTPS URL.
1076 * @param ActivityObject $object
1078 * @throws ServerException if feed info invalid
1080 protected static function getActivityObjectProfileURI(ActivityObject $object)
1083 if (ActivityUtils::validateUri($object->id)) {
1088 // If the id is missing or invalid (we've seen feeds mistakenly listing
1089 // things like local usernames in that field) then we'll use the profile
1090 // page link, if valid.
1091 if ($object->link && common_valid_http_url($object->link)) {
1092 return $object->link;
1094 // TRANS: Server exception.
1095 throw new ServerException(_m('No author ID URI found.'));
1099 * @todo FIXME: Validate stuff somewhere.
1103 * Create local ostatus_profile and profile/user_group entries for
1104 * the provided remote user or group.
1105 * This should never return null -- you will either get an object or
1106 * an exception will be thrown.
1108 * @param ActivityObject $object
1109 * @param array $hints
1111 * @return Ostatus_profile
1113 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1115 $homeuri = $object->id;
1119 common_debug(__METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1120 // TRANS: Exception.
1121 throw new Exception(_m('No profile URI.'));
1124 $user = User::getKV('uri', $homeuri);
1125 if ($user instanceof User) {
1126 // TRANS: Exception.
1127 throw new Exception(_m('Local user cannot be referenced as remote.'));
1130 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1131 // TRANS: Exception.
1132 throw new Exception(_m('Local group cannot be referenced as remote.'));
1135 $ptag = Profile_list::getKV('uri', $homeuri);
1136 if ($ptag instanceof Profile_list) {
1137 $local_user = User::getKV('id', $ptag->tagger);
1138 if ($local_user instanceof User) {
1139 // TRANS: Exception.
1140 throw new Exception(_m('Local list cannot be referenced as remote.'));
1144 if (array_key_exists('feedurl', $hints)) {
1145 $feeduri = $hints['feedurl'];
1147 $discover = new FeedDiscovery();
1148 $feeduri = $discover->discoverFromURL($homeuri);
1151 if (array_key_exists('salmon', $hints)) {
1152 $salmonuri = $hints['salmon'];
1155 $discover = new FeedDiscovery();
1156 $discover->discoverFromFeedURL($hints['feedurl']);
1158 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1159 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1160 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1163 if (array_key_exists('hub', $hints)) {
1164 $huburi = $hints['hub'];
1167 $discover = new FeedDiscovery();
1168 $discover->discoverFromFeedURL($hints['feedurl']);
1170 $huburi = $discover->getHubLink();
1173 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1174 // We can only deal with folks with a PuSH hub
1175 throw new FeedSubNoHubException();
1178 $oprofile = new Ostatus_profile();
1180 $oprofile->uri = $homeuri;
1181 $oprofile->feeduri = $feeduri;
1182 $oprofile->salmonuri = $salmonuri;
1184 $oprofile->created = common_sql_now();
1185 $oprofile->modified = common_sql_now();
1187 if ($object->type == ActivityObject::PERSON) {
1188 $profile = new Profile();
1189 $profile->created = common_sql_now();
1190 self::updateProfile($profile, $object, $hints);
1192 $oprofile->profile_id = $profile->insert();
1193 if ($oprofile->profile_id === false) {
1194 // TRANS: Server exception.
1195 throw new ServerException(_m('Cannot save local profile.'));
1197 } else if ($object->type == ActivityObject::GROUP) {
1198 $profile = new Profile();
1199 $profile->query('BEGIN');
1201 $group = new User_group();
1202 $group->uri = $homeuri;
1203 $group->created = common_sql_now();
1204 self::updateGroup($group, $object, $hints);
1206 // TODO: We should do this directly in User_group->insert()!
1207 // currently it's duplicated in User_group->update()
1208 // AND User_group->register()!!!
1209 $fields = array(/*group field => profile field*/
1210 'nickname' => 'nickname',
1211 'fullname' => 'fullname',
1212 'mainpage' => 'profileurl',
1213 'homepage' => 'homepage',
1214 'description' => 'bio',
1215 'location' => 'location',
1216 'created' => 'created',
1217 'modified' => 'modified',
1219 foreach ($fields as $gf=>$pf) {
1220 $profile->$pf = $group->$gf;
1222 $profile_id = $profile->insert();
1223 if ($profile_id === false) {
1224 $profile->query('ROLLBACK');
1225 throw new ServerException(_('Profile insertion failed.'));
1228 $group->profile_id = $profile_id;
1230 $oprofile->group_id = $group->insert();
1231 if ($oprofile->group_id === false) {
1232 $profile->query('ROLLBACK');
1233 // TRANS: Server exception.
1234 throw new ServerException(_m('Cannot save local profile.'));
1237 $profile->query('COMMIT');
1238 } else if ($object->type == ActivityObject::_LIST) {
1239 $ptag = new Profile_list();
1240 $ptag->uri = $homeuri;
1241 $ptag->created = common_sql_now();
1242 self::updatePeopletag($ptag, $object, $hints);
1244 $oprofile->peopletag_id = $ptag->insert();
1245 if ($oprofile->peopletag_id === false) {
1246 // TRANS: Server exception.
1247 throw new ServerException(_m('Cannot save local list.'));
1251 $ok = $oprofile->insert();
1253 if ($ok === false) {
1254 // TRANS: Server exception.
1255 throw new ServerException(_m('Cannot save OStatus profile.'));
1258 $avatar = self::getActivityObjectAvatar($object, $hints);
1262 $oprofile->updateAvatar($avatar);
1263 } catch (Exception $ex) {
1264 // Profile is saved, but Avatar is messed up. We're
1265 // just going to continue.
1266 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1274 * Save any updated profile information to our local copy.
1275 * @param ActivityObject $object
1276 * @param array $hints
1278 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1280 if ($this->isGroup()) {
1281 $group = $this->localGroup();
1282 self::updateGroup($group, $object, $hints);
1283 } else if ($this->isPeopletag()) {
1284 $ptag = $this->localPeopletag();
1285 self::updatePeopletag($ptag, $object, $hints);
1287 $profile = $this->localProfile();
1288 self::updateProfile($profile, $object, $hints);
1291 $avatar = self::getActivityObjectAvatar($object, $hints);
1292 if ($avatar && !isset($ptag)) {
1294 $this->updateAvatar($avatar);
1295 } catch (Exception $ex) {
1296 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1301 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1303 $orig = clone($profile);
1305 // Existing nickname is better than nothing.
1307 if (!array_key_exists('nickname', $hints)) {
1308 $hints['nickname'] = $profile->nickname;
1311 $nickname = self::getActivityObjectNickname($object, $hints);
1313 if (!empty($nickname)) {
1314 $profile->nickname = $nickname;
1317 if (!empty($object->title)) {
1318 $profile->fullname = $object->title;
1319 } else if (array_key_exists('fullname', $hints)) {
1320 $profile->fullname = $hints['fullname'];
1323 if (!empty($object->link)) {
1324 $profile->profileurl = $object->link;
1325 } else if (array_key_exists('profileurl', $hints)) {
1326 $profile->profileurl = $hints['profileurl'];
1327 } else if (common_valid_http_url($object->id)) {
1328 $profile->profileurl = $object->id;
1331 $bio = self::getActivityObjectBio($object, $hints);
1334 $profile->bio = $bio;
1337 $location = self::getActivityObjectLocation($object, $hints);
1339 if (!empty($location)) {
1340 $profile->location = $location;
1343 $homepage = self::getActivityObjectHomepage($object, $hints);
1345 if (!empty($homepage)) {
1346 $profile->homepage = $homepage;
1349 if (!empty($object->geopoint)) {
1350 $location = ActivityContext::locationFromPoint($object->geopoint);
1351 if (!empty($location)) {
1352 $profile->lat = $location->lat;
1353 $profile->lon = $location->lon;
1357 // @todo FIXME: tags/categories
1358 // @todo tags from categories
1361 common_debug("Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1362 $profile->update($orig);
1366 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1368 $orig = clone($group);
1370 $group->nickname = self::getActivityObjectNickname($object, $hints);
1371 $group->fullname = $object->title;
1373 if (!empty($object->link)) {
1374 $group->mainpage = $object->link;
1375 } else if (array_key_exists('profileurl', $hints)) {
1376 $group->mainpage = $hints['profileurl'];
1379 // @todo tags from categories
1380 $group->description = self::getActivityObjectBio($object, $hints);
1381 $group->location = self::getActivityObjectLocation($object, $hints);
1382 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1384 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1385 common_debug("Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1386 $group->update($orig);
1390 protected static function updatePeopletag(Peopletag $tag, ActivityObject $object, array $hints=array()) {
1391 $orig = clone($tag);
1393 $tag->tag = $object->title;
1395 if (!empty($object->link)) {
1396 $tag->mainpage = $object->link;
1397 } else if (array_key_exists('profileurl', $hints)) {
1398 $tag->mainpage = $hints['profileurl'];
1401 $tag->description = $object->summary;
1402 $tagger = self::ensureActivityObjectProfile($object->owner);
1403 $tag->tagger = $tagger->profile_id;
1406 common_debug("Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1407 $tag->update($orig);
1411 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1414 $poco = $object->poco;
1416 if (!empty($poco)) {
1417 $url = $poco->getPrimaryURL();
1418 if ($url && $url->type == 'homepage') {
1419 $homepage = $url->value;
1423 // @todo Try for a another PoCo URL?
1428 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1432 if (!empty($object->poco) &&
1433 isset($object->poco->address->formatted)) {
1434 $location = $object->poco->address->formatted;
1435 } else if (array_key_exists('location', $hints)) {
1436 $location = $hints['location'];
1439 if (!empty($location)) {
1440 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1441 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1445 // @todo Try to find location some othe way? Via goerss point?
1450 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1454 if (!empty($object->poco)) {
1455 $note = $object->poco->note;
1456 } else if (array_key_exists('bio', $hints)) {
1457 $note = $hints['bio'];
1460 if (!empty($note)) {
1461 if (Profile::bioTooLong($note)) {
1462 // XXX: truncate ok?
1463 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1469 // @todo Try to get bio info some other way?
1474 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1476 if ($object->poco) {
1477 if (!empty($object->poco->preferredUsername)) {
1478 return common_nicknamize($object->poco->preferredUsername);
1482 if (!empty($object->nickname)) {
1483 return common_nicknamize($object->nickname);
1486 if (array_key_exists('nickname', $hints)) {
1487 return $hints['nickname'];
1490 // Try the profile url (like foo.example.com or example.com/user/foo)
1491 if (!empty($object->link)) {
1492 $profileUrl = $object->link;
1493 } else if (!empty($hints['profileurl'])) {
1494 $profileUrl = $hints['profileurl'];
1497 if (!empty($profileUrl)) {
1498 $nickname = self::nicknameFromURI($profileUrl);
1501 // Try the URI (may be a tag:, http:, acct:, ...
1503 if (empty($nickname)) {
1504 $nickname = self::nicknameFromURI($object->id);
1507 // Try a Webfinger if one was passed (way) down
1509 if (empty($nickname)) {
1510 if (array_key_exists('webfinger', $hints)) {
1511 $nickname = self::nicknameFromURI($hints['webfinger']);
1517 if (empty($nickname)) {
1518 $nickname = common_nicknamize($object->title);
1524 protected static function nicknameFromURI($uri)
1526 if (preg_match('/(\w+):/', $uri, $matches)) {
1527 $protocol = $matches[1];
1532 switch ($protocol) {
1535 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1536 return common_canonical_nickname($matches[1]);
1540 return common_url_to_nickname($uri);
1548 * Look up, and if necessary create, an Ostatus_profile for the remote
1549 * entity with the given webfinger address.
1550 * This should never return null -- you will either get an object or
1551 * an exception will be thrown.
1553 * @param string $addr webfinger address
1554 * @return Ostatus_profile
1555 * @throws Exception on error conditions
1556 * @throws OStatusShadowException if this reference would obscure a local user/group
1558 public static function ensureWebfinger($addr)
1560 // First, try the cache
1562 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1564 if ($uri !== false) {
1565 if (is_null($uri)) {
1566 // Negative cache entry
1567 // TRANS: Exception.
1568 throw new Exception(_m('Not a valid webfinger address.'));
1570 $oprofile = Ostatus_profile::getKV('uri', $uri);
1571 if ($oprofile instanceof Ostatus_profile) {
1576 // Try looking it up
1577 $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1579 if ($oprofile instanceof Ostatus_profile) {
1580 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1584 // Now, try some discovery
1586 $disco = new Discovery();
1589 $xrd = $disco->lookup($addr);
1590 } catch (Exception $e) {
1591 // Save negative cache entry so we don't waste time looking it up again.
1592 // @todo FIXME: Distinguish temporary failures?
1593 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1594 // TRANS: Exception.
1595 throw new Exception(_m('Not a valid webfinger address.'));
1598 $hints = array_merge(array('webfinger' => $addr),
1599 DiscoveryHints::fromXRD($xrd));
1601 // If there's an Hcard, let's grab its info
1602 if (array_key_exists('hcard', $hints)) {
1603 if (!array_key_exists('profileurl', $hints) ||
1604 $hints['hcard'] != $hints['profileurl']) {
1605 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1606 $hints = array_merge($hcardHints, $hints);
1610 // If we got a feed URL, try that
1612 if (array_key_exists('feedurl', $hints)) {
1613 $feedUrl = $hints['feedurl'];
1615 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1616 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1617 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1619 } catch (Exception $e) {
1620 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1625 // If we got a profile page, try that!
1627 if (array_key_exists('profileurl', $hints)) {
1628 $profileUrl = $hints['profileurl'];
1630 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1631 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1632 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1634 } catch (OStatusShadowException $e) {
1635 // We've ended up with a remote reference to a local user or group.
1636 // @todo FIXME: Ideally we should be able to say who it was so we can
1637 // go back and refer to it the regular way
1639 } catch (Exception $e) {
1640 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1643 // @todo FIXME: This means an error discovering from profile page
1644 // may give us a corrupt entry using the webfinger URI, which
1645 // will obscure the correct page-keyed profile later on.
1652 if (array_key_exists('salmon', $hints)) {
1653 $salmonEndpoint = $hints['salmon'];
1655 // An account URL, a salmon endpoint, and a dream? Not much to go
1656 // on, but let's give it a try
1658 $uri = 'acct:'.$addr;
1660 $profile = new Profile();
1662 $profile->nickname = self::nicknameFromUri($uri);
1663 $profile->created = common_sql_now();
1665 if (!is_null($profileUrl)) {
1666 $profile->profileurl = $profileUrl;
1669 $profile_id = $profile->insert();
1671 if ($profile_id === false) {
1672 common_log_db_error($profile, 'INSERT', __FILE__);
1673 // TRANS: Exception. %s is a webfinger address.
1674 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1677 $oprofile = new Ostatus_profile();
1679 $oprofile->uri = $uri;
1680 $oprofile->salmonuri = $salmonEndpoint;
1681 $oprofile->profile_id = $profile_id;
1682 $oprofile->created = common_sql_now();
1684 if (!is_null($feedUrl)) {
1685 $oprofile->feeduri = $feedUrl;
1688 $result = $oprofile->insert();
1690 if ($result === false) {
1692 common_log_db_error($oprofile, 'INSERT', __FILE__);
1693 // TRANS: Exception. %s is a webfinger address.
1694 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1697 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1701 // TRANS: Exception. %s is a webfinger address.
1702 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1706 * Store the full-length scrubbed HTML of a remote notice to an attachment
1707 * file on our server. We'll link to this at the end of the cropped version.
1709 * @param string $title plaintext for HTML page's title
1710 * @param string $rendered HTML fragment for HTML page's body
1713 function saveHTMLFile($title, $rendered)
1715 $final = sprintf("<!DOCTYPE html>\n" .
1717 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1718 '<title>%s</title>' .
1720 '<body>%s</body></html>',
1721 htmlspecialchars($title),
1724 $filename = File::filename($this->localProfile(),
1725 'ostatus', // ignored?
1728 $filepath = File::path($filename);
1729 $fileurl = File::url($filename);
1731 file_put_contents($filepath, $final);
1735 $file->filename = $filename;
1736 $file->urlhash = File::hashurl($fileurl);
1737 $file->url = $fileurl;
1738 $file->size = filesize($filepath);
1739 $file->date = time();
1740 $file->mimetype = 'text/html';
1742 $file_id = $file->insert();
1744 if ($file_id === false) {
1745 common_log_db_error($file, "INSERT", __FILE__);
1746 // TRANS: Server exception.
1747 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1753 static function ensureProfileURI($uri)
1757 // First, try to query it
1759 $oprofile = Ostatus_profile::getKV('uri', $uri);
1761 if ($oprofile instanceof Ostatus_profile) {
1765 // If unfound, do discovery stuff
1766 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1767 $protocol = $match[1];
1768 switch ($protocol) {
1771 $oprofile = self::ensureProfileURL($uri);
1776 $oprofile = self::ensureWebfinger($rest);
1779 // TRANS: Server exception.
1780 // TRANS: %1$s is a protocol, %2$s is a URI.
1781 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1786 // TRANS: Server exception. %s is a URI.
1787 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1793 public function checkAuthorship(Activity $activity)
1795 if ($this->isGroup() || $this->isPeopletag()) {
1796 // A group or propletag feed will contain posts from multiple authors.
1797 $oprofile = self::ensureActorProfile($activity);
1798 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1799 // Groups can't post notices in StatusNet.
1800 common_log(LOG_WARNING,
1801 "OStatus: skipping post with group listed ".
1802 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1803 throw new ServerException('Activity author is a non-actor');
1806 $actor = $activity->actor;
1808 if (!$actor instanceof Profile) {
1809 // OK here! assume the default
1810 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1811 $this->updateFromActivityObject($actor);
1812 } else if ($actor->id) {
1813 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1814 // This isn't what we expect from mainline OStatus person feeds!
1815 // Group feeds go down another path, with different validation...
1816 // Most likely this is a plain ol' blog feed of some kind which
1817 // doesn't match our expectations. We'll take the entry, but ignore
1818 // the <author> info.
1819 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1821 // Plain <author> without ActivityStreams actor info.
1822 // We'll just ignore this info for now and save the update under the feed's identity.
1828 return $oprofile->localProfile();
1831 public function updateUriKeys($profile_uri, array $hints=array())
1833 $orig = clone($this);
1835 common_debug('URIFIX These identities both say they are each other: "'.$orig->uri.'" and "'.$profile_uri.'"');
1836 $this->uri = $profile_uri;
1838 if (array_key_exists('feedurl', $hints)) {
1839 if (!empty($this->feeduri)) {
1840 common_debug('URIFIX Changing FeedSub ['.$feedsub->id.'] feeduri "'.$feedsub->uri.'" to "'.$hints['feedurl']);
1841 $feedsub = FeedSub::getKV('uri', $this->feeduri);
1842 $feedorig = clone($feedsub);
1843 $feedsub->uri = $hints['feedurl'];
1844 $feedsub->updateWithKeys($feedorig);
1846 common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring feed: '.$hints['feedurl']);
1847 FeedSub::ensureFeed($hints['feedurl']);
1849 $this->feeduri = $hints['feedurl'];
1851 if (array_key_exists('salmon', $hints)) {
1852 common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
1853 $this->salmonuri = $hints['salmon'];
1856 common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
1857 $this->updateWithKeys($orig, 'uri'); // 'uri' is the primary key column
1859 common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);
1865 * Exception indicating we've got a remote reference to a local user,
1866 * not a remote user!
1868 * If we can ue a local profile after all, it's available as $e->profile.
1870 class OStatusShadowException extends Exception
1875 * @param Profile $profile
1876 * @param string $message
1878 function __construct($profile, $message) {
1879 $this->profile = $profile;
1880 parent::__construct($message);