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()
85 * Fetch the locally stored profile for this feed
87 * @throws NoProfileException if it was not found
89 public function localProfile()
91 $profile = Profile::getKV('id', $this->profile_id);
92 if ($profile instanceof Profile) {
95 throw new NoProfileException($this->profile_id);
99 * Fetch the StatusNet-side profile for this feed
102 public function localGroup()
104 if ($this->group_id) {
105 return User_group::getKV('id', $this->group_id);
111 * Fetch the StatusNet-side peopletag for this feed
114 public function localPeopletag()
116 if ($this->peopletag_id) {
117 return Profile_list::getKV('id', $this->peopletag_id);
123 * Returns an ActivityObject describing this remote user or group profile.
124 * Can then be used to generate Atom chunks.
126 * @return ActivityObject
128 function asActivityObject()
130 if ($this->isGroup()) {
131 return ActivityObject::fromGroup($this->localGroup());
132 } else if ($this->isPeopletag()) {
133 return ActivityObject::fromPeopletag($this->localPeopletag());
135 return ActivityObject::fromProfile($this->localProfile());
140 * Returns an XML string fragment with profile information as an
141 * Activity Streams noun object with the given element type.
143 * Assumes that 'activity' namespace has been previously defined.
145 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
147 * @param string $element one of 'actor', 'subject', 'object', 'target'
150 function asActivityNoun($element)
152 if ($this->isGroup()) {
153 $noun = ActivityObject::fromGroup($this->localGroup());
154 return $noun->asString('activity:' . $element);
155 } else if ($this->isPeopletag()) {
156 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
157 return $noun->asString('activity:' . $element);
159 $noun = ActivityObject::fromProfile($this->localProfile());
160 return $noun->asString('activity:' . $element);
165 * @return boolean true if this is a remote group
169 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
171 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
173 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
174 // TRANS: Server exception. %s is a URI
175 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
177 // TRANS: Server exception. %s is a URI
178 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
183 * @return boolean true if this is a remote peopletag
185 function isPeopletag()
187 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
189 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
191 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
192 // TRANS: Server exception. %s is a URI
193 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
195 // TRANS: Server exception. %s is a URI
196 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
201 * Send a subscription request to the hub for this feed.
202 * The hub will later send us a confirmation POST to /main/push/callback.
205 * @throws ServerException if feed state is not valid or subscription fails.
207 public function subscribe()
209 $feedsub = FeedSub::ensureFeed($this->feeduri);
210 if ($feedsub->sub_state == 'active') {
211 // Active subscription, we don't need to do anything.
215 // Inactive or we got left in an inconsistent state.
216 // Run a subscription request to make sure we're current!
217 return $feedsub->subscribe();
221 * Check if this remote profile has any active local subscriptions, and
222 * if not drop the PuSH subscription feed.
224 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
225 * @throws Exception of various kinds on failure.
227 public function unsubscribe() {
228 return $this->garbageCollect();
232 * Check if this remote profile has any active local subscriptions, and
233 * if not drop the PuSH subscription feed.
235 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
236 * @throws Exception of various kinds on failure.
238 public function garbageCollect()
240 $feedsub = FeedSub::getKV('uri', $this->feeduri);
241 if ($feedsub instanceof FeedSub) {
242 return $feedsub->garbageCollect();
244 // Since there's no FeedSub we can assume it's already garbage collected
249 * Check if this remote profile has any active local subscriptions, so the
250 * PuSH subscription layer can decide if it can drop the feed.
252 * This gets called via the FeedSubSubscriberCount event when running
253 * FeedSub::garbageCollect().
256 * @throws NoProfileException if there is no local profile for the object
258 public function subscriberCount()
260 if ($this->isGroup()) {
261 $members = $this->localGroup()->getMembers(0, 1);
262 $count = $members->N;
263 } else if ($this->isPeopletag()) {
264 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
265 $count = $subscribers->N;
267 $profile = $this->localProfile();
268 if ($profile->hasLocalTags()) {
271 $count = $profile->subscriberCount();
274 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
276 // Other plugins may be piggybacking on OStatus without having
277 // an active group or user-to-user subscription we know about.
278 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
279 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
285 * Send an Activity Streams notification to the remote Salmon endpoint,
288 * @param Profile $actor Actor who did the activity
289 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
290 * @param Object $object object of the action; must define asActivityNoun($tag)
292 public function notify(Profile $actor, $verb, $object=null, $target=null)
294 if ($object == null) {
297 if (empty($this->salmonuri)) {
301 $id = TagURI::mint('%s:%s:%s',
304 common_date_iso8601(time()));
306 // @todo FIXME: Consolidate all these NS settings somewhere.
307 $attributes = array('xmlns' => Activity::ATOM,
308 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
309 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
310 'xmlns:georss' => 'http://www.georss.org/georss',
311 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
312 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
313 'xmlns:media' => 'http://purl.org/syndication/atommedia');
315 $entry = new XMLStringer();
316 $entry->elementStart('entry', $attributes);
317 $entry->element('id', null, $id);
318 $entry->element('title', null, $text);
319 $entry->element('summary', null, $text);
320 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
322 $entry->element('activity:verb', null, $verb);
323 $entry->raw($actor->asAtomAuthor());
324 $entry->raw($actor->asActivityActor());
325 $entry->raw($object->asActivityNoun('object'));
326 if ($target != null) {
327 $entry->raw($target->asActivityNoun('target'));
329 $entry->elementEnd('entry');
331 $xml = $entry->getString();
332 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
334 Salmon::post($this->salmonuri, $xml, $actor->getUser());
338 * Send a Salmon notification ping immediately, and confirm that we got
339 * an acceptable response from the remote site.
341 * @param mixed $entry XML string, Notice, or Activity
342 * @param Profile $actor
343 * @return boolean success
345 public function notifyActivity($entry, Profile $actor)
347 if ($this->salmonuri) {
348 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor->getUser());
350 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
356 * Queue a Salmon notification for later. If queues are disabled we'll
357 * send immediately but won't get the return value.
359 * @param mixed $entry XML string, Notice, or Activity
360 * @return boolean success
362 public function notifyDeferred($entry, $actor)
364 if ($this->salmonuri) {
365 $data = array('salmonuri' => $this->salmonuri,
366 'entry' => $this->notifyPrepXml($entry),
367 'actor' => $actor->id);
369 $qm = QueueManager::get();
370 return $qm->enqueue($data, 'salmon');
376 protected function notifyPrepXml($entry)
378 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
379 if (is_string($entry)) {
381 } else if ($entry instanceof Activity) {
382 return $preamble . $entry->asString(true);
383 } else if ($entry instanceof Notice) {
384 return $preamble . $entry->asAtomEntry(true, true);
386 // TRANS: Server exception.
387 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
391 function getBestName()
393 if ($this->isGroup()) {
394 return $this->localGroup()->getBestName();
395 } else if ($this->isPeopletag()) {
396 return $this->localPeopletag()->getBestName();
398 return $this->localProfile()->getBestName();
403 * Read and post notices for updates from the feed.
404 * Currently assumes that all items in the feed are new,
405 * coming from a PuSH hub.
407 * @param DOMDocument $doc
408 * @param string $source identifier ("push")
410 public function processFeed(DOMDocument $doc, $source)
412 $feed = $doc->documentElement;
414 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
415 $this->processAtomFeed($feed, $source);
416 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
417 $this->processRssFeed($feed, $source);
420 throw new Exception(_m('Unknown feed format.'));
424 public function processAtomFeed(DOMElement $feed, $source)
426 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
427 if ($entries->length == 0) {
428 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
432 for ($i = 0; $i < $entries->length; $i++) {
433 $entry = $entries->item($i);
434 $this->processEntry($entry, $feed, $source);
438 public function processRssFeed(DOMElement $rss, $source)
440 $channels = $rss->getElementsByTagName('channel');
442 if ($channels->length == 0) {
444 throw new Exception(_m('RSS feed without a channel.'));
445 } else if ($channels->length > 1) {
446 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
449 $channel = $channels->item(0);
451 $items = $channel->getElementsByTagName('item');
453 for ($i = 0; $i < $items->length; $i++) {
454 $item = $items->item($i);
455 $this->processEntry($item, $channel, $source);
460 * Process a posted entry from this feed source.
462 * @param DOMElement $entry
463 * @param DOMElement $feed for context
464 * @param string $source identifier ("push" or "salmon")
466 * @return Notice Notice representing the new (or existing) activity
468 public function processEntry($entry, $feed, $source)
470 $activity = new Activity($entry, $feed);
471 return $this->processActivity($activity, $source);
474 // TODO: Make this throw an exception
475 public function processActivity($activity, $source)
479 // The "WithProfile" events were added later.
481 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this, &$notice)) &&
482 Event::handle('StartHandleFeedEntry', array($activity))) {
484 switch ($activity->verb) {
485 case ActivityVerb::POST:
486 // @todo process all activity objects
487 switch ($activity->objects[0]->type) {
488 case ActivityObject::ARTICLE:
489 case ActivityObject::BLOGENTRY:
490 case ActivityObject::NOTE:
491 case ActivityObject::STATUS:
492 case ActivityObject::COMMENT:
494 $notice = $this->processPost($activity, $source);
497 // TRANS: Client exception.
498 throw new ClientException(_m('Cannot handle that kind of post.'));
501 case ActivityVerb::SHARE:
502 $notice = $this->processShare($activity, $source);
505 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
508 Event::handle('EndHandleFeedEntry', array($activity));
509 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
515 public function processShare($activity, $method)
519 $oprofile = $this->checkAuthorship($activity);
521 if (!$oprofile instanceof Ostatus_profile) {
522 common_log(LOG_INFO, "No author matched share activity");
526 // The id URI will be used as a unique identifier for the notice,
527 // protecting against duplicate saves. It isn't required to be a URL;
528 // tag: URIs for instance are found in Google Buzz feeds.
529 $dupe = Notice::getKV('uri', $activity->id);
530 if ($dupe instanceof Notice) {
531 common_log(LOG_INFO, "OStatus: ignoring duplicate post: {$activity->id}");
535 if (count($activity->objects) != 1) {
536 // TRANS: Client exception thrown when trying to share multiple activities at once.
537 throw new ClientException(_m('Can only handle share activities with exactly one object.'));
540 $shared = $activity->objects[0];
542 if (!$shared instanceof Activity) {
543 // TRANS: Client exception thrown when trying to share a non-activity object.
544 throw new ClientException(_m('Can only handle shared activities.'));
547 $sharedId = $shared->id;
548 if (!empty($shared->objects[0]->id)) {
549 // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
550 // fucks up federation, because the URI is no longer recognised by the origin.
551 // So we set it to the object ID if it exists, otherwise we trust $shared->id
552 $sharedId = $shared->objects[0]->id;
554 if (empty($sharedId)) {
555 throw new ClientException(_m('Shared activity does not have an id'));
558 // First check if we have the shared activity. This has to be done first, because
559 // we can't use these functions to "ensureActivityObjectProfile" of a local user,
560 // who might be the creator of the shared activity in question.
561 $sharedNotice = Notice::getKV('uri', $sharedId);
562 if (!$sharedNotice instanceof Notice) {
563 // If no locally stored notice is found, process it!
564 // TODO: Remember to check Deleted_notice!
565 // TODO: If a post is shared that we can't retrieve - what to do?
567 $other = self::ensureActivityObjectProfile($shared->actor);
568 $sharedNotice = $other->processActivity($shared, $method);
569 if (!$sharedNotice instanceof Notice) {
570 // And if we apparently can't get the shared notice, we'll abort the whole thing.
571 // TRANS: Client exception thrown when saving an activity share fails.
572 // TRANS: %s is a share ID.
573 throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedId));
575 } catch (FeedSubException $e) {
576 // Remote feed could not be found or verified, should we
577 // transform this into an "RT @user Blah, blah, blah..."?
578 common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
583 // We'll want to save a web link to the original notice, if provided.
586 if ($activity->link) {
587 $sourceUrl = $activity->link;
588 } else if ($activity->link) {
589 $sourceUrl = $activity->link;
590 } else if (preg_match('!^https?://!', $activity->id)) {
591 $sourceUrl = $activity->id;
594 // Use summary as fallback for content
596 if (!empty($activity->content)) {
597 $sourceContent = $activity->content;
598 } else if (!empty($activity->summary)) {
599 $sourceContent = $activity->summary;
600 } else if (!empty($activity->title)) {
601 $sourceContent = $activity->title;
603 // @todo FIXME: Fetch from $sourceUrl?
604 // TRANS: Client exception. %s is a source URI.
605 throw new ClientException(sprintf(_m('No content for notice %s.'), $activity->id));
608 // Get (safe!) HTML and text versions of the content
610 $rendered = $this->purify($sourceContent);
611 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
613 $shortened = common_shorten_links($content);
615 // If it's too long, try using the summary, and make the
616 // HTML an attachment.
620 if (Notice::contentTooLong($shortened)) {
621 $attachment = $this->saveHTMLFile($activity->title, $rendered);
622 $summary = html_entity_decode(strip_tags($activity->summary), ENT_QUOTES, 'UTF-8');
623 if (empty($summary)) {
626 $shortSummary = common_shorten_links($summary);
627 if (Notice::contentTooLong($shortSummary)) {
628 $url = common_shorten_url($sourceUrl);
629 $shortSummary = substr($shortSummary,
631 Notice::maxContent() - (mb_strlen($url) + 2));
632 $content = $shortSummary . ' ' . $url;
634 // We mark up the attachment link specially for the HTML output
635 // so we can fold-out the full version inline.
637 // @todo FIXME i18n: This tooltip will be saved with the site's default language
638 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
639 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
640 $showMoreText = _m('Show more');
641 $attachUrl = common_local_url('attachment',
642 array('attachment' => $attachment->id));
643 $rendered = common_render_text($shortSummary) .
644 '<a href="' . htmlspecialchars($attachUrl) .'"'.
645 ' class="attachment more"' .
646 ' title="'. htmlspecialchars($showMoreText) . '">' .
652 $options = array('is_local' => Notice::REMOTE,
654 'uri' => $activity->id,
655 'rendered' => $rendered,
656 'replies' => array(),
658 'peopletags' => array(),
661 'repeat_of' => $sharedNotice->id,
662 'scope' => $sharedNotice->scope);
664 // Check for optional attributes...
666 if (!empty($activity->time)) {
667 $options['created'] = common_sql_date($activity->time);
670 if ($activity->context) {
671 // TODO: context->attention
672 list($options['groups'], $options['replies'])
673 = self::filterAttention($oprofile->localProfile(), $activity->context->attention);
675 // Maintain direct reply associations
676 // @todo FIXME: What about conversation ID?
677 if (!empty($activity->context->replyToID)) {
678 $orig = Notice::getKV('uri',
679 $activity->context->replyToID);
680 if ($orig instanceof Notice) {
681 $options['reply_to'] = $orig->id;
685 $location = $activity->context->location;
687 $options['lat'] = $location->lat;
688 $options['lon'] = $location->lon;
689 if ($location->location_id) {
690 $options['location_ns'] = $location->location_ns;
691 $options['location_id'] = $location->location_id;
696 if ($this->isPeopletag()) {
697 $options['peopletags'][] = $this->localPeopletag();
700 // Atom categories <-> hashtags
701 foreach ($activity->categories as $cat) {
703 $term = common_canonical_tag($cat->term);
705 $options['tags'][] = $term;
710 // Atom enclosures -> attachment URLs
711 foreach ($activity->enclosures as $href) {
712 // @todo FIXME: Save these locally or....?
713 $options['urls'][] = $href;
716 $notice = Notice::saveNew($oprofile->profile_id,
725 * Process an incoming post activity from this remote feed.
726 * @param Activity $activity
727 * @param string $method 'push' or 'salmon'
728 * @return mixed saved Notice or false
729 * @todo FIXME: Break up this function, it's getting nasty long
731 public function processPost($activity, $method)
735 $oprofile = $this->checkAuthorship($activity);
737 if (!$oprofile instanceof Ostatus_profile) {
741 // It's not always an ActivityObject::NOTE, but... let's just say it is.
743 $note = $activity->objects[0];
745 // The id URI will be used as a unique identifier for the notice,
746 // protecting against duplicate saves. It isn't required to be a URL;
747 // tag: URIs for instance are found in Google Buzz feeds.
748 $sourceUri = $note->id;
749 $dupe = Notice::getKV('uri', $sourceUri);
750 if ($dupe instanceof Notice) {
751 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
755 // We'll also want to save a web link to the original notice, if provided.
758 $sourceUrl = $note->link;
759 } else if ($activity->link) {
760 $sourceUrl = $activity->link;
761 } else if (preg_match('!^https?://!', $note->id)) {
762 $sourceUrl = $note->id;
765 // Use summary as fallback for content
767 if (!empty($note->content)) {
768 $sourceContent = $note->content;
769 } else if (!empty($note->summary)) {
770 $sourceContent = $note->summary;
771 } else if (!empty($note->title)) {
772 $sourceContent = $note->title;
774 // @todo FIXME: Fetch from $sourceUrl?
775 // TRANS: Client exception. %s is a source URI.
776 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
779 // Get (safe!) HTML and text versions of the content
781 $rendered = $this->purify($sourceContent);
782 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
784 $shortened = common_shorten_links($content);
786 // If it's too long, try using the summary, and make the
787 // HTML an attachment.
791 if (Notice::contentTooLong($shortened)) {
792 $attachment = $this->saveHTMLFile($note->title, $rendered);
793 $summary = html_entity_decode(strip_tags($note->summary), ENT_QUOTES, 'UTF-8');
794 if (empty($summary)) {
797 $shortSummary = common_shorten_links($summary);
798 if (Notice::contentTooLong($shortSummary)) {
799 $url = common_shorten_url($sourceUrl);
800 $shortSummary = substr($shortSummary,
802 Notice::maxContent() - (mb_strlen($url) + 2));
803 $content = $shortSummary . ' ' . $url;
805 // We mark up the attachment link specially for the HTML output
806 // so we can fold-out the full version inline.
808 // @todo FIXME i18n: This tooltip will be saved with the site's default language
809 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
810 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
811 $showMoreText = _m('Show more');
812 $attachUrl = common_local_url('attachment',
813 array('attachment' => $attachment->id));
814 $rendered = common_render_text($shortSummary) .
815 '<a href="' . htmlspecialchars($attachUrl) .'"'.
816 ' class="attachment more"' .
817 ' title="'. htmlspecialchars($showMoreText) . '">' .
823 $options = array('is_local' => Notice::REMOTE,
826 'rendered' => $rendered,
827 'replies' => array(),
829 'peopletags' => array(),
833 // Check for optional attributes...
835 if (!empty($activity->time)) {
836 $options['created'] = common_sql_date($activity->time);
839 if ($activity->context) {
840 // TODO: context->attention
841 list($options['groups'], $options['replies'])
842 = self::filterAttention($oprofile->localProfile(), $activity->context->attention);
844 // Maintain direct reply associations
845 // @todo FIXME: What about conversation ID?
846 if (!empty($activity->context->replyToID)) {
847 $orig = Notice::getKV('uri', $activity->context->replyToID);
848 if ($orig instanceof Notice) {
849 $options['reply_to'] = $orig->id;
853 $location = $activity->context->location;
855 $options['lat'] = $location->lat;
856 $options['lon'] = $location->lon;
857 if ($location->location_id) {
858 $options['location_ns'] = $location->location_ns;
859 $options['location_id'] = $location->location_id;
864 if ($this->isPeopletag()) {
865 $options['peopletags'][] = $this->localPeopletag();
868 // Atom categories <-> hashtags
869 foreach ($activity->categories as $cat) {
871 $term = common_canonical_tag($cat->term);
873 $options['tags'][] = $term;
878 // Atom enclosures -> attachment URLs
879 foreach ($activity->enclosures as $href) {
880 // @todo FIXME: Save these locally or....?
881 $options['urls'][] = $href;
885 $saved = Notice::saveNew($oprofile->profile_id,
889 if ($saved instanceof Notice) {
890 Ostatus_source::saveNew($saved, $this, $method);
891 if (!empty($attachment)) {
892 File_to_post::processNew($attachment->id, $saved->id);
895 } catch (Exception $e) {
896 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
899 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
906 protected function purify($html)
908 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
909 $config = array('safe' => 1,
910 'deny_attribute' => 'id,style,on*');
911 return htmLawed($html, $config);
915 * Filters a list of recipient ID URIs to just those for local delivery.
916 * @param Profile local profile of sender
917 * @param array in/out &$attention_uris set of URIs, will be pruned on output
918 * @return array of group IDs
920 static public function filterAttention(Profile $sender, array $attention)
922 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
925 foreach ($attention as $recipient=>$type) {
926 // Is the recipient a local user?
927 $user = User::getKV('uri', $recipient);
928 if ($user instanceof User) {
929 // @todo FIXME: Sender verification, spam etc?
930 $replies[] = $recipient;
934 // Is the recipient a local group?
935 // TODO: $group = User_group::getKV('uri', $recipient);
936 $id = OStatusPlugin::localGroupFromUrl($recipient);
938 $group = User_group::getKV('id', $id);
939 if ($group instanceof User_group) {
940 // Deliver to all members of this local group if allowed.
941 if ($sender->isMember($group)) {
942 $groups[] = $group->id;
944 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
948 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
952 // Is the recipient a remote user or group?
954 $oprofile = self::ensureProfileURI($recipient);
955 if ($oprofile->isGroup()) {
956 // Deliver to local members of this remote group.
957 // @todo FIXME: Sender verification?
958 $groups[] = $oprofile->group_id;
960 // may be canonicalized or something
961 $replies[] = $oprofile->getUri();
964 } catch (Exception $e) {
965 // Neither a recognizable local nor remote user!
966 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
970 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
971 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
972 return array($groups, $replies);
976 * Look up and if necessary create an Ostatus_profile for the remote entity
977 * with the given profile page URL. This should never return null -- you
978 * will either get an object or an exception will be thrown.
980 * @param string $profile_url
981 * @return Ostatus_profile
982 * @throws Exception on various error conditions
983 * @throws OStatusShadowException if this reference would obscure a local user/group
985 public static function ensureProfileURL($profile_url, $hints=array())
987 $oprofile = self::getFromProfileURL($profile_url);
989 if ($oprofile instanceof Ostatus_profile) {
993 $hints['profileurl'] = $profile_url;
998 $client = new HTTPClient();
999 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
1000 $response = $client->get($profile_url);
1002 if (!$response->isOk()) {
1003 // TRANS: Exception. %s is a profile URL.
1004 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
1007 // Check if we have a non-canonical URL
1009 $finalUrl = $response->getUrl();
1011 if ($finalUrl != $profile_url) {
1013 $hints['profileurl'] = $finalUrl;
1015 $oprofile = self::getFromProfileURL($finalUrl);
1017 if ($oprofile instanceof Ostatus_profile) {
1022 // Try to get some hCard data
1024 $body = $response->getBody();
1026 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1028 if (!empty($hcardHints)) {
1029 $hints = array_merge($hints, $hcardHints);
1032 // Check if they've got an LRDD header
1034 $lrdd = LinkHeader::getLink($response, 'lrdd');
1036 $xrd = new XML_XRD();
1037 $xrd->loadFile($lrdd);
1038 $xrdHints = DiscoveryHints::fromXRD($xrd);
1039 $hints = array_merge($hints, $xrdHints);
1040 } catch (Exception $e) {
1041 // No hints available from XRD
1044 // If discovery found a feedurl (probably from LRDD), use it.
1046 if (array_key_exists('feedurl', $hints)) {
1047 return self::ensureFeedURL($hints['feedurl'], $hints);
1050 // Get the feed URL from HTML
1052 $discover = new FeedDiscovery();
1054 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1056 if (!empty($feedurl)) {
1057 $hints['feedurl'] = $feedurl;
1058 return self::ensureFeedURL($feedurl, $hints);
1061 // TRANS: Exception. %s is a URL.
1062 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1066 * Look up the Ostatus_profile, if present, for a remote entity with the
1067 * given profile page URL. Will return null for both unknown and invalid
1070 * @return mixed Ostatus_profile or null
1071 * @throws OStatusShadowException for local profiles
1073 static function getFromProfileURL($profile_url)
1075 $profile = Profile::getKV('profileurl', $profile_url);
1076 if (!$profile instanceof Profile) {
1080 // Is it a known Ostatus profile?
1081 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1082 if ($oprofile instanceof Ostatus_profile) {
1086 // Is it a local user?
1087 $user = User::getKV('id', $profile->id);
1088 if ($user instanceof User) {
1089 // @todo i18n FIXME: use sprintf and add i18n (?)
1090 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1093 // Continue discovery; it's a remote profile
1094 // for OMB or some other protocol, may also
1101 * Look up and if necessary create an Ostatus_profile for remote entity
1102 * with the given update feed. This should never return null -- you will
1103 * either get an object or an exception will be thrown.
1105 * @return Ostatus_profile
1108 public static function ensureFeedURL($feed_url, $hints=array())
1110 $discover = new FeedDiscovery();
1112 $feeduri = $discover->discoverFromFeedURL($feed_url);
1113 $hints['feedurl'] = $feeduri;
1115 $huburi = $discover->getHubLink();
1116 $hints['hub'] = $huburi;
1118 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1119 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1120 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1121 $hints['salmon'] = $salmonuri;
1123 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1124 // We can only deal with folks with a PuSH hub
1125 throw new FeedSubNoHubException();
1128 $feedEl = $discover->root;
1130 if ($feedEl->tagName == 'feed') {
1131 return self::ensureAtomFeed($feedEl, $hints);
1132 } else if ($feedEl->tagName == 'channel') {
1133 return self::ensureRssChannel($feedEl, $hints);
1135 throw new FeedSubBadXmlException($feeduri);
1140 * Look up and, if necessary, create an Ostatus_profile for the remote
1141 * profile with the given Atom feed - actually loaded from the feed.
1142 * This should never return null -- you will either get an object or
1143 * an exception will be thrown.
1145 * @param DOMElement $feedEl root element of a loaded Atom feed
1146 * @param array $hints additional discovery information passed from higher levels
1147 * @todo FIXME: Should this be marked public?
1148 * @return Ostatus_profile
1151 public static function ensureAtomFeed($feedEl, $hints)
1153 $author = ActivityUtils::getFeedAuthor($feedEl);
1155 if (empty($author)) {
1156 // XXX: make some educated guesses here
1157 // TRANS: Feed sub exception.
1158 throw new FeedSubException(_m('Cannot find enough profile '.
1159 'information to make a feed.'));
1162 return self::ensureActivityObjectProfile($author, $hints);
1166 * Look up and, if necessary, create an Ostatus_profile for the remote
1167 * profile with the given RSS feed - actually loaded from the feed.
1168 * This should never return null -- you will either get an object or
1169 * an exception will be thrown.
1171 * @param DOMElement $feedEl root element of a loaded RSS feed
1172 * @param array $hints additional discovery information passed from higher levels
1173 * @todo FIXME: Should this be marked public?
1174 * @return Ostatus_profile
1177 public static function ensureRssChannel($feedEl, $hints)
1179 // Special-case for Posterous. They have some nice metadata in their
1180 // posterous:author elements. We should use them instead of the channel.
1182 $items = $feedEl->getElementsByTagName('item');
1184 if ($items->length > 0) {
1185 $item = $items->item(0);
1186 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1187 if (!empty($authorEl)) {
1188 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1189 // Posterous has multiple authors per feed, and multiple feeds
1190 // per author. We check if this is the "main" feed for this author.
1191 if (array_key_exists('profileurl', $hints) &&
1192 !empty($obj->poco) &&
1193 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1194 return self::ensureActivityObjectProfile($obj, $hints);
1199 // @todo FIXME: We should check whether this feed has elements
1200 // with different <author> or <dc:creator> elements, and... I dunno.
1201 // Do something about that.
1203 $obj = ActivityObject::fromRssChannel($feedEl);
1205 return self::ensureActivityObjectProfile($obj, $hints);
1209 * Download and update given avatar image
1211 * @param string $url
1212 * @throws Exception in various failure cases
1214 protected function updateAvatar($url)
1216 if ($url == $this->avatar) {
1217 // We've already got this one.
1220 if (!common_valid_http_url($url)) {
1221 // TRANS: Server exception. %s is a URL.
1222 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1225 if ($this->isGroup()) {
1226 // FIXME: throw exception for localGroup
1227 $self = $this->localGroup();
1229 // this throws an exception already
1230 $self = $this->localProfile();
1233 throw new ServerException(sprintf(
1234 // TRANS: Server exception. %s is a URI.
1235 _m('Tried to update avatar for unsaved remote profile %s.'),
1239 // @todo FIXME: This should be better encapsulated
1240 // ripped from oauthstore.php (for old OMB client)
1241 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1243 if (!copy($url, $temp_filename)) {
1244 // TRANS: Server exception. %s is a URL.
1245 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1248 if ($this->isGroup()) {
1249 $id = $this->group_id;
1251 $id = $this->profile_id;
1253 // @todo FIXME: Should we be using different ids?
1254 $imagefile = new ImageFile($id, $temp_filename);
1255 $filename = Avatar::filename($id,
1256 image_type_to_extension($imagefile->type),
1258 common_timestamp());
1259 rename($temp_filename, Avatar::path($filename));
1260 } catch (Exception $e) {
1261 unlink($temp_filename);
1264 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1265 // keep from accidentally saving images from command-line (queues)
1266 // that can't be read from web server, which causes hard-to-notice
1267 // problems later on:
1269 // http://status.net/open-source/issues/2663
1270 chmod(Avatar::path($filename), 0644);
1272 $self->setOriginal($filename);
1274 $orig = clone($this);
1275 $this->avatar = $url;
1276 $this->update($orig);
1280 * Pull avatar URL from ActivityObject or profile hints
1282 * @param ActivityObject $object
1283 * @param array $hints
1284 * @return mixed URL string or false
1286 public static function getActivityObjectAvatar($object, $hints=array())
1288 if ($object->avatarLinks) {
1290 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1291 foreach ($object->avatarLinks as $avatar) {
1292 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1297 if (!$best || $avatar->width > $best->width) {
1302 } else if (array_key_exists('avatar', $hints)) {
1303 return $hints['avatar'];
1309 * Get an appropriate avatar image source URL, if available.
1311 * @param ActivityObject $actor
1312 * @param DOMElement $feed
1315 protected static function getAvatar($actor, $feed)
1319 if ($actor->avatar) {
1320 $url = trim($actor->avatar);
1323 // Check <atom:logo> and <atom:icon> on the feed
1324 $els = $feed->childNodes();
1325 if ($els && $els->length) {
1326 for ($i = 0; $i < $els->length; $i++) {
1327 $el = $els->item($i);
1328 if ($el->namespaceURI == Activity::ATOM) {
1329 if (empty($url) && $el->localName == 'logo') {
1330 $url = trim($el->textContent);
1333 if (empty($icon) && $el->localName == 'icon') {
1334 // Use as a fallback
1335 $icon = trim($el->textContent);
1340 if ($icon && !$url) {
1345 $opts = array('allowed_schemes' => array('http', 'https'));
1346 if (common_valid_http_url($url)) {
1351 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1355 * Fetch, or build if necessary, an Ostatus_profile for the actor
1356 * in a given Activity Streams activity.
1357 * This should never return null -- you will either get an object or
1358 * an exception will be thrown.
1360 * @param Activity $activity
1361 * @param string $feeduri if we already know the canonical feed URI!
1362 * @param string $salmonuri if we already know the salmon return channel URI
1363 * @return Ostatus_profile
1366 public static function ensureActorProfile($activity, $hints=array())
1368 return self::ensureActivityObjectProfile($activity->actor, $hints);
1372 * Fetch, or build if necessary, an Ostatus_profile for the profile
1373 * in a given Activity Streams object (can be subject, actor, or object).
1374 * This should never return null -- you will either get an object or
1375 * an exception will be thrown.
1377 * @param ActivityObject $object
1378 * @param array $hints additional discovery information passed from higher levels
1379 * @return Ostatus_profile
1382 public static function ensureActivityObjectProfile($object, $hints=array())
1384 $profile = self::getActivityObjectProfile($object);
1385 if ($profile instanceof Ostatus_profile) {
1386 $profile->updateFromActivityObject($object, $hints);
1388 $profile = self::createActivityObjectProfile($object, $hints);
1394 * @param Activity $activity
1395 * @return mixed matching Ostatus_profile or false if none known
1396 * @throws ServerException if feed info invalid
1398 public static function getActorProfile($activity)
1400 return self::getActivityObjectProfile($activity->actor);
1404 * @param ActivityObject $activity
1405 * @return mixed matching Ostatus_profile or false if none known
1406 * @throws ServerException if feed info invalid
1408 protected static function getActivityObjectProfile($object)
1410 $uri = self::getActivityObjectProfileURI($object);
1411 return Ostatus_profile::getKV('uri', $uri);
1415 * Get the identifier URI for the remote entity described
1416 * by this ActivityObject. This URI is *not* guaranteed to be
1417 * a resolvable HTTP/HTTPS URL.
1419 * @param ActivityObject $object
1421 * @throws ServerException if feed info invalid
1423 protected static function getActivityObjectProfileURI($object)
1426 if (ActivityUtils::validateUri($object->id)) {
1431 // If the id is missing or invalid (we've seen feeds mistakenly listing
1432 // things like local usernames in that field) then we'll use the profile
1433 // page link, if valid.
1434 if ($object->link && common_valid_http_url($object->link)) {
1435 return $object->link;
1437 // TRANS: Server exception.
1438 throw new ServerException(_m('No author ID URI found.'));
1442 * @todo FIXME: Validate stuff somewhere.
1446 * Create local ostatus_profile and profile/user_group entries for
1447 * the provided remote user or group.
1448 * This should never return null -- you will either get an object or
1449 * an exception will be thrown.
1451 * @param ActivityObject $object
1452 * @param array $hints
1454 * @return Ostatus_profile
1456 protected static function createActivityObjectProfile($object, $hints=array())
1458 $homeuri = $object->id;
1462 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1463 // TRANS: Exception.
1464 throw new Exception(_m('No profile URI.'));
1467 $user = User::getKV('uri', $homeuri);
1468 if ($user instanceof User) {
1469 // TRANS: Exception.
1470 throw new Exception(_m('Local user cannot be referenced as remote.'));
1473 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1474 // TRANS: Exception.
1475 throw new Exception(_m('Local group cannot be referenced as remote.'));
1478 $ptag = Profile_list::getKV('uri', $homeuri);
1479 if ($ptag instanceof Profile_list) {
1480 $local_user = User::getKV('id', $ptag->tagger);
1481 if ($local_user instanceof User) {
1482 // TRANS: Exception.
1483 throw new Exception(_m('Local list cannot be referenced as remote.'));
1487 if (array_key_exists('feedurl', $hints)) {
1488 $feeduri = $hints['feedurl'];
1490 $discover = new FeedDiscovery();
1491 $feeduri = $discover->discoverFromURL($homeuri);
1494 if (array_key_exists('salmon', $hints)) {
1495 $salmonuri = $hints['salmon'];
1498 $discover = new FeedDiscovery();
1499 $discover->discoverFromFeedURL($hints['feedurl']);
1501 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1502 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1503 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1506 if (array_key_exists('hub', $hints)) {
1507 $huburi = $hints['hub'];
1510 $discover = new FeedDiscovery();
1511 $discover->discoverFromFeedURL($hints['feedurl']);
1513 $huburi = $discover->getHubLink();
1516 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1517 // We can only deal with folks with a PuSH hub
1518 throw new FeedSubNoHubException();
1521 $oprofile = new Ostatus_profile();
1523 $oprofile->uri = $homeuri;
1524 $oprofile->feeduri = $feeduri;
1525 $oprofile->salmonuri = $salmonuri;
1527 $oprofile->created = common_sql_now();
1528 $oprofile->modified = common_sql_now();
1530 if ($object->type == ActivityObject::PERSON) {
1531 $profile = new Profile();
1532 $profile->created = common_sql_now();
1533 self::updateProfile($profile, $object, $hints);
1535 $oprofile->profile_id = $profile->insert();
1536 if ($oprofile->profile_id === false) {
1537 // TRANS: Server exception.
1538 throw new ServerException(_m('Cannot save local profile.'));
1540 } else if ($object->type == ActivityObject::GROUP) {
1541 $profile = new Profile();
1542 $profile->query('BEGIN');
1544 $group = new User_group();
1545 $group->uri = $homeuri;
1546 $group->created = common_sql_now();
1547 self::updateGroup($group, $object, $hints);
1549 // TODO: We should do this directly in User_group->insert()!
1550 // currently it's duplicated in User_group->update()
1551 // AND User_group->register()!!!
1552 $fields = array(/*group field => profile field*/
1553 'nickname' => 'nickname',
1554 'fullname' => 'fullname',
1555 'mainpage' => 'profileurl',
1556 'homepage' => 'homepage',
1557 'description' => 'bio',
1558 'location' => 'location',
1559 'created' => 'created',
1560 'modified' => 'modified',
1562 foreach ($fields as $gf=>$pf) {
1563 $profile->$pf = $group->$gf;
1565 $profile_id = $profile->insert();
1566 if ($profile_id === false) {
1567 $profile->query('ROLLBACK');
1568 throw new ServerException(_('Profile insertion failed.'));
1571 $group->profile_id = $profile_id;
1573 $oprofile->group_id = $group->insert();
1574 if ($oprofile->group_id === false) {
1575 $profile->query('ROLLBACK');
1576 // TRANS: Server exception.
1577 throw new ServerException(_m('Cannot save local profile.'));
1580 $profile->query('COMMIT');
1581 } else if ($object->type == ActivityObject::_LIST) {
1582 $ptag = new Profile_list();
1583 $ptag->uri = $homeuri;
1584 $ptag->created = common_sql_now();
1585 self::updatePeopletag($ptag, $object, $hints);
1587 $oprofile->peopletag_id = $ptag->insert();
1588 if ($oprofile->peopletag_id === false) {
1589 // TRANS: Server exception.
1590 throw new ServerException(_m('Cannot save local list.'));
1594 $ok = $oprofile->insert();
1596 if ($ok === false) {
1597 // TRANS: Server exception.
1598 throw new ServerException(_m('Cannot save OStatus profile.'));
1601 $avatar = self::getActivityObjectAvatar($object, $hints);
1605 $oprofile->updateAvatar($avatar);
1606 } catch (Exception $ex) {
1607 // Profile is saved, but Avatar is messed up. We're
1608 // just going to continue.
1609 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1617 * Save any updated profile information to our local copy.
1618 * @param ActivityObject $object
1619 * @param array $hints
1621 public function updateFromActivityObject($object, $hints=array())
1623 if ($this->isGroup()) {
1624 $group = $this->localGroup();
1625 self::updateGroup($group, $object, $hints);
1626 } else if ($this->isPeopletag()) {
1627 $ptag = $this->localPeopletag();
1628 self::updatePeopletag($ptag, $object, $hints);
1630 $profile = $this->localProfile();
1631 self::updateProfile($profile, $object, $hints);
1634 $avatar = self::getActivityObjectAvatar($object, $hints);
1635 if ($avatar && !isset($ptag)) {
1637 $this->updateAvatar($avatar);
1638 } catch (Exception $ex) {
1639 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1644 public static function updateProfile($profile, $object, $hints=array())
1646 $orig = clone($profile);
1648 // Existing nickname is better than nothing.
1650 if (!array_key_exists('nickname', $hints)) {
1651 $hints['nickname'] = $profile->nickname;
1654 $nickname = self::getActivityObjectNickname($object, $hints);
1656 if (!empty($nickname)) {
1657 $profile->nickname = $nickname;
1660 if (!empty($object->title)) {
1661 $profile->fullname = $object->title;
1662 } else if (array_key_exists('fullname', $hints)) {
1663 $profile->fullname = $hints['fullname'];
1666 if (!empty($object->link)) {
1667 $profile->profileurl = $object->link;
1668 } else if (array_key_exists('profileurl', $hints)) {
1669 $profile->profileurl = $hints['profileurl'];
1670 } else if (common_valid_http_url($object->id)) {
1671 $profile->profileurl = $object->id;
1674 $bio = self::getActivityObjectBio($object, $hints);
1677 $profile->bio = $bio;
1680 $location = self::getActivityObjectLocation($object, $hints);
1682 if (!empty($location)) {
1683 $profile->location = $location;
1686 $homepage = self::getActivityObjectHomepage($object, $hints);
1688 if (!empty($homepage)) {
1689 $profile->homepage = $homepage;
1692 if (!empty($object->geopoint)) {
1693 $location = ActivityContext::locationFromPoint($object->geopoint);
1694 if (!empty($location)) {
1695 $profile->lat = $location->lat;
1696 $profile->lon = $location->lon;
1700 // @todo FIXME: tags/categories
1701 // @todo tags from categories
1704 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1705 $profile->update($orig);
1709 protected static function updateGroup(User_group $group, $object, $hints=array())
1711 $orig = clone($group);
1713 $group->nickname = self::getActivityObjectNickname($object, $hints);
1714 $group->fullname = $object->title;
1716 if (!empty($object->link)) {
1717 $group->mainpage = $object->link;
1718 } else if (array_key_exists('profileurl', $hints)) {
1719 $group->mainpage = $hints['profileurl'];
1722 // @todo tags from categories
1723 $group->description = self::getActivityObjectBio($object, $hints);
1724 $group->location = self::getActivityObjectLocation($object, $hints);
1725 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1727 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1728 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1729 $group->update($orig);
1733 protected static function updatePeopletag($tag, $object, $hints=array()) {
1734 $orig = clone($tag);
1736 $tag->tag = $object->title;
1738 if (!empty($object->link)) {
1739 $tag->mainpage = $object->link;
1740 } else if (array_key_exists('profileurl', $hints)) {
1741 $tag->mainpage = $hints['profileurl'];
1744 $tag->description = $object->summary;
1745 $tagger = self::ensureActivityObjectProfile($object->owner);
1746 $tag->tagger = $tagger->profile_id;
1749 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1750 $tag->update($orig);
1754 protected static function getActivityObjectHomepage($object, $hints=array())
1757 $poco = $object->poco;
1759 if (!empty($poco)) {
1760 $url = $poco->getPrimaryURL();
1761 if ($url && $url->type == 'homepage') {
1762 $homepage = $url->value;
1766 // @todo Try for a another PoCo URL?
1771 protected static function getActivityObjectLocation($object, $hints=array())
1775 if (!empty($object->poco) &&
1776 isset($object->poco->address->formatted)) {
1777 $location = $object->poco->address->formatted;
1778 } else if (array_key_exists('location', $hints)) {
1779 $location = $hints['location'];
1782 if (!empty($location)) {
1783 if (mb_strlen($location) > 255) {
1784 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1788 // @todo Try to find location some othe way? Via goerss point?
1793 protected static function getActivityObjectBio($object, $hints=array())
1797 if (!empty($object->poco)) {
1798 $note = $object->poco->note;
1799 } else if (array_key_exists('bio', $hints)) {
1800 $note = $hints['bio'];
1803 if (!empty($note)) {
1804 if (Profile::bioTooLong($note)) {
1805 // XXX: truncate ok?
1806 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1812 // @todo Try to get bio info some other way?
1817 public static function getActivityObjectNickname($object, $hints=array())
1819 if ($object->poco) {
1820 if (!empty($object->poco->preferredUsername)) {
1821 return common_nicknamize($object->poco->preferredUsername);
1825 if (!empty($object->nickname)) {
1826 return common_nicknamize($object->nickname);
1829 if (array_key_exists('nickname', $hints)) {
1830 return $hints['nickname'];
1833 // Try the profile url (like foo.example.com or example.com/user/foo)
1834 if (!empty($object->link)) {
1835 $profileUrl = $object->link;
1836 } else if (!empty($hints['profileurl'])) {
1837 $profileUrl = $hints['profileurl'];
1840 if (!empty($profileUrl)) {
1841 $nickname = self::nicknameFromURI($profileUrl);
1844 // Try the URI (may be a tag:, http:, acct:, ...
1846 if (empty($nickname)) {
1847 $nickname = self::nicknameFromURI($object->id);
1850 // Try a Webfinger if one was passed (way) down
1852 if (empty($nickname)) {
1853 if (array_key_exists('webfinger', $hints)) {
1854 $nickname = self::nicknameFromURI($hints['webfinger']);
1860 if (empty($nickname)) {
1861 $nickname = common_nicknamize($object->title);
1867 protected static function nicknameFromURI($uri)
1869 if (preg_match('/(\w+):/', $uri, $matches)) {
1870 $protocol = $matches[1];
1875 switch ($protocol) {
1878 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1879 return common_canonical_nickname($matches[1]);
1883 return common_url_to_nickname($uri);
1891 * Look up, and if necessary create, an Ostatus_profile for the remote
1892 * entity with the given webfinger address.
1893 * This should never return null -- you will either get an object or
1894 * an exception will be thrown.
1896 * @param string $addr webfinger address
1897 * @return Ostatus_profile
1898 * @throws Exception on error conditions
1899 * @throws OStatusShadowException if this reference would obscure a local user/group
1901 public static function ensureWebfinger($addr)
1903 // First, try the cache
1905 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1907 if ($uri !== false) {
1908 if (is_null($uri)) {
1909 // Negative cache entry
1910 // TRANS: Exception.
1911 throw new Exception(_m('Not a valid webfinger address.'));
1913 $oprofile = Ostatus_profile::getKV('uri', $uri);
1914 if ($oprofile instanceof Ostatus_profile) {
1919 // Try looking it up
1920 $oprofile = Ostatus_profile::getKV('uri', 'acct:'.$addr);
1922 if ($oprofile instanceof Ostatus_profile) {
1923 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1927 // Now, try some discovery
1929 $disco = new Discovery();
1932 $xrd = $disco->lookup($addr);
1933 } catch (Exception $e) {
1934 // Save negative cache entry so we don't waste time looking it up again.
1935 // @todo FIXME: Distinguish temporary failures?
1936 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1937 // TRANS: Exception.
1938 throw new Exception(_m('Not a valid webfinger address.'));
1941 $hints = array('webfinger' => $addr);
1943 $dhints = DiscoveryHints::fromXRD($xrd);
1945 $hints = array_merge($hints, $dhints);
1947 // If there's an Hcard, let's grab its info
1948 if (array_key_exists('hcard', $hints)) {
1949 if (!array_key_exists('profileurl', $hints) ||
1950 $hints['hcard'] != $hints['profileurl']) {
1951 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1952 $hints = array_merge($hcardHints, $hints);
1956 // If we got a feed URL, try that
1957 if (array_key_exists('feedurl', $hints)) {
1959 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1960 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1961 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1963 } catch (Exception $e) {
1964 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1969 // If we got a profile page, try that!
1970 if (array_key_exists('profileurl', $hints)) {
1972 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1973 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1974 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1976 } catch (OStatusShadowException $e) {
1977 // We've ended up with a remote reference to a local user or group.
1978 // @todo FIXME: Ideally we should be able to say who it was so we can
1979 // go back and refer to it the regular way
1981 } catch (Exception $e) {
1982 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1985 // @todo FIXME: This means an error discovering from profile page
1986 // may give us a corrupt entry using the webfinger URI, which
1987 // will obscure the correct page-keyed profile later on.
1994 if (array_key_exists('salmon', $hints)) {
1995 $salmonEndpoint = $hints['salmon'];
1997 // An account URL, a salmon endpoint, and a dream? Not much to go
1998 // on, but let's give it a try
2000 $uri = 'acct:'.$addr;
2002 $profile = new Profile();
2004 $profile->nickname = self::nicknameFromUri($uri);
2005 $profile->created = common_sql_now();
2007 if (isset($profileUrl)) {
2008 $profile->profileurl = $profileUrl;
2011 $profile_id = $profile->insert();
2013 if ($profile_id === false) {
2014 common_log_db_error($profile, 'INSERT', __FILE__);
2015 // TRANS: Exception. %s is a webfinger address.
2016 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2019 $oprofile = new Ostatus_profile();
2021 $oprofile->uri = $uri;
2022 $oprofile->salmonuri = $salmonEndpoint;
2023 $oprofile->profile_id = $profile_id;
2024 $oprofile->created = common_sql_now();
2026 if (isset($feedUrl)) {
2027 $profile->feeduri = $feedUrl;
2030 $result = $oprofile->insert();
2032 if ($result === false) {
2033 common_log_db_error($oprofile, 'INSERT', __FILE__);
2034 // TRANS: Exception. %s is a webfinger address.
2035 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2038 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
2042 // TRANS: Exception. %s is a webfinger address.
2043 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2047 * Store the full-length scrubbed HTML of a remote notice to an attachment
2048 * file on our server. We'll link to this at the end of the cropped version.
2050 * @param string $title plaintext for HTML page's title
2051 * @param string $rendered HTML fragment for HTML page's body
2054 function saveHTMLFile($title, $rendered)
2056 $final = sprintf("<!DOCTYPE html>\n" .
2058 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2059 '<title>%s</title>' .
2061 '<body>%s</body></html>',
2062 htmlspecialchars($title),
2065 $filename = File::filename($this->localProfile(),
2066 'ostatus', // ignored?
2069 $filepath = File::path($filename);
2071 file_put_contents($filepath, $final);
2075 $file->filename = $filename;
2076 $file->url = File::url($filename);
2077 $file->size = filesize($filepath);
2078 $file->date = time();
2079 $file->mimetype = 'text/html';
2081 $file_id = $file->insert();
2083 if ($file_id === false) {
2084 common_log_db_error($file, "INSERT", __FILE__);
2085 // TRANS: Server exception.
2086 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2092 static function ensureProfileURI($uri)
2096 // First, try to query it
2098 $oprofile = Ostatus_profile::getKV('uri', $uri);
2100 if ($oprofile instanceof Ostatus_profile) {
2104 // If unfound, do discovery stuff
2105 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2106 $protocol = $match[1];
2107 switch ($protocol) {
2110 $oprofile = self::ensureProfileURL($uri);
2115 $oprofile = self::ensureWebfinger($rest);
2118 // TRANS: Server exception.
2119 // TRANS: %1$s is a protocol, %2$s is a URI.
2120 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2126 // TRANS: Server exception. %s is a URI.
2127 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2133 function checkAuthorship($activity)
2135 if ($this->isGroup() || $this->isPeopletag()) {
2136 // A group or propletag feed will contain posts from multiple authors.
2137 $oprofile = self::ensureActorProfile($activity);
2138 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2139 // Groups can't post notices in StatusNet.
2140 common_log(LOG_WARNING,
2141 "OStatus: skipping post with group listed ".
2142 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
2146 $actor = $activity->actor;
2148 if (empty($actor)) {
2149 // OK here! assume the default
2150 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
2151 $this->updateFromActivityObject($actor);
2152 } else if ($actor->id) {
2153 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2154 // This isn't what we expect from mainline OStatus person feeds!
2155 // Group feeds go down another path, with different validation...
2156 // Most likely this is a plain ol' blog feed of some kind which
2157 // doesn't match our expectations. We'll take the entry, but ignore
2158 // the <author> info.
2159 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
2161 // Plain <author> without ActivityStreams actor info.
2162 // We'll just ignore this info for now and save the update under the feed's identity.
2173 * Exception indicating we've got a remote reference to a local user,
2174 * not a remote user!
2176 * If we can ue a local profile after all, it's available as $e->profile.
2178 class OStatusShadowException extends Exception
2183 * @param Profile $profile
2184 * @param string $message
2186 function __construct($profile, $message) {
2187 $this->profile = $profile;
2188 parent::__construct($message);