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_idx' => array('profile_id'),
67 'ostatus_profile_group_id_idx' => array('group_id'),
68 'ostatus_profile_peopletag_id_idx' => array('peopletag_id'),
69 'ostatus_profile_feeduri_idx' => 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 StatusNet-side profile for this feed
88 public function localProfile()
90 if ($this->profile_id) {
91 return Profile::getKV('id', $this->profile_id);
97 * Fetch the StatusNet-side profile for this feed
100 public function localGroup()
102 if ($this->group_id) {
103 return User_group::getKV('id', $this->group_id);
109 * Fetch the StatusNet-side peopletag for this feed
112 public function localPeopletag()
114 if ($this->peopletag_id) {
115 return Profile_list::getKV('id', $this->peopletag_id);
121 * Returns an ActivityObject describing this remote user or group profile.
122 * Can then be used to generate Atom chunks.
124 * @return ActivityObject
126 function asActivityObject()
128 if ($this->isGroup()) {
129 return ActivityObject::fromGroup($this->localGroup());
130 } else if ($this->isPeopletag()) {
131 return ActivityObject::fromPeopletag($this->localPeopletag());
133 return ActivityObject::fromProfile($this->localProfile());
138 * Returns an XML string fragment with profile information as an
139 * Activity Streams noun object with the given element type.
141 * Assumes that 'activity' namespace has been previously defined.
143 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
145 * @param string $element one of 'actor', 'subject', 'object', 'target'
148 function asActivityNoun($element)
150 if ($this->isGroup()) {
151 $noun = ActivityObject::fromGroup($this->localGroup());
152 return $noun->asString('activity:' . $element);
153 } else if ($this->isPeopletag()) {
154 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
155 return $noun->asString('activity:' . $element);
157 $noun = ActivityObject::fromProfile($this->localProfile());
158 return $noun->asString('activity:' . $element);
163 * @return boolean true if this is a remote group
167 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
169 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
171 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
172 // TRANS: Server exception. %s is a URI
173 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
175 // TRANS: Server exception. %s is a URI
176 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
181 * @return boolean true if this is a remote peopletag
183 function isPeopletag()
185 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
187 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
189 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
190 // TRANS: Server exception. %s is a URI
191 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->getUri()));
193 // TRANS: Server exception. %s is a URI
194 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->getUri()));
199 * Send a subscription request to the hub for this feed.
200 * The hub will later send us a confirmation POST to /main/push/callback.
202 * @return bool true on success, false on failure
203 * @throws ServerException if feed state is not valid
205 public function subscribe()
207 $feedsub = FeedSub::ensureFeed($this->feeduri);
208 if ($feedsub->sub_state == 'active') {
209 // Active subscription, we don't need to do anything.
212 // Inactive or we got left in an inconsistent state.
213 // Run a subscription request to make sure we're current!
214 return $feedsub->subscribe();
219 * Check if this remote profile has any active local subscriptions, and
220 * if not drop the PuSH subscription feed.
222 * @return bool true on success, false on failure
224 public function unsubscribe() {
225 $this->garbageCollect();
229 * Check if this remote profile has any active local subscriptions, and
230 * if not drop the PuSH subscription feed.
234 public function garbageCollect()
236 $feedsub = FeedSub::getKV('uri', $this->feeduri);
237 return $feedsub->garbageCollect();
241 * Check if this remote profile has any active local subscriptions, so the
242 * PuSH subscription layer can decide if it can drop the feed.
244 * This gets called via the FeedSubSubscriberCount event when running
245 * FeedSub::garbageCollect().
249 public function subscriberCount()
251 if ($this->isGroup()) {
252 $members = $this->localGroup()->getMembers(0, 1);
253 $count = $members->N;
254 } else if ($this->isPeopletag()) {
255 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
256 $count = $subscribers->N;
258 $profile = $this->localProfile();
259 $count = $profile->subscriberCount();
260 if ($profile->hasLocalTags()) {
264 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
266 // Other plugins may be piggybacking on OStatus without having
267 // an active group or user-to-user subscription we know about.
268 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
269 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
275 * Send an Activity Streams notification to the remote Salmon endpoint,
278 * @param Profile $actor Actor who did the activity
279 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
280 * @param Object $object object of the action; must define asActivityNoun($tag)
282 public function notify($actor, $verb, $object=null, $target=null)
284 if (!($actor instanceof Profile)) {
285 $type = gettype($actor);
286 if ($type == 'object') {
287 $type = get_class($actor);
289 // TRANS: Server exception.
290 // TRANS: %1$s is the method name the exception occured in, %2$s is the actor type.
291 throw new ServerException(sprintf(_m('Invalid actor passed to %1$s: %2$s.'),__METHOD__,$type));
293 if ($object == null) {
296 if ($this->salmonuri) {
298 $id = TagURI::mint('%s:%s:%s',
301 common_date_iso8601(time()));
303 // @todo FIXME: Consolidate all these NS settings somewhere.
304 $attributes = array('xmlns' => Activity::ATOM,
305 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
306 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
307 'xmlns:georss' => 'http://www.georss.org/georss',
308 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
309 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
310 'xmlns:media' => 'http://purl.org/syndication/atommedia');
312 $entry = new XMLStringer();
313 $entry->elementStart('entry', $attributes);
314 $entry->element('id', null, $id);
315 $entry->element('title', null, $text);
316 $entry->element('summary', null, $text);
317 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
319 $entry->element('activity:verb', null, $verb);
320 $entry->raw($actor->asAtomAuthor());
321 $entry->raw($actor->asActivityActor());
322 $entry->raw($object->asActivityNoun('object'));
323 if ($target != null) {
324 $entry->raw($target->asActivityNoun('target'));
326 $entry->elementEnd('entry');
328 $xml = $entry->getString();
329 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
331 $salmon = new Salmon(); // ?
332 return $salmon->post($this->salmonuri, $xml, $actor);
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, $actor)
347 if ($this->salmonuri) {
348 $salmon = new Salmon();
349 return $salmon->post($this->salmonuri, $this->notifyPrepXml($entry), $actor);
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 = $this->filterAttention($oprofile, $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 = $this->filterAttention($oprofile, $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 Ostatus_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 protected function filterAttention($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 $profile = $sender->localProfile();
942 if ($profile->isMember($group)) {
943 $groups[] = $group->id;
945 common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
949 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
953 // Is the recipient a remote user or group?
955 $oprofile = self::ensureProfileURI($recipient);
956 if ($oprofile->isGroup()) {
957 // Deliver to local members of this remote group.
958 // @todo FIXME: Sender verification?
959 $groups[] = $oprofile->group_id;
961 // may be canonicalized or something
962 $replies[] = $oprofile->getUri();
965 } catch (Exception $e) {
966 // Neither a recognizable local nor remote user!
967 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
971 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
972 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
973 return array($groups, $replies);
977 * Look up and if necessary create an Ostatus_profile for the remote entity
978 * with the given profile page URL. This should never return null -- you
979 * will either get an object or an exception will be thrown.
981 * @param string $profile_url
982 * @return Ostatus_profile
983 * @throws Exception on various error conditions
984 * @throws OStatusShadowException if this reference would obscure a local user/group
986 public static function ensureProfileURL($profile_url, $hints=array())
988 $oprofile = self::getFromProfileURL($profile_url);
990 if ($oprofile instanceof Ostatus_profile) {
994 $hints['profileurl'] = $profile_url;
999 $client = new HTTPClient();
1000 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
1001 $response = $client->get($profile_url);
1003 if (!$response->isOk()) {
1004 // TRANS: Exception. %s is a profile URL.
1005 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
1008 // Check if we have a non-canonical URL
1010 $finalUrl = $response->getUrl();
1012 if ($finalUrl != $profile_url) {
1014 $hints['profileurl'] = $finalUrl;
1016 $oprofile = self::getFromProfileURL($finalUrl);
1018 if ($oprofile instanceof Ostatus_profile) {
1023 // Try to get some hCard data
1025 $body = $response->getBody();
1027 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1029 if (!empty($hcardHints)) {
1030 $hints = array_merge($hints, $hcardHints);
1033 // Check if they've got an LRDD header
1035 $lrdd = LinkHeader::getLink($response, 'lrdd');
1037 $xrd = new XML_XRD();
1038 $xrd->loadFile($lrdd);
1039 $xrdHints = DiscoveryHints::fromXRD($xrd);
1040 $hints = array_merge($hints, $xrdHints);
1041 } catch (Exception $e) {
1042 // No hints available from XRD
1045 // If discovery found a feedurl (probably from LRDD), use it.
1047 if (array_key_exists('feedurl', $hints)) {
1048 return self::ensureFeedURL($hints['feedurl'], $hints);
1051 // Get the feed URL from HTML
1053 $discover = new FeedDiscovery();
1055 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1057 if (!empty($feedurl)) {
1058 $hints['feedurl'] = $feedurl;
1059 return self::ensureFeedURL($feedurl, $hints);
1062 // TRANS: Exception. %s is a URL.
1063 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1067 * Look up the Ostatus_profile, if present, for a remote entity with the
1068 * given profile page URL. Will return null for both unknown and invalid
1071 * @return mixed Ostatus_profile or null
1072 * @throws OStatusShadowException for local profiles
1074 static function getFromProfileURL($profile_url)
1076 $profile = Profile::getKV('profileurl', $profile_url);
1077 if (!$profile instanceof Profile) {
1081 // Is it a known Ostatus profile?
1082 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1083 if ($oprofile instanceof Ostatus_profile) {
1087 // Is it a local user?
1088 $user = User::getKV('id', $profile->id);
1089 if ($user instanceof User) {
1090 // @todo i18n FIXME: use sprintf and add i18n (?)
1091 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1094 // Continue discovery; it's a remote profile
1095 // for OMB or some other protocol, may also
1102 * Look up and if necessary create an Ostatus_profile for remote entity
1103 * with the given update feed. This should never return null -- you will
1104 * either get an object or an exception will be thrown.
1106 * @return Ostatus_profile
1109 public static function ensureFeedURL($feed_url, $hints=array())
1111 $discover = new FeedDiscovery();
1113 $feeduri = $discover->discoverFromFeedURL($feed_url);
1114 $hints['feedurl'] = $feeduri;
1116 $huburi = $discover->getHubLink();
1117 $hints['hub'] = $huburi;
1119 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1120 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1121 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1122 $hints['salmon'] = $salmonuri;
1124 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1125 // We can only deal with folks with a PuSH hub
1126 throw new FeedSubNoHubException();
1129 $feedEl = $discover->root;
1131 if ($feedEl->tagName == 'feed') {
1132 return self::ensureAtomFeed($feedEl, $hints);
1133 } else if ($feedEl->tagName == 'channel') {
1134 return self::ensureRssChannel($feedEl, $hints);
1136 throw new FeedSubBadXmlException($feeduri);
1141 * Look up and, if necessary, create an Ostatus_profile for the remote
1142 * profile with the given Atom feed - actually loaded from the feed.
1143 * This should never return null -- you will either get an object or
1144 * an exception will be thrown.
1146 * @param DOMElement $feedEl root element of a loaded Atom feed
1147 * @param array $hints additional discovery information passed from higher levels
1148 * @todo FIXME: Should this be marked public?
1149 * @return Ostatus_profile
1152 public static function ensureAtomFeed($feedEl, $hints)
1154 $author = ActivityUtils::getFeedAuthor($feedEl);
1156 if (empty($author)) {
1157 // XXX: make some educated guesses here
1158 // TRANS: Feed sub exception.
1159 throw new FeedSubException(_m('Cannot find enough profile '.
1160 'information to make a feed.'));
1163 return self::ensureActivityObjectProfile($author, $hints);
1167 * Look up and, if necessary, create an Ostatus_profile for the remote
1168 * profile with the given RSS feed - actually loaded from the feed.
1169 * This should never return null -- you will either get an object or
1170 * an exception will be thrown.
1172 * @param DOMElement $feedEl root element of a loaded RSS feed
1173 * @param array $hints additional discovery information passed from higher levels
1174 * @todo FIXME: Should this be marked public?
1175 * @return Ostatus_profile
1178 public static function ensureRssChannel($feedEl, $hints)
1180 // Special-case for Posterous. They have some nice metadata in their
1181 // posterous:author elements. We should use them instead of the channel.
1183 $items = $feedEl->getElementsByTagName('item');
1185 if ($items->length > 0) {
1186 $item = $items->item(0);
1187 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1188 if (!empty($authorEl)) {
1189 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1190 // Posterous has multiple authors per feed, and multiple feeds
1191 // per author. We check if this is the "main" feed for this author.
1192 if (array_key_exists('profileurl', $hints) &&
1193 !empty($obj->poco) &&
1194 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1195 return self::ensureActivityObjectProfile($obj, $hints);
1200 // @todo FIXME: We should check whether this feed has elements
1201 // with different <author> or <dc:creator> elements, and... I dunno.
1202 // Do something about that.
1204 $obj = ActivityObject::fromRssChannel($feedEl);
1206 return self::ensureActivityObjectProfile($obj, $hints);
1210 * Download and update given avatar image
1212 * @param string $url
1213 * @throws Exception in various failure cases
1215 protected function updateAvatar($url)
1217 if ($url == $this->avatar) {
1218 // We've already got this one.
1221 if (!common_valid_http_url($url)) {
1222 // TRANS: Server exception. %s is a URL.
1223 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1226 if ($this->isGroup()) {
1227 $self = $this->localGroup();
1229 $self = $this->localProfile();
1232 throw new ServerException(sprintf(
1233 // TRANS: Server exception. %s is a URI.
1234 _m('Tried to update avatar for unsaved remote profile %s.'),
1238 // @todo FIXME: This should be better encapsulated
1239 // ripped from oauthstore.php (for old OMB client)
1240 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1242 if (!copy($url, $temp_filename)) {
1243 // TRANS: Server exception. %s is a URL.
1244 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1247 if ($this->isGroup()) {
1248 $id = $this->group_id;
1250 $id = $this->profile_id;
1252 // @todo FIXME: Should we be using different ids?
1253 $imagefile = new ImageFile($id, $temp_filename);
1254 $filename = Avatar::filename($id,
1255 image_type_to_extension($imagefile->type),
1257 common_timestamp());
1258 rename($temp_filename, Avatar::path($filename));
1259 } catch (Exception $e) {
1260 unlink($temp_filename);
1263 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1264 // keep from accidentally saving images from command-line (queues)
1265 // that can't be read from web server, which causes hard-to-notice
1266 // problems later on:
1268 // http://status.net/open-source/issues/2663
1269 chmod(Avatar::path($filename), 0644);
1271 $self->setOriginal($filename);
1273 $orig = clone($this);
1274 $this->avatar = $url;
1275 $this->update($orig);
1279 * Pull avatar URL from ActivityObject or profile hints
1281 * @param ActivityObject $object
1282 * @param array $hints
1283 * @return mixed URL string or false
1285 public static function getActivityObjectAvatar($object, $hints=array())
1287 if ($object->avatarLinks) {
1289 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1290 foreach ($object->avatarLinks as $avatar) {
1291 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1296 if (!$best || $avatar->width > $best->width) {
1301 } else if (array_key_exists('avatar', $hints)) {
1302 return $hints['avatar'];
1308 * Get an appropriate avatar image source URL, if available.
1310 * @param ActivityObject $actor
1311 * @param DOMElement $feed
1314 protected static function getAvatar($actor, $feed)
1318 if ($actor->avatar) {
1319 $url = trim($actor->avatar);
1322 // Check <atom:logo> and <atom:icon> on the feed
1323 $els = $feed->childNodes();
1324 if ($els && $els->length) {
1325 for ($i = 0; $i < $els->length; $i++) {
1326 $el = $els->item($i);
1327 if ($el->namespaceURI == Activity::ATOM) {
1328 if (empty($url) && $el->localName == 'logo') {
1329 $url = trim($el->textContent);
1332 if (empty($icon) && $el->localName == 'icon') {
1333 // Use as a fallback
1334 $icon = trim($el->textContent);
1339 if ($icon && !$url) {
1344 $opts = array('allowed_schemes' => array('http', 'https'));
1345 if (common_valid_http_url($url)) {
1350 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1354 * Fetch, or build if necessary, an Ostatus_profile for the actor
1355 * in a given Activity Streams activity.
1356 * This should never return null -- you will either get an object or
1357 * an exception will be thrown.
1359 * @param Activity $activity
1360 * @param string $feeduri if we already know the canonical feed URI!
1361 * @param string $salmonuri if we already know the salmon return channel URI
1362 * @return Ostatus_profile
1365 public static function ensureActorProfile($activity, $hints=array())
1367 return self::ensureActivityObjectProfile($activity->actor, $hints);
1371 * Fetch, or build if necessary, an Ostatus_profile for the profile
1372 * in a given Activity Streams object (can be subject, actor, or object).
1373 * This should never return null -- you will either get an object or
1374 * an exception will be thrown.
1376 * @param ActivityObject $object
1377 * @param array $hints additional discovery information passed from higher levels
1378 * @return Ostatus_profile
1381 public static function ensureActivityObjectProfile($object, $hints=array())
1383 $profile = self::getActivityObjectProfile($object);
1385 $profile->updateFromActivityObject($object, $hints);
1387 $profile = self::createActivityObjectProfile($object, $hints);
1393 * @param Activity $activity
1394 * @return mixed matching Ostatus_profile or false if none known
1395 * @throws ServerException if feed info invalid
1397 public static function getActorProfile($activity)
1399 return self::getActivityObjectProfile($activity->actor);
1403 * @param ActivityObject $activity
1404 * @return mixed matching Ostatus_profile or false if none known
1405 * @throws ServerException if feed info invalid
1407 protected static function getActivityObjectProfile($object)
1409 $uri = self::getActivityObjectProfileURI($object);
1410 return Ostatus_profile::getKV('uri', $uri);
1414 * Get the identifier URI for the remote entity described
1415 * by this ActivityObject. This URI is *not* guaranteed to be
1416 * a resolvable HTTP/HTTPS URL.
1418 * @param ActivityObject $object
1420 * @throws ServerException if feed info invalid
1422 protected static function getActivityObjectProfileURI($object)
1425 if (ActivityUtils::validateUri($object->id)) {
1430 // If the id is missing or invalid (we've seen feeds mistakenly listing
1431 // things like local usernames in that field) then we'll use the profile
1432 // page link, if valid.
1433 if ($object->link && common_valid_http_url($object->link)) {
1434 return $object->link;
1436 // TRANS: Server exception.
1437 throw new ServerException(_m('No author ID URI found.'));
1441 * @todo FIXME: Validate stuff somewhere.
1445 * Create local ostatus_profile and profile/user_group entries for
1446 * the provided remote user or group.
1447 * This should never return null -- you will either get an object or
1448 * an exception will be thrown.
1450 * @param ActivityObject $object
1451 * @param array $hints
1453 * @return Ostatus_profile
1455 protected static function createActivityObjectProfile($object, $hints=array())
1457 $homeuri = $object->id;
1461 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1462 // TRANS: Exception.
1463 throw new Exception(_m('No profile URI.'));
1466 $user = User::getKV('uri', $homeuri);
1467 if ($user instanceof User) {
1468 // TRANS: Exception.
1469 throw new Exception(_m('Local user cannot be referenced as remote.'));
1472 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1473 // TRANS: Exception.
1474 throw new Exception(_m('Local group cannot be referenced as remote.'));
1477 $ptag = Profile_list::getKV('uri', $homeuri);
1478 if ($ptag instanceof Profile_list) {
1479 $local_user = User::getKV('id', $ptag->tagger);
1480 if ($local_user instanceof User) {
1481 // TRANS: Exception.
1482 throw new Exception(_m('Local list cannot be referenced as remote.'));
1486 if (array_key_exists('feedurl', $hints)) {
1487 $feeduri = $hints['feedurl'];
1489 $discover = new FeedDiscovery();
1490 $feeduri = $discover->discoverFromURL($homeuri);
1493 if (array_key_exists('salmon', $hints)) {
1494 $salmonuri = $hints['salmon'];
1497 $discover = new FeedDiscovery();
1498 $discover->discoverFromFeedURL($hints['feedurl']);
1500 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1501 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1502 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1505 if (array_key_exists('hub', $hints)) {
1506 $huburi = $hints['hub'];
1509 $discover = new FeedDiscovery();
1510 $discover->discoverFromFeedURL($hints['feedurl']);
1512 $huburi = $discover->getHubLink();
1515 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1516 // We can only deal with folks with a PuSH hub
1517 throw new FeedSubNoHubException();
1520 $oprofile = new Ostatus_profile();
1522 $oprofile->uri = $homeuri;
1523 $oprofile->feeduri = $feeduri;
1524 $oprofile->salmonuri = $salmonuri;
1526 $oprofile->created = common_sql_now();
1527 $oprofile->modified = common_sql_now();
1529 if ($object->type == ActivityObject::PERSON) {
1530 $profile = new Profile();
1531 $profile->created = common_sql_now();
1532 self::updateProfile($profile, $object, $hints);
1534 $oprofile->profile_id = $profile->insert();
1535 if ($oprofile->profile_id === false) {
1536 // TRANS: Server exception.
1537 throw new ServerException(_m('Cannot save local profile.'));
1539 } else if ($object->type == ActivityObject::GROUP) {
1540 $profile = new Profile();
1541 $profile->query('BEGIN');
1543 $group = new User_group();
1544 $group->uri = $homeuri;
1545 $group->created = common_sql_now();
1546 self::updateGroup($group, $object, $hints);
1548 // TODO: We should do this directly in User_group->insert()!
1549 // currently it's duplicated in User_group->update()
1550 // AND User_group->register()!!!
1551 $fields = array(/*group field => profile field*/
1552 'nickname' => 'nickname',
1553 'fullname' => 'fullname',
1554 'mainpage' => 'profileurl',
1555 'homepage' => 'homepage',
1556 'description' => 'bio',
1557 'location' => 'location',
1558 'created' => 'created',
1559 'modified' => 'modified',
1561 foreach ($fields as $gf=>$pf) {
1562 $profile->$pf = $group->$gf;
1564 $profile_id = $profile->insert();
1565 if ($profile_id === false) {
1566 $profile->query('ROLLBACK');
1567 throw new ServerException(_('Profile insertion failed.'));
1570 $group->profile_id = $profile_id;
1572 $oprofile->group_id = $group->insert();
1573 if ($oprofile->group_id === false) {
1574 $profile->query('ROLLBACK');
1575 // TRANS: Server exception.
1576 throw new ServerException(_m('Cannot save local profile.'));
1579 $profile->query('COMMIT');
1580 } else if ($object->type == ActivityObject::_LIST) {
1581 $ptag = new Profile_list();
1582 $ptag->uri = $homeuri;
1583 $ptag->created = common_sql_now();
1584 self::updatePeopletag($ptag, $object, $hints);
1586 $oprofile->peopletag_id = $ptag->insert();
1587 if ($oprofile->peopletag_id === false) {
1588 // TRANS: Server exception.
1589 throw new ServerException(_m('Cannot save local list.'));
1593 $ok = $oprofile->insert();
1595 if ($ok === false) {
1596 // TRANS: Server exception.
1597 throw new ServerException(_m('Cannot save OStatus profile.'));
1600 $avatar = self::getActivityObjectAvatar($object, $hints);
1604 $oprofile->updateAvatar($avatar);
1605 } catch (Exception $ex) {
1606 // Profile is saved, but Avatar is messed up. We're
1607 // just going to continue.
1608 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1616 * Save any updated profile information to our local copy.
1617 * @param ActivityObject $object
1618 * @param array $hints
1620 public function updateFromActivityObject($object, $hints=array())
1622 if ($this->isGroup()) {
1623 $group = $this->localGroup();
1624 self::updateGroup($group, $object, $hints);
1625 } else if ($this->isPeopletag()) {
1626 $ptag = $this->localPeopletag();
1627 self::updatePeopletag($ptag, $object, $hints);
1629 $profile = $this->localProfile();
1630 self::updateProfile($profile, $object, $hints);
1633 $avatar = self::getActivityObjectAvatar($object, $hints);
1634 if ($avatar && !isset($ptag)) {
1636 $this->updateAvatar($avatar);
1637 } catch (Exception $ex) {
1638 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1643 public static function updateProfile($profile, $object, $hints=array())
1645 $orig = clone($profile);
1647 // Existing nickname is better than nothing.
1649 if (!array_key_exists('nickname', $hints)) {
1650 $hints['nickname'] = $profile->nickname;
1653 $nickname = self::getActivityObjectNickname($object, $hints);
1655 if (!empty($nickname)) {
1656 $profile->nickname = $nickname;
1659 if (!empty($object->title)) {
1660 $profile->fullname = $object->title;
1661 } else if (array_key_exists('fullname', $hints)) {
1662 $profile->fullname = $hints['fullname'];
1665 if (!empty($object->link)) {
1666 $profile->profileurl = $object->link;
1667 } else if (array_key_exists('profileurl', $hints)) {
1668 $profile->profileurl = $hints['profileurl'];
1669 } else if (common_valid_http_url($object->id)) {
1670 $profile->profileurl = $object->id;
1673 $bio = self::getActivityObjectBio($object, $hints);
1676 $profile->bio = $bio;
1679 $location = self::getActivityObjectLocation($object, $hints);
1681 if (!empty($location)) {
1682 $profile->location = $location;
1685 $homepage = self::getActivityObjectHomepage($object, $hints);
1687 if (!empty($homepage)) {
1688 $profile->homepage = $homepage;
1691 if (!empty($object->geopoint)) {
1692 $location = ActivityContext::locationFromPoint($object->geopoint);
1693 if (!empty($location)) {
1694 $profile->lat = $location->lat;
1695 $profile->lon = $location->lon;
1699 // @todo FIXME: tags/categories
1700 // @todo tags from categories
1703 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1704 $profile->update($orig);
1708 protected static function updateGroup(User_group $group, $object, $hints=array())
1710 $orig = clone($group);
1712 $group->nickname = self::getActivityObjectNickname($object, $hints);
1713 $group->fullname = $object->title;
1715 if (!empty($object->link)) {
1716 $group->mainpage = $object->link;
1717 } else if (array_key_exists('profileurl', $hints)) {
1718 $group->mainpage = $hints['profileurl'];
1721 // @todo tags from categories
1722 $group->description = self::getActivityObjectBio($object, $hints);
1723 $group->location = self::getActivityObjectLocation($object, $hints);
1724 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1726 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1727 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1728 $group->update($orig);
1732 protected static function updatePeopletag($tag, $object, $hints=array()) {
1733 $orig = clone($tag);
1735 $tag->tag = $object->title;
1737 if (!empty($object->link)) {
1738 $tag->mainpage = $object->link;
1739 } else if (array_key_exists('profileurl', $hints)) {
1740 $tag->mainpage = $hints['profileurl'];
1743 $tag->description = $object->summary;
1744 $tagger = self::ensureActivityObjectProfile($object->owner);
1745 $tag->tagger = $tagger->profile_id;
1748 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1749 $tag->update($orig);
1753 protected static function getActivityObjectHomepage($object, $hints=array())
1756 $poco = $object->poco;
1758 if (!empty($poco)) {
1759 $url = $poco->getPrimaryURL();
1760 if ($url && $url->type == 'homepage') {
1761 $homepage = $url->value;
1765 // @todo Try for a another PoCo URL?
1770 protected static function getActivityObjectLocation($object, $hints=array())
1774 if (!empty($object->poco) &&
1775 isset($object->poco->address->formatted)) {
1776 $location = $object->poco->address->formatted;
1777 } else if (array_key_exists('location', $hints)) {
1778 $location = $hints['location'];
1781 if (!empty($location)) {
1782 if (mb_strlen($location) > 255) {
1783 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1787 // @todo Try to find location some othe way? Via goerss point?
1792 protected static function getActivityObjectBio($object, $hints=array())
1796 if (!empty($object->poco)) {
1797 $note = $object->poco->note;
1798 } else if (array_key_exists('bio', $hints)) {
1799 $note = $hints['bio'];
1802 if (!empty($note)) {
1803 if (Profile::bioTooLong($note)) {
1804 // XXX: truncate ok?
1805 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1811 // @todo Try to get bio info some other way?
1816 public static function getActivityObjectNickname($object, $hints=array())
1818 if ($object->poco) {
1819 if (!empty($object->poco->preferredUsername)) {
1820 return common_nicknamize($object->poco->preferredUsername);
1824 if (!empty($object->nickname)) {
1825 return common_nicknamize($object->nickname);
1828 if (array_key_exists('nickname', $hints)) {
1829 return $hints['nickname'];
1832 // Try the profile url (like foo.example.com or example.com/user/foo)
1833 if (!empty($object->link)) {
1834 $profileUrl = $object->link;
1835 } else if (!empty($hints['profileurl'])) {
1836 $profileUrl = $hints['profileurl'];
1839 if (!empty($profileUrl)) {
1840 $nickname = self::nicknameFromURI($profileUrl);
1843 // Try the URI (may be a tag:, http:, acct:, ...
1845 if (empty($nickname)) {
1846 $nickname = self::nicknameFromURI($object->id);
1849 // Try a Webfinger if one was passed (way) down
1851 if (empty($nickname)) {
1852 if (array_key_exists('webfinger', $hints)) {
1853 $nickname = self::nicknameFromURI($hints['webfinger']);
1859 if (empty($nickname)) {
1860 $nickname = common_nicknamize($object->title);
1866 protected static function nicknameFromURI($uri)
1868 if (preg_match('/(\w+):/', $uri, $matches)) {
1869 $protocol = $matches[1];
1874 switch ($protocol) {
1877 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1878 return common_canonical_nickname($matches[1]);
1882 return common_url_to_nickname($uri);
1890 * Look up, and if necessary create, an Ostatus_profile for the remote
1891 * entity with the given webfinger address.
1892 * This should never return null -- you will either get an object or
1893 * an exception will be thrown.
1895 * @param string $addr webfinger address
1896 * @return Ostatus_profile
1897 * @throws Exception on error conditions
1898 * @throws OStatusShadowException if this reference would obscure a local user/group
1900 public static function ensureWebfinger($addr)
1902 // First, try the cache
1904 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1906 if ($uri !== false) {
1907 if (is_null($uri)) {
1908 // Negative cache entry
1909 // TRANS: Exception.
1910 throw new Exception(_m('Not a valid webfinger address.'));
1912 $oprofile = Ostatus_profile::getKV('uri', $uri);
1913 if ($oprofile instanceof Ostatus_profile) {
1918 // Try looking it up
1919 $oprofile = Ostatus_profile::getKV('uri', 'acct:'.$addr);
1921 if ($oprofile instanceof Ostatus_profile) {
1922 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1926 // Now, try some discovery
1928 $disco = new Discovery();
1931 $xrd = $disco->lookup($addr);
1932 } catch (Exception $e) {
1933 // Save negative cache entry so we don't waste time looking it up again.
1934 // @todo FIXME: Distinguish temporary failures?
1935 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1936 // TRANS: Exception.
1937 throw new Exception(_m('Not a valid webfinger address.'));
1940 $hints = array('webfinger' => $addr);
1942 $dhints = DiscoveryHints::fromXRD($xrd);
1944 $hints = array_merge($hints, $dhints);
1946 // If there's an Hcard, let's grab its info
1947 if (array_key_exists('hcard', $hints)) {
1948 if (!array_key_exists('profileurl', $hints) ||
1949 $hints['hcard'] != $hints['profileurl']) {
1950 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1951 $hints = array_merge($hcardHints, $hints);
1955 // If we got a feed URL, try that
1956 if (array_key_exists('feedurl', $hints)) {
1958 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1959 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1960 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1962 } catch (Exception $e) {
1963 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1968 // If we got a profile page, try that!
1969 if (array_key_exists('profileurl', $hints)) {
1971 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1972 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1973 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1975 } catch (OStatusShadowException $e) {
1976 // We've ended up with a remote reference to a local user or group.
1977 // @todo FIXME: Ideally we should be able to say who it was so we can
1978 // go back and refer to it the regular way
1980 } catch (Exception $e) {
1981 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1984 // @todo FIXME: This means an error discovering from profile page
1985 // may give us a corrupt entry using the webfinger URI, which
1986 // will obscure the correct page-keyed profile later on.
1993 if (array_key_exists('salmon', $hints)) {
1994 $salmonEndpoint = $hints['salmon'];
1996 // An account URL, a salmon endpoint, and a dream? Not much to go
1997 // on, but let's give it a try
1999 $uri = 'acct:'.$addr;
2001 $profile = new Profile();
2003 $profile->nickname = self::nicknameFromUri($uri);
2004 $profile->created = common_sql_now();
2006 if (isset($profileUrl)) {
2007 $profile->profileurl = $profileUrl;
2010 $profile_id = $profile->insert();
2012 if ($profile_id === false) {
2013 common_log_db_error($profile, 'INSERT', __FILE__);
2014 // TRANS: Exception. %s is a webfinger address.
2015 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2018 $oprofile = new Ostatus_profile();
2020 $oprofile->uri = $uri;
2021 $oprofile->salmonuri = $salmonEndpoint;
2022 $oprofile->profile_id = $profile_id;
2023 $oprofile->created = common_sql_now();
2025 if (isset($feedUrl)) {
2026 $profile->feeduri = $feedUrl;
2029 $result = $oprofile->insert();
2031 if ($result === false) {
2032 common_log_db_error($oprofile, 'INSERT', __FILE__);
2033 // TRANS: Exception. %s is a webfinger address.
2034 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2037 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
2041 // TRANS: Exception. %s is a webfinger address.
2042 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2046 * Store the full-length scrubbed HTML of a remote notice to an attachment
2047 * file on our server. We'll link to this at the end of the cropped version.
2049 * @param string $title plaintext for HTML page's title
2050 * @param string $rendered HTML fragment for HTML page's body
2053 function saveHTMLFile($title, $rendered)
2055 $final = sprintf("<!DOCTYPE html>\n" .
2057 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2058 '<title>%s</title>' .
2060 '<body>%s</body></html>',
2061 htmlspecialchars($title),
2064 $filename = File::filename($this->localProfile(),
2065 'ostatus', // ignored?
2068 $filepath = File::path($filename);
2070 file_put_contents($filepath, $final);
2074 $file->filename = $filename;
2075 $file->url = File::url($filename);
2076 $file->size = filesize($filepath);
2077 $file->date = time();
2078 $file->mimetype = 'text/html';
2080 $file_id = $file->insert();
2082 if ($file_id === false) {
2083 common_log_db_error($file, "INSERT", __FILE__);
2084 // TRANS: Server exception.
2085 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2091 static function ensureProfileURI($uri)
2095 // First, try to query it
2097 $oprofile = Ostatus_profile::getKV('uri', $uri);
2099 if ($oprofile instanceof Ostatus_profile) {
2103 // If unfound, do discovery stuff
2104 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2105 $protocol = $match[1];
2106 switch ($protocol) {
2109 $oprofile = self::ensureProfileURL($uri);
2114 $oprofile = self::ensureWebfinger($rest);
2117 // TRANS: Server exception.
2118 // TRANS: %1$s is a protocol, %2$s is a URI.
2119 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2125 // TRANS: Server exception. %s is a URI.
2126 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2132 function checkAuthorship($activity)
2134 if ($this->isGroup() || $this->isPeopletag()) {
2135 // A group or propletag feed will contain posts from multiple authors.
2136 $oprofile = self::ensureActorProfile($activity);
2137 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2138 // Groups can't post notices in StatusNet.
2139 common_log(LOG_WARNING,
2140 "OStatus: skipping post with group listed ".
2141 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
2145 $actor = $activity->actor;
2147 if (empty($actor)) {
2148 // OK here! assume the default
2149 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
2150 $this->updateFromActivityObject($actor);
2151 } else if ($actor->id) {
2152 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2153 // This isn't what we expect from mainline OStatus person feeds!
2154 // Group feeds go down another path, with different validation...
2155 // Most likely this is a plain ol' blog feed of some kind which
2156 // doesn't match our expectations. We'll take the entry, but ignore
2157 // the <author> info.
2158 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
2160 // Plain <author> without ActivityStreams actor info.
2161 // We'll just ignore this info for now and save the update under the feed's identity.
2172 * Exception indicating we've got a remote reference to a local user,
2173 * not a remote user!
2175 * If we can ue a local profile after all, it's available as $e->profile.
2177 class OStatusShadowException extends Exception
2182 * @param Profile $profile
2183 * @param string $message
2185 function __construct($profile, $message) {
2186 $this->profile = $profile;
2187 parent::__construct($message);