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 static function fromProfile(Profile $profile)
85 $oprofile = Ostatus_profile::getKV('profile_id', $profile->getID());
86 if (!$oprofile instanceof Ostatus_profile) {
87 throw new Exception('No Ostatus_profile for Profile ID: '.$profile->getID());
93 * Fetch the locally stored profile for this feed
95 * @throws NoProfileException if it was not found
97 public function localProfile()
99 if ($this->isGroup()) {
100 return $this->localGroup()->getProfile();
103 $profile = Profile::getKV('id', $this->profile_id);
104 if (!$profile instanceof Profile) {
105 throw new NoProfileException($this->profile_id);
111 * Fetch the StatusNet-side profile for this feed
114 public function localGroup()
116 $group = User_group::getKV('id', $this->group_id);
118 if (!$group instanceof User_group) {
119 throw new NoSuchGroupException(array('id'=>$this->group_id));
126 * Fetch the StatusNet-side peopletag for this feed
129 public function localPeopletag()
131 if ($this->peopletag_id) {
132 return Profile_list::getKV('id', $this->peopletag_id);
138 * Returns an ActivityObject describing this remote user or group profile.
139 * Can then be used to generate Atom chunks.
141 * @return ActivityObject
143 function asActivityObject()
145 if ($this->isGroup()) {
146 return ActivityObject::fromGroup($this->localGroup());
147 } else if ($this->isPeopletag()) {
148 return ActivityObject::fromPeopletag($this->localPeopletag());
150 return $this->localProfile()->asActivityObject();
155 * Returns an XML string fragment with profile information as an
156 * Activity Streams noun object with the given element type.
158 * Assumes that 'activity' namespace has been previously defined.
160 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
162 * @param string $element one of 'actor', 'subject', 'object', 'target'
165 function asActivityNoun($element)
167 if ($this->isGroup()) {
168 $noun = ActivityObject::fromGroup($this->localGroup());
169 return $noun->asString('activity:' . $element);
170 } else if ($this->isPeopletag()) {
171 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
172 return $noun->asString('activity:' . $element);
174 $noun = $this->localProfile()->asActivityObject();
175 return $noun->asString('activity:' . $element);
180 * @return boolean true if this is a remote group
184 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
186 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
188 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
189 // TRANS: Server exception. %s is a URI
190 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
192 // TRANS: Server exception. %s is a URI
193 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
197 public function isPerson()
199 return $this->localProfile()->isPerson();
203 * @return boolean true if this is a remote peopletag
205 function isPeopletag()
207 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
209 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
211 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
212 // TRANS: Server exception. %s is a URI
213 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
215 // TRANS: Server exception. %s is a URI
216 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
221 * Send a subscription request to the hub for this feed.
222 * The hub will later send us a confirmation POST to /main/push/callback.
225 * @throws ServerException if feed state is not valid or subscription fails.
227 public function subscribe()
229 $feedsub = FeedSub::ensureFeed($this->feeduri);
230 if ($feedsub->sub_state == 'active') {
231 // Active subscription, we don't need to do anything.
235 // Inactive or we got left in an inconsistent state.
236 // Run a subscription request to make sure we're current!
237 return $feedsub->subscribe();
241 * Check if this remote profile has any active local subscriptions, and
242 * if not drop the PuSH subscription feed.
244 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
245 * @throws Exception of various kinds on failure.
247 public function unsubscribe() {
248 return $this->garbageCollect();
252 * Check if this remote profile has any active local subscriptions, and
253 * if not drop the PuSH subscription feed.
255 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
256 * @throws Exception of various kinds on failure.
258 public function garbageCollect()
260 $feedsub = FeedSub::getKV('uri', $this->feeduri);
261 if ($feedsub instanceof FeedSub) {
262 return $feedsub->garbageCollect();
264 // Since there's no FeedSub we can assume it's already garbage collected
269 * Check if this remote profile has any active local subscriptions, so the
270 * PuSH subscription layer can decide if it can drop the feed.
272 * This gets called via the FeedSubSubscriberCount event when running
273 * FeedSub::garbageCollect().
276 * @throws NoProfileException if there is no local profile for the object
278 public function subscriberCount()
280 if ($this->isGroup()) {
281 $members = $this->localGroup()->getMembers(0, 1);
282 $count = $members->N;
283 } else if ($this->isPeopletag()) {
284 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
285 $count = $subscribers->N;
287 $profile = $this->localProfile();
288 if ($profile->hasLocalTags()) {
291 $count = $profile->subscriberCount();
294 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
296 // Other plugins may be piggybacking on OStatus without having
297 // an active group or user-to-user subscription we know about.
298 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
299 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
305 * Send an Activity Streams notification to the remote Salmon endpoint,
308 * @param Profile $actor Actor who did the activity
309 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
310 * @param Object $object object of the action; must define asActivityNoun($tag)
312 public function notify(Profile $actor, $verb, $object=null, $target=null)
314 if ($object == null) {
317 if (empty($this->salmonuri)) {
321 $id = TagURI::mint('%s:%s:%s',
324 common_date_iso8601(time()));
326 // @todo FIXME: Consolidate all these NS settings somewhere.
327 $attributes = array('xmlns' => Activity::ATOM,
328 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
329 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
330 'xmlns:georss' => 'http://www.georss.org/georss',
331 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
332 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
333 'xmlns:media' => 'http://purl.org/syndication/atommedia');
335 $entry = new XMLStringer();
336 $entry->elementStart('entry', $attributes);
337 $entry->element('id', null, $id);
338 $entry->element('title', null, $text);
339 $entry->element('summary', null, $text);
340 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
342 $entry->element('activity:verb', null, $verb);
343 $entry->raw($actor->asAtomAuthor());
344 $entry->raw($actor->asActivityActor());
345 $entry->raw($object->asActivityNoun('object'));
346 if ($target != null) {
347 $entry->raw($target->asActivityNoun('target'));
349 $entry->elementEnd('entry');
351 $xml = $entry->getString();
352 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
354 Salmon::post($this->salmonuri, $xml, $actor);
358 * Send a Salmon notification ping immediately, and confirm that we got
359 * an acceptable response from the remote site.
361 * @param mixed $entry XML string, Notice, or Activity
362 * @param Profile $actor
363 * @return boolean success
365 public function notifyActivity($entry, Profile $actor)
367 if ($this->salmonuri) {
368 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor, $this->localProfile());
370 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
376 * Queue a Salmon notification for later. If queues are disabled we'll
377 * send immediately but won't get the return value.
379 * @param mixed $entry XML string, Notice, or Activity
380 * @return boolean success
382 public function notifyDeferred($entry, $actor)
384 if ($this->salmonuri) {
386 common_debug("OSTATUS: user {$actor->getNickname()} ({$actor->getID()}) wants to ping {$this->localProfile()->getNickname()} on {$this->salmonuri}");
387 $data = array('salmonuri' => $this->salmonuri,
388 'entry' => $this->notifyPrepXml($entry),
389 'actor' => $actor->getID(),
390 'target' => $this->localProfile()->getID());
392 $qm = QueueManager::get();
393 return $qm->enqueue($data, 'salmon');
394 } catch (Exception $e) {
395 common_log(LOG_ERR, 'OSTATUS: Something went wrong when creating a Salmon slap: '._ve($e->getMessage()));
403 protected function notifyPrepXml($entry)
405 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
406 if (is_string($entry)) {
408 } else if ($entry instanceof Activity) {
409 return $preamble . $entry->asString(true);
410 } else if ($entry instanceof Notice) {
411 return $preamble . $entry->asAtomEntry(true, true);
413 // TRANS: Server exception.
414 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
418 function getBestName()
420 if ($this->isGroup()) {
421 return $this->localGroup()->getBestName();
422 } else if ($this->isPeopletag()) {
423 return $this->localPeopletag()->getBestName();
425 return $this->localProfile()->getBestName();
430 * Read and post notices for updates from the feed.
431 * Currently assumes that all items in the feed are new,
432 * coming from a PuSH hub.
434 * @param DOMDocument $doc
435 * @param string $source identifier ("push")
437 public function processFeed(DOMDocument $doc, $source)
439 $feed = $doc->documentElement;
441 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
442 $this->processAtomFeed($feed, $source);
443 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
444 $this->processRssFeed($feed, $source);
447 throw new Exception(_m('Unknown feed format.'));
451 public function processAtomFeed(DOMElement $feed, $source)
453 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
454 if ($entries->length == 0) {
455 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
459 $this->processEntries($entries, $feed, $source);
462 public function processRssFeed(DOMElement $rss, $source)
464 $channels = $rss->getElementsByTagName('channel');
466 if ($channels->length == 0) {
468 throw new Exception(_m('RSS feed without a channel.'));
469 } else if ($channels->length > 1) {
470 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
473 $channel = $channels->item(0);
475 $items = $channel->getElementsByTagName('item');
477 $this->processEntries($items, $channel, $source);
480 public function processEntries(DOMNodeList $entries, DOMElement $feed, $source)
482 for ($i = 0; $i < $entries->length; $i++) {
483 $entry = $entries->item($i);
485 $this->processEntry($entry, $feed, $source);
486 } catch (AlreadyFulfilledException $e) {
487 common_debug('We already had this entry: '.$e->getMessage());
488 } catch (ServerException $e) {
489 // FIXME: This should be UnknownUriException and the ActivityUtils:: findLocalObject should only test one URI
490 common_log(LOG_ERR, 'Entry threw exception while processing a feed from '.$source.': '.$e->getMessage());
496 * Process a posted entry from this feed source.
498 * @param DOMElement $entry
499 * @param DOMElement $feed for context
500 * @param string $source identifier ("push" or "salmon")
502 * @return Notice Notice representing the new (or existing) activity
504 public function processEntry(DOMElement $entry, DOMElement $feed, $source)
506 $activity = new Activity($entry, $feed);
507 return $this->processActivity($activity, $source);
510 // TODO: Make this throw an exception
511 public function processActivity(Activity $activity, $source)
515 // The "WithProfile" events were added later.
517 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
518 Event::handle('StartHandleFeedEntry', array($activity))) {
520 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
522 Event::handle('EndHandleFeedEntry', array($activity));
523 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
530 * Process an incoming post activity from this remote feed.
531 * @param Activity $activity
532 * @param string $method 'push' or 'salmon'
533 * @return mixed saved Notice or false
535 public function processPost($activity, $method)
537 $actor = ActivityUtils::checkAuthorship($activity, $this->localProfile());
539 $options = array('is_local' => Notice::REMOTE);
542 $stored = Notice::saveActivity($activity, $actor, $options);
543 } catch (Exception $e) {
544 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
551 * Filters a list of recipient ID URIs to just those for local delivery.
552 * @param Profile local profile of sender
553 * @param array in/out &$attention_uris set of URIs, will be pruned on output
554 * @return array of group IDs
556 static public function filterAttention(Profile $sender, array $attention)
558 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
561 foreach ($attention as $recipient=>$type) {
562 // Is the recipient a local user?
563 $user = User::getKV('uri', $recipient);
564 if ($user instanceof User) {
565 // @todo FIXME: Sender verification, spam etc?
566 $replies[] = $recipient;
570 // Is the recipient a local group?
571 // TODO: $group = User_group::getKV('uri', $recipient);
572 $id = OStatusPlugin::localGroupFromUrl($recipient);
574 $group = User_group::getKV('id', $id);
575 if ($group instanceof User_group) {
576 // Deliver to all members of this local group if allowed.
577 if ($sender->isMember($group)) {
578 $groups[] = $group->id;
580 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
584 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
588 // Is the recipient a remote user or group?
590 $oprofile = self::ensureProfileURI($recipient);
591 if ($oprofile->isGroup()) {
592 // Deliver to local members of this remote group.
593 // @todo FIXME: Sender verification?
594 $groups[] = $oprofile->group_id;
596 // may be canonicalized or something
597 $replies[] = $oprofile->getUri();
600 } catch (Exception $e) {
601 // Neither a recognizable local nor remote user!
602 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
606 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
607 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
608 return array($groups, $replies);
612 * Look up and if necessary create an Ostatus_profile for the remote entity
613 * with the given profile page URL. This should never return null -- you
614 * will either get an object or an exception will be thrown.
616 * @param string $profile_url
617 * @return Ostatus_profile
618 * @throws Exception on various error conditions
619 * @throws OStatusShadowException if this reference would obscure a local user/group
621 public static function ensureProfileURL($profile_url, array $hints=array())
623 $oprofile = self::getFromProfileURL($profile_url);
625 if ($oprofile instanceof Ostatus_profile) {
629 $hints['profileurl'] = $profile_url;
634 $client = new HTTPClient();
635 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
636 $response = $client->get($profile_url);
638 if (!$response->isOk()) {
639 // TRANS: Exception. %s is a profile URL.
640 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
643 // Check if we have a non-canonical URL
645 $finalUrl = $response->getEffectiveUrl();
647 if ($finalUrl != $profile_url) {
649 $hints['profileurl'] = $finalUrl;
651 $oprofile = self::getFromProfileURL($finalUrl);
653 if ($oprofile instanceof Ostatus_profile) {
659 preg_replace('/\s*;.*$/', '', $response->getHeader('Content-Type')),
660 array('application/rss+xml', 'application/atom+xml', 'application/xml', 'text/xml'))
662 $hints['feedurl'] = $response->getEffectiveUrl();
664 // Try to get some hCard data
666 $body = $response->getBody();
668 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
670 if (!empty($hcardHints)) {
671 $hints = array_merge($hints, $hcardHints);
675 // Check if they've got an LRDD header
677 $lrdd = LinkHeader::getLink($response, 'lrdd');
679 $xrd = new XML_XRD();
680 $xrd->loadFile($lrdd);
681 $xrdHints = DiscoveryHints::fromXRD($xrd);
682 $hints = array_merge($hints, $xrdHints);
683 } catch (Exception $e) {
684 // No hints available from XRD
687 // If discovery found a feedurl (probably from LRDD), use it.
689 if (array_key_exists('feedurl', $hints)) {
690 return self::ensureFeedURL($hints['feedurl'], $hints);
693 // Get the feed URL from HTML
695 $discover = new FeedDiscovery();
697 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
699 if (!empty($feedurl)) {
700 $hints['feedurl'] = $feedurl;
701 return self::ensureFeedURL($feedurl, $hints);
704 // TRANS: Exception. %s is a URL.
705 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
709 * Look up the Ostatus_profile, if present, for a remote entity with the
710 * given profile page URL. Will return null for both unknown and invalid
713 * @return mixed Ostatus_profile or null
714 * @throws OStatusShadowException for local profiles
716 static function getFromProfileURL($profile_url)
718 $profile = Profile::getKV('profileurl', $profile_url);
719 if (!$profile instanceof Profile) {
724 $oprofile = self::getFromProfile($profile);
725 // We found the profile, return it!
727 } catch (NoResultException $e) {
728 // Could not find an OStatus profile, is it instead a local user?
729 $user = User::getKV('id', $profile->id);
730 if ($user instanceof User) {
731 // @todo i18n FIXME: use sprintf and add i18n (?)
732 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
736 // Continue discovery; it's a remote profile
737 // for OMB or some other protocol, may also
743 static function getFromProfile(Profile $profile)
745 $oprofile = new Ostatus_profile();
746 $oprofile->profile_id = $profile->id;
747 if (!$oprofile->find(true)) {
748 throw new NoResultException($oprofile);
754 * Look up and if necessary create an Ostatus_profile for remote entity
755 * with the given update feed. This should never return null -- you will
756 * either get an object or an exception will be thrown.
758 * @return Ostatus_profile
761 public static function ensureFeedURL($feed_url, array $hints=array())
763 $oprofile = Ostatus_profile::getKV('feeduri', $feed_url);
764 if ($oprofile instanceof Ostatus_profile) {
768 $discover = new FeedDiscovery();
770 $feeduri = $discover->discoverFromFeedURL($feed_url);
771 $hints['feedurl'] = $feeduri;
773 $huburi = $discover->getHubLink();
774 $hints['hub'] = $huburi;
776 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
777 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
778 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
779 $hints['salmon'] = $salmonuri;
781 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
782 // We can only deal with folks with a PuSH hub
783 // unless we have something similar available locally.
784 throw new FeedSubNoHubException();
787 $feedEl = $discover->root;
789 if ($feedEl->tagName == 'feed') {
790 return self::ensureAtomFeed($feedEl, $hints);
791 } else if ($feedEl->tagName == 'channel') {
792 return self::ensureRssChannel($feedEl, $hints);
794 throw new FeedSubBadXmlException($feeduri);
799 * Look up and, if necessary, create an Ostatus_profile for the remote
800 * profile with the given Atom feed - actually loaded from the feed.
801 * This should never return null -- you will either get an object or
802 * an exception will be thrown.
804 * @param DOMElement $feedEl root element of a loaded Atom feed
805 * @param array $hints additional discovery information passed from higher levels
806 * @todo FIXME: Should this be marked public?
807 * @return Ostatus_profile
810 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
812 $author = ActivityUtils::getFeedAuthor($feedEl);
814 if (empty($author)) {
815 // XXX: make some educated guesses here
816 // TRANS: Feed sub exception.
817 throw new FeedSubException(_m('Cannot find enough profile '.
818 'information to make a feed.'));
821 return self::ensureActivityObjectProfile($author, $hints);
825 * Look up and, if necessary, create an Ostatus_profile for the remote
826 * profile with the given RSS feed - actually loaded from the feed.
827 * This should never return null -- you will either get an object or
828 * an exception will be thrown.
830 * @param DOMElement $feedEl root element of a loaded RSS feed
831 * @param array $hints additional discovery information passed from higher levels
832 * @todo FIXME: Should this be marked public?
833 * @return Ostatus_profile
836 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
838 // Special-case for Posterous. They have some nice metadata in their
839 // posterous:author elements. We should use them instead of the channel.
841 $items = $feedEl->getElementsByTagName('item');
843 if ($items->length > 0) {
844 $item = $items->item(0);
845 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
846 if (!empty($authorEl)) {
847 $obj = ActivityObject::fromPosterousAuthor($authorEl);
848 // Posterous has multiple authors per feed, and multiple feeds
849 // per author. We check if this is the "main" feed for this author.
850 if (array_key_exists('profileurl', $hints) &&
851 !empty($obj->poco) &&
852 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
853 return self::ensureActivityObjectProfile($obj, $hints);
858 $obj = ActivityUtils::getFeedAuthor($feedEl);
860 // @todo FIXME: We should check whether this feed has elements
861 // with different <author> or <dc:creator> elements, and... I dunno.
862 // Do something about that.
864 if(empty($obj)) { $obj = ActivityObject::fromRssChannel($feedEl); }
866 return self::ensureActivityObjectProfile($obj, $hints);
870 * Download and update given avatar image
873 * @return Avatar The Avatar we have on disk. (seldom used)
874 * @throws Exception in various failure cases
876 public function updateAvatar($url, $force=false)
879 // If avatar URL differs: update. If URLs were identical but we're forced: update.
880 if ($url == $this->avatar && !$force) {
881 // If there's no locally stored avatar, throw an exception and continue fetching below.
882 $avatar = Avatar::getUploaded($this->localProfile()) instanceof Avatar;
885 } catch (NoAvatarException $e) {
886 // No avatar available, let's fetch it.
889 if (!common_valid_http_url($url)) {
890 // TRANS: Server exception. %s is a URL.
891 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
894 $self = $this->localProfile();
896 // @todo FIXME: This should be better encapsulated
897 // ripped from oauthstore.php (for old OMB client)
898 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
900 $imgData = HTTPClient::quickGet($url);
901 // Make sure it's at least an image file. ImageFile can do the rest.
902 if (false === getimagesizefromstring($imgData)) {
903 throw new UnsupportedMediaException(_('Downloaded group avatar was not an image.'));
905 file_put_contents($temp_filename, $imgData);
906 unset($imgData); // No need to carry this in memory.
908 if ($this->isGroup()) {
909 $id = $this->group_id;
911 $id = $this->profile_id;
913 $imagefile = new ImageFile(null, $temp_filename);
914 $filename = Avatar::filename($id,
915 image_type_to_extension($imagefile->type),
918 rename($temp_filename, Avatar::path($filename));
919 } catch (Exception $e) {
920 unlink($temp_filename);
923 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
924 // keep from accidentally saving images from command-line (queues)
925 // that can't be read from web server, which causes hard-to-notice
926 // problems later on:
928 // http://status.net/open-source/issues/2663
929 chmod(Avatar::path($filename), 0644);
931 $self->setOriginal($filename);
933 $orig = clone($this);
934 $this->avatar = $url;
935 $this->update($orig);
937 return Avatar::getUploaded($self);
941 * Pull avatar URL from ActivityObject or profile hints
943 * @param ActivityObject $object
944 * @param array $hints
945 * @return mixed URL string or false
947 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
949 if ($object->avatarLinks) {
951 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
952 foreach ($object->avatarLinks as $avatar) {
953 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
958 if (!$best || $avatar->width > $best->width) {
963 } else if (array_key_exists('avatar', $hints)) {
964 return $hints['avatar'];
970 * Get an appropriate avatar image source URL, if available.
972 * @param ActivityObject $actor
973 * @param DOMElement $feed
976 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
980 if ($actor->avatar) {
981 $url = trim($actor->avatar);
984 // Check <atom:logo> and <atom:icon> on the feed
985 $els = $feed->childNodes();
986 if ($els && $els->length) {
987 for ($i = 0; $i < $els->length; $i++) {
988 $el = $els->item($i);
989 if ($el->namespaceURI == Activity::ATOM) {
990 if (empty($url) && $el->localName == 'logo') {
991 $url = trim($el->textContent);
994 if (empty($icon) && $el->localName == 'icon') {
996 $icon = trim($el->textContent);
1001 if ($icon && !$url) {
1006 $opts = array('allowed_schemes' => array('http', 'https'));
1007 if (common_valid_http_url($url)) {
1012 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1016 * Fetch, or build if necessary, an Ostatus_profile for the actor
1017 * in a given Activity Streams activity.
1018 * This should never return null -- you will either get an object or
1019 * an exception will be thrown.
1021 * @param Activity $activity
1022 * @param string $feeduri if we already know the canonical feed URI!
1023 * @param string $salmonuri if we already know the salmon return channel URI
1024 * @return Ostatus_profile
1027 public static function ensureActorProfile(Activity $activity, array $hints=array())
1029 return self::ensureActivityObjectProfile($activity->actor, $hints);
1033 * Fetch, or build if necessary, an Ostatus_profile for the profile
1034 * in a given Activity Streams object (can be subject, actor, or object).
1035 * This should never return null -- you will either get an object or
1036 * an exception will be thrown.
1038 * @param ActivityObject $object
1039 * @param array $hints additional discovery information passed from higher levels
1040 * @return Ostatus_profile
1043 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1045 $profile = self::getActivityObjectProfile($object);
1046 if ($profile instanceof Ostatus_profile) {
1047 $profile->updateFromActivityObject($object, $hints);
1049 $profile = self::createActivityObjectProfile($object, $hints);
1055 * @param Activity $activity
1056 * @return mixed matching Ostatus_profile or false if none known
1057 * @throws ServerException if feed info invalid
1059 public static function getActorProfile(Activity $activity)
1061 return self::getActivityObjectProfile($activity->actor);
1065 * @param ActivityObject $activity
1066 * @return mixed matching Ostatus_profile or false if none known
1067 * @throws ServerException if feed info invalid
1069 protected static function getActivityObjectProfile(ActivityObject $object)
1071 $uri = self::getActivityObjectProfileURI($object);
1072 return Ostatus_profile::getKV('uri', $uri);
1076 * Get the identifier URI for the remote entity described
1077 * by this ActivityObject. This URI is *not* guaranteed to be
1078 * a resolvable HTTP/HTTPS URL.
1080 * @param ActivityObject $object
1082 * @throws ServerException if feed info invalid
1084 protected static function getActivityObjectProfileURI(ActivityObject $object)
1087 if (ActivityUtils::validateUri($object->id)) {
1092 // If the id is missing or invalid (we've seen feeds mistakenly listing
1093 // things like local usernames in that field) then we'll use the profile
1094 // page link, if valid.
1095 if ($object->link && common_valid_http_url($object->link)) {
1096 return $object->link;
1098 // TRANS: Server exception.
1099 throw new ServerException(_m('No author ID URI found.'));
1103 * @todo FIXME: Validate stuff somewhere.
1107 * Create local ostatus_profile and profile/user_group entries for
1108 * the provided remote user or group.
1109 * This should never return null -- you will either get an object or
1110 * an exception will be thrown.
1112 * @param ActivityObject $object
1113 * @param array $hints
1115 * @return Ostatus_profile
1117 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1119 common_debug('Attempting to create an Ostatus_profile from an ActivityObject with ID: '._ve($object->id));
1121 $homeuri = $object->id;
1125 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1126 // TRANS: Exception.
1127 throw new Exception(_m('No profile URI.'));
1130 $user = User::getKV('uri', $homeuri);
1131 if ($user instanceof User) {
1132 // TRANS: Exception.
1133 throw new Exception(_m('Local user cannot be referenced as remote.'));
1136 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1137 // TRANS: Exception.
1138 throw new Exception(_m('Local group cannot be referenced as remote.'));
1141 $ptag = Profile_list::getKV('uri', $homeuri);
1142 if ($ptag instanceof Profile_list) {
1143 $local_user = User::getKV('id', $ptag->tagger);
1144 if ($local_user instanceof User) {
1145 // TRANS: Exception.
1146 throw new Exception(_m('Local list cannot be referenced as remote.'));
1150 if (!array_key_exists('feedurl', $hints)) {
1151 $discover = new FeedDiscovery();
1152 $hints['feedurl'] = $discover->discoverFromURL($homeuri);
1153 common_debug(__METHOD__.' did not have a "feedurl" hint, FeedDiscovery found '._ve($hints['feedurl']));
1155 $feeduri = $hints['feedurl'];
1157 if (array_key_exists('salmon', $hints)) {
1158 $salmonuri = $hints['salmon'];
1161 $discover = new FeedDiscovery();
1162 $discover->discoverFromFeedURL($hints['feedurl']);
1164 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1165 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1166 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1169 if (array_key_exists('hub', $hints)) {
1170 $huburi = $hints['hub'];
1173 $discover = new FeedDiscovery();
1174 $discover->discoverFromFeedURL($hints['feedurl']);
1176 $huburi = $discover->getHubLink();
1179 if (!$huburi && !common_config('feedsub', 'fallback_hub') && !common_config('feedsub', 'nohub')) {
1180 // We can only deal with folks with a PuSH hub
1181 throw new FeedSubNoHubException();
1184 $oprofile = new Ostatus_profile();
1186 $oprofile->uri = $homeuri;
1187 $oprofile->feeduri = $feeduri;
1188 $oprofile->salmonuri = $salmonuri;
1190 $oprofile->created = common_sql_now();
1191 $oprofile->modified = common_sql_now();
1193 if ($object->type == ActivityObject::PERSON) {
1194 $profile = new Profile();
1195 $profile->created = common_sql_now();
1196 self::updateProfile($profile, $object, $hints);
1198 $oprofile->profile_id = $profile->insert();
1199 if ($oprofile->profile_id === false) {
1200 // TRANS: Server exception.
1201 throw new ServerException(_m('Cannot save local profile.'));
1203 } else if ($object->type == ActivityObject::GROUP) {
1204 $profile = new Profile();
1205 $profile->query('BEGIN');
1207 $group = new User_group();
1208 $group->uri = $homeuri;
1209 $group->created = common_sql_now();
1210 self::updateGroup($group, $object, $hints);
1212 // TODO: We should do this directly in User_group->insert()!
1213 // currently it's duplicated in User_group->update()
1214 // AND User_group->register()!!!
1215 $fields = array(/*group field => profile field*/
1216 'nickname' => 'nickname',
1217 'fullname' => 'fullname',
1218 'mainpage' => 'profileurl',
1219 'homepage' => 'homepage',
1220 'description' => 'bio',
1221 'location' => 'location',
1222 'created' => 'created',
1223 'modified' => 'modified',
1225 foreach ($fields as $gf=>$pf) {
1226 $profile->$pf = $group->$gf;
1228 $profile_id = $profile->insert();
1229 if ($profile_id === false) {
1230 $profile->query('ROLLBACK');
1231 throw new ServerException(_('Profile insertion failed.'));
1234 $group->profile_id = $profile_id;
1236 $oprofile->group_id = $group->insert();
1237 if ($oprofile->group_id === false) {
1238 $profile->query('ROLLBACK');
1239 // TRANS: Server exception.
1240 throw new ServerException(_m('Cannot save local profile.'));
1243 $profile->query('COMMIT');
1244 } else if ($object->type == ActivityObject::_LIST) {
1245 $ptag = new Profile_list();
1246 $ptag->uri = $homeuri;
1247 $ptag->created = common_sql_now();
1248 self::updatePeopletag($ptag, $object, $hints);
1250 $oprofile->peopletag_id = $ptag->insert();
1251 if ($oprofile->peopletag_id === false) {
1252 // TRANS: Server exception.
1253 throw new ServerException(_m('Cannot save local list.'));
1257 $ok = $oprofile->insert();
1259 if ($ok === false) {
1260 // TRANS: Server exception.
1261 throw new ServerException(_m('Cannot save OStatus profile.'));
1264 $avatar = self::getActivityObjectAvatar($object, $hints);
1268 $oprofile->updateAvatar($avatar);
1269 } catch (Exception $ex) {
1270 // Profile is saved, but Avatar is messed up. We're
1271 // just going to continue.
1272 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1280 * Save any updated profile information to our local copy.
1281 * @param ActivityObject $object
1282 * @param array $hints
1284 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1286 if (self::getActivityObjectProfileURI($object) !== $this->getUri()) {
1287 common_log(LOG_ERR, 'Trying to update profile with URI '._ve($this->getUri()).' from ActivityObject with URI: '._ve(self::getActivityObjectProfileURI($object)));
1288 // FIXME: Maybe not AuthorizationException?
1289 throw new AuthorizationException('Trying to update profile from ActivityObject with different URI.');
1292 common_debug('Updating Ostatus_profile with URI '._ve($this->getUri()).' from ActivityObject');
1294 if ($this->isGroup()) {
1295 $group = $this->localGroup();
1296 self::updateGroup($group, $object, $hints);
1297 } else if ($this->isPeopletag()) {
1298 $ptag = $this->localPeopletag();
1299 self::updatePeopletag($ptag, $object, $hints);
1301 $profile = $this->localProfile();
1302 self::updateProfile($profile, $object, $hints);
1305 $avatar = self::getActivityObjectAvatar($object, $hints);
1306 if ($avatar && !isset($ptag)) {
1308 $this->updateAvatar($avatar);
1309 } catch (Exception $e) {
1310 common_log(LOG_WARNING, 'Exception ('.get_class($e).') updating OStatus profile avatar: ' . $e->getMessage());
1315 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1317 $orig = clone($profile);
1319 // Existing nickname is better than nothing.
1321 if (!array_key_exists('nickname', $hints)) {
1322 $hints['nickname'] = $profile->nickname;
1325 $nickname = self::getActivityObjectNickname($object, $hints);
1327 if (!empty($nickname)) {
1328 $profile->nickname = $nickname;
1331 if (!empty($object->title)) {
1332 $profile->fullname = $object->title;
1333 } else if (array_key_exists('fullname', $hints)) {
1334 $profile->fullname = $hints['fullname'];
1337 if (!empty($object->link)) {
1338 $profile->profileurl = $object->link;
1339 } else if (array_key_exists('profileurl', $hints)) {
1340 $profile->profileurl = $hints['profileurl'];
1341 } else if (common_valid_http_url($object->id)) {
1342 $profile->profileurl = $object->id;
1345 $bio = self::getActivityObjectBio($object, $hints);
1348 $profile->bio = $bio;
1351 $location = self::getActivityObjectLocation($object, $hints);
1353 if (!empty($location)) {
1354 $profile->location = $location;
1357 $homepage = self::getActivityObjectHomepage($object, $hints);
1359 if (!empty($homepage)) {
1360 $profile->homepage = $homepage;
1363 if (!empty($object->geopoint)) {
1364 $location = ActivityContext::locationFromPoint($object->geopoint);
1365 if (!empty($location)) {
1366 $profile->lat = $location->lat;
1367 $profile->lon = $location->lon;
1371 // @todo FIXME: tags/categories
1372 // @todo tags from categories
1375 //common_debug('Updating OStatus profile '._ve($profile->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1376 common_debug('Updating OStatus profile '._ve($profile->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1377 $profile->update($orig);
1381 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1383 $orig = clone($group);
1385 $group->nickname = self::getActivityObjectNickname($object, $hints);
1386 $group->fullname = $object->title;
1388 if (!empty($object->link)) {
1389 $group->mainpage = $object->link;
1390 } else if (array_key_exists('profileurl', $hints)) {
1391 $group->mainpage = $hints['profileurl'];
1394 // @todo tags from categories
1395 $group->description = self::getActivityObjectBio($object, $hints);
1396 $group->location = self::getActivityObjectLocation($object, $hints);
1397 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1399 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1400 //common_debug('Updating OStatus group '._ve($group->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1401 common_debug('Updating OStatus group '._ve($group->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1402 $group->update($orig);
1406 protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array()) {
1407 $orig = clone($tag);
1409 $tag->tag = $object->title;
1411 if (!empty($object->link)) {
1412 $tag->mainpage = $object->link;
1413 } else if (array_key_exists('profileurl', $hints)) {
1414 $tag->mainpage = $hints['profileurl'];
1417 $tag->description = $object->summary;
1418 $tagger = self::ensureActivityObjectProfile($object->owner);
1419 $tag->tagger = $tagger->profile_id;
1422 //common_debug('Updating OStatus peopletag '._ve($tag->getID().' from remote info '._ve($object->id).': ' . _ve($object) . _ve($hints));
1423 common_debug('Updating OStatus peopletag '._ve($tag->getID()).' from remote info '._ve($object->id).' gathered from hints: '._ve($hints));
1424 $tag->update($orig);
1428 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1431 $poco = $object->poco;
1433 if (!empty($poco)) {
1434 $url = $poco->getPrimaryURL();
1435 if ($url && $url->type == 'homepage') {
1436 $homepage = $url->value;
1440 // @todo Try for a another PoCo URL?
1445 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1449 if (!empty($object->poco) &&
1450 isset($object->poco->address->formatted)) {
1451 $location = $object->poco->address->formatted;
1452 } else if (array_key_exists('location', $hints)) {
1453 $location = $hints['location'];
1456 if (!empty($location)) {
1457 if (mb_strlen($location) > 191) { // not 255 because utf8mb4 takes more space
1458 $location = mb_substr($note, 0, 191 - 3) . ' … ';
1462 // @todo Try to find location some othe way? Via goerss point?
1467 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1471 if (!empty($object->poco)) {
1472 $note = $object->poco->note;
1473 } else if (array_key_exists('bio', $hints)) {
1474 $note = $hints['bio'];
1477 if (!empty($note)) {
1478 if (Profile::bioTooLong($note)) {
1479 // XXX: truncate ok?
1480 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1486 // @todo Try to get bio info some other way?
1491 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1493 if ($object->poco) {
1494 if (!empty($object->poco->preferredUsername)) {
1495 return common_nicknamize($object->poco->preferredUsername);
1499 if (!empty($object->nickname)) {
1500 return common_nicknamize($object->nickname);
1503 if (array_key_exists('nickname', $hints)) {
1504 return $hints['nickname'];
1507 // Try the profile url (like foo.example.com or example.com/user/foo)
1508 if (!empty($object->link)) {
1509 $profileUrl = $object->link;
1510 } else if (!empty($hints['profileurl'])) {
1511 $profileUrl = $hints['profileurl'];
1514 if (!empty($profileUrl)) {
1515 $nickname = self::nicknameFromURI($profileUrl);
1518 // Try the URI (may be a tag:, http:, acct:, ...
1520 if (empty($nickname)) {
1521 $nickname = self::nicknameFromURI($object->id);
1524 // Try a Webfinger if one was passed (way) down
1526 if (empty($nickname)) {
1527 if (array_key_exists('webfinger', $hints)) {
1528 $nickname = self::nicknameFromURI($hints['webfinger']);
1534 if (empty($nickname)) {
1535 $nickname = common_nicknamize($object->title);
1541 protected static function nicknameFromURI($uri)
1543 if (preg_match('/(\w+):/', $uri, $matches)) {
1544 $protocol = $matches[1];
1549 switch ($protocol) {
1552 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1553 return common_canonical_nickname($matches[1]);
1557 return common_url_to_nickname($uri);
1565 * Look up, and if necessary create, an Ostatus_profile for the remote
1566 * entity with the given webfinger address.
1567 * This should never return null -- you will either get an object or
1568 * an exception will be thrown.
1570 * @param string $addr webfinger address
1571 * @return Ostatus_profile
1572 * @throws Exception on error conditions
1573 * @throws OStatusShadowException if this reference would obscure a local user/group
1575 public static function ensureWebfinger($addr)
1577 // Normalize $addr, i.e. add 'acct:' if missing
1578 $addr = Discovery::normalize($addr);
1581 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1583 if ($uri !== false) {
1584 if (is_null($uri)) {
1585 // Negative cache entry
1586 // TRANS: Exception.
1587 throw new Exception(_m('Not a valid webfinger address.'));
1589 $oprofile = Ostatus_profile::getKV('uri', $uri);
1590 if ($oprofile instanceof Ostatus_profile) {
1595 // Try looking it up
1596 $oprofile = Ostatus_profile::getKV('uri', $addr);
1598 if ($oprofile instanceof Ostatus_profile) {
1599 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1603 // Now, try some discovery
1605 $disco = new Discovery();
1608 $xrd = $disco->lookup($addr);
1609 } catch (Exception $e) {
1610 // Save negative cache entry so we don't waste time looking it up again.
1611 // @todo FIXME: Distinguish temporary failures?
1612 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1613 // TRANS: Exception.
1614 throw new Exception(_m('Not a valid webfinger address.'));
1617 $hints = array_merge(array('webfinger' => $addr),
1618 DiscoveryHints::fromXRD($xrd));
1620 // If there's an Hcard, let's grab its info
1621 if (array_key_exists('hcard', $hints)) {
1622 if (!array_key_exists('profileurl', $hints) ||
1623 $hints['hcard'] != $hints['profileurl']) {
1624 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1625 $hints = array_merge($hcardHints, $hints);
1629 // If we got a feed URL, try that
1631 if (array_key_exists('feedurl', $hints)) {
1632 $feedUrl = $hints['feedurl'];
1634 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1635 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1636 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1638 } catch (Exception $e) {
1639 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1644 // If we got a profile page, try that!
1646 if (array_key_exists('profileurl', $hints)) {
1647 $profileUrl = $hints['profileurl'];
1649 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1650 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1651 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1653 } catch (OStatusShadowException $e) {
1654 // We've ended up with a remote reference to a local user or group.
1655 // @todo FIXME: Ideally we should be able to say who it was so we can
1656 // go back and refer to it the regular way
1658 } catch (Exception $e) {
1659 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1662 // @todo FIXME: This means an error discovering from profile page
1663 // may give us a corrupt entry using the webfinger URI, which
1664 // will obscure the correct page-keyed profile later on.
1671 if (array_key_exists('salmon', $hints)) {
1672 $salmonEndpoint = $hints['salmon'];
1674 // An account URL, a salmon endpoint, and a dream? Not much to go
1675 // on, but let's give it a try
1677 $uri = 'acct:'.$addr;
1679 $profile = new Profile();
1681 $profile->nickname = self::nicknameFromUri($uri);
1682 $profile->created = common_sql_now();
1684 if (!is_null($profileUrl)) {
1685 $profile->profileurl = $profileUrl;
1688 $profile_id = $profile->insert();
1690 if ($profile_id === false) {
1691 common_log_db_error($profile, 'INSERT', __FILE__);
1692 // TRANS: Exception. %s is a webfinger address.
1693 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1696 $oprofile = new Ostatus_profile();
1698 $oprofile->uri = $uri;
1699 $oprofile->salmonuri = $salmonEndpoint;
1700 $oprofile->profile_id = $profile_id;
1701 $oprofile->created = common_sql_now();
1703 if (!is_null($feedUrl)) {
1704 $oprofile->feeduri = $feedUrl;
1707 $result = $oprofile->insert();
1709 if ($result === false) {
1711 common_log_db_error($oprofile, 'INSERT', __FILE__);
1712 // TRANS: Exception. %s is a webfinger address.
1713 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1716 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1720 // TRANS: Exception. %s is a webfinger address.
1721 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1725 * Store the full-length scrubbed HTML of a remote notice to an attachment
1726 * file on our server. We'll link to this at the end of the cropped version.
1728 * @param string $title plaintext for HTML page's title
1729 * @param string $rendered HTML fragment for HTML page's body
1732 function saveHTMLFile($title, $rendered)
1734 $final = sprintf("<!DOCTYPE html>\n" .
1736 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1737 '<title>%s</title>' .
1739 '<body>%s</body></html>',
1740 htmlspecialchars($title),
1743 $filename = File::filename($this->localProfile(),
1744 'ostatus', // ignored?
1747 $filepath = File::path($filename);
1748 $fileurl = File::url($filename);
1750 file_put_contents($filepath, $final);
1754 $file->filename = $filename;
1755 $file->urlhash = File::hashurl($fileurl);
1756 $file->url = $fileurl;
1757 $file->size = filesize($filepath);
1758 $file->date = time();
1759 $file->mimetype = 'text/html';
1761 $file_id = $file->insert();
1763 if ($file_id === false) {
1764 common_log_db_error($file, "INSERT", __FILE__);
1765 // TRANS: Server exception.
1766 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1772 static function ensureProfileURI($uri)
1776 // First, try to query it
1778 $oprofile = Ostatus_profile::getKV('uri', $uri);
1780 if ($oprofile instanceof Ostatus_profile) {
1784 // If unfound, do discovery stuff
1785 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1786 $protocol = $match[1];
1787 switch ($protocol) {
1790 $oprofile = self::ensureProfileURL($uri);
1795 $oprofile = self::ensureWebfinger($rest);
1798 // TRANS: Server exception.
1799 // TRANS: %1$s is a protocol, %2$s is a URI.
1800 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1805 // TRANS: Server exception. %s is a URI.
1806 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1812 public function checkAuthorship(Activity $activity)
1814 if ($this->isGroup() || $this->isPeopletag()) {
1815 // A group or propletag feed will contain posts from multiple authors.
1816 $oprofile = self::ensureActorProfile($activity);
1817 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1818 // Groups can't post notices in StatusNet.
1819 common_log(LOG_WARNING,
1820 "OStatus: skipping post with group listed ".
1821 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
1822 throw new ServerException('Activity author is a non-actor');
1825 $actor = $activity->actor;
1827 if (empty($actor)) {
1828 // OK here! assume the default
1829 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
1830 $this->updateFromActivityObject($actor);
1831 } else if ($actor->id) {
1832 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1833 // This isn't what we expect from mainline OStatus person feeds!
1834 // Group feeds go down another path, with different validation...
1835 // Most likely this is a plain ol' blog feed of some kind which
1836 // doesn't match our expectations. We'll take the entry, but ignore
1837 // the <author> info.
1838 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
1840 // Plain <author> without ActivityStreams actor info.
1841 // We'll just ignore this info for now and save the update under the feed's identity.
1847 return $oprofile->localProfile();
1850 public function updateUriKeys($profile_uri, array $hints=array())
1852 $orig = clone($this);
1854 common_debug('URIFIX These identities both say they are each other: '._ve($orig->uri).' and '._ve($profile_uri));
1855 $this->uri = $profile_uri;
1857 if (array_key_exists('feedurl', $hints) && common_valid_http_url($hints['feedurl'])) {
1859 $feedsub = FeedSub::getByUri($this->feeduri);
1860 common_debug('URIFIX Changing FeedSub id==['._ve($feedsub->id).'] feeduri '._ve($feedsub->uri).' to '._ve($hints['feedurl']));
1861 $feedorig = clone($feedsub);
1862 $feedsub->uri = $hints['feedurl'];
1863 $feedsub->updateWithKeys($feedorig);
1864 } catch (EmptyPkeyValueException $e) {
1865 common_debug('URIFIX Old Ostatus_profile did not have feedurl set, ensuring new feedurl: '._ve($hints['feedurl']));
1866 FeedSub::ensureFeed($hints['feedurl']);
1867 } catch (NoResultException $e) {
1868 common_debug('URIFIX Missing FeedSub entry for the Ostatus_profile, ensuring new feedurl: '._ve($hints['feedurl']));
1869 FeedSub::ensureFeed($hints['feedurl']);
1871 $this->feeduri = $hints['feedurl'];
1872 } elseif (array_key_exists('feedurl')) {
1873 common_log(LOG_WARN, 'The feedurl hint we got was not a valid HTTP URL: '._ve($hints['feedurl']));
1876 if (array_key_exists('salmon', $hints)) {
1877 common_debug('URIFIX Changing Ostatus_profile salmonuri from "'.$this->salmonuri.'" to "'.$hints['salmon'].'"');
1878 $this->salmonuri = $hints['salmon'];
1881 common_debug('URIFIX Updating Ostatus_profile URI for '.$orig->uri.' to '.$this->uri);
1882 $this->updateWithKeys($orig); // Will use the PID column(s) in the 'UPDATE ... WHERE [unique selector]'
1884 common_debug('URIFIX Subscribing/renewing feedsub for Ostatus_profile '.$this->uri);