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 if ($this->isGroup()) {
92 return $this->localGroup()->getProfile();
95 $profile = Profile::getKV('id', $this->profile_id);
96 if ($profile instanceof Profile) {
99 throw new NoProfileException($this->profile_id);
103 * Fetch the StatusNet-side profile for this feed
106 public function localGroup()
108 if ($this->group_id) {
109 return User_group::getKV('id', $this->group_id);
115 * Fetch the StatusNet-side peopletag for this feed
118 public function localPeopletag()
120 if ($this->peopletag_id) {
121 return Profile_list::getKV('id', $this->peopletag_id);
127 * Returns an ActivityObject describing this remote user or group profile.
128 * Can then be used to generate Atom chunks.
130 * @return ActivityObject
132 function asActivityObject()
134 if ($this->isGroup()) {
135 return ActivityObject::fromGroup($this->localGroup());
136 } else if ($this->isPeopletag()) {
137 return ActivityObject::fromPeopletag($this->localPeopletag());
139 return $this->localProfile()->asActivityObject();
144 * Returns an XML string fragment with profile information as an
145 * Activity Streams noun object with the given element type.
147 * Assumes that 'activity' namespace has been previously defined.
149 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
151 * @param string $element one of 'actor', 'subject', 'object', 'target'
154 function asActivityNoun($element)
156 if ($this->isGroup()) {
157 $noun = ActivityObject::fromGroup($this->localGroup());
158 return $noun->asString('activity:' . $element);
159 } else if ($this->isPeopletag()) {
160 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
161 return $noun->asString('activity:' . $element);
163 $noun = $this->localProfile()->asActivityObject();
164 return $noun->asString('activity:' . $element);
169 * @return boolean true if this is a remote group
173 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
175 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
177 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
178 // TRANS: Server exception. %s is a URI
179 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
181 // TRANS: Server exception. %s is a URI
182 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
187 * @return boolean true if this is a remote peopletag
189 function isPeopletag()
191 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
193 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
195 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
196 // TRANS: Server exception. %s is a URI
197 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
199 // TRANS: Server exception. %s is a URI
200 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
205 * Send a subscription request to the hub for this feed.
206 * The hub will later send us a confirmation POST to /main/push/callback.
209 * @throws ServerException if feed state is not valid or subscription fails.
211 public function subscribe()
213 $feedsub = FeedSub::ensureFeed($this->feeduri);
214 if ($feedsub->sub_state == 'active') {
215 // Active subscription, we don't need to do anything.
219 // Inactive or we got left in an inconsistent state.
220 // Run a subscription request to make sure we're current!
221 return $feedsub->subscribe();
225 * Check if this remote profile has any active local subscriptions, and
226 * if not drop the PuSH subscription feed.
228 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
229 * @throws Exception of various kinds on failure.
231 public function unsubscribe() {
232 return $this->garbageCollect();
236 * Check if this remote profile has any active local subscriptions, and
237 * if not drop the PuSH subscription feed.
239 * @return boolean true if subscription is removed, false if there are still subscribers to the feed
240 * @throws Exception of various kinds on failure.
242 public function garbageCollect()
244 $feedsub = FeedSub::getKV('uri', $this->feeduri);
245 if ($feedsub instanceof FeedSub) {
246 return $feedsub->garbageCollect();
248 // Since there's no FeedSub we can assume it's already garbage collected
253 * Check if this remote profile has any active local subscriptions, so the
254 * PuSH subscription layer can decide if it can drop the feed.
256 * This gets called via the FeedSubSubscriberCount event when running
257 * FeedSub::garbageCollect().
260 * @throws NoProfileException if there is no local profile for the object
262 public function subscriberCount()
264 if ($this->isGroup()) {
265 $members = $this->localGroup()->getMembers(0, 1);
266 $count = $members->N;
267 } else if ($this->isPeopletag()) {
268 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
269 $count = $subscribers->N;
271 $profile = $this->localProfile();
272 if ($profile->hasLocalTags()) {
275 $count = $profile->subscriberCount();
278 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
280 // Other plugins may be piggybacking on OStatus without having
281 // an active group or user-to-user subscription we know about.
282 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
283 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
289 * Send an Activity Streams notification to the remote Salmon endpoint,
292 * @param Profile $actor Actor who did the activity
293 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
294 * @param Object $object object of the action; must define asActivityNoun($tag)
296 public function notify(Profile $actor, $verb, $object=null, $target=null)
298 if ($object == null) {
301 if (empty($this->salmonuri)) {
305 $id = TagURI::mint('%s:%s:%s',
308 common_date_iso8601(time()));
310 // @todo FIXME: Consolidate all these NS settings somewhere.
311 $attributes = array('xmlns' => Activity::ATOM,
312 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
313 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
314 'xmlns:georss' => 'http://www.georss.org/georss',
315 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
316 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
317 'xmlns:media' => 'http://purl.org/syndication/atommedia');
319 $entry = new XMLStringer();
320 $entry->elementStart('entry', $attributes);
321 $entry->element('id', null, $id);
322 $entry->element('title', null, $text);
323 $entry->element('summary', null, $text);
324 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
326 $entry->element('activity:verb', null, $verb);
327 $entry->raw($actor->asAtomAuthor());
328 $entry->raw($actor->asActivityActor());
329 $entry->raw($object->asActivityNoun('object'));
330 if ($target != null) {
331 $entry->raw($target->asActivityNoun('target'));
333 $entry->elementEnd('entry');
335 $xml = $entry->getString();
336 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
338 Salmon::post($this->salmonuri, $xml, $actor->getUser());
342 * Send a Salmon notification ping immediately, and confirm that we got
343 * an acceptable response from the remote site.
345 * @param mixed $entry XML string, Notice, or Activity
346 * @param Profile $actor
347 * @return boolean success
349 public function notifyActivity($entry, Profile $actor)
351 if ($this->salmonuri) {
352 return Salmon::post($this->salmonuri, $this->notifyPrepXml($entry), $actor->getUser());
354 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
360 * Queue a Salmon notification for later. If queues are disabled we'll
361 * send immediately but won't get the return value.
363 * @param mixed $entry XML string, Notice, or Activity
364 * @return boolean success
366 public function notifyDeferred($entry, $actor)
368 if ($this->salmonuri) {
369 $data = array('salmonuri' => $this->salmonuri,
370 'entry' => $this->notifyPrepXml($entry),
371 'actor' => $actor->id);
373 $qm = QueueManager::get();
374 return $qm->enqueue($data, 'salmon');
380 protected function notifyPrepXml($entry)
382 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
383 if (is_string($entry)) {
385 } else if ($entry instanceof Activity) {
386 return $preamble . $entry->asString(true);
387 } else if ($entry instanceof Notice) {
388 return $preamble . $entry->asAtomEntry(true, true);
390 // TRANS: Server exception.
391 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
395 function getBestName()
397 if ($this->isGroup()) {
398 return $this->localGroup()->getBestName();
399 } else if ($this->isPeopletag()) {
400 return $this->localPeopletag()->getBestName();
402 return $this->localProfile()->getBestName();
407 * Read and post notices for updates from the feed.
408 * Currently assumes that all items in the feed are new,
409 * coming from a PuSH hub.
411 * @param DOMDocument $doc
412 * @param string $source identifier ("push")
414 public function processFeed(DOMDocument $doc, $source)
416 $feed = $doc->documentElement;
418 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
419 $this->processAtomFeed($feed, $source);
420 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
421 $this->processRssFeed($feed, $source);
424 throw new Exception(_m('Unknown feed format.'));
428 public function processAtomFeed(DOMElement $feed, $source)
430 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
431 if ($entries->length == 0) {
432 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
436 for ($i = 0; $i < $entries->length; $i++) {
437 $entry = $entries->item($i);
438 $this->processEntry($entry, $feed, $source);
442 public function processRssFeed(DOMElement $rss, $source)
444 $channels = $rss->getElementsByTagName('channel');
446 if ($channels->length == 0) {
448 throw new Exception(_m('RSS feed without a channel.'));
449 } else if ($channels->length > 1) {
450 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
453 $channel = $channels->item(0);
455 $items = $channel->getElementsByTagName('item');
457 for ($i = 0; $i < $items->length; $i++) {
458 $item = $items->item($i);
459 $this->processEntry($item, $channel, $source);
464 * Process a posted entry from this feed source.
466 * @param DOMElement $entry
467 * @param DOMElement $feed for context
468 * @param string $source identifier ("push" or "salmon")
470 * @return Notice Notice representing the new (or existing) activity
472 public function processEntry($entry, $feed, $source)
474 $activity = new Activity($entry, $feed);
475 return $this->processActivity($activity, $source);
478 // TODO: Make this throw an exception
479 public function processActivity($activity, $source)
483 // The "WithProfile" events were added later.
485 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this->localProfile(), &$notice)) &&
486 Event::handle('StartHandleFeedEntry', array($activity))) {
488 switch ($activity->verb) {
489 case ActivityVerb::POST:
490 // @todo process all activity objects
491 switch ($activity->objects[0]->type) {
492 case ActivityObject::ARTICLE:
493 case ActivityObject::BLOGENTRY:
494 case ActivityObject::NOTE:
495 case ActivityObject::STATUS:
496 case ActivityObject::COMMENT:
498 $notice = $this->processPost($activity, $source);
501 // TRANS: Client exception.
502 throw new ClientException(_m('Cannot handle that kind of post.'));
505 case ActivityVerb::SHARE:
506 $notice = $this->processShare($activity, $source);
509 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
512 Event::handle('EndHandleFeedEntry', array($activity));
513 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
519 public function processShare($activity, $method)
524 $profile = ActivityUtils::checkAuthorship($activity, $this->localProfile());
525 } catch (ServerException $e) {
529 // The id URI will be used as a unique identifier for the notice,
530 // protecting against duplicate saves. It isn't required to be a URL;
531 // tag: URIs for instance are found in Google Buzz feeds.
532 $dupe = Notice::getKV('uri', $activity->id);
533 if ($dupe instanceof Notice) {
534 common_log(LOG_INFO, "OStatus: ignoring duplicate post: {$activity->id}");
538 if (count($activity->objects) != 1) {
539 // TRANS: Client exception thrown when trying to share multiple activities at once.
540 throw new ClientException(_m('Can only handle share activities with exactly one object.'));
543 $shared = $activity->objects[0];
545 if (!$shared instanceof Activity) {
546 // TRANS: Client exception thrown when trying to share a non-activity object.
547 throw new ClientException(_m('Can only handle shared activities.'));
550 $sharedId = $shared->id;
551 if (!empty($shared->objects[0]->id)) {
552 // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
553 // fucks up federation, because the URI is no longer recognised by the origin.
554 // So we set it to the object ID if it exists, otherwise we trust $shared->id
555 $sharedId = $shared->objects[0]->id;
557 if (empty($sharedId)) {
558 throw new ClientException(_m('Shared activity does not have an id'));
561 // First check if we have the shared activity. This has to be done first, because
562 // we can't use these functions to "ensureActivityObjectProfile" of a local user,
563 // who might be the creator of the shared activity in question.
564 $sharedNotice = Notice::getKV('uri', $sharedId);
565 if (!$sharedNotice instanceof Notice) {
566 // If no locally stored notice is found, process it!
567 // TODO: Remember to check Deleted_notice!
568 // TODO: If a post is shared that we can't retrieve - what to do?
570 $other = self::ensureActivityObjectProfile($shared->actor);
571 $sharedNotice = $other->processActivity($shared, $method);
572 if (!$sharedNotice instanceof Notice) {
573 // And if we apparently can't get the shared notice, we'll abort the whole thing.
574 // TRANS: Client exception thrown when saving an activity share fails.
575 // TRANS: %s is a share ID.
576 throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedId));
578 } catch (FeedSubException $e) {
579 // Remote feed could not be found or verified, should we
580 // transform this into an "RT @user Blah, blah, blah..."?
581 common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
586 // We'll want to save a web link to the original notice, if provided.
589 if ($activity->link) {
590 $sourceUrl = $activity->link;
591 } else if ($activity->link) {
592 $sourceUrl = $activity->link;
593 } else if (preg_match('!^https?://!', $activity->id)) {
594 $sourceUrl = $activity->id;
597 // Use summary as fallback for content
599 if (!empty($activity->content)) {
600 $sourceContent = $activity->content;
601 } else if (!empty($activity->summary)) {
602 $sourceContent = $activity->summary;
603 } else if (!empty($activity->title)) {
604 $sourceContent = $activity->title;
606 // @todo FIXME: Fetch from $sourceUrl?
607 // TRANS: Client exception. %s is a source URI.
608 throw new ClientException(sprintf(_m('No content for notice %s.'), $activity->id));
611 // Get (safe!) HTML and text versions of the content
613 $rendered = $this->purify($sourceContent);
614 $content = common_strip_html($rendered);
616 $shortened = common_shorten_links($content);
618 // If it's too long, try using the summary, and make the
619 // HTML an attachment.
623 if (Notice::contentTooLong($shortened)) {
624 $attachment = $this->saveHTMLFile($activity->title, $rendered);
625 $summary = common_strip_html($activity->summary);
626 if (empty($summary)) {
629 $shortSummary = common_shorten_links($summary);
630 if (Notice::contentTooLong($shortSummary)) {
631 $url = common_shorten_url($sourceUrl);
632 $shortSummary = substr($shortSummary,
634 Notice::maxContent() - (mb_strlen($url) + 2));
635 $content = $shortSummary . ' ' . $url;
637 // We mark up the attachment link specially for the HTML output
638 // so we can fold-out the full version inline.
640 // @todo FIXME i18n: This tooltip will be saved with the site's default language
641 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
642 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
643 $showMoreText = _m('Show more');
644 $attachUrl = common_local_url('attachment',
645 array('attachment' => $attachment->id));
646 $rendered = common_render_text($shortSummary) .
647 '<a href="' . htmlspecialchars($attachUrl) .'"'.
648 ' class="attachment more"' .
649 ' title="'. htmlspecialchars($showMoreText) . '">' .
655 $options = array('is_local' => Notice::REMOTE,
657 'uri' => $activity->id,
658 'rendered' => $rendered,
659 'replies' => array(),
661 'peopletags' => array(),
664 'repeat_of' => $sharedNotice->id,
665 'scope' => $sharedNotice->scope);
667 // Check for optional attributes...
669 if (!empty($activity->time)) {
670 $options['created'] = common_sql_date($activity->time);
673 if ($activity->context) {
674 // TODO: context->attention
675 list($options['groups'], $options['replies'])
676 = self::filterAttention($profile, $activity->context->attention);
678 // Maintain direct reply associations
679 // @todo FIXME: What about conversation ID?
680 if (!empty($activity->context->replyToID)) {
681 $orig = Notice::getKV('uri',
682 $activity->context->replyToID);
683 if ($orig instanceof Notice) {
684 $options['reply_to'] = $orig->id;
688 $location = $activity->context->location;
690 $options['lat'] = $location->lat;
691 $options['lon'] = $location->lon;
692 if ($location->location_id) {
693 $options['location_ns'] = $location->location_ns;
694 $options['location_id'] = $location->location_id;
699 if ($this->isPeopletag()) {
700 $options['peopletags'][] = $this->localPeopletag();
703 // Atom categories <-> hashtags
704 foreach ($activity->categories as $cat) {
706 $term = common_canonical_tag($cat->term);
708 $options['tags'][] = $term;
713 // Atom enclosures -> attachment URLs
714 foreach ($activity->enclosures as $href) {
715 // @todo FIXME: Save these locally or....?
716 $options['urls'][] = $href;
719 $notice = Notice::saveNew($profile->id,
728 * Process an incoming post activity from this remote feed.
729 * @param Activity $activity
730 * @param string $method 'push' or 'salmon'
731 * @return mixed saved Notice or false
732 * @todo FIXME: Break up this function, it's getting nasty long
734 public function processPost($activity, $method)
738 $profile = ActivityUtils::checkAuthorship($activity, $this->localProfile());
740 // It's not always an ActivityObject::NOTE, but... let's just say it is.
742 $note = $activity->objects[0];
744 // The id URI will be used as a unique identifier for the notice,
745 // protecting against duplicate saves. It isn't required to be a URL;
746 // tag: URIs for instance are found in Google Buzz feeds.
747 $sourceUri = $note->id;
748 $dupe = Notice::getKV('uri', $sourceUri);
749 if ($dupe instanceof Notice) {
750 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
754 // We'll also want to save a web link to the original notice, if provided.
757 $sourceUrl = $note->link;
758 } else if ($activity->link) {
759 $sourceUrl = $activity->link;
760 } else if (preg_match('!^https?://!', $note->id)) {
761 $sourceUrl = $note->id;
764 // Use summary as fallback for content
766 if (!empty($note->content)) {
767 $sourceContent = $note->content;
768 } else if (!empty($note->summary)) {
769 $sourceContent = $note->summary;
770 } else if (!empty($note->title)) {
771 $sourceContent = $note->title;
773 // @todo FIXME: Fetch from $sourceUrl?
774 // TRANS: Client exception. %s is a source URI.
775 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
778 // Get (safe!) HTML and text versions of the content
780 $rendered = $this->purify($sourceContent);
781 $content = common_strip_html($rendered);
783 $shortened = common_shorten_links($content);
785 // If it's too long, try using the summary, and make the
786 // HTML an attachment.
790 if (Notice::contentTooLong($shortened)) {
791 $attachment = $this->saveHTMLFile($note->title, $rendered);
792 $summary = common_strip_html($note->summary);
793 if (empty($summary)) {
796 $shortSummary = common_shorten_links($summary);
797 if (Notice::contentTooLong($shortSummary)) {
798 $url = common_shorten_url($sourceUrl);
799 $shortSummary = substr($shortSummary,
801 Notice::maxContent() - (mb_strlen($url) + 2));
802 $content = $shortSummary . ' ' . $url;
804 // We mark up the attachment link specially for the HTML output
805 // so we can fold-out the full version inline.
807 // @todo FIXME i18n: This tooltip will be saved with the site's default language
808 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
809 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
810 $showMoreText = _m('Show more');
811 $attachUrl = common_local_url('attachment',
812 array('attachment' => $attachment->id));
813 $rendered = common_render_text($shortSummary) .
814 '<a href="' . htmlspecialchars($attachUrl) .'"'.
815 ' class="attachment more"' .
816 ' title="'. htmlspecialchars($showMoreText) . '">' .
822 $options = array('is_local' => Notice::REMOTE,
825 'rendered' => $rendered,
826 'replies' => array(),
828 'peopletags' => array(),
832 // Check for optional attributes...
834 if (!empty($activity->time)) {
835 $options['created'] = common_sql_date($activity->time);
838 if ($activity->context) {
839 // TODO: context->attention
840 list($options['groups'], $options['replies'])
841 = self::filterAttention($profile, $activity->context->attention);
843 // Maintain direct reply associations
844 // @todo FIXME: What about conversation ID?
845 if (!empty($activity->context->replyToID)) {
846 $orig = Notice::getKV('uri', $activity->context->replyToID);
847 if ($orig instanceof Notice) {
848 $options['reply_to'] = $orig->id;
851 if (!empty($activity->context->conversation)) {
852 // we store the URI here, Notice class can look it up later
853 $options['conversation'] = $activity->context->conversation;
856 $location = $activity->context->location;
858 $options['lat'] = $location->lat;
859 $options['lon'] = $location->lon;
860 if ($location->location_id) {
861 $options['location_ns'] = $location->location_ns;
862 $options['location_id'] = $location->location_id;
867 if ($this->isPeopletag()) {
868 $options['peopletags'][] = $this->localPeopletag();
871 // Atom categories <-> hashtags
872 foreach ($activity->categories as $cat) {
874 $term = common_canonical_tag($cat->term);
876 $options['tags'][] = $term;
881 // Atom enclosures -> attachment URLs
882 foreach ($activity->enclosures as $href) {
883 // @todo FIXME: Save these locally or....?
884 $options['urls'][] = $href;
888 $saved = Notice::saveNew($profile->id,
892 if ($saved instanceof Notice) {
893 Ostatus_source::saveNew($saved, $this, $method);
894 if (!empty($attachment)) {
895 File_to_post::processNew($attachment->id, $saved->id);
898 } catch (Exception $e) {
899 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
902 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
909 protected function purify($html)
911 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
912 $config = array('safe' => 1,
913 'deny_attribute' => 'id,style,on*');
914 return htmLawed($html, $config);
918 * Filters a list of recipient ID URIs to just those for local delivery.
919 * @param Profile local profile of sender
920 * @param array in/out &$attention_uris set of URIs, will be pruned on output
921 * @return array of group IDs
923 static public function filterAttention(Profile $sender, array $attention)
925 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
928 foreach ($attention as $recipient=>$type) {
929 // Is the recipient a local user?
930 $user = User::getKV('uri', $recipient);
931 if ($user instanceof User) {
932 // @todo FIXME: Sender verification, spam etc?
933 $replies[] = $recipient;
937 // Is the recipient a local group?
938 // TODO: $group = User_group::getKV('uri', $recipient);
939 $id = OStatusPlugin::localGroupFromUrl($recipient);
941 $group = User_group::getKV('id', $id);
942 if ($group instanceof User_group) {
943 // Deliver to all members of this local group if allowed.
944 if ($sender->isMember($group)) {
945 $groups[] = $group->id;
947 common_log(LOG_DEBUG, sprintf('Skipping reply to local group %s as sender %d is not a member', $group->getNickname(), $sender->id));
951 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
955 // Is the recipient a remote user or group?
957 $oprofile = self::ensureProfileURI($recipient);
958 if ($oprofile->isGroup()) {
959 // Deliver to local members of this remote group.
960 // @todo FIXME: Sender verification?
961 $groups[] = $oprofile->group_id;
963 // may be canonicalized or something
964 $replies[] = $oprofile->getUri();
967 } catch (Exception $e) {
968 // Neither a recognizable local nor remote user!
969 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
973 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
974 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
975 return array($groups, $replies);
979 * Look up and if necessary create an Ostatus_profile for the remote entity
980 * with the given profile page URL. This should never return null -- you
981 * will either get an object or an exception will be thrown.
983 * @param string $profile_url
984 * @return Ostatus_profile
985 * @throws Exception on various error conditions
986 * @throws OStatusShadowException if this reference would obscure a local user/group
988 public static function ensureProfileURL($profile_url, $hints=array())
990 $oprofile = self::getFromProfileURL($profile_url);
992 if ($oprofile instanceof Ostatus_profile) {
996 $hints['profileurl'] = $profile_url;
1001 $client = new HTTPClient();
1002 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
1003 $response = $client->get($profile_url);
1005 if (!$response->isOk()) {
1006 // TRANS: Exception. %s is a profile URL.
1007 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
1010 // Check if we have a non-canonical URL
1012 $finalUrl = $response->getUrl();
1014 if ($finalUrl != $profile_url) {
1016 $hints['profileurl'] = $finalUrl;
1018 $oprofile = self::getFromProfileURL($finalUrl);
1020 if ($oprofile instanceof Ostatus_profile) {
1025 // Try to get some hCard data
1027 $body = $response->getBody();
1029 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1031 if (!empty($hcardHints)) {
1032 $hints = array_merge($hints, $hcardHints);
1035 // Check if they've got an LRDD header
1037 $lrdd = LinkHeader::getLink($response, 'lrdd');
1039 $xrd = new XML_XRD();
1040 $xrd->loadFile($lrdd);
1041 $xrdHints = DiscoveryHints::fromXRD($xrd);
1042 $hints = array_merge($hints, $xrdHints);
1043 } catch (Exception $e) {
1044 // No hints available from XRD
1047 // If discovery found a feedurl (probably from LRDD), use it.
1049 if (array_key_exists('feedurl', $hints)) {
1050 return self::ensureFeedURL($hints['feedurl'], $hints);
1053 // Get the feed URL from HTML
1055 $discover = new FeedDiscovery();
1057 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1059 if (!empty($feedurl)) {
1060 $hints['feedurl'] = $feedurl;
1061 return self::ensureFeedURL($feedurl, $hints);
1064 // TRANS: Exception. %s is a URL.
1065 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1069 * Look up the Ostatus_profile, if present, for a remote entity with the
1070 * given profile page URL. Will return null for both unknown and invalid
1073 * @return mixed Ostatus_profile or null
1074 * @throws OStatusShadowException for local profiles
1076 static function getFromProfileURL($profile_url)
1078 $profile = Profile::getKV('profileurl', $profile_url);
1079 if (!$profile instanceof Profile) {
1084 $oprofile = self::getFromProfile($profile);
1085 // We found the profile, return it!
1087 } catch (NoResultException $e) {
1088 // Could not find an OStatus profile, is it instead a local user?
1089 $user = User::getKV('id', $profile->id);
1090 if ($user instanceof User) {
1091 // @todo i18n FIXME: use sprintf and add i18n (?)
1092 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1096 // Continue discovery; it's a remote profile
1097 // for OMB or some other protocol, may also
1103 static function getFromProfile(Profile $profile)
1105 $oprofile = new Ostatus_profile();
1106 $oprofile->profile_id = $profile->id;
1107 if (!$oprofile->find(true)) {
1108 throw new NoResultException($oprofile);
1114 * Look up and if necessary create an Ostatus_profile for remote entity
1115 * with the given update feed. This should never return null -- you will
1116 * either get an object or an exception will be thrown.
1118 * @return Ostatus_profile
1121 public static function ensureFeedURL($feed_url, $hints=array())
1123 $discover = new FeedDiscovery();
1125 $feeduri = $discover->discoverFromFeedURL($feed_url);
1126 $hints['feedurl'] = $feeduri;
1128 $huburi = $discover->getHubLink();
1129 $hints['hub'] = $huburi;
1131 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1132 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1133 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1134 $hints['salmon'] = $salmonuri;
1136 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1137 // We can only deal with folks with a PuSH hub
1138 throw new FeedSubNoHubException();
1141 $feedEl = $discover->root;
1143 if ($feedEl->tagName == 'feed') {
1144 return self::ensureAtomFeed($feedEl, $hints);
1145 } else if ($feedEl->tagName == 'channel') {
1146 return self::ensureRssChannel($feedEl, $hints);
1148 throw new FeedSubBadXmlException($feeduri);
1153 * Look up and, if necessary, create an Ostatus_profile for the remote
1154 * profile with the given Atom feed - actually loaded from the feed.
1155 * This should never return null -- you will either get an object or
1156 * an exception will be thrown.
1158 * @param DOMElement $feedEl root element of a loaded Atom feed
1159 * @param array $hints additional discovery information passed from higher levels
1160 * @todo FIXME: Should this be marked public?
1161 * @return Ostatus_profile
1164 public static function ensureAtomFeed($feedEl, $hints)
1166 $author = ActivityUtils::getFeedAuthor($feedEl);
1168 if (empty($author)) {
1169 // XXX: make some educated guesses here
1170 // TRANS: Feed sub exception.
1171 throw new FeedSubException(_m('Cannot find enough profile '.
1172 'information to make a feed.'));
1175 return self::ensureActivityObjectProfile($author, $hints);
1179 * Look up and, if necessary, create an Ostatus_profile for the remote
1180 * profile with the given RSS feed - actually loaded from the feed.
1181 * This should never return null -- you will either get an object or
1182 * an exception will be thrown.
1184 * @param DOMElement $feedEl root element of a loaded RSS feed
1185 * @param array $hints additional discovery information passed from higher levels
1186 * @todo FIXME: Should this be marked public?
1187 * @return Ostatus_profile
1190 public static function ensureRssChannel($feedEl, $hints)
1192 // Special-case for Posterous. They have some nice metadata in their
1193 // posterous:author elements. We should use them instead of the channel.
1195 $items = $feedEl->getElementsByTagName('item');
1197 if ($items->length > 0) {
1198 $item = $items->item(0);
1199 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1200 if (!empty($authorEl)) {
1201 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1202 // Posterous has multiple authors per feed, and multiple feeds
1203 // per author. We check if this is the "main" feed for this author.
1204 if (array_key_exists('profileurl', $hints) &&
1205 !empty($obj->poco) &&
1206 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1207 return self::ensureActivityObjectProfile($obj, $hints);
1212 // @todo FIXME: We should check whether this feed has elements
1213 // with different <author> or <dc:creator> elements, and... I dunno.
1214 // Do something about that.
1216 $obj = ActivityObject::fromRssChannel($feedEl);
1218 return self::ensureActivityObjectProfile($obj, $hints);
1222 * Download and update given avatar image
1224 * @param string $url
1225 * @throws Exception in various failure cases
1227 protected function updateAvatar($url)
1229 if ($url == $this->avatar) {
1230 // We've already got this one.
1233 if (!common_valid_http_url($url)) {
1234 // TRANS: Server exception. %s is a URL.
1235 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1238 if ($this->isGroup()) {
1239 // FIXME: throw exception for localGroup
1240 $self = $this->localGroup();
1242 // this throws an exception already
1243 $self = $this->localProfile();
1246 throw new ServerException(sprintf(
1247 // TRANS: Server exception. %s is a URI.
1248 _m('Tried to update avatar for unsaved remote profile %s.'),
1252 // @todo FIXME: This should be better encapsulated
1253 // ripped from oauthstore.php (for old OMB client)
1254 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1256 if (!copy($url, $temp_filename)) {
1257 // TRANS: Server exception. %s is a URL.
1258 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1261 if ($this->isGroup()) {
1262 $id = $this->group_id;
1264 $id = $this->profile_id;
1266 // @todo FIXME: Should we be using different ids?
1267 $imagefile = new ImageFile($id, $temp_filename);
1268 $filename = Avatar::filename($id,
1269 image_type_to_extension($imagefile->type),
1271 common_timestamp());
1272 rename($temp_filename, Avatar::path($filename));
1273 } catch (Exception $e) {
1274 unlink($temp_filename);
1277 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1278 // keep from accidentally saving images from command-line (queues)
1279 // that can't be read from web server, which causes hard-to-notice
1280 // problems later on:
1282 // http://status.net/open-source/issues/2663
1283 chmod(Avatar::path($filename), 0644);
1285 $self->setOriginal($filename);
1287 $orig = clone($this);
1288 $this->avatar = $url;
1289 $this->update($orig);
1293 * Pull avatar URL from ActivityObject or profile hints
1295 * @param ActivityObject $object
1296 * @param array $hints
1297 * @return mixed URL string or false
1299 public static function getActivityObjectAvatar($object, $hints=array())
1301 if ($object->avatarLinks) {
1303 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1304 foreach ($object->avatarLinks as $avatar) {
1305 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1310 if (!$best || $avatar->width > $best->width) {
1315 } else if (array_key_exists('avatar', $hints)) {
1316 return $hints['avatar'];
1322 * Get an appropriate avatar image source URL, if available.
1324 * @param ActivityObject $actor
1325 * @param DOMElement $feed
1328 protected static function getAvatar($actor, $feed)
1332 if ($actor->avatar) {
1333 $url = trim($actor->avatar);
1336 // Check <atom:logo> and <atom:icon> on the feed
1337 $els = $feed->childNodes();
1338 if ($els && $els->length) {
1339 for ($i = 0; $i < $els->length; $i++) {
1340 $el = $els->item($i);
1341 if ($el->namespaceURI == Activity::ATOM) {
1342 if (empty($url) && $el->localName == 'logo') {
1343 $url = trim($el->textContent);
1346 if (empty($icon) && $el->localName == 'icon') {
1347 // Use as a fallback
1348 $icon = trim($el->textContent);
1353 if ($icon && !$url) {
1358 $opts = array('allowed_schemes' => array('http', 'https'));
1359 if (common_valid_http_url($url)) {
1364 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1368 * Fetch, or build if necessary, an Ostatus_profile for the actor
1369 * in a given Activity Streams activity.
1370 * This should never return null -- you will either get an object or
1371 * an exception will be thrown.
1373 * @param Activity $activity
1374 * @param string $feeduri if we already know the canonical feed URI!
1375 * @param string $salmonuri if we already know the salmon return channel URI
1376 * @return Ostatus_profile
1379 public static function ensureActorProfile($activity, $hints=array())
1381 return self::ensureActivityObjectProfile($activity->actor, $hints);
1385 * Fetch, or build if necessary, an Ostatus_profile for the profile
1386 * in a given Activity Streams object (can be subject, actor, or object).
1387 * This should never return null -- you will either get an object or
1388 * an exception will be thrown.
1390 * @param ActivityObject $object
1391 * @param array $hints additional discovery information passed from higher levels
1392 * @return Ostatus_profile
1395 public static function ensureActivityObjectProfile($object, $hints=array())
1397 $profile = self::getActivityObjectProfile($object);
1398 if ($profile instanceof Ostatus_profile) {
1399 $profile->updateFromActivityObject($object, $hints);
1401 $profile = self::createActivityObjectProfile($object, $hints);
1407 * @param Activity $activity
1408 * @return mixed matching Ostatus_profile or false if none known
1409 * @throws ServerException if feed info invalid
1411 public static function getActorProfile($activity)
1413 return self::getActivityObjectProfile($activity->actor);
1417 * @param ActivityObject $activity
1418 * @return mixed matching Ostatus_profile or false if none known
1419 * @throws ServerException if feed info invalid
1421 protected static function getActivityObjectProfile($object)
1423 $uri = self::getActivityObjectProfileURI($object);
1424 return Ostatus_profile::getKV('uri', $uri);
1428 * Get the identifier URI for the remote entity described
1429 * by this ActivityObject. This URI is *not* guaranteed to be
1430 * a resolvable HTTP/HTTPS URL.
1432 * @param ActivityObject $object
1434 * @throws ServerException if feed info invalid
1436 protected static function getActivityObjectProfileURI($object)
1439 if (ActivityUtils::validateUri($object->id)) {
1444 // If the id is missing or invalid (we've seen feeds mistakenly listing
1445 // things like local usernames in that field) then we'll use the profile
1446 // page link, if valid.
1447 if ($object->link && common_valid_http_url($object->link)) {
1448 return $object->link;
1450 // TRANS: Server exception.
1451 throw new ServerException(_m('No author ID URI found.'));
1455 * @todo FIXME: Validate stuff somewhere.
1459 * Create local ostatus_profile and profile/user_group entries for
1460 * the provided remote user or group.
1461 * This should never return null -- you will either get an object or
1462 * an exception will be thrown.
1464 * @param ActivityObject $object
1465 * @param array $hints
1467 * @return Ostatus_profile
1469 protected static function createActivityObjectProfile($object, $hints=array())
1471 $homeuri = $object->id;
1475 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1476 // TRANS: Exception.
1477 throw new Exception(_m('No profile URI.'));
1480 $user = User::getKV('uri', $homeuri);
1481 if ($user instanceof User) {
1482 // TRANS: Exception.
1483 throw new Exception(_m('Local user cannot be referenced as remote.'));
1486 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1487 // TRANS: Exception.
1488 throw new Exception(_m('Local group cannot be referenced as remote.'));
1491 $ptag = Profile_list::getKV('uri', $homeuri);
1492 if ($ptag instanceof Profile_list) {
1493 $local_user = User::getKV('id', $ptag->tagger);
1494 if ($local_user instanceof User) {
1495 // TRANS: Exception.
1496 throw new Exception(_m('Local list cannot be referenced as remote.'));
1500 if (array_key_exists('feedurl', $hints)) {
1501 $feeduri = $hints['feedurl'];
1503 $discover = new FeedDiscovery();
1504 $feeduri = $discover->discoverFromURL($homeuri);
1507 if (array_key_exists('salmon', $hints)) {
1508 $salmonuri = $hints['salmon'];
1511 $discover = new FeedDiscovery();
1512 $discover->discoverFromFeedURL($hints['feedurl']);
1514 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1515 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1516 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1519 if (array_key_exists('hub', $hints)) {
1520 $huburi = $hints['hub'];
1523 $discover = new FeedDiscovery();
1524 $discover->discoverFromFeedURL($hints['feedurl']);
1526 $huburi = $discover->getHubLink();
1529 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1530 // We can only deal with folks with a PuSH hub
1531 throw new FeedSubNoHubException();
1534 $oprofile = new Ostatus_profile();
1536 $oprofile->uri = $homeuri;
1537 $oprofile->feeduri = $feeduri;
1538 $oprofile->salmonuri = $salmonuri;
1540 $oprofile->created = common_sql_now();
1541 $oprofile->modified = common_sql_now();
1543 if ($object->type == ActivityObject::PERSON) {
1544 $profile = new Profile();
1545 $profile->created = common_sql_now();
1546 self::updateProfile($profile, $object, $hints);
1548 $oprofile->profile_id = $profile->insert();
1549 if ($oprofile->profile_id === false) {
1550 // TRANS: Server exception.
1551 throw new ServerException(_m('Cannot save local profile.'));
1553 } else if ($object->type == ActivityObject::GROUP) {
1554 $profile = new Profile();
1555 $profile->query('BEGIN');
1557 $group = new User_group();
1558 $group->uri = $homeuri;
1559 $group->created = common_sql_now();
1560 self::updateGroup($group, $object, $hints);
1562 // TODO: We should do this directly in User_group->insert()!
1563 // currently it's duplicated in User_group->update()
1564 // AND User_group->register()!!!
1565 $fields = array(/*group field => profile field*/
1566 'nickname' => 'nickname',
1567 'fullname' => 'fullname',
1568 'mainpage' => 'profileurl',
1569 'homepage' => 'homepage',
1570 'description' => 'bio',
1571 'location' => 'location',
1572 'created' => 'created',
1573 'modified' => 'modified',
1575 foreach ($fields as $gf=>$pf) {
1576 $profile->$pf = $group->$gf;
1578 $profile_id = $profile->insert();
1579 if ($profile_id === false) {
1580 $profile->query('ROLLBACK');
1581 throw new ServerException(_('Profile insertion failed.'));
1584 $group->profile_id = $profile_id;
1586 $oprofile->group_id = $group->insert();
1587 if ($oprofile->group_id === false) {
1588 $profile->query('ROLLBACK');
1589 // TRANS: Server exception.
1590 throw new ServerException(_m('Cannot save local profile.'));
1593 $profile->query('COMMIT');
1594 } else if ($object->type == ActivityObject::_LIST) {
1595 $ptag = new Profile_list();
1596 $ptag->uri = $homeuri;
1597 $ptag->created = common_sql_now();
1598 self::updatePeopletag($ptag, $object, $hints);
1600 $oprofile->peopletag_id = $ptag->insert();
1601 if ($oprofile->peopletag_id === false) {
1602 // TRANS: Server exception.
1603 throw new ServerException(_m('Cannot save local list.'));
1607 $ok = $oprofile->insert();
1609 if ($ok === false) {
1610 // TRANS: Server exception.
1611 throw new ServerException(_m('Cannot save OStatus profile.'));
1614 $avatar = self::getActivityObjectAvatar($object, $hints);
1618 $oprofile->updateAvatar($avatar);
1619 } catch (Exception $ex) {
1620 // Profile is saved, but Avatar is messed up. We're
1621 // just going to continue.
1622 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1630 * Save any updated profile information to our local copy.
1631 * @param ActivityObject $object
1632 * @param array $hints
1634 public function updateFromActivityObject($object, $hints=array())
1636 if ($this->isGroup()) {
1637 $group = $this->localGroup();
1638 self::updateGroup($group, $object, $hints);
1639 } else if ($this->isPeopletag()) {
1640 $ptag = $this->localPeopletag();
1641 self::updatePeopletag($ptag, $object, $hints);
1643 $profile = $this->localProfile();
1644 self::updateProfile($profile, $object, $hints);
1647 $avatar = self::getActivityObjectAvatar($object, $hints);
1648 if ($avatar && !isset($ptag)) {
1650 $this->updateAvatar($avatar);
1651 } catch (Exception $ex) {
1652 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1657 public static function updateProfile($profile, $object, $hints=array())
1659 $orig = clone($profile);
1661 // Existing nickname is better than nothing.
1663 if (!array_key_exists('nickname', $hints)) {
1664 $hints['nickname'] = $profile->nickname;
1667 $nickname = self::getActivityObjectNickname($object, $hints);
1669 if (!empty($nickname)) {
1670 $profile->nickname = $nickname;
1673 if (!empty($object->title)) {
1674 $profile->fullname = $object->title;
1675 } else if (array_key_exists('fullname', $hints)) {
1676 $profile->fullname = $hints['fullname'];
1679 if (!empty($object->link)) {
1680 $profile->profileurl = $object->link;
1681 } else if (array_key_exists('profileurl', $hints)) {
1682 $profile->profileurl = $hints['profileurl'];
1683 } else if (common_valid_http_url($object->id)) {
1684 $profile->profileurl = $object->id;
1687 $bio = self::getActivityObjectBio($object, $hints);
1690 $profile->bio = $bio;
1693 $location = self::getActivityObjectLocation($object, $hints);
1695 if (!empty($location)) {
1696 $profile->location = $location;
1699 $homepage = self::getActivityObjectHomepage($object, $hints);
1701 if (!empty($homepage)) {
1702 $profile->homepage = $homepage;
1705 if (!empty($object->geopoint)) {
1706 $location = ActivityContext::locationFromPoint($object->geopoint);
1707 if (!empty($location)) {
1708 $profile->lat = $location->lat;
1709 $profile->lon = $location->lon;
1713 // @todo FIXME: tags/categories
1714 // @todo tags from categories
1717 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1718 $profile->update($orig);
1722 protected static function updateGroup(User_group $group, $object, $hints=array())
1724 $orig = clone($group);
1726 $group->nickname = self::getActivityObjectNickname($object, $hints);
1727 $group->fullname = $object->title;
1729 if (!empty($object->link)) {
1730 $group->mainpage = $object->link;
1731 } else if (array_key_exists('profileurl', $hints)) {
1732 $group->mainpage = $hints['profileurl'];
1735 // @todo tags from categories
1736 $group->description = self::getActivityObjectBio($object, $hints);
1737 $group->location = self::getActivityObjectLocation($object, $hints);
1738 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1740 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1741 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1742 $group->update($orig);
1746 protected static function updatePeopletag($tag, $object, $hints=array()) {
1747 $orig = clone($tag);
1749 $tag->tag = $object->title;
1751 if (!empty($object->link)) {
1752 $tag->mainpage = $object->link;
1753 } else if (array_key_exists('profileurl', $hints)) {
1754 $tag->mainpage = $hints['profileurl'];
1757 $tag->description = $object->summary;
1758 $tagger = self::ensureActivityObjectProfile($object->owner);
1759 $tag->tagger = $tagger->profile_id;
1762 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1763 $tag->update($orig);
1767 protected static function getActivityObjectHomepage($object, $hints=array())
1770 $poco = $object->poco;
1772 if (!empty($poco)) {
1773 $url = $poco->getPrimaryURL();
1774 if ($url && $url->type == 'homepage') {
1775 $homepage = $url->value;
1779 // @todo Try for a another PoCo URL?
1784 protected static function getActivityObjectLocation($object, $hints=array())
1788 if (!empty($object->poco) &&
1789 isset($object->poco->address->formatted)) {
1790 $location = $object->poco->address->formatted;
1791 } else if (array_key_exists('location', $hints)) {
1792 $location = $hints['location'];
1795 if (!empty($location)) {
1796 if (mb_strlen($location) > 255) {
1797 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1801 // @todo Try to find location some othe way? Via goerss point?
1806 protected static function getActivityObjectBio($object, $hints=array())
1810 if (!empty($object->poco)) {
1811 $note = $object->poco->note;
1812 } else if (array_key_exists('bio', $hints)) {
1813 $note = $hints['bio'];
1816 if (!empty($note)) {
1817 if (Profile::bioTooLong($note)) {
1818 // XXX: truncate ok?
1819 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1825 // @todo Try to get bio info some other way?
1830 public static function getActivityObjectNickname($object, $hints=array())
1832 if ($object->poco) {
1833 if (!empty($object->poco->preferredUsername)) {
1834 return common_nicknamize($object->poco->preferredUsername);
1838 if (!empty($object->nickname)) {
1839 return common_nicknamize($object->nickname);
1842 if (array_key_exists('nickname', $hints)) {
1843 return $hints['nickname'];
1846 // Try the profile url (like foo.example.com or example.com/user/foo)
1847 if (!empty($object->link)) {
1848 $profileUrl = $object->link;
1849 } else if (!empty($hints['profileurl'])) {
1850 $profileUrl = $hints['profileurl'];
1853 if (!empty($profileUrl)) {
1854 $nickname = self::nicknameFromURI($profileUrl);
1857 // Try the URI (may be a tag:, http:, acct:, ...
1859 if (empty($nickname)) {
1860 $nickname = self::nicknameFromURI($object->id);
1863 // Try a Webfinger if one was passed (way) down
1865 if (empty($nickname)) {
1866 if (array_key_exists('webfinger', $hints)) {
1867 $nickname = self::nicknameFromURI($hints['webfinger']);
1873 if (empty($nickname)) {
1874 $nickname = common_nicknamize($object->title);
1880 protected static function nicknameFromURI($uri)
1882 if (preg_match('/(\w+):/', $uri, $matches)) {
1883 $protocol = $matches[1];
1888 switch ($protocol) {
1891 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1892 return common_canonical_nickname($matches[1]);
1896 return common_url_to_nickname($uri);
1904 * Look up, and if necessary create, an Ostatus_profile for the remote
1905 * entity with the given webfinger address.
1906 * This should never return null -- you will either get an object or
1907 * an exception will be thrown.
1909 * @param string $addr webfinger address
1910 * @return Ostatus_profile
1911 * @throws Exception on error conditions
1912 * @throws OStatusShadowException if this reference would obscure a local user/group
1914 public static function ensureWebfinger($addr)
1916 // First, try the cache
1918 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1920 if ($uri !== false) {
1921 if (is_null($uri)) {
1922 // Negative cache entry
1923 // TRANS: Exception.
1924 throw new Exception(_m('Not a valid webfinger address.'));
1926 $oprofile = Ostatus_profile::getKV('uri', $uri);
1927 if ($oprofile instanceof Ostatus_profile) {
1932 // Try looking it up
1933 $oprofile = Ostatus_profile::getKV('uri', Discovery::normalize($addr));
1935 if ($oprofile instanceof Ostatus_profile) {
1936 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1940 // Now, try some discovery
1942 $disco = new Discovery();
1945 $xrd = $disco->lookup($addr);
1946 } catch (Exception $e) {
1947 // Save negative cache entry so we don't waste time looking it up again.
1948 // @todo FIXME: Distinguish temporary failures?
1949 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1950 // TRANS: Exception.
1951 throw new Exception(_m('Not a valid webfinger address.'));
1954 $hints = array('webfinger' => $addr);
1956 $dhints = DiscoveryHints::fromXRD($xrd);
1958 $hints = array_merge($hints, $dhints);
1960 // If there's an Hcard, let's grab its info
1961 if (array_key_exists('hcard', $hints)) {
1962 if (!array_key_exists('profileurl', $hints) ||
1963 $hints['hcard'] != $hints['profileurl']) {
1964 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1965 $hints = array_merge($hcardHints, $hints);
1969 // If we got a feed URL, try that
1971 if (array_key_exists('feedurl', $hints)) {
1972 $feedUrl = $hints['feedurl'];
1974 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1975 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1976 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1978 } catch (Exception $e) {
1979 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1984 // If we got a profile page, try that!
1986 if (array_key_exists('profileurl', $hints)) {
1987 $profileUrl = $hints['profileurl'];
1989 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1990 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1991 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1993 } catch (OStatusShadowException $e) {
1994 // We've ended up with a remote reference to a local user or group.
1995 // @todo FIXME: Ideally we should be able to say who it was so we can
1996 // go back and refer to it the regular way
1998 } catch (Exception $e) {
1999 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
2002 // @todo FIXME: This means an error discovering from profile page
2003 // may give us a corrupt entry using the webfinger URI, which
2004 // will obscure the correct page-keyed profile later on.
2011 if (array_key_exists('salmon', $hints)) {
2012 $salmonEndpoint = $hints['salmon'];
2014 // An account URL, a salmon endpoint, and a dream? Not much to go
2015 // on, but let's give it a try
2017 $uri = 'acct:'.$addr;
2019 $profile = new Profile();
2021 $profile->nickname = self::nicknameFromUri($uri);
2022 $profile->created = common_sql_now();
2024 if (!is_null($profileUrl)) {
2025 $profile->profileurl = $profileUrl;
2028 $profile_id = $profile->insert();
2030 if ($profile_id === false) {
2031 common_log_db_error($profile, 'INSERT', __FILE__);
2032 // TRANS: Exception. %s is a webfinger address.
2033 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2036 $oprofile = new Ostatus_profile();
2038 $oprofile->uri = $uri;
2039 $oprofile->salmonuri = $salmonEndpoint;
2040 $oprofile->profile_id = $profile_id;
2041 $oprofile->created = common_sql_now();
2043 if (!is_null($feedUrl)) {
2044 $oprofile->feeduri = $feedUrl;
2047 $result = $oprofile->insert();
2049 if ($result === false) {
2051 common_log_db_error($oprofile, 'INSERT', __FILE__);
2052 // TRANS: Exception. %s is a webfinger address.
2053 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2056 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
2060 // TRANS: Exception. %s is a webfinger address.
2061 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2065 * Store the full-length scrubbed HTML of a remote notice to an attachment
2066 * file on our server. We'll link to this at the end of the cropped version.
2068 * @param string $title plaintext for HTML page's title
2069 * @param string $rendered HTML fragment for HTML page's body
2072 function saveHTMLFile($title, $rendered)
2074 $final = sprintf("<!DOCTYPE html>\n" .
2076 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2077 '<title>%s</title>' .
2079 '<body>%s</body></html>',
2080 htmlspecialchars($title),
2083 $filename = File::filename($this->localProfile(),
2084 'ostatus', // ignored?
2087 $filepath = File::path($filename);
2089 file_put_contents($filepath, $final);
2093 $file->filename = $filename;
2094 $file->url = File::url($filename);
2095 $file->size = filesize($filepath);
2096 $file->date = time();
2097 $file->mimetype = 'text/html';
2099 $file_id = $file->insert();
2101 if ($file_id === false) {
2102 common_log_db_error($file, "INSERT", __FILE__);
2103 // TRANS: Server exception.
2104 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2110 static function ensureProfileURI($uri)
2114 // First, try to query it
2116 $oprofile = Ostatus_profile::getKV('uri', $uri);
2118 if ($oprofile instanceof Ostatus_profile) {
2122 // If unfound, do discovery stuff
2123 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2124 $protocol = $match[1];
2125 switch ($protocol) {
2128 $oprofile = self::ensureProfileURL($uri);
2133 $oprofile = self::ensureWebfinger($rest);
2136 // TRANS: Server exception.
2137 // TRANS: %1$s is a protocol, %2$s is a URI.
2138 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2144 // TRANS: Server exception. %s is a URI.
2145 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2151 public function checkAuthorship(Activity $activity)
2153 if ($this->isGroup() || $this->isPeopletag()) {
2154 // A group or propletag feed will contain posts from multiple authors.
2155 $oprofile = self::ensureActorProfile($activity);
2156 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2157 // Groups can't post notices in StatusNet.
2158 common_log(LOG_WARNING,
2159 "OStatus: skipping post with group listed ".
2160 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
2161 throw new ServerException('Activity author is a non-actor');
2164 $actor = $activity->actor;
2166 if (empty($actor)) {
2167 // OK here! assume the default
2168 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
2169 $this->updateFromActivityObject($actor);
2170 } else if ($actor->id) {
2171 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2172 // This isn't what we expect from mainline OStatus person feeds!
2173 // Group feeds go down another path, with different validation...
2174 // Most likely this is a plain ol' blog feed of some kind which
2175 // doesn't match our expectations. We'll take the entry, but ignore
2176 // the <author> info.
2177 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
2179 // Plain <author> without ActivityStreams actor info.
2180 // We'll just ignore this info for now and save the update under the feed's identity.
2186 return $oprofile->localProfile();
2191 * Exception indicating we've got a remote reference to a local user,
2192 * not a remote user!
2194 * If we can ue a local profile after all, it's available as $e->profile.
2196 class OStatusShadowException extends Exception
2201 * @param Profile $profile
2202 * @param string $message
2204 function __construct($profile, $message) {
2205 $this->profile = $profile;
2206 parent::__construct($message);