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('STATUSNET')) {
25 * @package OStatusPlugin
26 * @maintainer Brion Vibber <brion@status.net>
28 class Ostatus_profile extends Managed_DataObject
30 public $__table = 'ostatus_profile';
40 public $avatar; // remote URL of the last avatar we saved
46 * Return table definition for Schema setup and DB_DataObject usage.
48 * @return array array of column definitions
50 static function schemaDef()
54 'uri' => array('type' => 'varchar', 'length' => 255, 'not null' => true),
55 'profile_id' => array('type' => 'integer'),
56 'group_id' => array('type' => 'integer'),
57 'peopletag_id' => array('type' => 'integer'),
58 'feeduri' => array('type' => 'varchar', 'length' => 255),
59 'salmonuri' => array('type' => 'varchar', 'length' => 255),
60 'avatar' => array('type' => 'text'),
61 'created' => array('type' => 'datetime', 'not null' => true),
62 'modified' => array('type' => 'datetime', 'not null' => true),
64 'primary key' => array('uri'),
65 'unique keys' => array(
66 'ostatus_profile_profile_id_key' => array('profile_id'),
67 'ostatus_profile_group_id_key' => array('group_id'),
68 'ostatus_profile_peopletag_id_key' => array('peopletag_id'),
69 'ostatus_profile_feeduri_key' => array('feeduri'),
71 'foreign keys' => array(
72 'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
73 'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
74 'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
79 public function getUri()
84 public function fromProfile(Profile $profile)
86 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
87 if (!$oprofile instanceof Ostatus_profile) {
88 throw new Exception('No Ostatus_profile for Profile ID: '.$profile->id);
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 if ($this->group_id) {
117 return User_group::getKV('id', $this->group_id);
123 * Fetch the StatusNet-side peopletag for this feed
126 public function localPeopletag()
128 if ($this->peopletag_id) {
129 return Profile_list::getKV('id', $this->peopletag_id);
135 * Returns an ActivityObject describing this remote user or group profile.
136 * Can then be used to generate Atom chunks.
138 * @return ActivityObject
140 function asActivityObject()
142 if ($this->isGroup()) {
143 return ActivityObject::fromGroup($this->localGroup());
144 } else if ($this->isPeopletag()) {
145 return ActivityObject::fromPeopletag($this->localPeopletag());
147 return $this->localProfile()->asActivityObject();
152 * Returns an XML string fragment with profile information as an
153 * Activity Streams noun object with the given element type.
155 * Assumes that 'activity' namespace has been previously defined.
157 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
159 * @param string $element one of 'actor', 'subject', 'object', 'target'
162 function asActivityNoun($element)
164 if ($this->isGroup()) {
165 $noun = ActivityObject::fromGroup($this->localGroup());
166 return $noun->asString('activity:' . $element);
167 } else if ($this->isPeopletag()) {
168 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
169 return $noun->asString('activity:' . $element);
171 $noun = $this->localProfile()->asActivityObject();
172 return $noun->asString('activity:' . $element);
177 * @return boolean true if this is a remote group
181 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
183 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
185 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
186 // TRANS: Server exception. %s is a URI
187 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
189 // TRANS: Server exception. %s is a URI
190 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
195 * @return boolean true if this is a remote peopletag
197 function isPeopletag()
199 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
201 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
203 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
204 // TRANS: Server exception. %s is a URI
205 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
207 // TRANS: Server exception. %s is a URI
208 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
213 * Send a subscription request to the hub for this feed.
214 * The hub will later send us a confirmation POST to /main/push/callback.
217 * @throws ServerException if feed state is not valid or subscription fails.
219 public function subscribe()
221 $feedsub = FeedSub::ensureFeed($this->feeduri);
222 if ($feedsub->sub_state == 'active') {
223 // Active subscription, we don't need to do anything.
227 // Inactive or we got left in an inconsistent state.
228 // Run a subscription request to make sure we're current!
229 return $feedsub->subscribe();
233 * Check if this remote profile has any active local subscriptions, and
234 * if not drop the PuSH subscription feed.
236 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
237 * @throws Exception of various kinds on failure.
239 public function unsubscribe() {
240 return $this->garbageCollect();
244 * Check if this remote profile has any active local subscriptions, and
245 * if not drop the PuSH subscription feed.
247 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
248 * @throws Exception of various kinds on failure.
250 public function garbageCollect()
252 $feedsub = FeedSub::getKV('uri', $this->feeduri);
253 if ($feedsub instanceof FeedSub) {
254 return $feedsub->garbageCollect();
256 // Since there's no FeedSub we can assume it's already garbage collected
261 * Check if this remote profile has any active local subscriptions, so the
262 * PuSH subscription layer can decide if it can drop the feed.
264 * This gets called via the FeedSubSubscriberCount event when running
265 * FeedSub::garbageCollect().
268 * @throws NoProfileException if there is no local profile for the object
270 public function subscriberCount()
272 if ($this->isGroup()) {
273 $members = $this->localGroup()->getMembers(0, 1);
274 $count = $members->N;
275 } else if ($this->isPeopletag()) {
276 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
277 $count = $subscribers->N;
279 $profile = $this->localProfile();
280 if ($profile->hasLocalTags()) {
283 $count = $profile->subscriberCount();
286 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
288 // Other plugins may be piggybacking on OStatus without having
289 // an active group or user-to-user subscription we know about.
290 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
291 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
297 * Send an Activity Streams notification to the remote Salmon endpoint,
300 * @param Profile $actor Actor who did the activity
301 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
302 * @param Object $object object of the action; must define asActivityNoun($tag)
304 public function notify(Profile $actor, $verb, $object=null, $target=null)
306 if ($object == null) {
309 if (empty($this->salmonuri)) {
313 $id = TagURI::mint('%s:%s:%s',
316 common_date_iso8601(time()));
318 // @todo FIXME: Consolidate all these NS settings somewhere.
319 $attributes = array('xmlns' => Activity::ATOM,
320 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
321 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
322 'xmlns:georss' => 'http://www.georss.org/georss',
323 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
324 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
325 'xmlns:media' => 'http://purl.org/syndication/atommedia');
327 $entry = new XMLStringer();
328 $entry->elementStart('entry', $attributes);
329 $entry->element('id', null, $id);
330 $entry->element('title', null, $text);
331 $entry->element('summary', null, $text);
332 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
334 $entry->element('activity:verb', null, $verb);
335 $entry->raw($actor->asAtomAuthor());
336 $entry->raw($actor->asActivityActor());
337 $entry->raw($object->asActivityNoun('object'));
338 if ($target != null) {
339 $entry->raw($target->asActivityNoun('target'));
341 $entry->elementEnd('entry');
343 $xml = $entry->getString();
344 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
346 Salmon::post($this->salmonuri, $xml, $actor->getUser());
350 * Send a Salmon notification ping immediately, and confirm that we got
351 * an acceptable response from the remote site.
353 * @param mixed $entry XML string, Notice, or Activity
354 * @param Profile $actor
355 * @return boolean success
357 public function notifyActivity($entry, Profile $actor)
359 if ($this->salmonuri) {
360 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor->getUser());
362 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
368 * Queue a Salmon notification for later. If queues are disabled we'll
369 * send immediately but won't get the return value.
371 * @param mixed $entry XML string, Notice, or Activity
372 * @return boolean success
374 public function notifyDeferred($entry, $actor)
376 if ($this->salmonuri) {
377 $data = array('salmonuri' => $this->salmonuri,
378 'entry' => $this->notifyPrepXml($entry),
379 'actor' => $actor->id);
381 $qm = QueueManager::get();
382 return $qm->enqueue($data, 'salmon');
388 protected function notifyPrepXml($entry)
390 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
391 if (is_string($entry)) {
393 } else if ($entry instanceof Activity) {
394 return $preamble . $entry->asString(true);
395 } else if ($entry instanceof Notice) {
396 return $preamble . $entry->asAtomEntry(true, true);
398 // TRANS: Server exception.
399 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
403 function getBestName()
405 if ($this->isGroup()) {
406 return $this->localGroup()->getBestName();
407 } else if ($this->isPeopletag()) {
408 return $this->localPeopletag()->getBestName();
410 return $this->localProfile()->getBestName();
415 * Read and post notices for updates from the feed.
416 * Currently assumes that all items in the feed are new,
417 * coming from a PuSH hub.
419 * @param DOMDocument $doc
420 * @param string $source identifier ("push")
422 public function processFeed(DOMDocument $doc, $source)
424 $feed = $doc->documentElement;
426 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
427 $this->processAtomFeed($feed, $source);
428 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
429 $this->processRssFeed($feed, $source);
432 throw new Exception(_m('Unknown feed format.'));
436 public function processAtomFeed(DOMElement $feed, $source)
438 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
439 if ($entries->length == 0) {
440 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
444 for ($i = 0; $i < $entries->length; $i++) {
445 $entry = $entries->item($i);
446 $this->processEntry($entry, $feed, $source);
450 public function processRssFeed(DOMElement $rss, $source)
452 $channels = $rss->getElementsByTagName('channel');
454 if ($channels->length == 0) {
456 throw new Exception(_m('RSS feed without a channel.'));
457 } else if ($channels->length > 1) {
458 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
461 $channel = $channels->item(0);
463 $items = $channel->getElementsByTagName('item');
465 for ($i = 0; $i < $items->length; $i++) {
466 $item = $items->item($i);
467 $this->processEntry($item, $channel, $source);
472 * Process a posted entry from this feed source.
474 * @param DOMElement $entry
475 * @param DOMElement $feed for context
476 * @param string $source identifier ("push" or "salmon")
478 * @return Notice Notice representing the new (or existing) activity
480 public function processEntry($entry, $feed, $source)
482 $activity = new Activity($entry, $feed);
483 return $this->processActivity($activity, $source);
486 // TODO: Make this throw an exception
487 public function processActivity($activity, $source)
491 // The "WithProfile" events were added later.
493 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
494 Event::handle('StartHandleFeedEntry', array($activity))) {
496 switch ($activity->verb) {
497 case ActivityVerb::POST:
498 // @todo process all activity objects
499 switch ($activity->objects[0]->type) {
500 case ActivityObject::ARTICLE:
501 case ActivityObject::BLOGENTRY:
502 case ActivityObject::NOTE:
503 case ActivityObject::STATUS:
504 case ActivityObject::COMMENT:
506 $notice = $this->processPost($activity, $source);
509 // TRANS: Client exception.
510 throw new ClientException(_m('Cannot handle that kind of post.'));
513 case ActivityVerb::SHARE:
514 $notice = $this->processShare($activity, $source);
517 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
520 Event::handle('EndHandleFeedEntry', array($activity));
521 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
527 public function processShare($activity, $method)
532 $profile = ActivityUtils::checkAuthorship($activity, $this->localProfile());
533 } catch (ServerException $e) {
537 // The id URI will be used as a unique identifier for the notice,
538 // protecting against duplicate saves. It isn't required to be a URL;
539 // tag: URIs for instance are found in Google Buzz feeds.
540 $dupe = Notice::getKV('uri', $activity->id);
541 if ($dupe instanceof Notice) {
542 common_log(LOG_INFO, "OStatus: ignoring duplicate post: {$activity->id}");
546 if (count($activity->objects) != 1) {
547 // TRANS: Client exception thrown when trying to share multiple activities at once.
548 throw new ClientException(_m('Can only handle share activities with exactly one object.'));
551 $shared = $activity->objects[0];
553 if (!$shared instanceof Activity) {
554 // TRANS: Client exception thrown when trying to share a non-activity object.
555 throw new ClientException(_m('Can only handle shared activities.'));
558 $sharedId = $shared->id;
559 if (!empty($shared->objects[0]->id)) {
560 // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
561 // fucks up federation, because the URI is no longer recognised by the origin.
562 // So we set it to the object ID if it exists, otherwise we trust $shared->id
563 $sharedId = $shared->objects[0]->id;
565 if (empty($sharedId)) {
566 throw new ClientException(_m('Shared activity does not have an id'));
569 // First check if we have the shared activity. This has to be done first, because
570 // we can't use these functions to "ensureActivityObjectProfile" of a local user,
571 // who might be the creator of the shared activity in question.
572 $sharedNotice = Notice::getKV('uri', $sharedId);
573 if (!$sharedNotice instanceof Notice) {
574 // If no locally stored notice is found, process it!
575 // TODO: Remember to check Deleted_notice!
576 // TODO: If a post is shared that we can't retrieve - what to do?
578 $other = self::ensureActivityObjectProfile($shared->actor);
579 $sharedNotice = $other->processActivity($shared, $method);
580 if (!$sharedNotice instanceof Notice) {
581 // And if we apparently can't get the shared notice, we'll abort the whole thing.
582 // TRANS: Client exception thrown when saving an activity share fails.
583 // TRANS: %s is a share ID.
584 throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedId));
586 } catch (FeedSubException $e) {
587 // Remote feed could not be found or verified, should we
588 // transform this into an "RT @user Blah, blah, blah..."?
589 common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
594 // We'll want to save a web link to the original notice, if provided.
597 if ($activity->link) {
598 $sourceUrl = $activity->link;
599 } else if ($activity->link) {
600 $sourceUrl = $activity->link;
601 } else if (preg_match('!^https?://!', $activity->id)) {
602 $sourceUrl = $activity->id;
605 // Use summary as fallback for content
607 if (!empty($activity->content)) {
608 $sourceContent = $activity->content;
609 } else if (!empty($activity->summary)) {
610 $sourceContent = $activity->summary;
611 } else if (!empty($activity->title)) {
612 $sourceContent = $activity->title;
614 // @todo FIXME: Fetch from $sourceUrl?
615 // TRANS: Client exception. %s is a source URI.
616 throw new ClientException(sprintf(_m('No content for notice %s.'), $activity->id));
619 // Get (safe!) HTML and text versions of the content
621 $rendered = $this->purify($sourceContent);
622 $content = common_strip_html($rendered);
624 $shortened = common_shorten_links($content);
626 // If it's too long, try using the summary, and make the
627 // HTML an attachment.
631 if (Notice::contentTooLong($shortened)) {
632 $attachment = $this->saveHTMLFile($activity->title, $rendered);
633 $summary = common_strip_html($activity->summary);
634 if (empty($summary)) {
637 $shortSummary = common_shorten_links($summary);
638 if (Notice::contentTooLong($shortSummary)) {
639 $url = common_shorten_url($sourceUrl);
640 $shortSummary = substr($shortSummary,
642 Notice::maxContent() - (mb_strlen($url) + 2));
643 $content = $shortSummary . ' ' . $url;
645 // We mark up the attachment link specially for the HTML output
646 // so we can fold-out the full version inline.
648 // @todo FIXME i18n: This tooltip will be saved with the site's default language
649 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
650 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
651 $showMoreText = _m('Show more');
652 $attachUrl = common_local_url('attachment',
653 array('attachment' => $attachment->id));
654 $rendered = common_render_text($shortSummary) .
655 '<a href="' . htmlspecialchars($attachUrl) .'"'.
656 ' class="attachment more"' .
657 ' title="'. htmlspecialchars($showMoreText) . '">' .
663 $options = array('is_local' => Notice::REMOTE,
665 'uri' => $activity->id,
666 'rendered' => $rendered,
667 'replies' => array(),
669 'peopletags' => array(),
672 'repeat_of' => $sharedNotice->id,
673 'scope' => $sharedNotice->scope);
675 // Check for optional attributes...
677 if (!empty($activity->time)) {
678 $options['created'] = common_sql_date($activity->time);
681 if ($activity->context) {
682 // TODO: context->attention
683 list($options['groups'], $options['replies'])
684 = self::filterAttention($profile, $activity->context->attention);
686 // Maintain direct reply associations
687 // @todo FIXME: What about conversation ID?
688 if (!empty($activity->context->replyToID)) {
689 $orig = Notice::getKV('uri',
690 $activity->context->replyToID);
691 if ($orig instanceof Notice) {
692 $options['reply_to'] = $orig->id;
696 $location = $activity->context->location;
698 $options['lat'] = $location->lat;
699 $options['lon'] = $location->lon;
700 if ($location->location_id) {
701 $options['location_ns'] = $location->location_ns;
702 $options['location_id'] = $location->location_id;
707 if ($this->isPeopletag()) {
708 $options['peopletags'][] = $this->localPeopletag();
711 // Atom categories <-> hashtags
712 foreach ($activity->categories as $cat) {
714 $term = common_canonical_tag($cat->term);
716 $options['tags'][] = $term;
721 // Atom enclosures -> attachment URLs
722 foreach ($activity->enclosures as $href) {
723 // @todo FIXME: Save these locally or....?
724 $options['urls'][] = $href;
727 $notice = Notice::saveNew($profile->id,
736 * Process an incoming post activity from this remote feed.
737 * @param Activity $activity
738 * @param string $method 'push' or 'salmon'
739 * @return mixed saved Notice or false
740 * @todo FIXME: Break up this function, it's getting nasty long
742 public function processPost($activity, $method)
746 $profile = ActivityUtils::checkAuthorship($activity, $this->localProfile());
748 // It's not always an ActivityObject::NOTE, but... let's just say it is.
750 $note = $activity->objects[0];
752 // The id URI will be used as a unique identifier for the notice,
753 // protecting against duplicate saves. It isn't required to be a URL;
754 // tag: URIs for instance are found in Google Buzz feeds.
755 $sourceUri = $note->id;
756 $dupe = Notice::getKV('uri', $sourceUri);
757 if ($dupe instanceof Notice) {
758 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
762 // We'll also want to save a web link to the original notice, if provided.
765 $sourceUrl = $note->link;
766 } else if ($activity->link) {
767 $sourceUrl = $activity->link;
768 } else if (preg_match('!^https?://!', $note->id)) {
769 $sourceUrl = $note->id;
772 // Use summary as fallback for content
774 if (!empty($note->content)) {
775 $sourceContent = $note->content;
776 } else if (!empty($note->summary)) {
777 $sourceContent = $note->summary;
778 } else if (!empty($note->title)) {
779 $sourceContent = $note->title;
781 // @todo FIXME: Fetch from $sourceUrl?
782 // TRANS: Client exception. %s is a source URI.
783 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
786 // Get (safe!) HTML and text versions of the content
788 $rendered = $this->purify($sourceContent);
789 $content = common_strip_html($rendered);
791 $shortened = common_shorten_links($content);
793 // If it's too long, try using the summary, and make the
794 // HTML an attachment.
798 if (Notice::contentTooLong($shortened)) {
799 $attachment = $this->saveHTMLFile($note->title, $rendered);
800 $summary = common_strip_html($note->summary);
801 if (empty($summary)) {
804 $shortSummary = common_shorten_links($summary);
805 if (Notice::contentTooLong($shortSummary)) {
806 $url = common_shorten_url($sourceUrl);
807 $shortSummary = substr($shortSummary,
809 Notice::maxContent() - (mb_strlen($url) + 2));
810 $content = $shortSummary . ' ' . $url;
812 // We mark up the attachment link specially for the HTML output
813 // so we can fold-out the full version inline.
815 // @todo FIXME i18n: This tooltip will be saved with the site's default language
816 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
817 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
818 $showMoreText = _m('Show more');
819 $attachUrl = common_local_url('attachment',
820 array('attachment' => $attachment->id));
821 $rendered = common_render_text($shortSummary) .
822 '<a href="' . htmlspecialchars($attachUrl) .'"'.
823 ' class="attachment more"' .
824 ' title="'. htmlspecialchars($showMoreText) . '">' .
830 $options = array('is_local' => Notice::REMOTE,
833 'rendered' => $rendered,
834 'replies' => array(),
836 'peopletags' => array(),
840 // Check for optional attributes...
842 if (!empty($activity->time)) {
843 $options['created'] = common_sql_date($activity->time);
846 if ($activity->context) {
847 // TODO: context->attention
848 list($options['groups'], $options['replies'])
849 = self::filterAttention($profile, $activity->context->attention);
851 // Maintain direct reply associations
852 // @todo FIXME: What about conversation ID?
853 if (!empty($activity->context->replyToID)) {
854 $orig = Notice::getKV('uri', $activity->context->replyToID);
855 if ($orig instanceof Notice) {
856 $options['reply_to'] = $orig->id;
859 if (!empty($activity->context->conversation)) {
860 // we store the URI here, Notice class can look it up later
861 $options['conversation'] = $activity->context->conversation;
864 $location = $activity->context->location;
866 $options['lat'] = $location->lat;
867 $options['lon'] = $location->lon;
868 if ($location->location_id) {
869 $options['location_ns'] = $location->location_ns;
870 $options['location_id'] = $location->location_id;
875 if ($this->isPeopletag()) {
876 $options['peopletags'][] = $this->localPeopletag();
879 // Atom categories <-> hashtags
880 foreach ($activity->categories as $cat) {
882 $term = common_canonical_tag($cat->term);
884 $options['tags'][] = $term;
889 // Atom enclosures -> attachment URLs
890 foreach ($activity->enclosures as $href) {
891 // @todo FIXME: Save these locally or....?
892 $options['urls'][] = $href;
896 $saved = Notice::saveNew($profile->id,
900 if ($saved instanceof Notice) {
901 Ostatus_source::saveNew($saved, $this, $method);
902 if (!empty($attachment)) {
903 File_to_post::processNew($attachment->id, $saved->id);
906 } catch (Exception $e) {
907 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
910 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
917 protected function purify($html)
919 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
920 $config = array('safe' => 1,
921 'deny_attribute' => 'id,style,on*');
922 return htmLawed($html, $config);
926 * Filters a list of recipient ID URIs to just those for local delivery.
927 * @param Profile local profile of sender
928 * @param array in/out &$attention_uris set of URIs, will be pruned on output
929 * @return array of group IDs
931 static public function filterAttention(Profile $sender, array $attention)
933 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
936 foreach ($attention as $recipient=>$type) {
937 // Is the recipient a local user?
938 $user = User::getKV('uri', $recipient);
939 if ($user instanceof User) {
940 // @todo FIXME: Sender verification, spam etc?
941 $replies[] = $recipient;
945 // Is the recipient a local group?
946 // TODO: $group = User_group::getKV('uri', $recipient);
947 $id = OStatusPlugin::localGroupFromUrl($recipient);
949 $group = User_group::getKV('id', $id);
950 if ($group instanceof User_group) {
951 // Deliver to all members of this local group if allowed.
952 if ($sender->isMember($group)) {
953 $groups[] = $group->id;
955 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
959 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
963 // Is the recipient a remote user or group?
965 $oprofile = self::ensureProfileURI($recipient);
966 if ($oprofile->isGroup()) {
967 // Deliver to local members of this remote group.
968 // @todo FIXME: Sender verification?
969 $groups[] = $oprofile->group_id;
971 // may be canonicalized or something
972 $replies[] = $oprofile->getUri();
975 } catch (Exception $e) {
976 // Neither a recognizable local nor remote user!
977 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
981 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
982 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
983 return array($groups, $replies);
987 * Look up and if necessary create an Ostatus_profile for the remote entity
988 * with the given profile page URL. This should never return null -- you
989 * will either get an object or an exception will be thrown.
991 * @param string $profile_url
992 * @return Ostatus_profile
993 * @throws Exception on various error conditions
994 * @throws OStatusShadowException if this reference would obscure a local user/group
996 public static function ensureProfileURL($profile_url, array $hints=array())
998 $oprofile = self::getFromProfileURL($profile_url);
1000 if ($oprofile instanceof Ostatus_profile) {
1004 $hints['profileurl'] = $profile_url;
1007 // XXX: HTTP caching
1009 $client = new HTTPClient();
1010 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
1011 $response = $client->get($profile_url);
1013 if (!$response->isOk()) {
1014 // TRANS: Exception. %s is a profile URL.
1015 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
1018 // Check if we have a non-canonical URL
1020 $finalUrl = $response->getUrl();
1022 if ($finalUrl != $profile_url) {
1024 $hints['profileurl'] = $finalUrl;
1026 $oprofile = self::getFromProfileURL($finalUrl);
1028 if ($oprofile instanceof Ostatus_profile) {
1033 // Try to get some hCard data
1035 $body = $response->getBody();
1037 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1039 if (!empty($hcardHints)) {
1040 $hints = array_merge($hints, $hcardHints);
1043 // Check if they've got an LRDD header
1045 $lrdd = LinkHeader::getLink($response, 'lrdd');
1047 $xrd = new XML_XRD();
1048 $xrd->loadFile($lrdd);
1049 $xrdHints = DiscoveryHints::fromXRD($xrd);
1050 $hints = array_merge($hints, $xrdHints);
1051 } catch (Exception $e) {
1052 // No hints available from XRD
1055 // If discovery found a feedurl (probably from LRDD), use it.
1057 if (array_key_exists('feedurl', $hints)) {
1058 return self::ensureFeedURL($hints['feedurl'], $hints);
1061 // Get the feed URL from HTML
1063 $discover = new FeedDiscovery();
1065 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1067 if (!empty($feedurl)) {
1068 $hints['feedurl'] = $feedurl;
1069 return self::ensureFeedURL($feedurl, $hints);
1072 // TRANS: Exception. %s is a URL.
1073 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1077 * Look up the Ostatus_profile, if present, for a remote entity with the
1078 * given profile page URL. Will return null for both unknown and invalid
1081 * @return mixed Ostatus_profile or null
1082 * @throws OStatusShadowException for local profiles
1084 static function getFromProfileURL($profile_url)
1086 $profile = Profile::getKV('profileurl', $profile_url);
1087 if (!$profile instanceof Profile) {
1092 $oprofile = self::getFromProfile($profile);
1093 // We found the profile, return it!
1095 } catch (NoResultException $e) {
1096 // Could not find an OStatus profile, is it instead a local user?
1097 $user = User::getKV('id', $profile->id);
1098 if ($user instanceof User) {
1099 // @todo i18n FIXME: use sprintf and add i18n (?)
1100 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1104 // Continue discovery; it's a remote profile
1105 // for OMB or some other protocol, may also
1111 static function getFromProfile(Profile $profile)
1113 $oprofile = new Ostatus_profile();
1114 $oprofile->profile_id = $profile->id;
1115 if (!$oprofile->find(true)) {
1116 throw new NoResultException($oprofile);
1122 * Look up and if necessary create an Ostatus_profile for remote entity
1123 * with the given update feed. This should never return null -- you will
1124 * either get an object or an exception will be thrown.
1126 * @return Ostatus_profile
1129 public static function ensureFeedURL($feed_url, array $hints=array())
1131 $discover = new FeedDiscovery();
1133 $feeduri = $discover->discoverFromFeedURL($feed_url);
1134 $hints['feedurl'] = $feeduri;
1136 $huburi = $discover->getHubLink();
1137 $hints['hub'] = $huburi;
1139 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1140 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1141 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1142 $hints['salmon'] = $salmonuri;
1144 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1145 // We can only deal with folks with a PuSH hub
1146 throw new FeedSubNoHubException();
1149 $feedEl = $discover->root;
1151 if ($feedEl->tagName == 'feed') {
1152 return self::ensureAtomFeed($feedEl, $hints);
1153 } else if ($feedEl->tagName == 'channel') {
1154 return self::ensureRssChannel($feedEl, $hints);
1156 throw new FeedSubBadXmlException($feeduri);
1161 * Look up and, if necessary, create an Ostatus_profile for the remote
1162 * profile with the given Atom feed - actually loaded from the feed.
1163 * This should never return null -- you will either get an object or
1164 * an exception will be thrown.
1166 * @param DOMElement $feedEl root element of a loaded Atom feed
1167 * @param array $hints additional discovery information passed from higher levels
1168 * @todo FIXME: Should this be marked public?
1169 * @return Ostatus_profile
1172 public static function ensureAtomFeed(DOMElement $feedEl, array $hints)
1174 $author = ActivityUtils::getFeedAuthor($feedEl);
1176 if (empty($author)) {
1177 // XXX: make some educated guesses here
1178 // TRANS: Feed sub exception.
1179 throw new FeedSubException(_m('Cannot find enough profile '.
1180 'information to make a feed.'));
1183 return self::ensureActivityObjectProfile($author, $hints);
1187 * Look up and, if necessary, create an Ostatus_profile for the remote
1188 * profile with the given RSS feed - actually loaded from the feed.
1189 * This should never return null -- you will either get an object or
1190 * an exception will be thrown.
1192 * @param DOMElement $feedEl root element of a loaded RSS feed
1193 * @param array $hints additional discovery information passed from higher levels
1194 * @todo FIXME: Should this be marked public?
1195 * @return Ostatus_profile
1198 public static function ensureRssChannel(DOMElement $feedEl, array $hints)
1200 // Special-case for Posterous. They have some nice metadata in their
1201 // posterous:author elements. We should use them instead of the channel.
1203 $items = $feedEl->getElementsByTagName('item');
1205 if ($items->length > 0) {
1206 $item = $items->item(0);
1207 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1208 if (!empty($authorEl)) {
1209 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1210 // Posterous has multiple authors per feed, and multiple feeds
1211 // per author. We check if this is the "main" feed for this author.
1212 if (array_key_exists('profileurl', $hints) &&
1213 !empty($obj->poco) &&
1214 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1215 return self::ensureActivityObjectProfile($obj, $hints);
1220 // @todo FIXME: We should check whether this feed has elements
1221 // with different <author> or <dc:creator> elements, and... I dunno.
1222 // Do something about that.
1224 $obj = ActivityObject::fromRssChannel($feedEl);
1226 return self::ensureActivityObjectProfile($obj, $hints);
1230 * Download and update given avatar image
1232 * @param string $url
1233 * @throws Exception in various failure cases
1235 protected function updateAvatar($url)
1237 if ($url == $this->avatar) {
1238 // We've already got this one.
1241 if (!common_valid_http_url($url)) {
1242 // TRANS: Server exception. %s is a URL.
1243 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1246 if ($this->isGroup()) {
1247 // FIXME: throw exception for localGroup
1248 $self = $this->localGroup();
1250 // this throws an exception already
1251 $self = $this->localProfile();
1254 throw new ServerException(sprintf(
1255 // TRANS: Server exception. %s is a URI.
1256 _m('Tried to update avatar for unsaved remote profile %s.'),
1260 // @todo FIXME: This should be better encapsulated
1261 // ripped from oauthstore.php (for old OMB client)
1262 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1264 if (!copy($url, $temp_filename)) {
1265 // TRANS: Server exception. %s is a URL.
1266 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1269 if ($this->isGroup()) {
1270 $id = $this->group_id;
1272 $id = $this->profile_id;
1274 // @todo FIXME: Should we be using different ids?
1275 $imagefile = new ImageFile($id, $temp_filename);
1276 $filename = Avatar::filename($id,
1277 image_type_to_extension($imagefile->type),
1279 common_timestamp());
1280 rename($temp_filename, Avatar::path($filename));
1281 } catch (Exception $e) {
1282 unlink($temp_filename);
1285 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1286 // keep from accidentally saving images from command-line (queues)
1287 // that can't be read from web server, which causes hard-to-notice
1288 // problems later on:
1290 // http://status.net/open-source/issues/2663
1291 chmod(Avatar::path($filename), 0644);
1293 $self->setOriginal($filename);
1295 $orig = clone($this);
1296 $this->avatar = $url;
1297 $this->update($orig);
1301 * Pull avatar URL from ActivityObject or profile hints
1303 * @param ActivityObject $object
1304 * @param array $hints
1305 * @return mixed URL string or false
1307 public static function getActivityObjectAvatar(ActivityObject $object, array $hints=array())
1309 if ($object->avatarLinks) {
1311 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1312 foreach ($object->avatarLinks as $avatar) {
1313 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1318 if (!$best || $avatar->width > $best->width) {
1323 } else if (array_key_exists('avatar', $hints)) {
1324 return $hints['avatar'];
1330 * Get an appropriate avatar image source URL, if available.
1332 * @param ActivityObject $actor
1333 * @param DOMElement $feed
1336 protected static function getAvatar(ActivityObject $actor, DOMElement $feed)
1340 if ($actor->avatar) {
1341 $url = trim($actor->avatar);
1344 // Check <atom:logo> and <atom:icon> on the feed
1345 $els = $feed->childNodes();
1346 if ($els && $els->length) {
1347 for ($i = 0; $i < $els->length; $i++) {
1348 $el = $els->item($i);
1349 if ($el->namespaceURI == Activity::ATOM) {
1350 if (empty($url) && $el->localName == 'logo') {
1351 $url = trim($el->textContent);
1354 if (empty($icon) && $el->localName == 'icon') {
1355 // Use as a fallback
1356 $icon = trim($el->textContent);
1361 if ($icon && !$url) {
1366 $opts = array('allowed_schemes' => array('http', 'https'));
1367 if (common_valid_http_url($url)) {
1372 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1376 * Fetch, or build if necessary, an Ostatus_profile for the actor
1377 * in a given Activity Streams activity.
1378 * This should never return null -- you will either get an object or
1379 * an exception will be thrown.
1381 * @param Activity $activity
1382 * @param string $feeduri if we already know the canonical feed URI!
1383 * @param string $salmonuri if we already know the salmon return channel URI
1384 * @return Ostatus_profile
1387 public static function ensureActorProfile(Activity $activity, array $hints=array())
1389 return self::ensureActivityObjectProfile($activity->actor, $hints);
1393 * Fetch, or build if necessary, an Ostatus_profile for the profile
1394 * in a given Activity Streams object (can be subject, actor, or object).
1395 * This should never return null -- you will either get an object or
1396 * an exception will be thrown.
1398 * @param ActivityObject $object
1399 * @param array $hints additional discovery information passed from higher levels
1400 * @return Ostatus_profile
1403 public static function ensureActivityObjectProfile(ActivityObject $object, array $hints=array())
1405 $profile = self::getActivityObjectProfile($object);
1406 if ($profile instanceof Ostatus_profile) {
1407 $profile->updateFromActivityObject($object, $hints);
1409 $profile = self::createActivityObjectProfile($object, $hints);
1415 * @param Activity $activity
1416 * @return mixed matching Ostatus_profile or false if none known
1417 * @throws ServerException if feed info invalid
1419 public static function getActorProfile(Activity $activity)
1421 return self::getActivityObjectProfile($activity->actor);
1425 * @param ActivityObject $activity
1426 * @return mixed matching Ostatus_profile or false if none known
1427 * @throws ServerException if feed info invalid
1429 protected static function getActivityObjectProfile(ActivityObject $object)
1431 $uri = self::getActivityObjectProfileURI($object);
1432 return Ostatus_profile::getKV('uri', $uri);
1436 * Get the identifier URI for the remote entity described
1437 * by this ActivityObject. This URI is *not* guaranteed to be
1438 * a resolvable HTTP/HTTPS URL.
1440 * @param ActivityObject $object
1442 * @throws ServerException if feed info invalid
1444 protected static function getActivityObjectProfileURI(ActivityObject $object)
1447 if (ActivityUtils::validateUri($object->id)) {
1452 // If the id is missing or invalid (we've seen feeds mistakenly listing
1453 // things like local usernames in that field) then we'll use the profile
1454 // page link, if valid.
1455 if ($object->link && common_valid_http_url($object->link)) {
1456 return $object->link;
1458 // TRANS: Server exception.
1459 throw new ServerException(_m('No author ID URI found.'));
1463 * @todo FIXME: Validate stuff somewhere.
1467 * Create local ostatus_profile and profile/user_group entries for
1468 * the provided remote user or group.
1469 * This should never return null -- you will either get an object or
1470 * an exception will be thrown.
1472 * @param ActivityObject $object
1473 * @param array $hints
1475 * @return Ostatus_profile
1477 protected static function createActivityObjectProfile(ActivityObject $object, array $hints=array())
1479 $homeuri = $object->id;
1483 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1484 // TRANS: Exception.
1485 throw new Exception(_m('No profile URI.'));
1488 $user = User::getKV('uri', $homeuri);
1489 if ($user instanceof User) {
1490 // TRANS: Exception.
1491 throw new Exception(_m('Local user cannot be referenced as remote.'));
1494 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1495 // TRANS: Exception.
1496 throw new Exception(_m('Local group cannot be referenced as remote.'));
1499 $ptag = Profile_list::getKV('uri', $homeuri);
1500 if ($ptag instanceof Profile_list) {
1501 $local_user = User::getKV('id', $ptag->tagger);
1502 if ($local_user instanceof User) {
1503 // TRANS: Exception.
1504 throw new Exception(_m('Local list cannot be referenced as remote.'));
1508 if (array_key_exists('feedurl', $hints)) {
1509 $feeduri = $hints['feedurl'];
1511 $discover = new FeedDiscovery();
1512 $feeduri = $discover->discoverFromURL($homeuri);
1515 if (array_key_exists('salmon', $hints)) {
1516 $salmonuri = $hints['salmon'];
1519 $discover = new FeedDiscovery();
1520 $discover->discoverFromFeedURL($hints['feedurl']);
1522 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1523 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1524 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1527 if (array_key_exists('hub', $hints)) {
1528 $huburi = $hints['hub'];
1531 $discover = new FeedDiscovery();
1532 $discover->discoverFromFeedURL($hints['feedurl']);
1534 $huburi = $discover->getHubLink();
1537 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1538 // We can only deal with folks with a PuSH hub
1539 throw new FeedSubNoHubException();
1542 $oprofile = new Ostatus_profile();
1544 $oprofile->uri = $homeuri;
1545 $oprofile->feeduri = $feeduri;
1546 $oprofile->salmonuri = $salmonuri;
1548 $oprofile->created = common_sql_now();
1549 $oprofile->modified = common_sql_now();
1551 if ($object->type == ActivityObject::PERSON) {
1552 $profile = new Profile();
1553 $profile->created = common_sql_now();
1554 self::updateProfile($profile, $object, $hints);
1556 $oprofile->profile_id = $profile->insert();
1557 if ($oprofile->profile_id === false) {
1558 // TRANS: Server exception.
1559 throw new ServerException(_m('Cannot save local profile.'));
1561 } else if ($object->type == ActivityObject::GROUP) {
1562 $profile = new Profile();
1563 $profile->query('BEGIN');
1565 $group = new User_group();
1566 $group->uri = $homeuri;
1567 $group->created = common_sql_now();
1568 self::updateGroup($group, $object, $hints);
1570 // TODO: We should do this directly in User_group->insert()!
1571 // currently it's duplicated in User_group->update()
1572 // AND User_group->register()!!!
1573 $fields = array(/*group field => profile field*/
1574 'nickname' => 'nickname',
1575 'fullname' => 'fullname',
1576 'mainpage' => 'profileurl',
1577 'homepage' => 'homepage',
1578 'description' => 'bio',
1579 'location' => 'location',
1580 'created' => 'created',
1581 'modified' => 'modified',
1583 foreach ($fields as $gf=>$pf) {
1584 $profile->$pf = $group->$gf;
1586 $profile_id = $profile->insert();
1587 if ($profile_id === false) {
1588 $profile->query('ROLLBACK');
1589 throw new ServerException(_('Profile insertion failed.'));
1592 $group->profile_id = $profile_id;
1594 $oprofile->group_id = $group->insert();
1595 if ($oprofile->group_id === false) {
1596 $profile->query('ROLLBACK');
1597 // TRANS: Server exception.
1598 throw new ServerException(_m('Cannot save local profile.'));
1601 $profile->query('COMMIT');
1602 } else if ($object->type == ActivityObject::_LIST) {
1603 $ptag = new Profile_list();
1604 $ptag->uri = $homeuri;
1605 $ptag->created = common_sql_now();
1606 self::updatePeopletag($ptag, $object, $hints);
1608 $oprofile->peopletag_id = $ptag->insert();
1609 if ($oprofile->peopletag_id === false) {
1610 // TRANS: Server exception.
1611 throw new ServerException(_m('Cannot save local list.'));
1615 $ok = $oprofile->insert();
1617 if ($ok === false) {
1618 // TRANS: Server exception.
1619 throw new ServerException(_m('Cannot save OStatus profile.'));
1622 $avatar = self::getActivityObjectAvatar($object, $hints);
1626 $oprofile->updateAvatar($avatar);
1627 } catch (Exception $ex) {
1628 // Profile is saved, but Avatar is messed up. We're
1629 // just going to continue.
1630 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1638 * Save any updated profile information to our local copy.
1639 * @param ActivityObject $object
1640 * @param array $hints
1642 public function updateFromActivityObject(ActivityObject $object, array $hints=array())
1644 if ($this->isGroup()) {
1645 $group = $this->localGroup();
1646 self::updateGroup($group, $object, $hints);
1647 } else if ($this->isPeopletag()) {
1648 $ptag = $this->localPeopletag();
1649 self::updatePeopletag($ptag, $object, $hints);
1651 $profile = $this->localProfile();
1652 self::updateProfile($profile, $object, $hints);
1655 $avatar = self::getActivityObjectAvatar($object, $hints);
1656 if ($avatar && !isset($ptag)) {
1658 $this->updateAvatar($avatar);
1659 } catch (Exception $ex) {
1660 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1665 public static function updateProfile(Profile $profile, ActivityObject $object, array $hints=array())
1667 $orig = clone($profile);
1669 // Existing nickname is better than nothing.
1671 if (!array_key_exists('nickname', $hints)) {
1672 $hints['nickname'] = $profile->nickname;
1675 $nickname = self::getActivityObjectNickname($object, $hints);
1677 if (!empty($nickname)) {
1678 $profile->nickname = $nickname;
1681 if (!empty($object->title)) {
1682 $profile->fullname = $object->title;
1683 } else if (array_key_exists('fullname', $hints)) {
1684 $profile->fullname = $hints['fullname'];
1687 if (!empty($object->link)) {
1688 $profile->profileurl = $object->link;
1689 } else if (array_key_exists('profileurl', $hints)) {
1690 $profile->profileurl = $hints['profileurl'];
1691 } else if (common_valid_http_url($object->id)) {
1692 $profile->profileurl = $object->id;
1695 $bio = self::getActivityObjectBio($object, $hints);
1698 $profile->bio = $bio;
1701 $location = self::getActivityObjectLocation($object, $hints);
1703 if (!empty($location)) {
1704 $profile->location = $location;
1707 $homepage = self::getActivityObjectHomepage($object, $hints);
1709 if (!empty($homepage)) {
1710 $profile->homepage = $homepage;
1713 if (!empty($object->geopoint)) {
1714 $location = ActivityContext::locationFromPoint($object->geopoint);
1715 if (!empty($location)) {
1716 $profile->lat = $location->lat;
1717 $profile->lon = $location->lon;
1721 // @todo FIXME: tags/categories
1722 // @todo tags from categories
1725 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1726 $profile->update($orig);
1730 protected static function updateGroup(User_group $group, ActivityObject $object, array $hints=array())
1732 $orig = clone($group);
1734 $group->nickname = self::getActivityObjectNickname($object, $hints);
1735 $group->fullname = $object->title;
1737 if (!empty($object->link)) {
1738 $group->mainpage = $object->link;
1739 } else if (array_key_exists('profileurl', $hints)) {
1740 $group->mainpage = $hints['profileurl'];
1743 // @todo tags from categories
1744 $group->description = self::getActivityObjectBio($object, $hints);
1745 $group->location = self::getActivityObjectLocation($object, $hints);
1746 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1748 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1749 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1750 $group->update($orig);
1754 protected static function updatePeopletag($tag, ActivityObject $object, array $hints=array()) {
1755 $orig = clone($tag);
1757 $tag->tag = $object->title;
1759 if (!empty($object->link)) {
1760 $tag->mainpage = $object->link;
1761 } else if (array_key_exists('profileurl', $hints)) {
1762 $tag->mainpage = $hints['profileurl'];
1765 $tag->description = $object->summary;
1766 $tagger = self::ensureActivityObjectProfile($object->owner);
1767 $tag->tagger = $tagger->profile_id;
1770 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1771 $tag->update($orig);
1775 protected static function getActivityObjectHomepage(ActivityObject $object, array $hints=array())
1778 $poco = $object->poco;
1780 if (!empty($poco)) {
1781 $url = $poco->getPrimaryURL();
1782 if ($url && $url->type == 'homepage') {
1783 $homepage = $url->value;
1787 // @todo Try for a another PoCo URL?
1792 protected static function getActivityObjectLocation(ActivityObject $object, array $hints=array())
1796 if (!empty($object->poco) &&
1797 isset($object->poco->address->formatted)) {
1798 $location = $object->poco->address->formatted;
1799 } else if (array_key_exists('location', $hints)) {
1800 $location = $hints['location'];
1803 if (!empty($location)) {
1804 if (mb_strlen($location) > 255) {
1805 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1809 // @todo Try to find location some othe way? Via goerss point?
1814 protected static function getActivityObjectBio(ActivityObject $object, array $hints=array())
1818 if (!empty($object->poco)) {
1819 $note = $object->poco->note;
1820 } else if (array_key_exists('bio', $hints)) {
1821 $note = $hints['bio'];
1824 if (!empty($note)) {
1825 if (Profile::bioTooLong($note)) {
1826 // XXX: truncate ok?
1827 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1833 // @todo Try to get bio info some other way?
1838 public static function getActivityObjectNickname(ActivityObject $object, array $hints=array())
1840 if ($object->poco) {
1841 if (!empty($object->poco->preferredUsername)) {
1842 return common_nicknamize($object->poco->preferredUsername);
1846 if (!empty($object->nickname)) {
1847 return common_nicknamize($object->nickname);
1850 if (array_key_exists('nickname', $hints)) {
1851 return $hints['nickname'];
1854 // Try the profile url (like foo.example.com or example.com/user/foo)
1855 if (!empty($object->link)) {
1856 $profileUrl = $object->link;
1857 } else if (!empty($hints['profileurl'])) {
1858 $profileUrl = $hints['profileurl'];
1861 if (!empty($profileUrl)) {
1862 $nickname = self::nicknameFromURI($profileUrl);
1865 // Try the URI (may be a tag:, http:, acct:, ...
1867 if (empty($nickname)) {
1868 $nickname = self::nicknameFromURI($object->id);
1871 // Try a Webfinger if one was passed (way) down
1873 if (empty($nickname)) {
1874 if (array_key_exists('webfinger', $hints)) {
1875 $nickname = self::nicknameFromURI($hints['webfinger']);
1881 if (empty($nickname)) {
1882 $nickname = common_nicknamize($object->title);
1888 protected static function nicknameFromURI($uri)
1890 if (preg_match('/(\w+):/', $uri, $matches)) {
1891 $protocol = $matches[1];
1896 switch ($protocol) {
1899 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1900 return common_canonical_nickname($matches[1]);
1904 return common_url_to_nickname($uri);
1912 * Look up, and if necessary create, an Ostatus_profile for the remote
1913 * entity with the given webfinger address.
1914 * This should never return null -- you will either get an object or
1915 * an exception will be thrown.
1917 * @param string $addr webfinger address
1918 * @return Ostatus_profile
1919 * @throws Exception on error conditions
1920 * @throws OStatusShadowException if this reference would obscure a local user/group
1922 public static function ensureWebfinger($addr)
1924 // First, try the cache
1926 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1928 if ($uri !== false) {
1929 if (is_null($uri)) {
1930 // Negative cache entry
1931 // TRANS: Exception.
1932 throw new Exception(_m('Not a valid webfinger address.'));
1934 $oprofile = Ostatus_profile::getKV('uri', $uri);
1935 if ($oprofile instanceof Ostatus_profile) {
1940 // Try looking it up
1941 $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1943 if ($oprofile instanceof Ostatus_profile) {
1944 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1948 // Now, try some discovery
1950 $disco = new Discovery();
1953 $xrd = $disco->lookup($addr);
1954 } catch (Exception $e) {
1955 // Save negative cache entry so we don't waste time looking it up again.
1956 // @todo FIXME: Distinguish temporary failures?
1957 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1958 // TRANS: Exception.
1959 throw new Exception(_m('Not a valid webfinger address.'));
1962 $hints = array('webfinger' => $addr);
1964 $dhints = DiscoveryHints::fromXRD($xrd);
1966 $hints = array_merge($hints, $dhints);
1968 // If there's an Hcard, let's grab its info
1969 if (array_key_exists('hcard', $hints)) {
1970 if (!array_key_exists('profileurl', $hints) ||
1971 $hints['hcard'] != $hints['profileurl']) {
1972 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1973 $hints = array_merge($hcardHints, $hints);
1977 // If we got a feed URL, try that
1979 if (array_key_exists('feedurl', $hints)) {
1980 $feedUrl = $hints['feedurl'];
1982 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1983 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1984 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1986 } catch (Exception $e) {
1987 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1992 // If we got a profile page, try that!
1994 if (array_key_exists('profileurl', $hints)) {
1995 $profileUrl = $hints['profileurl'];
1997 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1998 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1999 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
2001 } catch (OStatusShadowException $e) {
2002 // We've ended up with a remote reference to a local user or group.
2003 // @todo FIXME: Ideally we should be able to say who it was so we can
2004 // go back and refer to it the regular way
2006 } catch (Exception $e) {
2007 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
2010 // @todo FIXME: This means an error discovering from profile page
2011 // may give us a corrupt entry using the webfinger URI, which
2012 // will obscure the correct page-keyed profile later on.
2019 if (array_key_exists('salmon', $hints)) {
2020 $salmonEndpoint = $hints['salmon'];
2022 // An account URL, a salmon endpoint, and a dream? Not much to go
2023 // on, but let's give it a try
2025 $uri = 'acct:'.$addr;
2027 $profile = new Profile();
2029 $profile->nickname = self::nicknameFromUri($uri);
2030 $profile->created = common_sql_now();
2032 if (!is_null($profileUrl)) {
2033 $profile->profileurl = $profileUrl;
2036 $profile_id = $profile->insert();
2038 if ($profile_id === false) {
2039 common_log_db_error($profile, 'INSERT', __FILE__);
2040 // TRANS: Exception. %s is a webfinger address.
2041 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2044 $oprofile = new Ostatus_profile();
2046 $oprofile->uri = $uri;
2047 $oprofile->salmonuri = $salmonEndpoint;
2048 $oprofile->profile_id = $profile_id;
2049 $oprofile->created = common_sql_now();
2051 if (!is_null($feedUrl)) {
2052 $oprofile->feeduri = $feedUrl;
2055 $result = $oprofile->insert();
2057 if ($result === false) {
2059 common_log_db_error($oprofile, 'INSERT', __FILE__);
2060 // TRANS: Exception. %s is a webfinger address.
2061 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2064 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
2068 // TRANS: Exception. %s is a webfinger address.
2069 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2073 * Store the full-length scrubbed HTML of a remote notice to an attachment
2074 * file on our server. We'll link to this at the end of the cropped version.
2076 * @param string $title plaintext for HTML page's title
2077 * @param string $rendered HTML fragment for HTML page's body
2080 function saveHTMLFile($title, $rendered)
2082 $final = sprintf("<!DOCTYPE html>\n" .
2084 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2085 '<title>%s</title>' .
2087 '<body>%s</body></html>',
2088 htmlspecialchars($title),
2091 $filename = File::filename($this->localProfile(),
2092 'ostatus', // ignored?
2095 $filepath = File::path($filename);
2097 file_put_contents($filepath, $final);
2101 $file->filename = $filename;
2102 $file->url = File::url($filename);
2103 $file->size = filesize($filepath);
2104 $file->date = time();
2105 $file->mimetype = 'text/html';
2107 $file_id = $file->insert();
2109 if ($file_id === false) {
2110 common_log_db_error($file, "INSERT", __FILE__);
2111 // TRANS: Server exception.
2112 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2118 static function ensureProfileURI($uri)
2122 // First, try to query it
2124 $oprofile = Ostatus_profile::getKV('uri', $uri);
2126 if ($oprofile instanceof Ostatus_profile) {
2130 // If unfound, do discovery stuff
2131 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2132 $protocol = $match[1];
2133 switch ($protocol) {
2136 $oprofile = self::ensureProfileURL($uri);
2141 $oprofile = self::ensureWebfinger($rest);
2144 // TRANS: Server exception.
2145 // TRANS: %1$s is a protocol, %2$s is a URI.
2146 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2152 // TRANS: Server exception. %s is a URI.
2153 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2159 public function checkAuthorship(Activity $activity)
2161 if ($this->isGroup() || $this->isPeopletag()) {
2162 // A group or propletag feed will contain posts from multiple authors.
2163 $oprofile = self::ensureActorProfile($activity);
2164 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2165 // Groups can't post notices in StatusNet.
2166 common_log(LOG_WARNING,
2167 "OStatus: skipping post with group listed ".
2168 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
2169 throw new ServerException('Activity author is a non-actor');
2172 $actor = $activity->actor;
2174 if (empty($actor)) {
2175 // OK here! assume the default
2176 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
2177 $this->updateFromActivityObject($actor);
2178 } else if ($actor->id) {
2179 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2180 // This isn't what we expect from mainline OStatus person feeds!
2181 // Group feeds go down another path, with different validation...
2182 // Most likely this is a plain ol' blog feed of some kind which
2183 // doesn't match our expectations. We'll take the entry, but ignore
2184 // the <author> info.
2185 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
2187 // Plain <author> without ActivityStreams actor info.
2188 // We'll just ignore this info for now and save the update under the feed's identity.
2194 return $oprofile->localProfile();
2199 * Exception indicating we've got a remote reference to a local user,
2200 * not a remote user!
2202 * If we can ue a local profile after all, it's available as $e->profile.
2204 class OStatusShadowException extends Exception
2209 * @param Profile $profile
2210 * @param string $message
2212 function __construct($profile, $message) {
2213 $this->profile = $profile;
2214 parent::__construct($message);