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, Profile $actor)
347 if ($this->salmonuri) {
348 $salmon = new Salmon();
349 return $salmon->post($this->salmonuri, $this->notifyPrepXml($entry), $actor);
351 common_debug(__CLASS__.' error: No salmonuri for Ostatus_profile uri: '.$this->uri);
357 * Queue a Salmon notification for later. If queues are disabled we'll
358 * send immediately but won't get the return value.
360 * @param mixed $entry XML string, Notice, or Activity
361 * @return boolean success
363 public function notifyDeferred($entry, $actor)
365 if ($this->salmonuri) {
366 $data = array('salmonuri' => $this->salmonuri,
367 'entry' => $this->notifyPrepXml($entry),
368 'actor' => $actor->id);
370 $qm = QueueManager::get();
371 return $qm->enqueue($data, 'salmon');
377 protected function notifyPrepXml($entry)
379 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
380 if (is_string($entry)) {
382 } else if ($entry instanceof Activity) {
383 return $preamble . $entry->asString(true);
384 } else if ($entry instanceof Notice) {
385 return $preamble . $entry->asAtomEntry(true, true);
387 // TRANS: Server exception.
388 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
392 function getBestName()
394 if ($this->isGroup()) {
395 return $this->localGroup()->getBestName();
396 } else if ($this->isPeopletag()) {
397 return $this->localPeopletag()->getBestName();
399 return $this->localProfile()->getBestName();
404 * Read and post notices for updates from the feed.
405 * Currently assumes that all items in the feed are new,
406 * coming from a PuSH hub.
408 * @param DOMDocument $doc
409 * @param string $source identifier ("push")
411 public function processFeed(DOMDocument $doc, $source)
413 $feed = $doc->documentElement;
415 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
416 $this->processAtomFeed($feed, $source);
417 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
418 $this->processRssFeed($feed, $source);
421 throw new Exception(_m('Unknown feed format.'));
425 public function processAtomFeed(DOMElement $feed, $source)
427 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
428 if ($entries->length == 0) {
429 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
433 for ($i = 0; $i < $entries->length; $i++) {
434 $entry = $entries->item($i);
435 $this->processEntry($entry, $feed, $source);
439 public function processRssFeed(DOMElement $rss, $source)
441 $channels = $rss->getElementsByTagName('channel');
443 if ($channels->length == 0) {
445 throw new Exception(_m('RSS feed without a channel.'));
446 } else if ($channels->length > 1) {
447 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
450 $channel = $channels->item(0);
452 $items = $channel->getElementsByTagName('item');
454 for ($i = 0; $i < $items->length; $i++) {
455 $item = $items->item($i);
456 $this->processEntry($item, $channel, $source);
461 * Process a posted entry from this feed source.
463 * @param DOMElement $entry
464 * @param DOMElement $feed for context
465 * @param string $source identifier ("push" or "salmon")
467 * @return Notice Notice representing the new (or existing) activity
469 public function processEntry($entry, $feed, $source)
471 $activity = new Activity($entry, $feed);
472 return $this->processActivity($activity, $source);
475 // TODO: Make this throw an exception
476 public function processActivity($activity, $source)
480 // The "WithProfile" events were added later.
482 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this, &$notice)) &&
483 Event::handle('StartHandleFeedEntry', array($activity))) {
485 switch ($activity->verb) {
486 case ActivityVerb::POST:
487 // @todo process all activity objects
488 switch ($activity->objects[0]->type) {
489 case ActivityObject::ARTICLE:
490 case ActivityObject::BLOGENTRY:
491 case ActivityObject::NOTE:
492 case ActivityObject::STATUS:
493 case ActivityObject::COMMENT:
495 $notice = $this->processPost($activity, $source);
498 // TRANS: Client exception.
499 throw new ClientException(_m('Cannot handle that kind of post.'));
502 case ActivityVerb::SHARE:
503 $notice = $this->processShare($activity, $source);
506 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
509 Event::handle('EndHandleFeedEntry', array($activity));
510 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
516 public function processShare($activity, $method)
520 $oprofile = $this->checkAuthorship($activity);
522 if (!$oprofile instanceof Ostatus_profile) {
523 common_log(LOG_INFO, "No author matched share activity");
527 // The id URI will be used as a unique identifier for the notice,
528 // protecting against duplicate saves. It isn't required to be a URL;
529 // tag: URIs for instance are found in Google Buzz feeds.
530 $dupe = Notice::getKV('uri', $activity->id);
531 if ($dupe instanceof Notice) {
532 common_log(LOG_INFO, "OStatus: ignoring duplicate post: {$activity->id}");
536 if (count($activity->objects) != 1) {
537 // TRANS: Client exception thrown when trying to share multiple activities at once.
538 throw new ClientException(_m('Can only handle share activities with exactly one object.'));
541 $shared = $activity->objects[0];
543 if (!$shared instanceof Activity) {
544 // TRANS: Client exception thrown when trying to share a non-activity object.
545 throw new ClientException(_m('Can only handle shared activities.'));
548 $sharedId = $shared->id;
549 if (!empty($shared->objects[0]->id)) {
550 // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
551 // fucks up federation, because the URI is no longer recognised by the origin.
552 // So we set it to the object ID if it exists, otherwise we trust $shared->id
553 $sharedId = $shared->objects[0]->id;
555 if (empty($sharedId)) {
556 throw new ClientException(_m('Shared activity does not have an id'));
559 // First check if we have the shared activity. This has to be done first, because
560 // we can't use these functions to "ensureActivityObjectProfile" of a local user,
561 // who might be the creator of the shared activity in question.
562 $sharedNotice = Notice::getKV('uri', $sharedId);
563 if (!$sharedNotice instanceof Notice) {
564 // If no locally stored notice is found, process it!
565 // TODO: Remember to check Deleted_notice!
566 // TODO: If a post is shared that we can't retrieve - what to do?
568 $other = self::ensureActivityObjectProfile($shared->actor);
569 $sharedNotice = $other->processActivity($shared, $method);
570 if (!$sharedNotice instanceof Notice) {
571 // And if we apparently can't get the shared notice, we'll abort the whole thing.
572 // TRANS: Client exception thrown when saving an activity share fails.
573 // TRANS: %s is a share ID.
574 throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedId));
576 } catch (FeedSubException $e) {
577 // Remote feed could not be found or verified, should we
578 // transform this into an "RT @user Blah, blah, blah..."?
579 common_log(LOG_INFO, __METHOD__ . ' got a ' . get_class($e) . ': ' . $e->getMessage());
584 // We'll want to save a web link to the original notice, if provided.
587 if ($activity->link) {
588 $sourceUrl = $activity->link;
589 } else if ($activity->link) {
590 $sourceUrl = $activity->link;
591 } else if (preg_match('!^https?://!', $activity->id)) {
592 $sourceUrl = $activity->id;
595 // Use summary as fallback for content
597 if (!empty($activity->content)) {
598 $sourceContent = $activity->content;
599 } else if (!empty($activity->summary)) {
600 $sourceContent = $activity->summary;
601 } else if (!empty($activity->title)) {
602 $sourceContent = $activity->title;
604 // @todo FIXME: Fetch from $sourceUrl?
605 // TRANS: Client exception. %s is a source URI.
606 throw new ClientException(sprintf(_m('No content for notice %s.'), $activity->id));
609 // Get (safe!) HTML and text versions of the content
611 $rendered = $this->purify($sourceContent);
612 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
614 $shortened = common_shorten_links($content);
616 // If it's too long, try using the summary, and make the
617 // HTML an attachment.
621 if (Notice::contentTooLong($shortened)) {
622 $attachment = $this->saveHTMLFile($activity->title, $rendered);
623 $summary = html_entity_decode(strip_tags($activity->summary), ENT_QUOTES, 'UTF-8');
624 if (empty($summary)) {
627 $shortSummary = common_shorten_links($summary);
628 if (Notice::contentTooLong($shortSummary)) {
629 $url = common_shorten_url($sourceUrl);
630 $shortSummary = substr($shortSummary,
632 Notice::maxContent() - (mb_strlen($url) + 2));
633 $content = $shortSummary . ' ' . $url;
635 // We mark up the attachment link specially for the HTML output
636 // so we can fold-out the full version inline.
638 // @todo FIXME i18n: This tooltip will be saved with the site's default language
639 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
640 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
641 $showMoreText = _m('Show more');
642 $attachUrl = common_local_url('attachment',
643 array('attachment' => $attachment->id));
644 $rendered = common_render_text($shortSummary) .
645 '<a href="' . htmlspecialchars($attachUrl) .'"'.
646 ' class="attachment more"' .
647 ' title="'. htmlspecialchars($showMoreText) . '">' .
653 $options = array('is_local' => Notice::REMOTE,
655 'uri' => $activity->id,
656 'rendered' => $rendered,
657 'replies' => array(),
659 'peopletags' => array(),
662 'repeat_of' => $sharedNotice->id,
663 'scope' => $sharedNotice->scope);
665 // Check for optional attributes...
667 if (!empty($activity->time)) {
668 $options['created'] = common_sql_date($activity->time);
671 if ($activity->context) {
672 // TODO: context->attention
673 list($options['groups'], $options['replies'])
674 = $this->filterAttention($oprofile, $activity->context->attention);
676 // Maintain direct reply associations
677 // @todo FIXME: What about conversation ID?
678 if (!empty($activity->context->replyToID)) {
679 $orig = Notice::getKV('uri',
680 $activity->context->replyToID);
681 if ($orig instanceof Notice) {
682 $options['reply_to'] = $orig->id;
686 $location = $activity->context->location;
688 $options['lat'] = $location->lat;
689 $options['lon'] = $location->lon;
690 if ($location->location_id) {
691 $options['location_ns'] = $location->location_ns;
692 $options['location_id'] = $location->location_id;
697 if ($this->isPeopletag()) {
698 $options['peopletags'][] = $this->localPeopletag();
701 // Atom categories <-> hashtags
702 foreach ($activity->categories as $cat) {
704 $term = common_canonical_tag($cat->term);
706 $options['tags'][] = $term;
711 // Atom enclosures -> attachment URLs
712 foreach ($activity->enclosures as $href) {
713 // @todo FIXME: Save these locally or....?
714 $options['urls'][] = $href;
717 $notice = Notice::saveNew($oprofile->profile_id,
726 * Process an incoming post activity from this remote feed.
727 * @param Activity $activity
728 * @param string $method 'push' or 'salmon'
729 * @return mixed saved Notice or false
730 * @todo FIXME: Break up this function, it's getting nasty long
732 public function processPost($activity, $method)
736 $oprofile = $this->checkAuthorship($activity);
738 if (!$oprofile instanceof Ostatus_profile) {
742 // It's not always an ActivityObject::NOTE, but... let's just say it is.
744 $note = $activity->objects[0];
746 // The id URI will be used as a unique identifier for the notice,
747 // protecting against duplicate saves. It isn't required to be a URL;
748 // tag: URIs for instance are found in Google Buzz feeds.
749 $sourceUri = $note->id;
750 $dupe = Notice::getKV('uri', $sourceUri);
751 if ($dupe instanceof Notice) {
752 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
756 // We'll also want to save a web link to the original notice, if provided.
759 $sourceUrl = $note->link;
760 } else if ($activity->link) {
761 $sourceUrl = $activity->link;
762 } else if (preg_match('!^https?://!', $note->id)) {
763 $sourceUrl = $note->id;
766 // Use summary as fallback for content
768 if (!empty($note->content)) {
769 $sourceContent = $note->content;
770 } else if (!empty($note->summary)) {
771 $sourceContent = $note->summary;
772 } else if (!empty($note->title)) {
773 $sourceContent = $note->title;
775 // @todo FIXME: Fetch from $sourceUrl?
776 // TRANS: Client exception. %s is a source URI.
777 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
780 // Get (safe!) HTML and text versions of the content
782 $rendered = $this->purify($sourceContent);
783 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
785 $shortened = common_shorten_links($content);
787 // If it's too long, try using the summary, and make the
788 // HTML an attachment.
792 if (Notice::contentTooLong($shortened)) {
793 $attachment = $this->saveHTMLFile($note->title, $rendered);
794 $summary = html_entity_decode(strip_tags($note->summary), ENT_QUOTES, 'UTF-8');
795 if (empty($summary)) {
798 $shortSummary = common_shorten_links($summary);
799 if (Notice::contentTooLong($shortSummary)) {
800 $url = common_shorten_url($sourceUrl);
801 $shortSummary = substr($shortSummary,
803 Notice::maxContent() - (mb_strlen($url) + 2));
804 $content = $shortSummary . ' ' . $url;
806 // We mark up the attachment link specially for the HTML output
807 // so we can fold-out the full version inline.
809 // @todo FIXME i18n: This tooltip will be saved with the site's default language
810 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
811 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
812 $showMoreText = _m('Show more');
813 $attachUrl = common_local_url('attachment',
814 array('attachment' => $attachment->id));
815 $rendered = common_render_text($shortSummary) .
816 '<a href="' . htmlspecialchars($attachUrl) .'"'.
817 ' class="attachment more"' .
818 ' title="'. htmlspecialchars($showMoreText) . '">' .
824 $options = array('is_local' => Notice::REMOTE,
827 'rendered' => $rendered,
828 'replies' => array(),
830 'peopletags' => array(),
834 // Check for optional attributes...
836 if (!empty($activity->time)) {
837 $options['created'] = common_sql_date($activity->time);
840 if ($activity->context) {
841 // TODO: context->attention
842 list($options['groups'], $options['replies'])
843 = $this->filterAttention($oprofile, $activity->context->attention);
845 // Maintain direct reply associations
846 // @todo FIXME: What about conversation ID?
847 if (!empty($activity->context->replyToID)) {
848 $orig = Notice::getKV('uri', $activity->context->replyToID);
849 if ($orig instanceof Notice) {
850 $options['reply_to'] = $orig->id;
854 $location = $activity->context->location;
856 $options['lat'] = $location->lat;
857 $options['lon'] = $location->lon;
858 if ($location->location_id) {
859 $options['location_ns'] = $location->location_ns;
860 $options['location_id'] = $location->location_id;
865 if ($this->isPeopletag()) {
866 $options['peopletags'][] = $this->localPeopletag();
869 // Atom categories <-> hashtags
870 foreach ($activity->categories as $cat) {
872 $term = common_canonical_tag($cat->term);
874 $options['tags'][] = $term;
879 // Atom enclosures -> attachment URLs
880 foreach ($activity->enclosures as $href) {
881 // @todo FIXME: Save these locally or....?
882 $options['urls'][] = $href;
886 $saved = Notice::saveNew($oprofile->profile_id,
890 if ($saved instanceof Notice) {
891 Ostatus_source::saveNew($saved, $this, $method);
892 if (!empty($attachment)) {
893 File_to_post::processNew($attachment->id, $saved->id);
896 } catch (Exception $e) {
897 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
900 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
907 protected function purify($html)
909 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
910 $config = array('safe' => 1,
911 'deny_attribute' => 'id,style,on*');
912 return htmLawed($html, $config);
916 * Filters a list of recipient ID URIs to just those for local delivery.
917 * @param Ostatus_profile local profile of sender
918 * @param array in/out &$attention_uris set of URIs, will be pruned on output
919 * @return array of group IDs
921 protected function filterAttention($sender, array $attention)
923 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', array_keys($attention)));
926 foreach ($attention as $recipient=>$type) {
927 // Is the recipient a local user?
928 $user = User::getKV('uri', $recipient);
929 if ($user instanceof User) {
930 // @todo FIXME: Sender verification, spam etc?
931 $replies[] = $recipient;
935 // Is the recipient a local group?
936 // TODO: $group = User_group::getKV('uri', $recipient);
937 $id = OStatusPlugin::localGroupFromUrl($recipient);
939 $group = User_group::getKV('id', $id);
940 if ($group instanceof User_group) {
941 // Deliver to all members of this local group if allowed.
942 $profile = $sender->localProfile();
943 if ($profile->isMember($group)) {
944 $groups[] = $group->id;
946 common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
950 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
954 // Is the recipient a remote user or group?
956 $oprofile = self::ensureProfileURI($recipient);
957 if ($oprofile->isGroup()) {
958 // Deliver to local members of this remote group.
959 // @todo FIXME: Sender verification?
960 $groups[] = $oprofile->group_id;
962 // may be canonicalized or something
963 $replies[] = $oprofile->getUri();
966 } catch (Exception $e) {
967 // Neither a recognizable local nor remote user!
968 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
972 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
973 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
974 return array($groups, $replies);
978 * Look up and if necessary create an Ostatus_profile for the remote entity
979 * with the given profile page URL. This should never return null -- you
980 * will either get an object or an exception will be thrown.
982 * @param string $profile_url
983 * @return Ostatus_profile
984 * @throws Exception on various error conditions
985 * @throws OStatusShadowException if this reference would obscure a local user/group
987 public static function ensureProfileURL($profile_url, $hints=array())
989 $oprofile = self::getFromProfileURL($profile_url);
991 if ($oprofile instanceof Ostatus_profile) {
995 $hints['profileurl'] = $profile_url;
1000 $client = new HTTPClient();
1001 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
1002 $response = $client->get($profile_url);
1004 if (!$response->isOk()) {
1005 // TRANS: Exception. %s is a profile URL.
1006 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
1009 // Check if we have a non-canonical URL
1011 $finalUrl = $response->getUrl();
1013 if ($finalUrl != $profile_url) {
1015 $hints['profileurl'] = $finalUrl;
1017 $oprofile = self::getFromProfileURL($finalUrl);
1019 if ($oprofile instanceof Ostatus_profile) {
1024 // Try to get some hCard data
1026 $body = $response->getBody();
1028 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1030 if (!empty($hcardHints)) {
1031 $hints = array_merge($hints, $hcardHints);
1034 // Check if they've got an LRDD header
1036 $lrdd = LinkHeader::getLink($response, 'lrdd');
1038 $xrd = new XML_XRD();
1039 $xrd->loadFile($lrdd);
1040 $xrdHints = DiscoveryHints::fromXRD($xrd);
1041 $hints = array_merge($hints, $xrdHints);
1042 } catch (Exception $e) {
1043 // No hints available from XRD
1046 // If discovery found a feedurl (probably from LRDD), use it.
1048 if (array_key_exists('feedurl', $hints)) {
1049 return self::ensureFeedURL($hints['feedurl'], $hints);
1052 // Get the feed URL from HTML
1054 $discover = new FeedDiscovery();
1056 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1058 if (!empty($feedurl)) {
1059 $hints['feedurl'] = $feedurl;
1060 return self::ensureFeedURL($feedurl, $hints);
1063 // TRANS: Exception. %s is a URL.
1064 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1068 * Look up the Ostatus_profile, if present, for a remote entity with the
1069 * given profile page URL. Will return null for both unknown and invalid
1072 * @return mixed Ostatus_profile or null
1073 * @throws OStatusShadowException for local profiles
1075 static function getFromProfileURL($profile_url)
1077 $profile = Profile::getKV('profileurl', $profile_url);
1078 if (!$profile instanceof Profile) {
1082 // Is it a known Ostatus profile?
1083 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1084 if ($oprofile instanceof Ostatus_profile) {
1088 // Is it 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}'.");
1095 // Continue discovery; it's a remote profile
1096 // for OMB or some other protocol, may also
1103 * Look up and if necessary create an Ostatus_profile for remote entity
1104 * with the given update feed. This should never return null -- you will
1105 * either get an object or an exception will be thrown.
1107 * @return Ostatus_profile
1110 public static function ensureFeedURL($feed_url, $hints=array())
1112 $discover = new FeedDiscovery();
1114 $feeduri = $discover->discoverFromFeedURL($feed_url);
1115 $hints['feedurl'] = $feeduri;
1117 $huburi = $discover->getHubLink();
1118 $hints['hub'] = $huburi;
1120 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1121 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1122 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1123 $hints['salmon'] = $salmonuri;
1125 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1126 // We can only deal with folks with a PuSH hub
1127 throw new FeedSubNoHubException();
1130 $feedEl = $discover->root;
1132 if ($feedEl->tagName == 'feed') {
1133 return self::ensureAtomFeed($feedEl, $hints);
1134 } else if ($feedEl->tagName == 'channel') {
1135 return self::ensureRssChannel($feedEl, $hints);
1137 throw new FeedSubBadXmlException($feeduri);
1142 * Look up and, if necessary, create an Ostatus_profile for the remote
1143 * profile with the given Atom feed - actually loaded from the feed.
1144 * This should never return null -- you will either get an object or
1145 * an exception will be thrown.
1147 * @param DOMElement $feedEl root element of a loaded Atom feed
1148 * @param array $hints additional discovery information passed from higher levels
1149 * @todo FIXME: Should this be marked public?
1150 * @return Ostatus_profile
1153 public static function ensureAtomFeed($feedEl, $hints)
1155 $author = ActivityUtils::getFeedAuthor($feedEl);
1157 if (empty($author)) {
1158 // XXX: make some educated guesses here
1159 // TRANS: Feed sub exception.
1160 throw new FeedSubException(_m('Cannot find enough profile '.
1161 'information to make a feed.'));
1164 return self::ensureActivityObjectProfile($author, $hints);
1168 * Look up and, if necessary, create an Ostatus_profile for the remote
1169 * profile with the given RSS feed - actually loaded from the feed.
1170 * This should never return null -- you will either get an object or
1171 * an exception will be thrown.
1173 * @param DOMElement $feedEl root element of a loaded RSS feed
1174 * @param array $hints additional discovery information passed from higher levels
1175 * @todo FIXME: Should this be marked public?
1176 * @return Ostatus_profile
1179 public static function ensureRssChannel($feedEl, $hints)
1181 // Special-case for Posterous. They have some nice metadata in their
1182 // posterous:author elements. We should use them instead of the channel.
1184 $items = $feedEl->getElementsByTagName('item');
1186 if ($items->length > 0) {
1187 $item = $items->item(0);
1188 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1189 if (!empty($authorEl)) {
1190 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1191 // Posterous has multiple authors per feed, and multiple feeds
1192 // per author. We check if this is the "main" feed for this author.
1193 if (array_key_exists('profileurl', $hints) &&
1194 !empty($obj->poco) &&
1195 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1196 return self::ensureActivityObjectProfile($obj, $hints);
1201 // @todo FIXME: We should check whether this feed has elements
1202 // with different <author> or <dc:creator> elements, and... I dunno.
1203 // Do something about that.
1205 $obj = ActivityObject::fromRssChannel($feedEl);
1207 return self::ensureActivityObjectProfile($obj, $hints);
1211 * Download and update given avatar image
1213 * @param string $url
1214 * @throws Exception in various failure cases
1216 protected function updateAvatar($url)
1218 if ($url == $this->avatar) {
1219 // We've already got this one.
1222 if (!common_valid_http_url($url)) {
1223 // TRANS: Server exception. %s is a URL.
1224 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1227 if ($this->isGroup()) {
1228 $self = $this->localGroup();
1230 $self = $this->localProfile();
1233 throw new ServerException(sprintf(
1234 // TRANS: Server exception. %s is a URI.
1235 _m('Tried to update avatar for unsaved remote profile %s.'),
1239 // @todo FIXME: This should be better encapsulated
1240 // ripped from oauthstore.php (for old OMB client)
1241 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1243 if (!copy($url, $temp_filename)) {
1244 // TRANS: Server exception. %s is a URL.
1245 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1248 if ($this->isGroup()) {
1249 $id = $this->group_id;
1251 $id = $this->profile_id;
1253 // @todo FIXME: Should we be using different ids?
1254 $imagefile = new ImageFile($id, $temp_filename);
1255 $filename = Avatar::filename($id,
1256 image_type_to_extension($imagefile->type),
1258 common_timestamp());
1259 rename($temp_filename, Avatar::path($filename));
1260 } catch (Exception $e) {
1261 unlink($temp_filename);
1264 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1265 // keep from accidentally saving images from command-line (queues)
1266 // that can't be read from web server, which causes hard-to-notice
1267 // problems later on:
1269 // http://status.net/open-source/issues/2663
1270 chmod(Avatar::path($filename), 0644);
1272 $self->setOriginal($filename);
1274 $orig = clone($this);
1275 $this->avatar = $url;
1276 $this->update($orig);
1280 * Pull avatar URL from ActivityObject or profile hints
1282 * @param ActivityObject $object
1283 * @param array $hints
1284 * @return mixed URL string or false
1286 public static function getActivityObjectAvatar($object, $hints=array())
1288 if ($object->avatarLinks) {
1290 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1291 foreach ($object->avatarLinks as $avatar) {
1292 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1297 if (!$best || $avatar->width > $best->width) {
1302 } else if (array_key_exists('avatar', $hints)) {
1303 return $hints['avatar'];
1309 * Get an appropriate avatar image source URL, if available.
1311 * @param ActivityObject $actor
1312 * @param DOMElement $feed
1315 protected static function getAvatar($actor, $feed)
1319 if ($actor->avatar) {
1320 $url = trim($actor->avatar);
1323 // Check <atom:logo> and <atom:icon> on the feed
1324 $els = $feed->childNodes();
1325 if ($els && $els->length) {
1326 for ($i = 0; $i < $els->length; $i++) {
1327 $el = $els->item($i);
1328 if ($el->namespaceURI == Activity::ATOM) {
1329 if (empty($url) && $el->localName == 'logo') {
1330 $url = trim($el->textContent);
1333 if (empty($icon) && $el->localName == 'icon') {
1334 // Use as a fallback
1335 $icon = trim($el->textContent);
1340 if ($icon && !$url) {
1345 $opts = array('allowed_schemes' => array('http', 'https'));
1346 if (common_valid_http_url($url)) {
1351 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1355 * Fetch, or build if necessary, an Ostatus_profile for the actor
1356 * in a given Activity Streams activity.
1357 * This should never return null -- you will either get an object or
1358 * an exception will be thrown.
1360 * @param Activity $activity
1361 * @param string $feeduri if we already know the canonical feed URI!
1362 * @param string $salmonuri if we already know the salmon return channel URI
1363 * @return Ostatus_profile
1366 public static function ensureActorProfile($activity, $hints=array())
1368 return self::ensureActivityObjectProfile($activity->actor, $hints);
1372 * Fetch, or build if necessary, an Ostatus_profile for the profile
1373 * in a given Activity Streams object (can be subject, actor, or object).
1374 * This should never return null -- you will either get an object or
1375 * an exception will be thrown.
1377 * @param ActivityObject $object
1378 * @param array $hints additional discovery information passed from higher levels
1379 * @return Ostatus_profile
1382 public static function ensureActivityObjectProfile($object, $hints=array())
1384 $profile = self::getActivityObjectProfile($object);
1386 $profile->updateFromActivityObject($object, $hints);
1388 $profile = self::createActivityObjectProfile($object, $hints);
1394 * @param Activity $activity
1395 * @return mixed matching Ostatus_profile or false if none known
1396 * @throws ServerException if feed info invalid
1398 public static function getActorProfile($activity)
1400 return self::getActivityObjectProfile($activity->actor);
1404 * @param ActivityObject $activity
1405 * @return mixed matching Ostatus_profile or false if none known
1406 * @throws ServerException if feed info invalid
1408 protected static function getActivityObjectProfile($object)
1410 $uri = self::getActivityObjectProfileURI($object);
1411 return Ostatus_profile::getKV('uri', $uri);
1415 * Get the identifier URI for the remote entity described
1416 * by this ActivityObject. This URI is *not* guaranteed to be
1417 * a resolvable HTTP/HTTPS URL.
1419 * @param ActivityObject $object
1421 * @throws ServerException if feed info invalid
1423 protected static function getActivityObjectProfileURI($object)
1426 if (ActivityUtils::validateUri($object->id)) {
1431 // If the id is missing or invalid (we've seen feeds mistakenly listing
1432 // things like local usernames in that field) then we'll use the profile
1433 // page link, if valid.
1434 if ($object->link && common_valid_http_url($object->link)) {
1435 return $object->link;
1437 // TRANS: Server exception.
1438 throw new ServerException(_m('No author ID URI found.'));
1442 * @todo FIXME: Validate stuff somewhere.
1446 * Create local ostatus_profile and profile/user_group entries for
1447 * the provided remote user or group.
1448 * This should never return null -- you will either get an object or
1449 * an exception will be thrown.
1451 * @param ActivityObject $object
1452 * @param array $hints
1454 * @return Ostatus_profile
1456 protected static function createActivityObjectProfile($object, $hints=array())
1458 $homeuri = $object->id;
1462 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1463 // TRANS: Exception.
1464 throw new Exception(_m('No profile URI.'));
1467 $user = User::getKV('uri', $homeuri);
1468 if ($user instanceof User) {
1469 // TRANS: Exception.
1470 throw new Exception(_m('Local user cannot be referenced as remote.'));
1473 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1474 // TRANS: Exception.
1475 throw new Exception(_m('Local group cannot be referenced as remote.'));
1478 $ptag = Profile_list::getKV('uri', $homeuri);
1479 if ($ptag instanceof Profile_list) {
1480 $local_user = User::getKV('id', $ptag->tagger);
1481 if ($local_user instanceof User) {
1482 // TRANS: Exception.
1483 throw new Exception(_m('Local list cannot be referenced as remote.'));
1487 if (array_key_exists('feedurl', $hints)) {
1488 $feeduri = $hints['feedurl'];
1490 $discover = new FeedDiscovery();
1491 $feeduri = $discover->discoverFromURL($homeuri);
1494 if (array_key_exists('salmon', $hints)) {
1495 $salmonuri = $hints['salmon'];
1498 $discover = new FeedDiscovery();
1499 $discover->discoverFromFeedURL($hints['feedurl']);
1501 // XXX: NS_REPLIES is deprecated anyway, so let's remove it in the future.
1502 $salmonuri = $discover->getAtomLink(Salmon::REL_SALMON)
1503 ?: $discover->getAtomLink(Salmon::NS_REPLIES);
1506 if (array_key_exists('hub', $hints)) {
1507 $huburi = $hints['hub'];
1510 $discover = new FeedDiscovery();
1511 $discover->discoverFromFeedURL($hints['feedurl']);
1513 $huburi = $discover->getHubLink();
1516 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1517 // We can only deal with folks with a PuSH hub
1518 throw new FeedSubNoHubException();
1521 $oprofile = new Ostatus_profile();
1523 $oprofile->uri = $homeuri;
1524 $oprofile->feeduri = $feeduri;
1525 $oprofile->salmonuri = $salmonuri;
1527 $oprofile->created = common_sql_now();
1528 $oprofile->modified = common_sql_now();
1530 if ($object->type == ActivityObject::PERSON) {
1531 $profile = new Profile();
1532 $profile->created = common_sql_now();
1533 self::updateProfile($profile, $object, $hints);
1535 $oprofile->profile_id = $profile->insert();
1536 if ($oprofile->profile_id === false) {
1537 // TRANS: Server exception.
1538 throw new ServerException(_m('Cannot save local profile.'));
1540 } else if ($object->type == ActivityObject::GROUP) {
1541 $profile = new Profile();
1542 $profile->query('BEGIN');
1544 $group = new User_group();
1545 $group->uri = $homeuri;
1546 $group->created = common_sql_now();
1547 self::updateGroup($group, $object, $hints);
1549 // TODO: We should do this directly in User_group->insert()!
1550 // currently it's duplicated in User_group->update()
1551 // AND User_group->register()!!!
1552 $fields = array(/*group field => profile field*/
1553 'nickname' => 'nickname',
1554 'fullname' => 'fullname',
1555 'mainpage' => 'profileurl',
1556 'homepage' => 'homepage',
1557 'description' => 'bio',
1558 'location' => 'location',
1559 'created' => 'created',
1560 'modified' => 'modified',
1562 foreach ($fields as $gf=>$pf) {
1563 $profile->$pf = $group->$gf;
1565 $profile_id = $profile->insert();
1566 if ($profile_id === false) {
1567 $profile->query('ROLLBACK');
1568 throw new ServerException(_('Profile insertion failed.'));
1571 $group->profile_id = $profile_id;
1573 $oprofile->group_id = $group->insert();
1574 if ($oprofile->group_id === false) {
1575 $profile->query('ROLLBACK');
1576 // TRANS: Server exception.
1577 throw new ServerException(_m('Cannot save local profile.'));
1580 $profile->query('COMMIT');
1581 } else if ($object->type == ActivityObject::_LIST) {
1582 $ptag = new Profile_list();
1583 $ptag->uri = $homeuri;
1584 $ptag->created = common_sql_now();
1585 self::updatePeopletag($ptag, $object, $hints);
1587 $oprofile->peopletag_id = $ptag->insert();
1588 if ($oprofile->peopletag_id === false) {
1589 // TRANS: Server exception.
1590 throw new ServerException(_m('Cannot save local list.'));
1594 $ok = $oprofile->insert();
1596 if ($ok === false) {
1597 // TRANS: Server exception.
1598 throw new ServerException(_m('Cannot save OStatus profile.'));
1601 $avatar = self::getActivityObjectAvatar($object, $hints);
1605 $oprofile->updateAvatar($avatar);
1606 } catch (Exception $ex) {
1607 // Profile is saved, but Avatar is messed up. We're
1608 // just going to continue.
1609 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1617 * Save any updated profile information to our local copy.
1618 * @param ActivityObject $object
1619 * @param array $hints
1621 public function updateFromActivityObject($object, $hints=array())
1623 if ($this->isGroup()) {
1624 $group = $this->localGroup();
1625 self::updateGroup($group, $object, $hints);
1626 } else if ($this->isPeopletag()) {
1627 $ptag = $this->localPeopletag();
1628 self::updatePeopletag($ptag, $object, $hints);
1630 $profile = $this->localProfile();
1631 self::updateProfile($profile, $object, $hints);
1634 $avatar = self::getActivityObjectAvatar($object, $hints);
1635 if ($avatar && !isset($ptag)) {
1637 $this->updateAvatar($avatar);
1638 } catch (Exception $ex) {
1639 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1644 public static function updateProfile($profile, $object, $hints=array())
1646 $orig = clone($profile);
1648 // Existing nickname is better than nothing.
1650 if (!array_key_exists('nickname', $hints)) {
1651 $hints['nickname'] = $profile->nickname;
1654 $nickname = self::getActivityObjectNickname($object, $hints);
1656 if (!empty($nickname)) {
1657 $profile->nickname = $nickname;
1660 if (!empty($object->title)) {
1661 $profile->fullname = $object->title;
1662 } else if (array_key_exists('fullname', $hints)) {
1663 $profile->fullname = $hints['fullname'];
1666 if (!empty($object->link)) {
1667 $profile->profileurl = $object->link;
1668 } else if (array_key_exists('profileurl', $hints)) {
1669 $profile->profileurl = $hints['profileurl'];
1670 } else if (common_valid_http_url($object->id)) {
1671 $profile->profileurl = $object->id;
1674 $bio = self::getActivityObjectBio($object, $hints);
1677 $profile->bio = $bio;
1680 $location = self::getActivityObjectLocation($object, $hints);
1682 if (!empty($location)) {
1683 $profile->location = $location;
1686 $homepage = self::getActivityObjectHomepage($object, $hints);
1688 if (!empty($homepage)) {
1689 $profile->homepage = $homepage;
1692 if (!empty($object->geopoint)) {
1693 $location = ActivityContext::locationFromPoint($object->geopoint);
1694 if (!empty($location)) {
1695 $profile->lat = $location->lat;
1696 $profile->lon = $location->lon;
1700 // @todo FIXME: tags/categories
1701 // @todo tags from categories
1704 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1705 $profile->update($orig);
1709 protected static function updateGroup(User_group $group, $object, $hints=array())
1711 $orig = clone($group);
1713 $group->nickname = self::getActivityObjectNickname($object, $hints);
1714 $group->fullname = $object->title;
1716 if (!empty($object->link)) {
1717 $group->mainpage = $object->link;
1718 } else if (array_key_exists('profileurl', $hints)) {
1719 $group->mainpage = $hints['profileurl'];
1722 // @todo tags from categories
1723 $group->description = self::getActivityObjectBio($object, $hints);
1724 $group->location = self::getActivityObjectLocation($object, $hints);
1725 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1727 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1728 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1729 $group->update($orig);
1733 protected static function updatePeopletag($tag, $object, $hints=array()) {
1734 $orig = clone($tag);
1736 $tag->tag = $object->title;
1738 if (!empty($object->link)) {
1739 $tag->mainpage = $object->link;
1740 } else if (array_key_exists('profileurl', $hints)) {
1741 $tag->mainpage = $hints['profileurl'];
1744 $tag->description = $object->summary;
1745 $tagger = self::ensureActivityObjectProfile($object->owner);
1746 $tag->tagger = $tagger->profile_id;
1749 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1750 $tag->update($orig);
1754 protected static function getActivityObjectHomepage($object, $hints=array())
1757 $poco = $object->poco;
1759 if (!empty($poco)) {
1760 $url = $poco->getPrimaryURL();
1761 if ($url && $url->type == 'homepage') {
1762 $homepage = $url->value;
1766 // @todo Try for a another PoCo URL?
1771 protected static function getActivityObjectLocation($object, $hints=array())
1775 if (!empty($object->poco) &&
1776 isset($object->poco->address->formatted)) {
1777 $location = $object->poco->address->formatted;
1778 } else if (array_key_exists('location', $hints)) {
1779 $location = $hints['location'];
1782 if (!empty($location)) {
1783 if (mb_strlen($location) > 255) {
1784 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1788 // @todo Try to find location some othe way? Via goerss point?
1793 protected static function getActivityObjectBio($object, $hints=array())
1797 if (!empty($object->poco)) {
1798 $note = $object->poco->note;
1799 } else if (array_key_exists('bio', $hints)) {
1800 $note = $hints['bio'];
1803 if (!empty($note)) {
1804 if (Profile::bioTooLong($note)) {
1805 // XXX: truncate ok?
1806 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1812 // @todo Try to get bio info some other way?
1817 public static function getActivityObjectNickname($object, $hints=array())
1819 if ($object->poco) {
1820 if (!empty($object->poco->preferredUsername)) {
1821 return common_nicknamize($object->poco->preferredUsername);
1825 if (!empty($object->nickname)) {
1826 return common_nicknamize($object->nickname);
1829 if (array_key_exists('nickname', $hints)) {
1830 return $hints['nickname'];
1833 // Try the profile url (like foo.example.com or example.com/user/foo)
1834 if (!empty($object->link)) {
1835 $profileUrl = $object->link;
1836 } else if (!empty($hints['profileurl'])) {
1837 $profileUrl = $hints['profileurl'];
1840 if (!empty($profileUrl)) {
1841 $nickname = self::nicknameFromURI($profileUrl);
1844 // Try the URI (may be a tag:, http:, acct:, ...
1846 if (empty($nickname)) {
1847 $nickname = self::nicknameFromURI($object->id);
1850 // Try a Webfinger if one was passed (way) down
1852 if (empty($nickname)) {
1853 if (array_key_exists('webfinger', $hints)) {
1854 $nickname = self::nicknameFromURI($hints['webfinger']);
1860 if (empty($nickname)) {
1861 $nickname = common_nicknamize($object->title);
1867 protected static function nicknameFromURI($uri)
1869 if (preg_match('/(\w+):/', $uri, $matches)) {
1870 $protocol = $matches[1];
1875 switch ($protocol) {
1878 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1879 return common_canonical_nickname($matches[1]);
1883 return common_url_to_nickname($uri);
1891 * Look up, and if necessary create, an Ostatus_profile for the remote
1892 * entity with the given webfinger address.
1893 * This should never return null -- you will either get an object or
1894 * an exception will be thrown.
1896 * @param string $addr webfinger address
1897 * @return Ostatus_profile
1898 * @throws Exception on error conditions
1899 * @throws OStatusShadowException if this reference would obscure a local user/group
1901 public static function ensureWebfinger($addr)
1903 // First, try the cache
1905 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1907 if ($uri !== false) {
1908 if (is_null($uri)) {
1909 // Negative cache entry
1910 // TRANS: Exception.
1911 throw new Exception(_m('Not a valid webfinger address.'));
1913 $oprofile = Ostatus_profile::getKV('uri', $uri);
1914 if ($oprofile instanceof Ostatus_profile) {
1919 // Try looking it up
1920 $oprofile = Ostatus_profile::getKV('uri', 'acct:'.$addr);
1922 if ($oprofile instanceof Ostatus_profile) {
1923 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1927 // Now, try some discovery
1929 $disco = new Discovery();
1932 $xrd = $disco->lookup($addr);
1933 } catch (Exception $e) {
1934 // Save negative cache entry so we don't waste time looking it up again.
1935 // @todo FIXME: Distinguish temporary failures?
1936 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1937 // TRANS: Exception.
1938 throw new Exception(_m('Not a valid webfinger address.'));
1941 $hints = array('webfinger' => $addr);
1943 $dhints = DiscoveryHints::fromXRD($xrd);
1945 $hints = array_merge($hints, $dhints);
1947 // If there's an Hcard, let's grab its info
1948 if (array_key_exists('hcard', $hints)) {
1949 if (!array_key_exists('profileurl', $hints) ||
1950 $hints['hcard'] != $hints['profileurl']) {
1951 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1952 $hints = array_merge($hcardHints, $hints);
1956 // If we got a feed URL, try that
1957 if (array_key_exists('feedurl', $hints)) {
1959 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1960 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1961 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1963 } catch (Exception $e) {
1964 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1969 // If we got a profile page, try that!
1970 if (array_key_exists('profileurl', $hints)) {
1972 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1973 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1974 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
1976 } catch (OStatusShadowException $e) {
1977 // We've ended up with a remote reference to a local user or group.
1978 // @todo FIXME: Ideally we should be able to say who it was so we can
1979 // go back and refer to it the regular way
1981 } catch (Exception $e) {
1982 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1985 // @todo FIXME: This means an error discovering from profile page
1986 // may give us a corrupt entry using the webfinger URI, which
1987 // will obscure the correct page-keyed profile later on.
1994 if (array_key_exists('salmon', $hints)) {
1995 $salmonEndpoint = $hints['salmon'];
1997 // An account URL, a salmon endpoint, and a dream? Not much to go
1998 // on, but let's give it a try
2000 $uri = 'acct:'.$addr;
2002 $profile = new Profile();
2004 $profile->nickname = self::nicknameFromUri($uri);
2005 $profile->created = common_sql_now();
2007 if (isset($profileUrl)) {
2008 $profile->profileurl = $profileUrl;
2011 $profile_id = $profile->insert();
2013 if ($profile_id === false) {
2014 common_log_db_error($profile, 'INSERT', __FILE__);
2015 // TRANS: Exception. %s is a webfinger address.
2016 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2019 $oprofile = new Ostatus_profile();
2021 $oprofile->uri = $uri;
2022 $oprofile->salmonuri = $salmonEndpoint;
2023 $oprofile->profile_id = $profile_id;
2024 $oprofile->created = common_sql_now();
2026 if (isset($feedUrl)) {
2027 $profile->feeduri = $feedUrl;
2030 $result = $oprofile->insert();
2032 if ($result === false) {
2033 common_log_db_error($oprofile, 'INSERT', __FILE__);
2034 // TRANS: Exception. %s is a webfinger address.
2035 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2038 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->getUri());
2042 // TRANS: Exception. %s is a webfinger address.
2043 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2047 * Store the full-length scrubbed HTML of a remote notice to an attachment
2048 * file on our server. We'll link to this at the end of the cropped version.
2050 * @param string $title plaintext for HTML page's title
2051 * @param string $rendered HTML fragment for HTML page's body
2054 function saveHTMLFile($title, $rendered)
2056 $final = sprintf("<!DOCTYPE html>\n" .
2058 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2059 '<title>%s</title>' .
2061 '<body>%s</body></html>',
2062 htmlspecialchars($title),
2065 $filename = File::filename($this->localProfile(),
2066 'ostatus', // ignored?
2069 $filepath = File::path($filename);
2071 file_put_contents($filepath, $final);
2075 $file->filename = $filename;
2076 $file->url = File::url($filename);
2077 $file->size = filesize($filepath);
2078 $file->date = time();
2079 $file->mimetype = 'text/html';
2081 $file_id = $file->insert();
2083 if ($file_id === false) {
2084 common_log_db_error($file, "INSERT", __FILE__);
2085 // TRANS: Server exception.
2086 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2092 static function ensureProfileURI($uri)
2096 // First, try to query it
2098 $oprofile = Ostatus_profile::getKV('uri', $uri);
2100 if ($oprofile instanceof Ostatus_profile) {
2104 // If unfound, do discovery stuff
2105 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2106 $protocol = $match[1];
2107 switch ($protocol) {
2110 $oprofile = self::ensureProfileURL($uri);
2115 $oprofile = self::ensureWebfinger($rest);
2118 // TRANS: Server exception.
2119 // TRANS: %1$s is a protocol, %2$s is a URI.
2120 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2126 // TRANS: Server exception. %s is a URI.
2127 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2133 function checkAuthorship($activity)
2135 if ($this->isGroup() || $this->isPeopletag()) {
2136 // A group or propletag feed will contain posts from multiple authors.
2137 $oprofile = self::ensureActorProfile($activity);
2138 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2139 // Groups can't post notices in StatusNet.
2140 common_log(LOG_WARNING,
2141 "OStatus: skipping post with group listed ".
2142 "as author: " . $oprofile->getUri() . " in feed from " . $this->getUri());
2146 $actor = $activity->actor;
2148 if (empty($actor)) {
2149 // OK here! assume the default
2150 } else if ($actor->id == $this->getUri() || $actor->link == $this->getUri()) {
2151 $this->updateFromActivityObject($actor);
2152 } else if ($actor->id) {
2153 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2154 // This isn't what we expect from mainline OStatus person feeds!
2155 // Group feeds go down another path, with different validation...
2156 // Most likely this is a plain ol' blog feed of some kind which
2157 // doesn't match our expectations. We'll take the entry, but ignore
2158 // the <author> info.
2159 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for " . $this->getUri());
2161 // Plain <author> without ActivityStreams actor info.
2162 // We'll just ignore this info for now and save the update under the feed's identity.
2173 * Exception indicating we've got a remote reference to a local user,
2174 * not a remote user!
2176 * If we can ue a local profile after all, it's available as $e->profile.
2178 class OStatusShadowException extends Exception
2183 * @param Profile $profile
2184 * @param string $message
2186 function __construct($profile, $message) {
2187 $this->profile = $profile;
2188 parent::__construct($message);