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()));
196 public function isPerson()
198 return $this->localProfile()->isPerson();
202 * @return boolean true if this is a remote peopletag
204 function isPeopletag()
206 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
208 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
210 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
211 // TRANS: Server exception. %s is a URI
212 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
214 // TRANS: Server exception. %s is a URI
215 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
220 * Send a subscription request to the hub for this feed.
221 * The hub will later send us a confirmation POST to /main/push/callback.
224 * @throws ServerException if feed state is not valid or subscription fails.
226 public function subscribe()
228 $feedsub = FeedSub::ensureFeed($this->feeduri);
229 if ($feedsub->sub_state == 'active') {
230 // Active subscription, we don't need to do anything.
234 // Inactive or we got left in an inconsistent state.
235 // Run a subscription request to make sure we're current!
236 return $feedsub->subscribe();
240 * Check if this remote profile has any active local subscriptions, and
241 * if not drop the PuSH subscription feed.
243 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
244 * @throws Exception of various kinds on failure.
246 public function unsubscribe() {
247 return $this->garbageCollect();
251 * Check if this remote profile has any active local subscriptions, and
252 * if not drop the PuSH subscription feed.
254 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
255 * @throws Exception of various kinds on failure.
257 public function garbageCollect()
259 $feedsub = FeedSub::getKV('uri', $this->feeduri);
260 if ($feedsub instanceof FeedSub) {
261 return $feedsub->garbageCollect();
263 // Since there's no FeedSub we can assume it's already garbage collected
268 * Check if this remote profile has any active local subscriptions, so the
269 * PuSH subscription layer can decide if it can drop the feed.
271 * This gets called via the FeedSubSubscriberCount event when running
272 * FeedSub::garbageCollect().
275 * @throws NoProfileException if there is no local profile for the object
277 public function subscriberCount()
279 if ($this->isGroup()) {
280 $members = $this->localGroup()->getMembers(0, 1);
281 $count = $members->N;
282 } else if ($this->isPeopletag()) {
283 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
284 $count = $subscribers->N;
286 $profile = $this->localProfile();
287 if ($profile->hasLocalTags()) {
290 $count = $profile->subscriberCount();
293 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
295 // Other plugins may be piggybacking on OStatus without having
296 // an active group or user-to-user subscription we know about.
297 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
298 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
304 * Send an Activity Streams notification to the remote Salmon endpoint,
307 * @param Profile $actor Actor who did the activity
308 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
309 * @param Object $object object of the action; must define asActivityNoun($tag)
311 public function notify(Profile $actor, $verb, $object=null, $target=null)
313 if ($object == null) {
316 if (empty($this->salmonuri)) {
320 $id = TagURI::mint('%s:%s:%s',
323 common_date_iso8601(time()));
325 // @todo FIXME: Consolidate all these NS settings somewhere.
326 $attributes = array('xmlns' => Activity::ATOM,
327 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
328 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
329 'xmlns:georss' => 'http://www.georss.org/georss',
330 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
331 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
332 'xmlns:media' => 'http://purl.org/syndication/atommedia');
334 $entry = new XMLStringer();
335 $entry->elementStart('entry', $attributes);
336 $entry->element('id', null, $id);
337 $entry->element('title', null, $text);
338 $entry->element('summary', null, $text);
339 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
341 $entry->element('activity:verb', null, $verb);
342 $entry->raw($actor->asAtomAuthor());
343 $entry->raw($actor->asActivityActor());
344 $entry->raw($object->asActivityNoun('object'));
345 if ($target != null) {
346 $entry->raw($target->asActivityNoun('target'));
348 $entry->elementEnd('entry');
350 $xml = $entry->getString();
351 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
353 Salmon::post($this->salmonuri, $xml, $actor);
357 * Send a Salmon notification ping immediately, and confirm that we got
358 * an acceptable response from the remote site.
360 * @param mixed $entry XML string, Notice, or Activity
361 * @param Profile $actor
362 * @return boolean success
364 public function notifyActivity($entry, Profile $actor)
366 if ($this->salmonuri) {
367 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor, $this->localProfile());
369 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
375 * Queue a Salmon notification for later. If queues are disabled we'll
376 * send immediately but won't get the return value.
378 * @param mixed $entry XML string, Notice, or Activity
379 * @return boolean success
381 public function notifyDeferred($entry, $actor)
383 if ($this->salmonuri) {
385 common_debug("OSTATUS: user {$actor->getNickname()} ({$actor->getID()}) wants to ping {$this->localProfile()->getNickname()} on {$this->salmonuri}");
386 $data = array('salmonuri' => $this->salmonuri,
387 'entry' => $this->notifyPrepXml($entry),
388 'actor' => $actor->getID(),
389 'target' => $this->localProfile()->getID());
391 $qm = QueueManager::get();
392 return $qm->enqueue($data, 'salmon');
393 } catch (Exception $e) {
394 common_log(LOG_ERR, 'OSTATUS: Something went wrong when creating a Salmon slap: '._ve($e->getMessage()));
402 protected function notifyPrepXml($entry)
404 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
405 if (is_string($entry)) {
407 } else if ($entry instanceof Activity) {
408 return $preamble . $entry->asString(true);
409 } else if ($entry instanceof Notice) {
410 return $preamble . $entry->asAtomEntry(true, true);
412 // TRANS: Server exception.
413 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
417 function getBestName()
419 if ($this->isGroup()) {
420 return $this->localGroup()->getBestName();
421 } else if ($this->isPeopletag()) {
422 return $this->localPeopletag()->getBestName();
424 return $this->localProfile()->getBestName();
429 * Read and post notices for updates from the feed.
430 * Currently assumes that all items in the feed are new,
431 * coming from a PuSH hub.
433 * @param DOMDocument $doc
434 * @param string $source identifier ("push")
436 public function processFeed(DOMDocument $doc, $source)
438 $feed = $doc->documentElement;
440 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
441 $this->processAtomFeed($feed, $source);
442 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
443 $this->processRssFeed($feed, $source);
446 throw new Exception(_m('Unknown feed format.'));
450 public function processAtomFeed(DOMElement $feed, $source)
452 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
453 if ($entries->length == 0) {
454 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
458 $this->processEntries($entries, $feed, $source);
461 public function processRssFeed(DOMElement $rss, $source)
463 $channels = $rss->getElementsByTagName('channel');
465 if ($channels->length == 0) {
467 throw new Exception(_m('RSS feed without a channel.'));
468 } else if ($channels->length > 1) {
469 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
472 $channel = $channels->item(0);
474 $items = $channel->getElementsByTagName('item');
476 $this->processEntries($items, $channel, $source);
479 public function processEntries(DOMNodeList $entries, DOMElement $feed, $source)
481 for ($i = 0; $i < $entries->length; $i++) {
482 $entry = $entries->item($i);
484 $this->processEntry($entry, $feed, $source);
485 } catch (AlreadyFulfilledException $e) {
486 common_debug('We already had this entry: '.$e->getMessage());
487 } catch (ServerException $e) {
488 // FIXME: This should be UnknownUriException and the ActivityUtils:: findLocalObject should only test one URI
489 common_log(LOG_ERR, 'Entry threw exception while processing a feed from '.$source.': '.$e->getMessage());
495 * Process a posted entry from this feed source.
497 * @param DOMElement $entry
498 * @param DOMElement $feed for context
499 * @param string $source identifier ("push" or "salmon")
501 * @return Notice Notice representing the new (or existing) activity
503 public function processEntry(DOMElement $entry, DOMElement $feed, $source)
505 $activity = new Activity($entry, $feed);
506 return $this->processActivity($activity, $source);
509 // TODO: Make this throw an exception
510 public function processActivity(Activity $activity, $source)
514 // The "WithProfile" events were added later.
516 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
517 Event::handle('StartHandleFeedEntry', array($activity))) {
519 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
521 Event::handle('EndHandleFeedEntry', array($activity));
522 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
529 * Process an incoming post activity from this remote feed.
530 * @param Activity $activity
531 * @param string $method 'push' or 'salmon'
532 * @return mixed saved Notice or false
534 public function processPost($activity, $method)
536 $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
538 $options = array('is_local' => Notice::REMOTE);
541 $stored = Notice::saveActivity($activity, $actor, $options);
542 } catch (Exception $e) {
543 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
550 * Filters a list of recipient ID URIs to just those for local delivery.
551 * @param Profile local profile of sender
552 * @param array in/out &$attention_uris set of URIs, will be pruned on output
553 * @return array of group IDs
555 static public function filterAttention(Profile $sender, array $attention)
557 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
560 foreach ($attention as $recipient=>$type) {
561 // Is the recipient a local user?
562 $user = User::getKV('uri', $recipient);
563 if ($user instanceof User) {
564 // @todo FIXME: Sender verification, spam etc?
565 $replies[] = $recipient;
569 // Is the recipient a local group?
570 // TODO: $group = User_group::getKV('uri', $recipient);
571 $id = OStatusPlugin::localGroupFromUrl($recipient);
573 $group = User_group::getKV('id', $id);
574 if ($group instanceof User_group) {
575 // Deliver to all members of this local group if allowed.
576 if ($sender->isMember($group)) {
577 $groups[] = $group->id;
579 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
583 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
587 // Is the recipient a remote user or group?
589 $oprofile = self::ensureProfileURI($recipient);
590 if ($oprofile->isGroup()) {
591 // Deliver to local members of this remote group.
592 // @todo FIXME: Sender verification?
593 $groups[] = $oprofile->group_id;
595 // may be canonicalized or something
596 $replies[] = $oprofile->getUri();
599 } catch (Exception $e) {
600 // Neither a recognizable local nor remote user!
601 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
605 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
606 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
607 return array($groups, $replies);
611 * Look up and if necessary create an Ostatus_profile for the remote entity
612 * with the given profile page URL. This should never return null -- you
613 * will either get an object or an exception will be thrown.
615 * @param string $profile_url
616 * @return Ostatus_profile
617 * @throws Exception on various error conditions
618 * @throws OStatusShadowException if this reference would obscure a local user/group
620 public static function ensureProfileURL($profile_url, array $hints=array())
622 $oprofile = self::getFromProfileURL($profile_url);
624 if ($oprofile instanceof Ostatus_profile) {
628 $hints['profileurl'] = $profile_url;
633 $client = new HTTPClient();
634 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
635 $response = $client->get($profile_url);
637 if (!$response->isOk()) {
638 // TRANS: Exception. %s is a profile URL.
639 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
642 // Check if we have a non-canonical URL
644 $finalUrl = $response->getEffectiveUrl();
646 if ($finalUrl != $profile_url) {
648 $hints['profileurl'] = $finalUrl;
650 $oprofile = self::getFromProfileURL($finalUrl);
652 if ($oprofile instanceof Ostatus_profile) {
658 preg_replace('/\s*;.*$/', '', $response->getHeader('Content-Type')),
659 array('application/rss+xml', 'application/atom+xml', 'application/xml', 'text/xml'))
661 $hints['feedurl'] = $response->getEffectiveUrl();
663 // Try to get some hCard data
665 $body = $response->getBody();
667 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
669 if (!empty($hcardHints)) {
670 $hints = array_merge($hints, $hcardHints);
674 // Check if they've got an LRDD header
676 $lrdd = LinkHeader::getLink($response, 'lrdd');
678 $xrd = new XML_XRD();
679 $xrd->loadFile($lrdd);
680 $xrdHints = DiscoveryHints::fromXRD($xrd);
681 $hints = array_merge($hints, $xrdHints);
682 } catch (Exception $e) {
683 // No hints available from XRD
686 // If discovery found a feedurl (probably from LRDD), use it.
688 if (array_key_exists('feedurl', $hints)) {
689 return self::ensureFeedURL($hints['feedurl'], $hints);
692 // Get the feed URL from HTML
694 $discover = new FeedDiscovery();
696 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
698 if (!empty($feedurl)) {
699 $hints['feedurl'] = $feedurl;
700 return self::ensureFeedURL($feedurl, $hints);
703 // TRANS: Exception. %s is a URL.
704 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
708 * Look up the Ostatus_profile, if present, for a remote entity with the
709 * given profile page URL. Will return null for both unknown and invalid
712 * @return mixed Ostatus_profile or null
713 * @throws OStatusShadowException for local profiles
715 static function getFromProfileURL($profile_url)
717 $profile = Profile::getKV('profileurl', $profile_url);
718 if (!$profile instanceof Profile) {
723 $oprofile = self::getFromProfile($profile);
724 // We found the profile, return it!
726 } catch (NoResultException $e) {
727 // Could not find an OStatus profile, is it instead a local user?
728 $user = User::getKV('id', $profile->id);
729 if ($user instanceof User) {
730 // @todo i18n FIXME: use sprintf and add i18n (?)
731 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
735 // Continue discovery; it's a remote profile
736 // for OMB or some other protocol, may also
742 static function getFromProfile(Profile $profile)
744 $oprofile = new Ostatus_profile();
745 $oprofile->profile_id = $profile->id;
746 if (!$oprofile->find(true)) {
747 throw new NoResultException($oprofile);
753 * Look up and if necessary create an Ostatus_profile for remote entity
754 * with the given update feed. This should never return null -- you will
755 * either get an object or an exception will be thrown.
757 * @return Ostatus_profile
760 public static function ensureFeedURL($feed_url, array $hints=array())
762 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
763 if ($oprofile instanceof Ostatus_profile) {
767 $discover = new FeedDiscovery();
769 $feeduri = $discover->discoverFromFeedURL($feed_url);
770 $hints['feedurl'] = $feeduri;
772 $huburi = $discover->getHubLink();
773 $hints['hub'] = $huburi;
775 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
776 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
777 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
778 $hints['salmon'] = $salmonuri;
780 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
781 // We can only deal with folks with a PuSH hub
782 // unless we have something similar available locally.
783 throw new FeedSubNoHubException();
786 $feedEl = $discover->root;
788 if ($feedEl->tagName == 'feed') {
789 return self::ensureAtomFeed($feedEl, $hints);
790 } else if ($feedEl->tagName == 'channel') {
791 return self::ensureRssChannel($feedEl, $hints);
793 throw new FeedSubBadXmlException($feeduri);
798 * Look up and, if necessary, create an Ostatus_profile for the remote
799 * profile with the given Atom feed - actually loaded from the feed.
800 * This should never return null -- you will either get an object or
801 * an exception will be thrown.
803 * @param DOMElement $feedEl root element of a loaded Atom feed
804 * @param array $hints additional discovery information passed from higher levels
805 * @todo FIXME: Should this be marked public?
806 * @return Ostatus_profile
809 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
811 $author = ActivityUtils::getFeedAuthor($feedEl);
813 if (empty($author)) {
814 // XXX: make some educated guesses here
815 // TRANS: Feed sub exception.
816 throw new FeedSubException(_m('Cannot find enough profile '.
817 'information to make a feed.'));
820 return self::ensureActivityObjectProfile($author, $hints);
824 * Look up and, if necessary, create an Ostatus_profile for the remote
825 * profile with the given RSS feed - actually loaded from the feed.
826 * This should never return null -- you will either get an object or
827 * an exception will be thrown.
829 * @param DOMElement $feedEl root element of a loaded RSS feed
830 * @param array $hints additional discovery information passed from higher levels
831 * @todo FIXME: Should this be marked public?
832 * @return Ostatus_profile
835 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
837 // Special-case for Posterous. They have some nice metadata in their
838 // posterous:author elements. We should use them instead of the channel.
840 $items = $feedEl->getElementsByTagName('item');
842 if ($items->length > 0) {
843 $item = $items->item(0);
844 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
845 if (!empty($authorEl)) {
846 $obj = ActivityObject::fromPosterousAuthor($authorEl);
847 // Posterous has multiple authors per feed, and multiple feeds
848 // per author. We check if this is the "main" feed for this author.
849 if (array_key_exists('profileurl', $hints) &&
850 !empty($obj->poco) &&
851 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
852 return self::ensureActivityObjectProfile($obj, $hints);
857 $obj = ActivityUtils::getFeedAuthor($feedEl);
859 // @todo FIXME: We should check whether this feed has elements
860 // with different <author> or <dc:creator> elements, and... I dunno.
861 // Do something about that.
863 if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
865 return self::ensureActivityObjectProfile($obj, $hints);
869 * Download and update given avatar image
872 * @return Avatar The Avatar we have on disk. (seldom used)
873 * @throws Exception in various failure cases
875 public function updateAvatar($url, $force=false)
878 // If avatar URL differs: update. If URLs were identical but we're forced: update.
879 if ($url == $this->avatar && !$force) {
880 // If there's no locally stored avatar, throw an exception and continue fetching below.
881 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
884 } catch (NoAvatarException $e) {
885 // No avatar available, let's fetch it.
888 if (!common_valid_http_url($url)) {
889 // TRANS: Server exception. %s is a URL.
890 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
893 $self = $this->localProfile();
895 // @todo FIXME: This should be better encapsulated
896 // ripped from oauthstore.php (for old OMB client)
897 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
899 $imgData = HTTPClient::quickGet($url);
900 // Make sure it's at least an image file. ImageFile can do the rest.
901 if (false === getimagesizefromstring($imgData)) {
902 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
904 file_put_contents($temp_filename, $imgData);
905 unset($imgData); // No need to carry this in memory.
907 if ($this->isGroup()) {
908 $id = $this->group_id;
910 $id = $this->profile_id;
912 $imagefile = new ImageFile(null, $temp_filename);
913 $filename = Avatar::filename($id,
914 image_type_to_extension($imagefile->type),
917 rename($temp_filename, Avatar::path($filename));
918 } catch (Exception $e) {
919 unlink($temp_filename);
922 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
923 // keep from accidentally saving images from command-line (queues)
924 // that can't be read from web server, which causes hard-to-notice
925 // problems later on:
927 // http://status.net/open-source/issues/2663
928 chmod(Avatar::path($filename), 0644);
930 $self->setOriginal($filename);
932 $orig = clone($this);
933 $this->avatar = $url;
934 $this->update($orig);
936 return Avatar::getUploaded($self);
940 * Pull avatar URL from ActivityObject or profile hints
942 * @param ActivityObject $object
943 * @param array $hints
944 * @return mixed URL string or false
946 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
948 if ($object->avatarLinks) {
950 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
951 foreach ($object->avatarLinks as $avatar) {
952 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
957 if (!$best || $avatar->width > $best->width) {
962 } else if (array_key_exists('avatar', $hints)) {
963 return $hints['avatar'];
969 * Get an appropriate avatar image source URL, if available.
971 * @param ActivityObject $actor
972 * @param DOMElement $feed
975 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
979 if ($actor->avatar) {
980 $url = trim($actor->avatar);
983 // Check <atom:logo> and <atom:icon> on the feed
984 $els = $feed->childNodes();
985 if ($els && $els->length) {
986 for ($i = 0; $i < $els->length; $i++) {
987 $el = $els->item($i);
988 if ($el->namespaceURI == Activity::ATOM) {
989 if (empty($url) && $el->localName == 'logo') {
990 $url = trim($el->textContent);
993 if (empty($icon) && $el->localName == 'icon') {
995 $icon = trim($el->textContent);
1000 if ($icon && !$url) {
1005 $opts = array('allowed_schemes' => array('http', 'https'));
1006 if (common_valid_http_url($url)) {
1011 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1015 * Fetch, or build if necessary, an Ostatus_profile for the actor
1016 * in a given Activity Streams activity.
1017 * This should never return null -- you will either get an object or
1018 * an exception will be thrown.
1020 * @param Activity $activity
1021 * @param string $feeduri if we already know the canonical feed URI!
1022 * @param string $salmonuri if we already know the salmon return channel URI
1023 * @return Ostatus_profile
1026 public static function ensureActorProfile(Activity $activity, array $hints=array())
1028 return self::ensureActivityObjectProfile($activity->actor, $hints);
1032 * Fetch, or build if necessary, an Ostatus_profile for the profile
1033 * in a given Activity Streams object (can be subject, actor, or object).
1034 * This should never return null -- you will either get an object or
1035 * an exception will be thrown.
1037 * @param ActivityObject $object
1038 * @param array $hints additional discovery information passed from higher levels
1039 * @return Ostatus_profile
1042 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1044 $profile = self::getActivityObjectProfile($object);
1045 if ($profile instanceof Ostatus_profile) {
1046 $profile->updateFromActivityObject($object, $hints);
1048 $profile = self::createActivityObjectProfile($object, $hints);
1054 * @param Activity $activity
1055 * @return mixed matching Ostatus_profile or false if none known
1056 * @throws ServerException if feed info invalid
1058 public static function getActorProfile(Activity $activity)
1060 return self::getActivityObjectProfile($activity->actor);
1064 * @param ActivityObject $activity
1065 * @return mixed matching Ostatus_profile or false if none known
1066 * @throws ServerException if feed info invalid
1068 protected static function getActivityObjectProfile(ActivityObject $object)
1070 $uri = self::getActivityObjectProfileURI($object);
1071 return Ostatus_profile::getKV('uri', $uri);
1075 * Get the identifier URI for the remote entity described
1076 * by this ActivityObject. This URI is *not* guaranteed to be
1077 * a resolvable HTTP/HTTPS URL.
1079 * @param ActivityObject $object
1081 * @throws ServerException if feed info invalid
1083 protected static function getActivityObjectProfileURI(ActivityObject $object)
1086 if (ActivityUtils::validateUri($object->id)) {
1091 // If the id is missing or invalid (we've seen feeds mistakenly listing
1092 // things like local usernames in that field) then we'll use the profile
1093 // page link, if valid.
1094 if ($object->link && common_valid_http_url($object->link)) {
1095 return $object->link;
1097 // TRANS: Server exception.
1098 throw new ServerException(_m('No author ID URI found.'));
1102 * @todo FIXME: Validate stuff somewhere.
1106 * Create local ostatus_profile and profile/user_group entries for
1107 * the provided remote user or group.
1108 * This should never return null -- you will either get an object or
1109 * an exception will be thrown.
1111 * @param ActivityObject $object
1112 * @param array $hints
1114 * @return Ostatus_profile
1116 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1118 $homeuri = $object->id;
1122 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1123 // TRANS: Exception.
1124 throw new Exception(_m('No profile URI.'));
1127 $user = User::getKV('uri', $homeuri);
1128 if ($user instanceof User) {
1129 // TRANS: Exception.
1130 throw new Exception(_m('Local user cannot be referenced as remote.'));
1133 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1134 // TRANS: Exception.
1135 throw new Exception(_m('Local group cannot be referenced as remote.'));
1138 $ptag = Profile_list::getKV('uri', $homeuri);
1139 if ($ptag instanceof Profile_list) {
1140 $local_user = User::getKV('id', $ptag->tagger);
1141 if ($local_user instanceof User) {
1142 // TRANS: Exception.
1143 throw new Exception(_m('Local list cannot be referenced as remote.'));
1147 if (array_key_exists('feedurl', $hints)) {
1148 $feeduri = $hints['feedurl'];
1150 $discover = new FeedDiscovery();
1151 $feeduri = $discover->discoverFromURL($homeuri);
1154 if (array_key_exists('salmon', $hints)) {
1155 $salmonuri = $hints['salmon'];
1158 $discover = new FeedDiscovery();
1159 $discover->discoverFromFeedURL($hints['feedurl']);
1161 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1162 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1163 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1166 if (array_key_exists('hub', $hints)) {
1167 $huburi = $hints['hub'];
1170 $discover = new FeedDiscovery();
1171 $discover->discoverFromFeedURL($hints['feedurl']);
1173 $huburi = $discover->getHubLink();
1176 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1177 // We can only deal with folks with a PuSH hub
1178 throw new FeedSubNoHubException();
1181 $oprofile = new Ostatus_profile();
1183 $oprofile->uri = $homeuri;
1184 $oprofile->feeduri = $feeduri;
1185 $oprofile->salmonuri = $salmonuri;
1187 $oprofile->created = common_sql_now();
1188 $oprofile->modified = common_sql_now();
1190 if ($object->type == ActivityObject::PERSON) {
1191 $profile = new Profile();
1192 $profile->created = common_sql_now();
1193 self::updateProfile($profile, $object, $hints);
1195 $oprofile->profile_id = $profile->insert();
1196 if ($oprofile->profile_id === false) {
1197 // TRANS: Server exception.
1198 throw new ServerException(_m('Cannot save local profile.'));
1200 } else if ($object->type == ActivityObject::GROUP) {
1201 $profile = new Profile();
1202 $profile->query('BEGIN');
1204 $group = new User_group();
1205 $group->uri = $homeuri;
1206 $group->created = common_sql_now();
1207 self::updateGroup($group, $object, $hints);
1209 // TODO: We should do this directly in User_group->insert()!
1210 // currently it's duplicated in User_group->update()
1211 // AND User_group->register()!!!
1212 $fields = array(/*group field => profile field*/
1213 'nickname' => 'nickname',
1214 'fullname' => 'fullname',
1215 'mainpage' => 'profileurl',
1216 'homepage' => 'homepage',
1217 'description' => 'bio',
1218 'location' => 'location',
1219 'created' => 'created',
1220 'modified' => 'modified',
1222 foreach ($fields as $gf=>$pf) {
1223 $profile->$pf = $group->$gf;
1225 $profile_id = $profile->insert();
1226 if ($profile_id === false) {
1227 $profile->query('ROLLBACK');
1228 throw new ServerException(_('Profile insertion failed.'));
1231 $group->profile_id = $profile_id;
1233 $oprofile->group_id = $group->insert();
1234 if ($oprofile->group_id === false) {
1235 $profile->query('ROLLBACK');
1236 // TRANS: Server exception.
1237 throw new ServerException(_m('Cannot save local profile.'));
1240 $profile->query('COMMIT');
1241 } else if ($object->type == ActivityObject::_LIST) {
1242 $ptag = new Profile_list();
1243 $ptag->uri = $homeuri;
1244 $ptag->created = common_sql_now();
1245 self::updatePeopletag($ptag, $object, $hints);
1247 $oprofile->peopletag_id = $ptag->insert();
1248 if ($oprofile->peopletag_id === false) {
1249 // TRANS: Server exception.
1250 throw new ServerException(_m('Cannot save local list.'));
1254 $ok = $oprofile->insert();
1256 if ($ok === false) {
1257 // TRANS: Server exception.
1258 throw new ServerException(_m('Cannot save OStatus profile.'));
1261 $avatar = self::getActivityObjectAvatar($object, $hints);
1265 $oprofile->updateAvatar($avatar);
1266 } catch (Exception $ex) {
1267 // Profile is saved, but Avatar is messed up. We're
1268 // just going to continue.
1269 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1277 * Save any updated profile information to our local copy.
1278 * @param ActivityObject $object
1279 * @param array $hints
1281 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1283 if ($this->isGroup()) {
1284 $group = $this->localGroup();
1285 self::updateGroup($group, $object, $hints);
1286 } else if ($this->isPeopletag()) {
1287 $ptag = $this->localPeopletag();
1288 self::updatePeopletag($ptag, $object, $hints);
1290 $profile = $this->localProfile();
1291 self::updateProfile($profile, $object, $hints);
1294 $avatar = self::getActivityObjectAvatar($object, $hints);
1295 if ($avatar && !isset($ptag)) {
1297 $this->updateAvatar($avatar);
1298 } catch (Exception $ex) {
1299 common_log(LOG_WARNING, "Exception updating OStatus profile avatar: " . $ex->getMessage());
1304 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1306 $orig = clone($profile);
1308 // Existing nickname is better than nothing.
1310 if (!array_key_exists('nickname', $hints)) {
1311 $hints['nickname'] = $profile->nickname;
1314 $nickname = self::getActivityObjectNickname($object, $hints);
1316 if (!empty($nickname)) {
1317 $profile->nickname = $nickname;
1320 if (!empty($object->title)) {
1321 $profile->fullname = $object->title;
1322 } else if (array_key_exists('fullname', $hints)) {
1323 $profile->fullname = $hints['fullname'];
1326 if (!empty($object->link)) {
1327 $profile->profileurl = $object->link;
1328 } else if (array_key_exists('profileurl', $hints)) {
1329 $profile->profileurl = $hints['profileurl'];
1330 } else if (common_valid_http_url($object->id)) {
1331 $profile->profileurl = $object->id;
1334 $bio = self::getActivityObjectBio($object, $hints);
1337 $profile->bio = $bio;
1340 $location = self::getActivityObjectLocation($object, $hints);
1342 if (!empty($location)) {
1343 $profile->location = $location;
1346 $homepage = self::getActivityObjectHomepage($object, $hints);
1348 if (!empty($homepage)) {
1349 $profile->homepage = $homepage;
1352 if (!empty($object->geopoint)) {
1353 $location = ActivityContext::locationFromPoint($object->geopoint);
1354 if (!empty($location)) {
1355 $profile->lat = $location->lat;
1356 $profile->lon = $location->lon;
1360 // @todo FIXME: tags/categories
1361 // @todo tags from categories
1364 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1365 $profile->update($orig);
1369 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1371 $orig = clone($group);
1373 $group->nickname = self::getActivityObjectNickname($object, $hints);
1374 $group->fullname = $object->title;
1376 if (!empty($object->link)) {
1377 $group->mainpage = $object->link;
1378 } else if (array_key_exists('profileurl', $hints)) {
1379 $group->mainpage = $hints['profileurl'];
1382 // @todo tags from categories
1383 $group->description = self::getActivityObjectBio($object, $hints);
1384 $group->location = self::getActivityObjectLocation($object, $hints);
1385 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1387 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1388 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1389 $group->update($orig);
1393 protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array()) {
1394 $orig = clone($tag);
1396 $tag->tag = $object->title;
1398 if (!empty($object->link)) {
1399 $tag->mainpage = $object->link;
1400 } else if (array_key_exists('profileurl', $hints)) {
1401 $tag->mainpage = $hints['profileurl'];
1404 $tag->description = $object->summary;
1405 $tagger = self::ensureActivityObjectProfile($object->owner);
1406 $tag->tagger = $tagger->profile_id;
1409 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1410 $tag->update($orig);
1414 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1417 $poco = $object->poco;
1419 if (!empty($poco)) {
1420 $url = $poco->getPrimaryURL();
1421 if ($url && $url->type == 'homepage') {
1422 $homepage = $url->value;
1426 // @todo Try for a another PoCo URL?
1431 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1435 if (!empty($object->poco) &&
1436 isset($object->poco->address->formatted)) {
1437 $location = $object->poco->address->formatted;
1438 } else if (array_key_exists('location', $hints)) {
1439 $location = $hints['location'];
1442 if (!empty($location)) {
1443 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1444 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1448 // @todo Try to find location some othe way? Via goerss point?
1453 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1457 if (!empty($object->poco)) {
1458 $note = $object->poco->note;
1459 } else if (array_key_exists('bio', $hints)) {
1460 $note = $hints['bio'];
1463 if (!empty($note)) {
1464 if (Profile::bioTooLong($note)) {
1465 // XXX: truncate ok?
1466 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1472 // @todo Try to get bio info some other way?
1477 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1479 if ($object->poco) {
1480 if (!empty($object->poco->preferredUsername)) {
1481 return common_nicknamize($object->poco->preferredUsername);
1485 if (!empty($object->nickname)) {
1486 return common_nicknamize($object->nickname);
1489 if (array_key_exists('nickname', $hints)) {
1490 return $hints['nickname'];
1493 // Try the profile url (like foo.example.com or example.com/user/foo)
1494 if (!empty($object->link)) {
1495 $profileUrl = $object->link;
1496 } else if (!empty($hints['profileurl'])) {
1497 $profileUrl = $hints['profileurl'];
1500 if (!empty($profileUrl)) {
1501 $nickname = self::nicknameFromURI($profileUrl);
1504 // Try the URI (may be a tag:, http:, acct:, ...
1506 if (empty($nickname)) {
1507 $nickname = self::nicknameFromURI($object->id);
1510 // Try a Webfinger if one was passed (way) down
1512 if (empty($nickname)) {
1513 if (array_key_exists('webfinger', $hints)) {
1514 $nickname = self::nicknameFromURI($hints['webfinger']);
1520 if (empty($nickname)) {
1521 $nickname = common_nicknamize($object->title);
1527 protected static function nicknameFromURI($uri)
1529 if (preg_match('/(\w+):/', $uri, $matches)) {
1530 $protocol = $matches[1];
1535 switch ($protocol) {
1538 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1539 return common_canonical_nickname($matches[1]);
1543 return common_url_to_nickname($uri);
1551 * Look up, and if necessary create, an Ostatus_profile for the remote
1552 * entity with the given webfinger address.
1553 * This should never return null -- you will either get an object or
1554 * an exception will be thrown.
1556 * @param string $addr webfinger address
1557 * @return Ostatus_profile
1558 * @throws Exception on error conditions
1559 * @throws OStatusShadowException if this reference would obscure a local user/group
1561 public static function ensureWebfinger($addr)
1563 // First, try the cache
1565 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1567 if ($uri !== false) {
1568 if (is_null($uri)) {
1569 // Negative cache entry
1570 // TRANS: Exception.
1571 throw new Exception(_m('Not a valid webfinger address.'));
1573 $oprofile = Ostatus_profile::getKV('uri', $uri);
1574 if ($oprofile instanceof Ostatus_profile) {
1579 // Try looking it up
1580 $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1582 if ($oprofile instanceof Ostatus_profile) {
1583 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1587 // Now, try some discovery
1589 $disco = new Discovery();
1592 $xrd = $disco->lookup($addr);
1593 } catch (Exception $e) {
1594 // Save negative cache entry so we don't waste time looking it up again.
1595 // @todo FIXME: Distinguish temporary failures?
1596 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1597 // TRANS: Exception.
1598 throw new Exception(_m('Not a valid webfinger address.'));
1601 $hints = array_merge(array('webfinger' => $addr),
1602 DiscoveryHints::fromXRD($xrd));
1604 // If there's an Hcard, let's grab its info
1605 if (array_key_exists('hcard', $hints)) {
1606 if (!array_key_exists('profileurl', $hints) ||
1607 $hints['hcard'] != $hints['profileurl']) {
1608 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1609 $hints = array_merge($hcardHints, $hints);
1613 // If we got a feed URL, try that
1615 if (array_key_exists('feedurl', $hints)) {
1616 $feedUrl = $hints['feedurl'];
1618 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1619 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1620 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1622 } catch (Exception $e) {
1623 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1628 // If we got a profile page, try that!
1630 if (array_key_exists('profileurl', $hints)) {
1631 $profileUrl = $hints['profileurl'];
1633 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1634 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1635 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1637 } catch (OStatusShadowException $e) {
1638 // We've ended up with a remote reference to a local user or group.
1639 // @todo FIXME: Ideally we should be able to say who it was so we can
1640 // go back and refer to it the regular way
1642 } catch (Exception $e) {
1643 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1646 // @todo FIXME: This means an error discovering from profile page
1647 // may give us a corrupt entry using the webfinger URI, which
1648 // will obscure the correct page-keyed profile later on.
1655 if (array_key_exists('salmon', $hints)) {
1656 $salmonEndpoint = $hints['salmon'];
1658 // An account URL, a salmon endpoint, and a dream? Not much to go
1659 // on, but let's give it a try
1661 $uri = 'acct:'.$addr;
1663 $profile = new Profile();
1665 $profile->nickname = self::nicknameFromUri($uri);
1666 $profile->created = common_sql_now();
1668 if (!is_null($profileUrl)) {
1669 $profile->profileurl = $profileUrl;
1672 $profile_id = $profile->insert();
1674 if ($profile_id === false) {
1675 common_log_db_error($profile, 'INSERT', __FILE__);
1676 // TRANS: Exception. %s is a webfinger address.
1677 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1680 $oprofile = new Ostatus_profile();
1682 $oprofile->uri = $uri;
1683 $oprofile->salmonuri = $salmonEndpoint;
1684 $oprofile->profile_id = $profile_id;
1685 $oprofile->created = common_sql_now();
1687 if (!is_null($feedUrl)) {
1688 $oprofile->feeduri = $feedUrl;
1691 $result = $oprofile->insert();
1693 if ($result === false) {
1695 common_log_db_error($oprofile, 'INSERT', __FILE__);
1696 // TRANS: Exception. %s is a webfinger address.
1697 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1700 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1704 // TRANS: Exception. %s is a webfinger address.
1705 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1709 * Store the full-length scrubbed HTML of a remote notice to an attachment
1710 * file on our server. We'll link to this at the end of the cropped version.
1712 * @param string $title plaintext for HTML page's title
1713 * @param string $rendered HTML fragment for HTML page's body
1716 function saveHTMLFile($title, $rendered)
1718 $final = sprintf("<!DOCTYPE html>\n" .
1720 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1721 '<title>%s</title>' .
1723 '<body>%s</body></html>',
1724 htmlspecialchars($title),
1727 $filename = File::filename($this->localProfile(),
1728 'ostatus', // ignored?
1731 $filepath = File::path($filename);
1732 $fileurl = File::url($filename);
1734 file_put_contents($filepath, $final);
1738 $file->filename = $filename;
1739 $file->urlhash = File::hashurl($fileurl);
1740 $file->url = $fileurl;
1741 $file->size = filesize($filepath);
1742 $file->date = time();
1743 $file->mimetype = 'text/html';
1745 $file_id = $file->insert();
1747 if ($file_id === false) {
1748 common_log_db_error($file, "INSERT", __FILE__);
1749 // TRANS: Server exception.
1750 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1756 static function ensureProfileURI($uri)
1760 // First, try to query it
1762 $oprofile = Ostatus_profile::getKV('uri', $uri);
1764 if ($oprofile instanceof Ostatus_profile) {
1768 // If unfound, do discovery stuff
1769 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1770 $protocol = $match[1];
1771 switch ($protocol) {
1774 $oprofile = self::ensureProfileURL($uri);
1779 $oprofile = self::ensureWebfinger($rest);
1782 // TRANS: Server exception.
1783 // TRANS: %1$s is a protocol, %2$s is a URI.
1784 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1789 // TRANS: Server exception. %s is a URI.
1790 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1796 public function checkAuthorship(Activity $activity)
1798 if ($this->isGroup() || $this->isPeopletag()) {
1799 // A group or propletag feed will contain posts from multiple authors.
1800 $oprofile = self::ensureActorProfile($activity);
1801 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1802 // Groups can't post notices in StatusNet.
1803 common_log(LOG_WARNING,
1804 "OStatus: skipping post with group listed ".
1805 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1806 throw new ServerException('Activity author is a non-actor');
1809 $actor = $activity->actor;
1811 if (empty($actor)) {
1812 // OK here! assume the default
1813 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1814 $this->updateFromActivityObject($actor);
1815 } else if ($actor->id) {
1816 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1817 // This isn't what we expect from mainline OStatus person feeds!
1818 // Group feeds go down another path, with different validation...
1819 // Most likely this is a plain ol' blog feed of some kind which
1820 // doesn't match our expectations. We'll take the entry, but ignore
1821 // the <author> info.
1822 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1824 // Plain <author> without ActivityStreams actor info.
1825 // We'll just ignore this info for now and save the update under the feed's identity.
1831 return $oprofile->localProfile();
1834 public function updateUriKeys($profile_uri, array $hints=array())
1836 $orig = clone($this);
1838 common_debug('URIFIX These identities both say they are each other: "'.$orig->uri.'" and "'.$profile_uri.'"');
1839 $this->uri = $profile_uri;
1841 if (array_key_exists('feedurl', $hints)) {
1842 if (!empty($this->feeduri)) {
1843 common_debug('URIFIX Changing FeedSub ['.$feedsub->id.'] feeduri "'.$feedsub->uri.'" to "'.$hints['feedurl']);
1844 $feedsub = FeedSub::getKV('uri', $this->feeduri);
1845 $feedorig = clone($feedsub);
1846 $feedsub->uri = $hints['feedurl'];
1847 $feedsub->updateWithKeys($feedorig);
1849 common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring feed: '.$hints['feedurl']);
1850 FeedSub::ensureFeed($hints['feedurl']);
1852 $this->feeduri = $hints['feedurl'];
1854 if (array_key_exists('salmon', $hints)) {
1855 common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
1856 $this->salmonuri = $hints['salmon'];
1859 common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
1860 $this->updateWithKeys($orig); // Will use the PID column(s) in the 'UPDATE ... WHERE [unique selector]'
1862 common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);