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 * @return boolean success
376 public function notifyDeferred($entry, $actor)
378 if ($this->salmonuri) {
379 $data = array('salmonuri' => $this->salmonuri,
380 'entry' => $this->notifyPrepXml($entry),
381 'actor' => $actor->getID(),
382 'target' => $this->localProfile()->getID());
384 $qm = QueueManager::get();
385 return $qm->enqueue($data, 'salmon');
391 protected function notifyPrepXml($entry)
393 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
394 if (is_string($entry)) {
396 } else if ($entry instanceof Activity) {
397 return $preamble . $entry->asString(true);
398 } else if ($entry instanceof Notice) {
399 return $preamble . $entry->asAtomEntry(true, true);
401 // TRANS: Server exception.
402 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
406 function getBestName()
408 if ($this->isGroup()) {
409 return $this->localGroup()->getBestName();
410 } else if ($this->isPeopletag()) {
411 return $this->localPeopletag()->getBestName();
413 return $this->localProfile()->getBestName();
418 * Read and post notices for updates from the feed.
419 * Currently assumes that all items in the feed are new,
420 * coming from a PuSH hub.
422 * @param DOMDocument $doc
423 * @param string $source identifier ("push")
425 public function processFeed(DOMDocument $doc, $source)
427 $feed = $doc->documentElement;
429 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
430 $this->processAtomFeed($feed, $source);
431 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
432 $this->processRssFeed($feed, $source);
435 throw new Exception(_m('Unknown feed format.'));
439 public function processAtomFeed(DOMElement $feed, $source)
441 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
442 if ($entries->length == 0) {
443 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
447 for ($i = 0; $i < $entries->length; $i++) {
448 $entry = $entries->item($i);
449 $this->processEntry($entry, $feed, $source);
453 public function processRssFeed(DOMElement $rss, $source)
455 $channels = $rss->getElementsByTagName('channel');
457 if ($channels->length == 0) {
459 throw new Exception(_m('RSS feed without a channel.'));
460 } else if ($channels->length > 1) {
461 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
464 $channel = $channels->item(0);
466 $items = $channel->getElementsByTagName('item');
468 for ($i = 0; $i < $items->length; $i++) {
469 $item = $items->item($i);
470 $this->processEntry($item, $channel, $source);
475 * Process a posted entry from this feed source.
477 * @param DOMElement $entry
478 * @param DOMElement $feed for context
479 * @param string $source identifier ("push" or "salmon")
481 * @return Notice Notice representing the new (or existing) activity
483 public function processEntry($entry, $feed, $source)
485 $activity = new Activity($entry, $feed);
486 return $this->processActivity($activity, $source);
489 // TODO: Make this throw an exception
490 public function processActivity($activity, $source)
494 // The "WithProfile" events were added later.
496 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
497 Event::handle('StartHandleFeedEntry', array($activity))) {
499 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
501 Event::handle('EndHandleFeedEntry', array($activity));
502 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
509 * Process an incoming post activity from this remote feed.
510 * @param Activity $activity
511 * @param string $method 'push' or 'salmon'
512 * @return mixed saved Notice or false
514 public function processPost($activity, $method)
516 $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
518 $options = array('is_local' => Notice::REMOTE);
521 $stored = Notice::saveActivity($activity, $actor, $options);
522 Ostatus_source::saveNew($stored, $this, $method);
523 } catch (Exception $e) {
524 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
531 * Filters a list of recipient ID URIs to just those for local delivery.
532 * @param Profile local profile of sender
533 * @param array in/out &$attention_uris set of URIs, will be pruned on output
534 * @return array of group IDs
536 static public function filterAttention(Profile $sender, array $attention)
538 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
541 foreach ($attention as $recipient=>$type) {
542 // Is the recipient a local user?
543 $user = User::getKV('uri', $recipient);
544 if ($user instanceof User) {
545 // @todo FIXME: Sender verification, spam etc?
546 $replies[] = $recipient;
550 // Is the recipient a local group?
551 // TODO: $group = User_group::getKV('uri', $recipient);
552 $id = OStatusPlugin::localGroupFromUrl($recipient);
554 $group = User_group::getKV('id', $id);
555 if ($group instanceof User_group) {
556 // Deliver to all members of this local group if allowed.
557 if ($sender->isMember($group)) {
558 $groups[] = $group->id;
560 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
564 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
568 // Is the recipient a remote user or group?
570 $oprofile = self::ensureProfileURI($recipient);
571 if ($oprofile->isGroup()) {
572 // Deliver to local members of this remote group.
573 // @todo FIXME: Sender verification?
574 $groups[] = $oprofile->group_id;
576 // may be canonicalized or something
577 $replies[] = $oprofile->getUri();
580 } catch (Exception $e) {
581 // Neither a recognizable local nor remote user!
582 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
586 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
587 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
588 return array($groups, $replies);
592 * Look up and if necessary create an Ostatus_profile for the remote entity
593 * with the given profile page URL. This should never return null -- you
594 * will either get an object or an exception will be thrown.
596 * @param string $profile_url
597 * @return Ostatus_profile
598 * @throws Exception on various error conditions
599 * @throws OStatusShadowException if this reference would obscure a local user/group
601 public static function ensureProfileURL($profile_url, array $hints=array())
603 $oprofile = self::getFromProfileURL($profile_url);
605 if ($oprofile instanceof Ostatus_profile) {
609 $hints['profileurl'] = $profile_url;
614 $client = new HTTPClient();
615 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
616 $response = $client->get($profile_url);
618 if (!$response->isOk()) {
619 // TRANS: Exception. %s is a profile URL.
620 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
623 // Check if we have a non-canonical URL
625 $finalUrl = $response->getUrl();
627 if ($finalUrl != $profile_url) {
629 $hints['profileurl'] = $finalUrl;
631 $oprofile = self::getFromProfileURL($finalUrl);
633 if ($oprofile instanceof Ostatus_profile) {
638 // Try to get some hCard data
640 $body = $response->getBody();
642 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
644 if (!empty($hcardHints)) {
645 $hints = array_merge($hints, $hcardHints);
648 // Check if they've got an LRDD header
650 $lrdd = LinkHeader::getLink($response, 'lrdd');
652 $xrd = new XML_XRD();
653 $xrd->loadFile($lrdd);
654 $xrdHints = DiscoveryHints::fromXRD($xrd);
655 $hints = array_merge($hints, $xrdHints);
656 } catch (Exception $e) {
657 // No hints available from XRD
660 // If discovery found a feedurl (probably from LRDD), use it.
662 if (array_key_exists('feedurl', $hints)) {
663 return self::ensureFeedURL($hints['feedurl'], $hints);
666 // Get the feed URL from HTML
668 $discover = new FeedDiscovery();
670 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
672 if (!empty($feedurl)) {
673 $hints['feedurl'] = $feedurl;
674 return self::ensureFeedURL($feedurl, $hints);
677 // TRANS: Exception. %s is a URL.
678 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
682 * Look up the Ostatus_profile, if present, for a remote entity with the
683 * given profile page URL. Will return null for both unknown and invalid
686 * @return mixed Ostatus_profile or null
687 * @throws OStatusShadowException for local profiles
689 static function getFromProfileURL($profile_url)
691 $profile = Profile::getKV('profileurl', $profile_url);
692 if (!$profile instanceof Profile) {
697 $oprofile = self::getFromProfile($profile);
698 // We found the profile, return it!
700 } catch (NoResultException $e) {
701 // Could not find an OStatus profile, is it instead a local user?
702 $user = User::getKV('id', $profile->id);
703 if ($user instanceof User) {
704 // @todo i18n FIXME: use sprintf and add i18n (?)
705 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
709 // Continue discovery; it's a remote profile
710 // for OMB or some other protocol, may also
716 static function getFromProfile(Profile $profile)
718 $oprofile = new Ostatus_profile();
719 $oprofile->profile_id = $profile->id;
720 if (!$oprofile->find(true)) {
721 throw new NoResultException($oprofile);
727 * Look up and if necessary create an Ostatus_profile for remote entity
728 * with the given update feed. This should never return null -- you will
729 * either get an object or an exception will be thrown.
731 * @return Ostatus_profile
734 public static function ensureFeedURL($feed_url, array $hints=array())
736 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
737 if ($oprofile instanceof Ostatus_profile) {
741 $discover = new FeedDiscovery();
743 $feeduri = $discover->discoverFromFeedURL($feed_url);
744 $hints['feedurl'] = $feeduri;
746 $huburi = $discover->getHubLink();
747 $hints['hub'] = $huburi;
749 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
750 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
751 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
752 $hints['salmon'] = $salmonuri;
754 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
755 // We can only deal with folks with a PuSH hub
756 // unless we have something similar available locally.
757 throw new FeedSubNoHubException();
760 $feedEl = $discover->root;
762 if ($feedEl->tagName == 'feed') {
763 return self::ensureAtomFeed($feedEl, $hints);
764 } else if ($feedEl->tagName == 'channel') {
765 return self::ensureRssChannel($feedEl, $hints);
767 throw new FeedSubBadXmlException($feeduri);
772 * Look up and, if necessary, create an Ostatus_profile for the remote
773 * profile with the given Atom feed - actually loaded from the feed.
774 * This should never return null -- you will either get an object or
775 * an exception will be thrown.
777 * @param DOMElement $feedEl root element of a loaded Atom feed
778 * @param array $hints additional discovery information passed from higher levels
779 * @todo FIXME: Should this be marked public?
780 * @return Ostatus_profile
783 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
785 $author = ActivityUtils::getFeedAuthor($feedEl);
787 if (empty($author)) {
788 // XXX: make some educated guesses here
789 // TRANS: Feed sub exception.
790 throw new FeedSubException(_m('Cannot find enough profile '.
791 'information to make a feed.'));
794 return self::ensureActivityObjectProfile($author, $hints);
798 * Look up and, if necessary, create an Ostatus_profile for the remote
799 * profile with the given RSS 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 RSS 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 ensureRssChannel(DOMElement $feedEl, array $hints)
811 // Special-case for Posterous. They have some nice metadata in their
812 // posterous:author elements. We should use them instead of the channel.
814 $items = $feedEl->getElementsByTagName('item');
816 if ($items->length > 0) {
817 $item = $items->item(0);
818 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
819 if (!empty($authorEl)) {
820 $obj = ActivityObject::fromPosterousAuthor($authorEl);
821 // Posterous has multiple authors per feed, and multiple feeds
822 // per author. We check if this is the "main" feed for this author.
823 if (array_key_exists('profileurl', $hints) &&
824 !empty($obj->poco) &&
825 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
826 return self::ensureActivityObjectProfile($obj, $hints);
831 // @todo FIXME: We should check whether this feed has elements
832 // with different <author> or <dc:creator> elements, and... I dunno.
833 // Do something about that.
835 $obj = ActivityObject::fromRssChannel($feedEl);
837 return self::ensureActivityObjectProfile($obj, $hints);
841 * Download and update given avatar image
844 * @return Avatar The Avatar we have on disk. (seldom used)
845 * @throws Exception in various failure cases
847 public function updateAvatar($url, $force=false)
850 // If avatar URL differs: update. If URLs were identical but we're forced: update.
851 if ($url == $this->avatar && !$force) {
852 // If there's no locally stored avatar, throw an exception and continue fetching below.
853 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
856 } catch (NoAvatarException $e) {
857 // No avatar available, let's fetch it.
860 if (!common_valid_http_url($url)) {
861 // TRANS: Server exception. %s is a URL.
862 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
865 $self = $this->localProfile();
867 // @todo FIXME: This should be better encapsulated
868 // ripped from oauthstore.php (for old OMB client)
869 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
871 $imgData = HTTPClient::quickGet($url);
872 // Make sure it's at least an image file. ImageFile can do the rest.
873 if (false === getimagesizefromstring($imgData)) {
874 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
876 file_put_contents($temp_filename, $imgData);
877 unset($imgData); // No need to carry this in memory.
879 if ($this->isGroup()) {
880 $id = $this->group_id;
882 $id = $this->profile_id;
884 $imagefile = new ImageFile(null, $temp_filename);
885 $filename = Avatar::filename($id,
886 image_type_to_extension($imagefile->type),
889 rename($temp_filename, Avatar::path($filename));
890 } catch (Exception $e) {
891 unlink($temp_filename);
894 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
895 // keep from accidentally saving images from command-line (queues)
896 // that can't be read from web server, which causes hard-to-notice
897 // problems later on:
899 // http://status.net/open-source/issues/2663
900 chmod(Avatar::path($filename), 0644);
902 $self->setOriginal($filename);
904 $orig = clone($this);
905 $this->avatar = $url;
906 $this->update($orig);
908 return Avatar::getUploaded($self);
912 * Pull avatar URL from ActivityObject or profile hints
914 * @param ActivityObject $object
915 * @param array $hints
916 * @return mixed URL string or false
918 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
920 if ($object->avatarLinks) {
922 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
923 foreach ($object->avatarLinks as $avatar) {
924 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
929 if (!$best || $avatar->width > $best->width) {
934 } else if (array_key_exists('avatar', $hints)) {
935 return $hints['avatar'];
941 * Get an appropriate avatar image source URL, if available.
943 * @param ActivityObject $actor
944 * @param DOMElement $feed
947 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
951 if ($actor->avatar) {
952 $url = trim($actor->avatar);
955 // Check <atom:logo> and <atom:icon> on the feed
956 $els = $feed->childNodes();
957 if ($els && $els->length) {
958 for ($i = 0; $i < $els->length; $i++) {
959 $el = $els->item($i);
960 if ($el->namespaceURI == Activity::ATOM) {
961 if (empty($url) && $el->localName == 'logo') {
962 $url = trim($el->textContent);
965 if (empty($icon) && $el->localName == 'icon') {
967 $icon = trim($el->textContent);
972 if ($icon && !$url) {
977 $opts = array('allowed_schemes' => array('http', 'https'));
978 if (common_valid_http_url($url)) {
983 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
987 * Fetch, or build if necessary, an Ostatus_profile for the actor
988 * in a given Activity Streams activity.
989 * This should never return null -- you will either get an object or
990 * an exception will be thrown.
992 * @param Activity $activity
993 * @param string $feeduri if we already know the canonical feed URI!
994 * @param string $salmonuri if we already know the salmon return channel URI
995 * @return Ostatus_profile
998 public static function ensureActorProfile(Activity $activity, array $hints=array())
1000 return self::ensureActivityObjectProfile($activity->actor, $hints);
1004 * Fetch, or build if necessary, an Ostatus_profile for the profile
1005 * in a given Activity Streams object (can be subject, actor, or object).
1006 * This should never return null -- you will either get an object or
1007 * an exception will be thrown.
1009 * @param ActivityObject $object
1010 * @param array $hints additional discovery information passed from higher levels
1011 * @return Ostatus_profile
1014 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1016 $profile = self::getActivityObjectProfile($object);
1017 if ($profile instanceof Ostatus_profile) {
1018 $profile->updateFromActivityObject($object, $hints);
1020 $profile = self::createActivityObjectProfile($object, $hints);
1026 * @param Activity $activity
1027 * @return mixed matching Ostatus_profile or false if none known
1028 * @throws ServerException if feed info invalid
1030 public static function getActorProfile(Activity $activity)
1032 return self::getActivityObjectProfile($activity->actor);
1036 * @param ActivityObject $activity
1037 * @return mixed matching Ostatus_profile or false if none known
1038 * @throws ServerException if feed info invalid
1040 protected static function getActivityObjectProfile(ActivityObject $object)
1042 $uri = self::getActivityObjectProfileURI($object);
1043 return Ostatus_profile::getKV('uri', $uri);
1047 * Get the identifier URI for the remote entity described
1048 * by this ActivityObject. This URI is *not* guaranteed to be
1049 * a resolvable HTTP/HTTPS URL.
1051 * @param ActivityObject $object
1053 * @throws ServerException if feed info invalid
1055 protected static function getActivityObjectProfileURI(ActivityObject $object)
1058 if (ActivityUtils::validateUri($object->id)) {
1063 // If the id is missing or invalid (we've seen feeds mistakenly listing
1064 // things like local usernames in that field) then we'll use the profile
1065 // page link, if valid.
1066 if ($object->link && common_valid_http_url($object->link)) {
1067 return $object->link;
1069 // TRANS: Server exception.
1070 throw new ServerException(_m('No author ID URI found.'));
1074 * @todo FIXME: Validate stuff somewhere.
1078 * Create local ostatus_profile and profile/user_group entries for
1079 * the provided remote user or group.
1080 * This should never return null -- you will either get an object or
1081 * an exception will be thrown.
1083 * @param ActivityObject $object
1084 * @param array $hints
1086 * @return Ostatus_profile
1088 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1090 $homeuri = $object->id;
1094 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1095 // TRANS: Exception.
1096 throw new Exception(_m('No profile URI.'));
1099 $user = User::getKV('uri', $homeuri);
1100 if ($user instanceof User) {
1101 // TRANS: Exception.
1102 throw new Exception(_m('Local user cannot be referenced as remote.'));
1105 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1106 // TRANS: Exception.
1107 throw new Exception(_m('Local group cannot be referenced as remote.'));
1110 $ptag = Profile_list::getKV('uri', $homeuri);
1111 if ($ptag instanceof Profile_list) {
1112 $local_user = User::getKV('id', $ptag->tagger);
1113 if ($local_user instanceof User) {
1114 // TRANS: Exception.
1115 throw new Exception(_m('Local list cannot be referenced as remote.'));
1119 if (array_key_exists('feedurl', $hints)) {
1120 $feeduri = $hints['feedurl'];
1122 $discover = new FeedDiscovery();
1123 $feeduri = $discover->discoverFromURL($homeuri);
1126 if (array_key_exists('salmon', $hints)) {
1127 $salmonuri = $hints['salmon'];
1130 $discover = new FeedDiscovery();
1131 $discover->discoverFromFeedURL($hints['feedurl']);
1133 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1134 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1135 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1138 if (array_key_exists('hub', $hints)) {
1139 $huburi = $hints['hub'];
1142 $discover = new FeedDiscovery();
1143 $discover->discoverFromFeedURL($hints['feedurl']);
1145 $huburi = $discover->getHubLink();
1148 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1149 // We can only deal with folks with a PuSH hub
1150 throw new FeedSubNoHubException();
1153 $oprofile = new Ostatus_profile();
1155 $oprofile->uri = $homeuri;
1156 $oprofile->feeduri = $feeduri;
1157 $oprofile->salmonuri = $salmonuri;
1159 $oprofile->created = common_sql_now();
1160 $oprofile->modified = common_sql_now();
1162 if ($object->type == ActivityObject::PERSON) {
1163 $profile = new Profile();
1164 $profile->created = common_sql_now();
1165 self::updateProfile($profile, $object, $hints);
1167 $oprofile->profile_id = $profile->insert();
1168 if ($oprofile->profile_id === false) {
1169 // TRANS: Server exception.
1170 throw new ServerException(_m('Cannot save local profile.'));
1172 } else if ($object->type == ActivityObject::GROUP) {
1173 $profile = new Profile();
1174 $profile->query('BEGIN');
1176 $group = new User_group();
1177 $group->uri = $homeuri;
1178 $group->created = common_sql_now();
1179 self::updateGroup($group, $object, $hints);
1181 // TODO: We should do this directly in User_group->insert()!
1182 // currently it's duplicated in User_group->update()
1183 // AND User_group->register()!!!
1184 $fields = array(/*group field => profile field*/
1185 'nickname' => 'nickname',
1186 'fullname' => 'fullname',
1187 'mainpage' => 'profileurl',
1188 'homepage' => 'homepage',
1189 'description' => 'bio',
1190 'location' => 'location',
1191 'created' => 'created',
1192 'modified' => 'modified',
1194 foreach ($fields as $gf=>$pf) {
1195 $profile->$pf = $group->$gf;
1197 $profile_id = $profile->insert();
1198 if ($profile_id === false) {
1199 $profile->query('ROLLBACK');
1200 throw new ServerException(_('Profile insertion failed.'));
1203 $group->profile_id = $profile_id;
1205 $oprofile->group_id = $group->insert();
1206 if ($oprofile->group_id === false) {
1207 $profile->query('ROLLBACK');
1208 // TRANS: Server exception.
1209 throw new ServerException(_m('Cannot save local profile.'));
1212 $profile->query('COMMIT');
1213 } else if ($object->type == ActivityObject::_LIST) {
1214 $ptag = new Profile_list();
1215 $ptag->uri = $homeuri;
1216 $ptag->created = common_sql_now();
1217 self::updatePeopletag($ptag, $object, $hints);
1219 $oprofile->peopletag_id = $ptag->insert();
1220 if ($oprofile->peopletag_id === false) {
1221 // TRANS: Server exception.
1222 throw new ServerException(_m('Cannot save local list.'));
1226 $ok = $oprofile->insert();
1228 if ($ok === false) {
1229 // TRANS: Server exception.
1230 throw new ServerException(_m('Cannot save OStatus profile.'));
1233 $avatar = self::getActivityObjectAvatar($object, $hints);
1237 $oprofile->updateAvatar($avatar);
1238 } catch (Exception $ex) {
1239 // Profile is saved, but Avatar is messed up. We're
1240 // just going to continue.
1241 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1249 * Save any updated profile information to our local copy.
1250 * @param ActivityObject $object
1251 * @param array $hints
1253 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1255 if ($this->isGroup()) {
1256 $group = $this->localGroup();
1257 self::updateGroup($group, $object, $hints);
1258 } else if ($this->isPeopletag()) {
1259 $ptag = $this->localPeopletag();
1260 self::updatePeopletag($ptag, $object, $hints);
1262 $profile = $this->localProfile();
1263 self::updateProfile($profile, $object, $hints);
1266 $avatar = self::getActivityObjectAvatar($object, $hints);
1267 if ($avatar && !isset($ptag)) {
1269 $this->updateAvatar($avatar);
1270 } catch (Exception $ex) {
1271 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1276 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1278 $orig = clone($profile);
1280 // Existing nickname is better than nothing.
1282 if (!array_key_exists('nickname', $hints)) {
1283 $hints['nickname'] = $profile->nickname;
1286 $nickname = self::getActivityObjectNickname($object, $hints);
1288 if (!empty($nickname)) {
1289 $profile->nickname = $nickname;
1292 if (!empty($object->title)) {
1293 $profile->fullname = $object->title;
1294 } else if (array_key_exists('fullname', $hints)) {
1295 $profile->fullname = $hints['fullname'];
1298 if (!empty($object->link)) {
1299 $profile->profileurl = $object->link;
1300 } else if (array_key_exists('profileurl', $hints)) {
1301 $profile->profileurl = $hints['profileurl'];
1302 } else if (common_valid_http_url($object->id)) {
1303 $profile->profileurl = $object->id;
1306 $bio = self::getActivityObjectBio($object, $hints);
1309 $profile->bio = $bio;
1312 $location = self::getActivityObjectLocation($object, $hints);
1314 if (!empty($location)) {
1315 $profile->location = $location;
1318 $homepage = self::getActivityObjectHomepage($object, $hints);
1320 if (!empty($homepage)) {
1321 $profile->homepage = $homepage;
1324 if (!empty($object->geopoint)) {
1325 $location = ActivityContext::locationFromPoint($object->geopoint);
1326 if (!empty($location)) {
1327 $profile->lat = $location->lat;
1328 $profile->lon = $location->lon;
1332 // @todo FIXME: tags/categories
1333 // @todo tags from categories
1336 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1337 $profile->update($orig);
1341 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1343 $orig = clone($group);
1345 $group->nickname = self::getActivityObjectNickname($object, $hints);
1346 $group->fullname = $object->title;
1348 if (!empty($object->link)) {
1349 $group->mainpage = $object->link;
1350 } else if (array_key_exists('profileurl', $hints)) {
1351 $group->mainpage = $hints['profileurl'];
1354 // @todo tags from categories
1355 $group->description = self::getActivityObjectBio($object, $hints);
1356 $group->location = self::getActivityObjectLocation($object, $hints);
1357 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1359 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1360 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1361 $group->update($orig);
1365 protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array()) {
1366 $orig = clone($tag);
1368 $tag->tag = $object->title;
1370 if (!empty($object->link)) {
1371 $tag->mainpage = $object->link;
1372 } else if (array_key_exists('profileurl', $hints)) {
1373 $tag->mainpage = $hints['profileurl'];
1376 $tag->description = $object->summary;
1377 $tagger = self::ensureActivityObjectProfile($object->owner);
1378 $tag->tagger = $tagger->profile_id;
1381 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1382 $tag->update($orig);
1386 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1389 $poco = $object->poco;
1391 if (!empty($poco)) {
1392 $url = $poco->getPrimaryURL();
1393 if ($url && $url->type == 'homepage') {
1394 $homepage = $url->value;
1398 // @todo Try for a another PoCo URL?
1403 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1407 if (!empty($object->poco) &&
1408 isset($object->poco->address->formatted)) {
1409 $location = $object->poco->address->formatted;
1410 } else if (array_key_exists('location', $hints)) {
1411 $location = $hints['location'];
1414 if (!empty($location)) {
1415 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1416 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1420 // @todo Try to find location some othe way? Via goerss point?
1425 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1429 if (!empty($object->poco)) {
1430 $note = $object->poco->note;
1431 } else if (array_key_exists('bio', $hints)) {
1432 $note = $hints['bio'];
1435 if (!empty($note)) {
1436 if (Profile::bioTooLong($note)) {
1437 // XXX: truncate ok?
1438 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1444 // @todo Try to get bio info some other way?
1449 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1451 if ($object->poco) {
1452 if (!empty($object->poco->preferredUsername)) {
1453 return common_nicknamize($object->poco->preferredUsername);
1457 if (!empty($object->nickname)) {
1458 return common_nicknamize($object->nickname);
1461 if (array_key_exists('nickname', $hints)) {
1462 return $hints['nickname'];
1465 // Try the profile url (like foo.example.com or example.com/user/foo)
1466 if (!empty($object->link)) {
1467 $profileUrl = $object->link;
1468 } else if (!empty($hints['profileurl'])) {
1469 $profileUrl = $hints['profileurl'];
1472 if (!empty($profileUrl)) {
1473 $nickname = self::nicknameFromURI($profileUrl);
1476 // Try the URI (may be a tag:, http:, acct:, ...
1478 if (empty($nickname)) {
1479 $nickname = self::nicknameFromURI($object->id);
1482 // Try a Webfinger if one was passed (way) down
1484 if (empty($nickname)) {
1485 if (array_key_exists('webfinger', $hints)) {
1486 $nickname = self::nicknameFromURI($hints['webfinger']);
1492 if (empty($nickname)) {
1493 $nickname = common_nicknamize($object->title);
1499 protected static function nicknameFromURI($uri)
1501 if (preg_match('/(\w+):/', $uri, $matches)) {
1502 $protocol = $matches[1];
1507 switch ($protocol) {
1510 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1511 return common_canonical_nickname($matches[1]);
1515 return common_url_to_nickname($uri);
1523 * Look up, and if necessary create, an Ostatus_profile for the remote
1524 * entity with the given webfinger address.
1525 * This should never return null -- you will either get an object or
1526 * an exception will be thrown.
1528 * @param string $addr webfinger address
1529 * @return Ostatus_profile
1530 * @throws Exception on error conditions
1531 * @throws OStatusShadowException if this reference would obscure a local user/group
1533 public static function ensureWebfinger($addr)
1535 // First, try the cache
1537 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1539 if ($uri !== false) {
1540 if (is_null($uri)) {
1541 // Negative cache entry
1542 // TRANS: Exception.
1543 throw new Exception(_m('Not a valid webfinger address.'));
1545 $oprofile = Ostatus_profile::getKV('uri', $uri);
1546 if ($oprofile instanceof Ostatus_profile) {
1551 // Try looking it up
1552 $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1554 if ($oprofile instanceof Ostatus_profile) {
1555 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1559 // Now, try some discovery
1561 $disco = new Discovery();
1564 $xrd = $disco->lookup($addr);
1565 } catch (Exception $e) {
1566 // Save negative cache entry so we don't waste time looking it up again.
1567 // @todo FIXME: Distinguish temporary failures?
1568 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1569 // TRANS: Exception.
1570 throw new Exception(_m('Not a valid webfinger address.'));
1573 $hints = array_merge(array('webfinger' => $addr),
1574 DiscoveryHints::fromXRD($xrd));
1576 // If there's an Hcard, let's grab its info
1577 if (array_key_exists('hcard', $hints)) {
1578 if (!array_key_exists('profileurl', $hints) ||
1579 $hints['hcard'] != $hints['profileurl']) {
1580 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1581 $hints = array_merge($hcardHints, $hints);
1585 // If we got a feed URL, try that
1587 if (array_key_exists('feedurl', $hints)) {
1588 $feedUrl = $hints['feedurl'];
1590 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1591 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1592 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1594 } catch (Exception $e) {
1595 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1600 // If we got a profile page, try that!
1602 if (array_key_exists('profileurl', $hints)) {
1603 $profileUrl = $hints['profileurl'];
1605 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1606 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1607 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1609 } catch (OStatusShadowException $e) {
1610 // We've ended up with a remote reference to a local user or group.
1611 // @todo FIXME: Ideally we should be able to say who it was so we can
1612 // go back and refer to it the regular way
1614 } catch (Exception $e) {
1615 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1618 // @todo FIXME: This means an error discovering from profile page
1619 // may give us a corrupt entry using the webfinger URI, which
1620 // will obscure the correct page-keyed profile later on.
1627 if (array_key_exists('salmon', $hints)) {
1628 $salmonEndpoint = $hints['salmon'];
1630 // An account URL, a salmon endpoint, and a dream? Not much to go
1631 // on, but let's give it a try
1633 $uri = 'acct:'.$addr;
1635 $profile = new Profile();
1637 $profile->nickname = self::nicknameFromUri($uri);
1638 $profile->created = common_sql_now();
1640 if (!is_null($profileUrl)) {
1641 $profile->profileurl = $profileUrl;
1644 $profile_id = $profile->insert();
1646 if ($profile_id === false) {
1647 common_log_db_error($profile, 'INSERT', __FILE__);
1648 // TRANS: Exception. %s is a webfinger address.
1649 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1652 $oprofile = new Ostatus_profile();
1654 $oprofile->uri = $uri;
1655 $oprofile->salmonuri = $salmonEndpoint;
1656 $oprofile->profile_id = $profile_id;
1657 $oprofile->created = common_sql_now();
1659 if (!is_null($feedUrl)) {
1660 $oprofile->feeduri = $feedUrl;
1663 $result = $oprofile->insert();
1665 if ($result === false) {
1667 common_log_db_error($oprofile, 'INSERT', __FILE__);
1668 // TRANS: Exception. %s is a webfinger address.
1669 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1672 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1676 // TRANS: Exception. %s is a webfinger address.
1677 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1681 * Store the full-length scrubbed HTML of a remote notice to an attachment
1682 * file on our server. We'll link to this at the end of the cropped version.
1684 * @param string $title plaintext for HTML page's title
1685 * @param string $rendered HTML fragment for HTML page's body
1688 function saveHTMLFile($title, $rendered)
1690 $final = sprintf("<!DOCTYPE html>\n" .
1692 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1693 '<title>%s</title>' .
1695 '<body>%s</body></html>',
1696 htmlspecialchars($title),
1699 $filename = File::filename($this->localProfile(),
1700 'ostatus', // ignored?
1703 $filepath = File::path($filename);
1704 $fileurl = File::url($filename);
1706 file_put_contents($filepath, $final);
1710 $file->filename = $filename;
1711 $file->urlhash = File::hashurl($fileurl);
1712 $file->url = $fileurl;
1713 $file->size = filesize($filepath);
1714 $file->date = time();
1715 $file->mimetype = 'text/html';
1717 $file_id = $file->insert();
1719 if ($file_id === false) {
1720 common_log_db_error($file, "INSERT", __FILE__);
1721 // TRANS: Server exception.
1722 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1728 static function ensureProfileURI($uri)
1732 // First, try to query it
1734 $oprofile = Ostatus_profile::getKV('uri', $uri);
1736 if ($oprofile instanceof Ostatus_profile) {
1740 // If unfound, do discovery stuff
1741 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1742 $protocol = $match[1];
1743 switch ($protocol) {
1746 $oprofile = self::ensureProfileURL($uri);
1751 $oprofile = self::ensureWebfinger($rest);
1754 // TRANS: Server exception.
1755 // TRANS: %1$s is a protocol, %2$s is a URI.
1756 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1761 // TRANS: Server exception. %s is a URI.
1762 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1768 public function checkAuthorship(Activity $activity)
1770 if ($this->isGroup() || $this->isPeopletag()) {
1771 // A group or propletag feed will contain posts from multiple authors.
1772 $oprofile = self::ensureActorProfile($activity);
1773 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1774 // Groups can't post notices in StatusNet.
1775 common_log(LOG_WARNING,
1776 "OStatus: skipping post with group listed ".
1777 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1778 throw new ServerException('Activity author is a non-actor');
1781 $actor = $activity->actor;
1783 if (empty($actor)) {
1784 // OK here! assume the default
1785 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1786 $this->updateFromActivityObject($actor);
1787 } else if ($actor->id) {
1788 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1789 // This isn't what we expect from mainline OStatus person feeds!
1790 // Group feeds go down another path, with different validation...
1791 // Most likely this is a plain ol' blog feed of some kind which
1792 // doesn't match our expectations. We'll take the entry, but ignore
1793 // the <author> info.
1794 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1796 // Plain <author> without ActivityStreams actor info.
1797 // We'll just ignore this info for now and save the update under the feed's identity.
1803 return $oprofile->localProfile();
1806 public function updateUriKeys($profile_uri, array $hints=array())
1808 $orig = clone($this);
1810 common_debug('URIFIX These identities both say they are each other: "'.$orig->uri.'" and "'.$profile_uri.'"');
1811 $this->uri = $profile_uri;
1813 if (array_key_exists('feedurl', $hints)) {
1814 if (!empty($this->feeduri)) {
1815 common_debug('URIFIX Changing FeedSub ['.$feedsub->id.'] feeduri "'.$feedsub->uri.'" to "'.$hints['feedurl']);
1816 $feedsub = FeedSub::getKV('uri', $this->feeduri);
1817 $feedorig = clone($feedsub);
1818 $feedsub->uri = $hints['feedurl'];
1819 $feedsub->updateWithKeys($feedorig);
1821 common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring feed: '.$hints['feedurl']);
1822 FeedSub::ensureFeed($hints['feedurl']);
1824 $this->feeduri = $hints['feedurl'];
1826 if (array_key_exists('salmon', $hints)) {
1827 common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
1828 $this->salmonuri = $hints['salmon'];
1831 common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
1832 $this->updateWithKeys($orig, 'uri'); // 'uri' is the primary key column
1834 common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);
1840 * Exception indicating we've got a remote reference to a local user,
1841 * not a remote user!
1843 * If we can ue a local profile after all, it's available as $e->profile.
1845 class OStatusShadowException extends Exception
1850 * @param Profile $profile
1851 * @param string $message
1853 function __construct($profile, $message) {
1854 $this->profile = $profile;
1855 parent::__construct($message);