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')),
80 * Fetch the StatusNet-side profile for this feed
83 public function localProfile()
85 if ($this->profile_id) {
86 return Profile::getKV('id', $this->profile_id);
92 * Fetch the StatusNet-side profile for this feed
95 public function localGroup()
97 if ($this->group_id) {
98 return User_group::getKV('id', $this->group_id);
104 * Fetch the StatusNet-side peopletag for this feed
107 public function localPeopletag()
109 if ($this->peopletag_id) {
110 return Profile_list::getKV('id', $this->peopletag_id);
116 * Returns an ActivityObject describing this remote user or group profile.
117 * Can then be used to generate Atom chunks.
119 * @return ActivityObject
121 function asActivityObject()
123 if ($this->isGroup()) {
124 return ActivityObject::fromGroup($this->localGroup());
125 } else if ($this->isPeopletag()) {
126 return ActivityObject::fromPeopletag($this->localPeopletag());
128 return ActivityObject::fromProfile($this->localProfile());
133 * Returns an XML string fragment with profile information as an
134 * Activity Streams noun object with the given element type.
136 * Assumes that 'activity' namespace has been previously defined.
138 * @todo FIXME: Replace with wrappers on asActivityObject when it's got everything.
140 * @param string $element one of 'actor', 'subject', 'object', 'target'
143 function asActivityNoun($element)
145 if ($this->isGroup()) {
146 $noun = ActivityObject::fromGroup($this->localGroup());
147 return $noun->asString('activity:' . $element);
148 } else if ($this->isPeopletag()) {
149 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
150 return $noun->asString('activity:' . $element);
152 $noun = ActivityObject::fromProfile($this->localProfile());
153 return $noun->asString('activity:' . $element);
158 * @return boolean true if this is a remote group
162 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
164 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
166 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
167 // TRANS: Server exception. %s is a URI
168 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->uri));
170 // TRANS: Server exception. %s is a URI
171 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->uri));
176 * @return boolean true if this is a remote peopletag
178 function isPeopletag()
180 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
182 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
184 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
185 // TRANS: Server exception. %s is a URI
186 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->uri));
188 // TRANS: Server exception. %s is a URI
189 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->uri));
194 * Send a subscription request to the hub for this feed.
195 * The hub will later send us a confirmation POST to /main/push/callback.
197 * @return bool true on success, false on failure
198 * @throws ServerException if feed state is not valid
200 public function subscribe()
202 $feedsub = FeedSub::ensureFeed($this->feeduri);
203 if ($feedsub->sub_state == 'active') {
204 // Active subscription, we don't need to do anything.
207 // Inactive or we got left in an inconsistent state.
208 // Run a subscription request to make sure we're current!
209 return $feedsub->subscribe();
214 * Check if this remote profile has any active local subscriptions, and
215 * if not drop the PuSH subscription feed.
217 * @return bool true on success, false on failure
219 public function unsubscribe() {
220 $this->garbageCollect();
224 * Check if this remote profile has any active local subscriptions, and
225 * if not drop the PuSH subscription feed.
229 public function garbageCollect()
231 $feedsub = FeedSub::getKV('uri', $this->feeduri);
232 return $feedsub->garbageCollect();
236 * Check if this remote profile has any active local subscriptions, so the
237 * PuSH subscription layer can decide if it can drop the feed.
239 * This gets called via the FeedSubSubscriberCount event when running
240 * FeedSub::garbageCollect().
244 public function subscriberCount()
246 if ($this->isGroup()) {
247 $members = $this->localGroup()->getMembers(0, 1);
248 $count = $members->N;
249 } else if ($this->isPeopletag()) {
250 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
251 $count = $subscribers->N;
253 $profile = $this->localProfile();
254 $count = $profile->subscriberCount();
255 if ($profile->hasLocalTags()) {
259 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
261 // Other plugins may be piggybacking on OStatus without having
262 // an active group or user-to-user subscription we know about.
263 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
264 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
270 * Send an Activity Streams notification to the remote Salmon endpoint,
273 * @param Profile $actor Actor who did the activity
274 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
275 * @param Object $object object of the action; must define asActivityNoun($tag)
277 public function notify($actor, $verb, $object=null, $target=null)
279 if (!($actor instanceof Profile)) {
280 $type = gettype($actor);
281 if ($type == 'object') {
282 $type = get_class($actor);
284 // TRANS: Server exception.
285 // TRANS: %1$s is the method name the exception occured in, %2$s is the actor type.
286 throw new ServerException(sprintf(_m('Invalid actor passed to %1$s: %2$s.'),__METHOD__,$type));
288 if ($object == null) {
291 if ($this->salmonuri) {
293 $id = TagURI::mint('%s:%s:%s',
296 common_date_iso8601(time()));
298 // @todo FIXME: Consolidate all these NS settings somewhere.
299 $attributes = array('xmlns' => Activity::ATOM,
300 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
301 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
302 'xmlns:georss' => 'http://www.georss.org/georss',
303 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
304 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
305 'xmlns:media' => 'http://purl.org/syndication/atommedia');
307 $entry = new XMLStringer();
308 $entry->elementStart('entry', $attributes);
309 $entry->element('id', null, $id);
310 $entry->element('title', null, $text);
311 $entry->element('summary', null, $text);
312 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
314 $entry->element('activity:verb', null, $verb);
315 $entry->raw($actor->asAtomAuthor());
316 $entry->raw($actor->asActivityActor());
317 $entry->raw($object->asActivityNoun('object'));
318 if ($target != null) {
319 $entry->raw($target->asActivityNoun('target'));
321 $entry->elementEnd('entry');
323 $xml = $entry->getString();
324 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
326 $salmon = new Salmon(); // ?
327 return $salmon->post($this->salmonuri, $xml, $actor);
333 * Send a Salmon notification ping immediately, and confirm that we got
334 * an acceptable response from the remote site.
336 * @param mixed $entry XML string, Notice, or Activity
337 * @param Profile $actor
338 * @return boolean success
340 public function notifyActivity($entry, $actor)
342 if ($this->salmonuri) {
343 $salmon = new Salmon();
344 return $salmon->post($this->salmonuri, $this->notifyPrepXml($entry), $actor);
351 * Queue a Salmon notification for later. If queues are disabled we'll
352 * send immediately but won't get the return value.
354 * @param mixed $entry XML string, Notice, or Activity
355 * @return boolean success
357 public function notifyDeferred($entry, $actor)
359 if ($this->salmonuri) {
360 $data = array('salmonuri' => $this->salmonuri,
361 'entry' => $this->notifyPrepXml($entry),
362 'actor' => $actor->id);
364 $qm = QueueManager::get();
365 return $qm->enqueue($data, 'salmon');
371 protected function notifyPrepXml($entry)
373 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
374 if (is_string($entry)) {
376 } else if ($entry instanceof Activity) {
377 return $preamble . $entry->asString(true);
378 } else if ($entry instanceof Notice) {
379 return $preamble . $entry->asAtomEntry(true, true);
381 // TRANS: Server exception.
382 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
386 function getBestName()
388 if ($this->isGroup()) {
389 return $this->localGroup()->getBestName();
390 } else if ($this->isPeopletag()) {
391 return $this->localPeopletag()->getBestName();
393 return $this->localProfile()->getBestName();
398 * Read and post notices for updates from the feed.
399 * Currently assumes that all items in the feed are new,
400 * coming from a PuSH hub.
402 * @param DOMDocument $doc
403 * @param string $source identifier ("push")
405 public function processFeed(DOMDocument $doc, $source)
407 $feed = $doc->documentElement;
409 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
410 $this->processAtomFeed($feed, $source);
411 } else if ($feed->localName == 'rss') { // @todo FIXME: Check namespace.
412 $this->processRssFeed($feed, $source);
415 throw new Exception(_m('Unknown feed format.'));
419 public function processAtomFeed(DOMElement $feed, $source)
421 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
422 if ($entries->length == 0) {
423 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
427 for ($i = 0; $i < $entries->length; $i++) {
428 $entry = $entries->item($i);
429 $this->processEntry($entry, $feed, $source);
433 public function processRssFeed(DOMElement $rss, $source)
435 $channels = $rss->getElementsByTagName('channel');
437 if ($channels->length == 0) {
439 throw new Exception(_m('RSS feed without a channel.'));
440 } else if ($channels->length > 1) {
441 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
444 $channel = $channels->item(0);
446 $items = $channel->getElementsByTagName('item');
448 for ($i = 0; $i < $items->length; $i++) {
449 $item = $items->item($i);
450 $this->processEntry($item, $channel, $source);
455 * Process a posted entry from this feed source.
457 * @param DOMElement $entry
458 * @param DOMElement $feed for context
459 * @param string $source identifier ("push" or "salmon")
461 * @return Notice Notice representing the new (or existing) activity
463 public function processEntry($entry, $feed, $source)
465 $activity = new Activity($entry, $feed);
466 return $this->processActivity($activity, $source);
469 // TODO: Make this throw an exception
470 public function processActivity($activity, $source)
474 // The "WithProfile" events were added later.
476 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this, &$notice)) &&
477 Event::handle('StartHandleFeedEntry', array($activity))) {
479 switch ($activity->verb) {
480 case ActivityVerb::POST:
481 // @todo process all activity objects
482 switch ($activity->objects[0]->type) {
483 case ActivityObject::ARTICLE:
484 case ActivityObject::BLOGENTRY:
485 case ActivityObject::NOTE:
486 case ActivityObject::STATUS:
487 case ActivityObject::COMMENT:
489 $notice = $this->processPost($activity, $source);
492 // TRANS: Client exception.
493 throw new ClientException(_m('Cannot handle that kind of post.'));
496 case ActivityVerb::SHARE:
497 $notice = $this->processShare($activity, $source);
500 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
503 Event::handle('EndHandleFeedEntry', array($activity));
504 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
510 public function processShare($activity, $method)
514 $oprofile = $this->checkAuthorship($activity);
516 if (empty($oprofile)) {
517 common_log(LOG_INFO, "No author matched share activity");
521 // The id URI will be used as a unique identifier for the notice,
522 // protecting against duplicate saves. It isn't required to be a URL;
523 // tag: URIs for instance are found in Google Buzz feeds.
524 $dupe = Notice::getKV('uri', $activity->id);
525 if ($dupe instanceof Notice) {
526 common_log(LOG_INFO, "OStatus: ignoring duplicate post: {$activity->id}");
530 if (count($activity->objects) != 1) {
531 // TRANS: Client exception thrown when trying to share multiple activities at once.
532 throw new ClientException(_m('Can only handle share activities with exactly one object.'));
535 $shared = $activity->objects[0];
537 if (!($shared instanceof Activity)) {
538 // TRANS: Client exception thrown when trying to share a non-activity object.
539 throw new ClientException(_m('Can only handle shared activities.'));
542 $sharedId = $shared->id;
543 if (!empty($shared->objects[0]->id)) {
544 // Because StatusNet since commit 8cc4660 sets $shared->id to a TagURI which
545 // fucks up federation, because the URI is no longer recognised by the origin.
546 // ...but it might still be empty (not present) because $shared->id is set.
547 $sharedId = $shared->objects[0]->id;
549 if (empty($sharedId)) {
550 throw new ClientException(_m('Shared activity does not have an id'));
553 // First check if we have the shared activity. This has to be done first, because
554 // we can't use these functions to "ensureActivityObjectProfile" of a local user,
555 // who might be the creator of the shared activity in question.
556 $sharedNotice = Notice::getKV('uri', $sharedId);
557 if (!($sharedNotice instanceof Notice)) {
558 // If no local notice is found, process it!
559 // TODO: Remember to check Deleted_notice!
560 $other = Ostatus_profile::ensureActivityObjectProfile($shared->actor);
561 $sharedNotice = $other->processActivity($shared, $method);
564 if (!($sharedNotice instanceof Notice)) {
565 // And if we apparently can't get the shared notice, we'll abort the whole thing.
566 // TRANS: Client exception thrown when saving an activity share fails.
567 // TRANS: %s is a share ID.
568 throw new ClientException(sprintf(_m('Failed to save activity %s.'), $sharedId));
571 // We'll want to save a web link to the original notice, if provided.
574 if ($activity->link) {
575 $sourceUrl = $activity->link;
576 } else if ($activity->link) {
577 $sourceUrl = $activity->link;
578 } else if (preg_match('!^https?://!', $activity->id)) {
579 $sourceUrl = $activity->id;
582 // Use summary as fallback for content
584 if (!empty($activity->content)) {
585 $sourceContent = $activity->content;
586 } else if (!empty($activity->summary)) {
587 $sourceContent = $activity->summary;
588 } else if (!empty($activity->title)) {
589 $sourceContent = $activity->title;
591 // @todo FIXME: Fetch from $sourceUrl?
592 // TRANS: Client exception. %s is a source URI.
593 throw new ClientException(sprintf(_m('No content for notice %s.'), $activity->id));
596 // Get (safe!) HTML and text versions of the content
598 $rendered = $this->purify($sourceContent);
599 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
601 $shortened = common_shorten_links($content);
603 // If it's too long, try using the summary, and make the
604 // HTML an attachment.
608 if (Notice::contentTooLong($shortened)) {
609 $attachment = $this->saveHTMLFile($activity->title, $rendered);
610 $summary = html_entity_decode(strip_tags($activity->summary), ENT_QUOTES, 'UTF-8');
611 if (empty($summary)) {
614 $shortSummary = common_shorten_links($summary);
615 if (Notice::contentTooLong($shortSummary)) {
616 $url = common_shorten_url($sourceUrl);
617 $shortSummary = substr($shortSummary,
619 Notice::maxContent() - (mb_strlen($url) + 2));
620 $content = $shortSummary . ' ' . $url;
622 // We mark up the attachment link specially for the HTML output
623 // so we can fold-out the full version inline.
625 // @todo FIXME i18n: This tooltip will be saved with the site's default language
626 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
627 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
628 $showMoreText = _m('Show more');
629 $attachUrl = common_local_url('attachment',
630 array('attachment' => $attachment->id));
631 $rendered = common_render_text($shortSummary) .
632 '<a href="' . htmlspecialchars($attachUrl) .'"'.
633 ' class="attachment more"' .
634 ' title="'. htmlspecialchars($showMoreText) . '">' .
640 $options = array('is_local' => Notice::REMOTE,
642 'uri' => $activity->id,
643 'rendered' => $rendered,
644 'replies' => array(),
646 'peopletags' => array(),
649 'repeat_of' => $sharedNotice->id,
650 'scope' => $sharedNotice->scope);
652 // Check for optional attributes...
654 if (!empty($activity->time)) {
655 $options['created'] = common_sql_date($activity->time);
658 if ($activity->context) {
659 // TODO: context->attention
660 list($options['groups'], $options['replies'])
661 = $this->filterReplies($oprofile, $activity->context->attention);
663 // Maintain direct reply associations
664 // @todo FIXME: What about conversation ID?
665 if (!empty($activity->context->replyToID)) {
666 $orig = Notice::getKV('uri',
667 $activity->context->replyToID);
669 $options['reply_to'] = $orig->id;
673 $location = $activity->context->location;
675 $options['lat'] = $location->lat;
676 $options['lon'] = $location->lon;
677 if ($location->location_id) {
678 $options['location_ns'] = $location->location_ns;
679 $options['location_id'] = $location->location_id;
684 if ($this->isPeopletag()) {
685 $options['peopletags'][] = $this->localPeopletag();
688 // Atom categories <-> hashtags
689 foreach ($activity->categories as $cat) {
691 $term = common_canonical_tag($cat->term);
693 $options['tags'][] = $term;
698 // Atom enclosures -> attachment URLs
699 foreach ($activity->enclosures as $href) {
700 // @todo FIXME: Save these locally or....?
701 $options['urls'][] = $href;
704 $notice = Notice::saveNew($oprofile->profile_id,
713 * Process an incoming post activity from this remote feed.
714 * @param Activity $activity
715 * @param string $method 'push' or 'salmon'
716 * @return mixed saved Notice or false
717 * @todo FIXME: Break up this function, it's getting nasty long
719 public function processPost($activity, $method)
723 $oprofile = $this->checkAuthorship($activity);
725 if (empty($oprofile)) {
729 // It's not always an ActivityObject::NOTE, but... let's just say it is.
731 $note = $activity->objects[0];
733 // The id URI will be used as a unique identifier for for the notice,
734 // protecting against duplicate saves. It isn't required to be a URL;
735 // tag: URIs for instance are found in Google Buzz feeds.
736 $sourceUri = $note->id;
737 $dupe = Notice::getKV('uri', $sourceUri);
739 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
743 // We'll also want to save a web link to the original notice, if provided.
746 $sourceUrl = $note->link;
747 } else if ($activity->link) {
748 $sourceUrl = $activity->link;
749 } else if (preg_match('!^https?://!', $note->id)) {
750 $sourceUrl = $note->id;
753 // Use summary as fallback for content
755 if (!empty($note->content)) {
756 $sourceContent = $note->content;
757 } else if (!empty($note->summary)) {
758 $sourceContent = $note->summary;
759 } else if (!empty($note->title)) {
760 $sourceContent = $note->title;
762 // @todo FIXME: Fetch from $sourceUrl?
763 // TRANS: Client exception. %s is a source URI.
764 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
767 // Get (safe!) HTML and text versions of the content
769 $rendered = $this->purify($sourceContent);
770 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
772 $shortened = common_shorten_links($content);
774 // If it's too long, try using the summary, and make the
775 // HTML an attachment.
779 if (Notice::contentTooLong($shortened)) {
780 $attachment = $this->saveHTMLFile($note->title, $rendered);
781 $summary = html_entity_decode(strip_tags($note->summary), ENT_QUOTES, 'UTF-8');
782 if (empty($summary)) {
785 $shortSummary = common_shorten_links($summary);
786 if (Notice::contentTooLong($shortSummary)) {
787 $url = common_shorten_url($sourceUrl);
788 $shortSummary = substr($shortSummary,
790 Notice::maxContent() - (mb_strlen($url) + 2));
791 $content = $shortSummary . ' ' . $url;
793 // We mark up the attachment link specially for the HTML output
794 // so we can fold-out the full version inline.
796 // @todo FIXME i18n: This tooltip will be saved with the site's default language
797 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
798 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
799 $showMoreText = _m('Show more');
800 $attachUrl = common_local_url('attachment',
801 array('attachment' => $attachment->id));
802 $rendered = common_render_text($shortSummary) .
803 '<a href="' . htmlspecialchars($attachUrl) .'"'.
804 ' class="attachment more"' .
805 ' title="'. htmlspecialchars($showMoreText) . '">' .
811 $options = array('is_local' => Notice::REMOTE,
814 'rendered' => $rendered,
815 'replies' => array(),
817 'peopletags' => array(),
821 // Check for optional attributes...
823 if (!empty($activity->time)) {
824 $options['created'] = common_sql_date($activity->time);
827 if ($activity->context) {
828 // TODO: context->attention
829 list($options['groups'], $options['replies'])
830 = $this->filterReplies($oprofile, $activity->context->attention);
832 // Maintain direct reply associations
833 // @todo FIXME: What about conversation ID?
834 if (!empty($activity->context->replyToID)) {
835 $orig = Notice::getKV('uri',
836 $activity->context->replyToID);
838 $options['reply_to'] = $orig->id;
842 $location = $activity->context->location;
844 $options['lat'] = $location->lat;
845 $options['lon'] = $location->lon;
846 if ($location->location_id) {
847 $options['location_ns'] = $location->location_ns;
848 $options['location_id'] = $location->location_id;
853 if ($this->isPeopletag()) {
854 $options['peopletags'][] = $this->localPeopletag();
857 // Atom categories <-> hashtags
858 foreach ($activity->categories as $cat) {
860 $term = common_canonical_tag($cat->term);
862 $options['tags'][] = $term;
867 // Atom enclosures -> attachment URLs
868 foreach ($activity->enclosures as $href) {
869 // @todo FIXME: Save these locally or....?
870 $options['urls'][] = $href;
874 $saved = Notice::saveNew($oprofile->profile_id,
879 Ostatus_source::saveNew($saved, $this, $method);
880 if (!empty($attachment)) {
881 File_to_post::processNew($attachment->id, $saved->id);
884 } catch (Exception $e) {
885 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
888 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
895 protected function purify($html)
897 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
898 $config = array('safe' => 1,
899 'deny_attribute' => 'id,style,on*');
900 return htmLawed($html, $config);
904 * Filters a list of recipient ID URIs to just those for local delivery.
905 * @param Ostatus_profile local profile of sender
906 * @param array in/out &$attention_uris set of URIs, will be pruned on output
907 * @return array of group IDs
909 protected function filterReplies($sender, array $attention)
911 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', $attention));
914 foreach ($attention as $recipient=>$type) {
915 // Is the recipient a local user?
916 $user = User::getKV('uri', $recipient);
917 if ($user instanceof User) {
918 // @todo FIXME: Sender verification, spam etc?
919 $replies[] = $recipient;
923 // Is the recipient a local group?
924 // TODO: $group = User_group::getKV('uri', $recipient);
925 $id = OStatusPlugin::localGroupFromUrl($recipient);
927 $group = User_group::getKV('id', $id);
928 if ($group instanceof User_group) {
929 // Deliver to all members of this local group if allowed.
930 $profile = $sender->localProfile();
931 if ($profile->isMember($group)) {
932 $groups[] = $group->id;
934 common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
938 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
942 // Is the recipient a remote user or group?
944 $oprofile = Ostatus_profile::ensureProfileURI($recipient);
945 if ($oprofile->isGroup()) {
946 // Deliver to local members of this remote group.
947 // @todo FIXME: Sender verification?
948 $groups[] = $oprofile->group_id;
950 // may be canonicalized or something
951 $replies[] = $oprofile->uri;
954 } catch (Exception $e) {
955 // Neither a recognizable local nor remote user!
956 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
960 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
961 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
962 return array($groups, $replies);
966 * Look up and if necessary create an Ostatus_profile for the remote entity
967 * with the given profile page URL. This should never return null -- you
968 * will either get an object or an exception will be thrown.
970 * @param string $profile_url
971 * @return Ostatus_profile
972 * @throws Exception on various error conditions
973 * @throws OStatusShadowException if this reference would obscure a local user/group
975 public static function ensureProfileURL($profile_url, $hints=array())
977 $oprofile = self::getFromProfileURL($profile_url);
979 if (!empty($oprofile)) {
983 $hints['profileurl'] = $profile_url;
988 $client = new HTTPClient();
989 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
990 $response = $client->get($profile_url);
992 if (!$response->isOk()) {
993 // TRANS: Exception. %s is a profile URL.
994 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
997 // Check if we have a non-canonical URL
999 $finalUrl = $response->getUrl();
1001 if ($finalUrl != $profile_url) {
1003 $hints['profileurl'] = $finalUrl;
1005 $oprofile = self::getFromProfileURL($finalUrl);
1007 if (!empty($oprofile)) {
1012 // Try to get some hCard data
1014 $body = $response->getBody();
1016 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1018 if (!empty($hcardHints)) {
1019 $hints = array_merge($hints, $hcardHints);
1022 // Check if they've got an LRDD header
1024 $lrdd = LinkHeader::getLink($response, 'lrdd');
1026 $xrd = new XML_XRD();
1027 $xrd->loadFile($lrdd);
1028 $xrdHints = DiscoveryHints::fromXRD($xrd);
1029 $hints = array_merge($hints, $xrdHints);
1030 } catch (Exception $e) {
1031 // No hints available from XRD
1034 // If discovery found a feedurl (probably from LRDD), use it.
1036 if (array_key_exists('feedurl', $hints)) {
1037 return self::ensureFeedURL($hints['feedurl'], $hints);
1040 // Get the feed URL from HTML
1042 $discover = new FeedDiscovery();
1044 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1046 if (!empty($feedurl)) {
1047 $hints['feedurl'] = $feedurl;
1048 return self::ensureFeedURL($feedurl, $hints);
1051 // TRANS: Exception. %s is a URL.
1052 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1056 * Look up the Ostatus_profile, if present, for a remote entity with the
1057 * given profile page URL. Will return null for both unknown and invalid
1060 * @return mixed Ostatus_profile or null
1061 * @throws OStatusShadowException for local profiles
1063 static function getFromProfileURL($profile_url)
1065 $profile = Profile::getKV('profileurl', $profile_url);
1067 if (empty($profile)) {
1071 // Is it a known Ostatus profile?
1073 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1075 if (!empty($oprofile)) {
1079 // Is it a local user?
1081 $user = User::getKV('id', $profile->id);
1083 if (!empty($user)) {
1084 // @todo i18n FIXME: use sprintf and add i18n (?)
1085 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1088 // Continue discovery; it's a remote profile
1089 // for OMB or some other protocol, may also
1096 * Look up and if necessary create an Ostatus_profile for remote entity
1097 * with the given update feed. This should never return null -- you will
1098 * either get an object or an exception will be thrown.
1100 * @return Ostatus_profile
1103 public static function ensureFeedURL($feed_url, $hints=array())
1105 $discover = new FeedDiscovery();
1107 $feeduri = $discover->discoverFromFeedURL($feed_url);
1108 $hints['feedurl'] = $feeduri;
1110 $huburi = $discover->getHubLink();
1111 $hints['hub'] = $huburi;
1112 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1113 $hints['salmon'] = $salmonuri;
1115 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1116 // We can only deal with folks with a PuSH hub
1117 throw new FeedSubNoHubException();
1120 $feedEl = $discover->root;
1122 if ($feedEl->tagName == 'feed') {
1123 return self::ensureAtomFeed($feedEl, $hints);
1124 } else if ($feedEl->tagName == 'channel') {
1125 return self::ensureRssChannel($feedEl, $hints);
1127 throw new FeedSubBadXmlException($feeduri);
1132 * Look up and, if necessary, create an Ostatus_profile for the remote
1133 * profile with the given Atom feed - actually loaded from the feed.
1134 * This should never return null -- you will either get an object or
1135 * an exception will be thrown.
1137 * @param DOMElement $feedEl root element of a loaded Atom feed
1138 * @param array $hints additional discovery information passed from higher levels
1139 * @todo FIXME: Should this be marked public?
1140 * @return Ostatus_profile
1143 public static function ensureAtomFeed($feedEl, $hints)
1145 $author = ActivityUtils::getFeedAuthor($feedEl);
1147 if (empty($author)) {
1148 // XXX: make some educated guesses here
1149 // TRANS: Feed sub exception.
1150 throw new FeedSubException(_m('Cannot find enough profile '.
1151 'information to make a feed.'));
1154 return self::ensureActivityObjectProfile($author, $hints);
1158 * Look up and, if necessary, create an Ostatus_profile for the remote
1159 * profile with the given RSS feed - actually loaded from the feed.
1160 * This should never return null -- you will either get an object or
1161 * an exception will be thrown.
1163 * @param DOMElement $feedEl root element of a loaded RSS feed
1164 * @param array $hints additional discovery information passed from higher levels
1165 * @todo FIXME: Should this be marked public?
1166 * @return Ostatus_profile
1169 public static function ensureRssChannel($feedEl, $hints)
1171 // Special-case for Posterous. They have some nice metadata in their
1172 // posterous:author elements. We should use them instead of the channel.
1174 $items = $feedEl->getElementsByTagName('item');
1176 if ($items->length > 0) {
1177 $item = $items->item(0);
1178 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1179 if (!empty($authorEl)) {
1180 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1181 // Posterous has multiple authors per feed, and multiple feeds
1182 // per author. We check if this is the "main" feed for this author.
1183 if (array_key_exists('profileurl', $hints) &&
1184 !empty($obj->poco) &&
1185 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1186 return self::ensureActivityObjectProfile($obj, $hints);
1191 // @todo FIXME: We should check whether this feed has elements
1192 // with different <author> or <dc:creator> elements, and... I dunno.
1193 // Do something about that.
1195 $obj = ActivityObject::fromRssChannel($feedEl);
1197 return self::ensureActivityObjectProfile($obj, $hints);
1201 * Download and update given avatar image
1203 * @param string $url
1204 * @throws Exception in various failure cases
1206 protected function updateAvatar($url)
1208 if ($url == $this->avatar) {
1209 // We've already got this one.
1212 if (!common_valid_http_url($url)) {
1213 // TRANS: Server exception. %s is a URL.
1214 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1217 if ($this->isGroup()) {
1218 $self = $this->localGroup();
1220 $self = $this->localProfile();
1223 throw new ServerException(sprintf(
1224 // TRANS: Server exception. %s is a URI.
1225 _m('Tried to update avatar for unsaved remote profile %s.'),
1229 // @todo FIXME: This should be better encapsulated
1230 // ripped from oauthstore.php (for old OMB client)
1231 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1233 if (!copy($url, $temp_filename)) {
1234 // TRANS: Server exception. %s is a URL.
1235 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1238 if ($this->isGroup()) {
1239 $id = $this->group_id;
1241 $id = $this->profile_id;
1243 // @todo FIXME: Should we be using different ids?
1244 $imagefile = new ImageFile($id, $temp_filename);
1245 $filename = Avatar::filename($id,
1246 image_type_to_extension($imagefile->type),
1248 common_timestamp());
1249 rename($temp_filename, Avatar::path($filename));
1250 } catch (Exception $e) {
1251 unlink($temp_filename);
1254 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1255 // keep from accidentally saving images from command-line (queues)
1256 // that can't be read from web server, which causes hard-to-notice
1257 // problems later on:
1259 // http://status.net/open-source/issues/2663
1260 chmod(Avatar::path($filename), 0644);
1262 $self->setOriginal($filename);
1264 $orig = clone($this);
1265 $this->avatar = $url;
1266 $this->update($orig);
1270 * Pull avatar URL from ActivityObject or profile hints
1272 * @param ActivityObject $object
1273 * @param array $hints
1274 * @return mixed URL string or false
1276 public static function getActivityObjectAvatar($object, $hints=array())
1278 if ($object->avatarLinks) {
1280 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1281 foreach ($object->avatarLinks as $avatar) {
1282 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1287 if (!$best || $avatar->width > $best->width) {
1292 } else if (array_key_exists('avatar', $hints)) {
1293 return $hints['avatar'];
1299 * Get an appropriate avatar image source URL, if available.
1301 * @param ActivityObject $actor
1302 * @param DOMElement $feed
1305 protected static function getAvatar($actor, $feed)
1309 if ($actor->avatar) {
1310 $url = trim($actor->avatar);
1313 // Check <atom:logo> and <atom:icon> on the feed
1314 $els = $feed->childNodes();
1315 if ($els && $els->length) {
1316 for ($i = 0; $i < $els->length; $i++) {
1317 $el = $els->item($i);
1318 if ($el->namespaceURI == Activity::ATOM) {
1319 if (empty($url) && $el->localName == 'logo') {
1320 $url = trim($el->textContent);
1323 if (empty($icon) && $el->localName == 'icon') {
1324 // Use as a fallback
1325 $icon = trim($el->textContent);
1330 if ($icon && !$url) {
1335 $opts = array('allowed_schemes' => array('http', 'https'));
1336 if (common_valid_http_url($url)) {
1341 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1345 * Fetch, or build if necessary, an Ostatus_profile for the actor
1346 * in a given Activity Streams activity.
1347 * This should never return null -- you will either get an object or
1348 * an exception will be thrown.
1350 * @param Activity $activity
1351 * @param string $feeduri if we already know the canonical feed URI!
1352 * @param string $salmonuri if we already know the salmon return channel URI
1353 * @return Ostatus_profile
1356 public static function ensureActorProfile($activity, $hints=array())
1358 return self::ensureActivityObjectProfile($activity->actor, $hints);
1362 * Fetch, or build if necessary, an Ostatus_profile for the profile
1363 * in a given Activity Streams object (can be subject, actor, or object).
1364 * This should never return null -- you will either get an object or
1365 * an exception will be thrown.
1367 * @param ActivityObject $object
1368 * @param array $hints additional discovery information passed from higher levels
1369 * @return Ostatus_profile
1372 public static function ensureActivityObjectProfile($object, $hints=array())
1374 $profile = self::getActivityObjectProfile($object);
1376 $profile->updateFromActivityObject($object, $hints);
1378 $profile = self::createActivityObjectProfile($object, $hints);
1384 * @param Activity $activity
1385 * @return mixed matching Ostatus_profile or false if none known
1386 * @throws ServerException if feed info invalid
1388 public static function getActorProfile($activity)
1390 return self::getActivityObjectProfile($activity->actor);
1394 * @param ActivityObject $activity
1395 * @return mixed matching Ostatus_profile or false if none known
1396 * @throws ServerException if feed info invalid
1398 protected static function getActivityObjectProfile($object)
1400 $uri = self::getActivityObjectProfileURI($object);
1401 return Ostatus_profile::getKV('uri', $uri);
1405 * Get the identifier URI for the remote entity described
1406 * by this ActivityObject. This URI is *not* guaranteed to be
1407 * a resolvable HTTP/HTTPS URL.
1409 * @param ActivityObject $object
1411 * @throws ServerException if feed info invalid
1413 protected static function getActivityObjectProfileURI($object)
1416 if (ActivityUtils::validateUri($object->id)) {
1421 // If the id is missing or invalid (we've seen feeds mistakenly listing
1422 // things like local usernames in that field) then we'll use the profile
1423 // page link, if valid.
1424 if ($object->link && common_valid_http_url($object->link)) {
1425 return $object->link;
1427 // TRANS: Server exception.
1428 throw new ServerException(_m('No author ID URI found.'));
1432 * @todo FIXME: Validate stuff somewhere.
1436 * Create local ostatus_profile and profile/user_group entries for
1437 * the provided remote user or group.
1438 * This should never return null -- you will either get an object or
1439 * an exception will be thrown.
1441 * @param ActivityObject $object
1442 * @param array $hints
1444 * @return Ostatus_profile
1446 protected static function createActivityObjectProfile($object, $hints=array())
1448 $homeuri = $object->id;
1452 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1453 // TRANS: Exception.
1454 throw new Exception(_m('No profile URI.'));
1457 $user = User::getKV('uri', $homeuri);
1459 // TRANS: Exception.
1460 throw new Exception(_m('Local user cannot be referenced as remote.'));
1463 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1464 // TRANS: Exception.
1465 throw new Exception(_m('Local group cannot be referenced as remote.'));
1468 $ptag = Profile_list::getKV('uri', $homeuri);
1470 $local_user = User::getKV('id', $ptag->tagger);
1471 if (!empty($local_user)) {
1472 // TRANS: Exception.
1473 throw new Exception(_m('Local list cannot be referenced as remote.'));
1477 if (array_key_exists('feedurl', $hints)) {
1478 $feeduri = $hints['feedurl'];
1480 $discover = new FeedDiscovery();
1481 $feeduri = $discover->discoverFromURL($homeuri);
1484 if (array_key_exists('salmon', $hints)) {
1485 $salmonuri = $hints['salmon'];
1488 $discover = new FeedDiscovery();
1489 $discover->discoverFromFeedURL($hints['feedurl']);
1491 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1494 if (array_key_exists('hub', $hints)) {
1495 $huburi = $hints['hub'];
1498 $discover = new FeedDiscovery();
1499 $discover->discoverFromFeedURL($hints['feedurl']);
1501 $huburi = $discover->getHubLink();
1504 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1505 // We can only deal with folks with a PuSH hub
1506 throw new FeedSubNoHubException();
1509 $oprofile = new Ostatus_profile();
1511 $oprofile->uri = $homeuri;
1512 $oprofile->feeduri = $feeduri;
1513 $oprofile->salmonuri = $salmonuri;
1515 $oprofile->created = common_sql_now();
1516 $oprofile->modified = common_sql_now();
1518 if ($object->type == ActivityObject::PERSON) {
1519 $profile = new Profile();
1520 $profile->created = common_sql_now();
1521 self::updateProfile($profile, $object, $hints);
1523 $oprofile->profile_id = $profile->insert();
1524 if ($oprofile->profile_id === false) {
1525 // TRANS: Server exception.
1526 throw new ServerException(_m('Cannot save local profile.'));
1528 } else if ($object->type == ActivityObject::GROUP) {
1529 $profile = new Profile();
1530 $profile->query('BEGIN');
1532 $group = new User_group();
1533 $group->uri = $homeuri;
1534 $group->created = common_sql_now();
1535 self::updateGroup($group, $object, $hints);
1537 // TODO: We should do this directly in User_group->insert()!
1538 // currently it's duplicated in User_group->update()
1539 // AND User_group->register()!!!
1540 $fields = array(/*group field => profile field*/
1541 'nickname' => 'nickname',
1542 'fullname' => 'fullname',
1543 'mainpage' => 'profileurl',
1544 'homepage' => 'homepage',
1545 'description' => 'bio',
1546 'location' => 'location',
1547 'created' => 'created',
1548 'modified' => 'modified',
1550 foreach ($fields as $gf=>$pf) {
1551 $profile->$pf = $group->$gf;
1553 $profile_id = $profile->insert();
1554 if ($profile_id === false) {
1555 $profile->query('ROLLBACK');
1556 throw new ServerException(_('Profile insertion failed.'));
1559 $group->profile_id = $profile_id;
1561 $oprofile->group_id = $group->insert();
1562 if ($oprofile->group_id === false) {
1563 $profile->query('ROLLBACK');
1564 // TRANS: Server exception.
1565 throw new ServerException(_m('Cannot save local profile.'));
1568 $profile->query('COMMIT');
1569 } else if ($object->type == ActivityObject::_LIST) {
1570 $ptag = new Profile_list();
1571 $ptag->uri = $homeuri;
1572 $ptag->created = common_sql_now();
1573 self::updatePeopletag($ptag, $object, $hints);
1575 $oprofile->peopletag_id = $ptag->insert();
1576 if ($oprofile->peopletag_id === false) {
1577 // TRANS: Server exception.
1578 throw new ServerException(_m('Cannot save local list.'));
1582 $ok = $oprofile->insert();
1584 if ($ok === false) {
1585 // TRANS: Server exception.
1586 throw new ServerException(_m('Cannot save OStatus profile.'));
1589 $avatar = self::getActivityObjectAvatar($object, $hints);
1593 $oprofile->updateAvatar($avatar);
1594 } catch (Exception $ex) {
1595 // Profile is saved, but Avatar is messed up. We're
1596 // just going to continue.
1597 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1605 * Save any updated profile information to our local copy.
1606 * @param ActivityObject $object
1607 * @param array $hints
1609 public function updateFromActivityObject($object, $hints=array())
1611 if ($this->isGroup()) {
1612 $group = $this->localGroup();
1613 self::updateGroup($group, $object, $hints);
1614 } else if ($this->isPeopletag()) {
1615 $ptag = $this->localPeopletag();
1616 self::updatePeopletag($ptag, $object, $hints);
1618 $profile = $this->localProfile();
1619 self::updateProfile($profile, $object, $hints);
1622 $avatar = self::getActivityObjectAvatar($object, $hints);
1623 if ($avatar && !isset($ptag)) {
1625 $this->updateAvatar($avatar);
1626 } catch (Exception $ex) {
1627 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1632 public static function updateProfile($profile, $object, $hints=array())
1634 $orig = clone($profile);
1636 // Existing nickname is better than nothing.
1638 if (!array_key_exists('nickname', $hints)) {
1639 $hints['nickname'] = $profile->nickname;
1642 $nickname = self::getActivityObjectNickname($object, $hints);
1644 if (!empty($nickname)) {
1645 $profile->nickname = $nickname;
1648 if (!empty($object->title)) {
1649 $profile->fullname = $object->title;
1650 } else if (array_key_exists('fullname', $hints)) {
1651 $profile->fullname = $hints['fullname'];
1654 if (!empty($object->link)) {
1655 $profile->profileurl = $object->link;
1656 } else if (array_key_exists('profileurl', $hints)) {
1657 $profile->profileurl = $hints['profileurl'];
1658 } else if (common_valid_http_url($object->id)) {
1659 $profile->profileurl = $object->id;
1662 $bio = self::getActivityObjectBio($object, $hints);
1665 $profile->bio = $bio;
1668 $location = self::getActivityObjectLocation($object, $hints);
1670 if (!empty($location)) {
1671 $profile->location = $location;
1674 $homepage = self::getActivityObjectHomepage($object, $hints);
1676 if (!empty($homepage)) {
1677 $profile->homepage = $homepage;
1680 if (!empty($object->geopoint)) {
1681 $location = ActivityContext::locationFromPoint($object->geopoint);
1682 if (!empty($location)) {
1683 $profile->lat = $location->lat;
1684 $profile->lon = $location->lon;
1688 // @todo FIXME: tags/categories
1689 // @todo tags from categories
1692 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1693 $profile->update($orig);
1697 protected static function updateGroup(User_group $group, $object, $hints=array())
1699 $orig = clone($group);
1701 $group->nickname = self::getActivityObjectNickname($object, $hints);
1702 $group->fullname = $object->title;
1704 if (!empty($object->link)) {
1705 $group->mainpage = $object->link;
1706 } else if (array_key_exists('profileurl', $hints)) {
1707 $group->mainpage = $hints['profileurl'];
1710 // @todo tags from categories
1711 $group->description = self::getActivityObjectBio($object, $hints);
1712 $group->location = self::getActivityObjectLocation($object, $hints);
1713 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1715 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1716 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1717 $group->update($orig);
1721 protected static function updatePeopletag($tag, $object, $hints=array()) {
1722 $orig = clone($tag);
1724 $tag->tag = $object->title;
1726 if (!empty($object->link)) {
1727 $tag->mainpage = $object->link;
1728 } else if (array_key_exists('profileurl', $hints)) {
1729 $tag->mainpage = $hints['profileurl'];
1732 $tag->description = $object->summary;
1733 $tagger = self::ensureActivityObjectProfile($object->owner);
1734 $tag->tagger = $tagger->profile_id;
1737 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1738 $tag->update($orig);
1742 protected static function getActivityObjectHomepage($object, $hints=array())
1745 $poco = $object->poco;
1747 if (!empty($poco)) {
1748 $url = $poco->getPrimaryURL();
1749 if ($url && $url->type == 'homepage') {
1750 $homepage = $url->value;
1754 // @todo Try for a another PoCo URL?
1759 protected static function getActivityObjectLocation($object, $hints=array())
1763 if (!empty($object->poco) &&
1764 isset($object->poco->address->formatted)) {
1765 $location = $object->poco->address->formatted;
1766 } else if (array_key_exists('location', $hints)) {
1767 $location = $hints['location'];
1770 if (!empty($location)) {
1771 if (mb_strlen($location) > 255) {
1772 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1776 // @todo Try to find location some othe way? Via goerss point?
1781 protected static function getActivityObjectBio($object, $hints=array())
1785 if (!empty($object->poco)) {
1786 $note = $object->poco->note;
1787 } else if (array_key_exists('bio', $hints)) {
1788 $note = $hints['bio'];
1791 if (!empty($note)) {
1792 if (Profile::bioTooLong($note)) {
1793 // XXX: truncate ok?
1794 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1800 // @todo Try to get bio info some other way?
1805 public static function getActivityObjectNickname($object, $hints=array())
1807 if ($object->poco) {
1808 if (!empty($object->poco->preferredUsername)) {
1809 return common_nicknamize($object->poco->preferredUsername);
1813 if (!empty($object->nickname)) {
1814 return common_nicknamize($object->nickname);
1817 if (array_key_exists('nickname', $hints)) {
1818 return $hints['nickname'];
1821 // Try the profile url (like foo.example.com or example.com/user/foo)
1822 if (!empty($object->link)) {
1823 $profileUrl = $object->link;
1824 } else if (!empty($hints['profileurl'])) {
1825 $profileUrl = $hints['profileurl'];
1828 if (!empty($profileUrl)) {
1829 $nickname = self::nicknameFromURI($profileUrl);
1832 // Try the URI (may be a tag:, http:, acct:, ...
1834 if (empty($nickname)) {
1835 $nickname = self::nicknameFromURI($object->id);
1838 // Try a Webfinger if one was passed (way) down
1840 if (empty($nickname)) {
1841 if (array_key_exists('webfinger', $hints)) {
1842 $nickname = self::nicknameFromURI($hints['webfinger']);
1848 if (empty($nickname)) {
1849 $nickname = common_nicknamize($object->title);
1855 protected static function nicknameFromURI($uri)
1857 if (preg_match('/(\w+):/', $uri, $matches)) {
1858 $protocol = $matches[1];
1863 switch ($protocol) {
1866 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1867 return common_canonical_nickname($matches[1]);
1871 return common_url_to_nickname($uri);
1879 * Look up, and if necessary create, an Ostatus_profile for the remote
1880 * entity with the given webfinger address.
1881 * This should never return null -- you will either get an object or
1882 * an exception will be thrown.
1884 * @param string $addr webfinger address
1885 * @return Ostatus_profile
1886 * @throws Exception on error conditions
1887 * @throws OStatusShadowException if this reference would obscure a local user/group
1889 public static function ensureWebfinger($addr)
1891 // First, try the cache
1893 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1895 if ($uri !== false) {
1896 if (is_null($uri)) {
1897 // Negative cache entry
1898 // TRANS: Exception.
1899 throw new Exception(_m('Not a valid webfinger address.'));
1901 $oprofile = Ostatus_profile::getKV('uri', $uri);
1902 if (!empty($oprofile)) {
1907 // Try looking it up
1908 $oprofile = Ostatus_profile::getKV('uri', 'acct:'.$addr);
1910 if (!empty($oprofile)) {
1911 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1915 // Now, try some discovery
1917 $disco = new Discovery();
1920 $xrd = $disco->lookup($addr);
1921 } catch (Exception $e) {
1922 // Save negative cache entry so we don't waste time looking it up again.
1923 // @todo FIXME: Distinguish temporary failures?
1924 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1925 // TRANS: Exception.
1926 throw new Exception(_m('Not a valid webfinger address.'));
1929 $hints = array('webfinger' => $addr);
1931 $dhints = DiscoveryHints::fromXRD($xrd);
1933 $hints = array_merge($hints, $dhints);
1935 // If there's an Hcard, let's grab its info
1936 if (array_key_exists('hcard', $hints)) {
1937 if (!array_key_exists('profileurl', $hints) ||
1938 $hints['hcard'] != $hints['profileurl']) {
1939 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1940 $hints = array_merge($hcardHints, $hints);
1944 // If we got a feed URL, try that
1945 if (array_key_exists('feedurl', $hints)) {
1947 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1948 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1949 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1951 } catch (Exception $e) {
1952 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1957 // If we got a profile page, try that!
1958 if (array_key_exists('profileurl', $hints)) {
1960 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1961 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1962 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1964 } catch (OStatusShadowException $e) {
1965 // We've ended up with a remote reference to a local user or group.
1966 // @todo FIXME: Ideally we should be able to say who it was so we can
1967 // go back and refer to it the regular way
1969 } catch (Exception $e) {
1970 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1973 // @todo FIXME: This means an error discovering from profile page
1974 // may give us a corrupt entry using the webfinger URI, which
1975 // will obscure the correct page-keyed profile later on.
1982 if (array_key_exists('salmon', $hints)) {
1983 $salmonEndpoint = $hints['salmon'];
1985 // An account URL, a salmon endpoint, and a dream? Not much to go
1986 // on, but let's give it a try
1988 $uri = 'acct:'.$addr;
1990 $profile = new Profile();
1992 $profile->nickname = self::nicknameFromUri($uri);
1993 $profile->created = common_sql_now();
1995 if (isset($profileUrl)) {
1996 $profile->profileurl = $profileUrl;
1999 $profile_id = $profile->insert();
2002 common_log_db_error($profile, 'INSERT', __FILE__);
2003 // TRANS: Exception. %s is a webfinger address.
2004 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2007 $oprofile = new Ostatus_profile();
2009 $oprofile->uri = $uri;
2010 $oprofile->salmonuri = $salmonEndpoint;
2011 $oprofile->profile_id = $profile_id;
2012 $oprofile->created = common_sql_now();
2014 if (isset($feedUrl)) {
2015 $profile->feeduri = $feedUrl;
2018 $result = $oprofile->insert();
2021 common_log_db_error($oprofile, 'INSERT', __FILE__);
2022 // TRANS: Exception. %s is a webfinger address.
2023 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2026 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
2030 // TRANS: Exception. %s is a webfinger address.
2031 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2035 * Store the full-length scrubbed HTML of a remote notice to an attachment
2036 * file on our server. We'll link to this at the end of the cropped version.
2038 * @param string $title plaintext for HTML page's title
2039 * @param string $rendered HTML fragment for HTML page's body
2042 function saveHTMLFile($title, $rendered)
2044 $final = sprintf("<!DOCTYPE html>\n" .
2046 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2047 '<title>%s</title>' .
2049 '<body>%s</body></html>',
2050 htmlspecialchars($title),
2053 $filename = File::filename($this->localProfile(),
2054 'ostatus', // ignored?
2057 $filepath = File::path($filename);
2059 file_put_contents($filepath, $final);
2063 $file->filename = $filename;
2064 $file->url = File::url($filename);
2065 $file->size = filesize($filepath);
2066 $file->date = time();
2067 $file->mimetype = 'text/html';
2069 $file_id = $file->insert();
2071 if ($file_id === false) {
2072 common_log_db_error($file, "INSERT", __FILE__);
2073 // TRANS: Server exception.
2074 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2080 static function ensureProfileURI($uri)
2084 // First, try to query it
2086 $oprofile = Ostatus_profile::getKV('uri', $uri);
2088 // If unfound, do discovery stuff
2090 if (empty($oprofile)) {
2091 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2092 $protocol = $match[1];
2093 switch ($protocol) {
2096 $oprofile = Ostatus_profile::ensureProfileURL($uri);
2101 $oprofile = Ostatus_profile::ensureWebfinger($rest);
2104 // TRANS: Server exception.
2105 // TRANS: %1$s is a protocol, %2$s is a URI.
2106 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2112 // TRANS: Server exception. %s is a URI.
2113 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2120 function checkAuthorship($activity)
2122 if ($this->isGroup() || $this->isPeopletag()) {
2123 // A group or propletag feed will contain posts from multiple authors.
2124 $oprofile = self::ensureActorProfile($activity);
2125 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2126 // Groups can't post notices in StatusNet.
2127 common_log(LOG_WARNING,
2128 "OStatus: skipping post with group listed ".
2129 "as author: $oprofile->uri in feed from $this->uri");
2133 $actor = $activity->actor;
2135 if (empty($actor)) {
2136 // OK here! assume the default
2137 } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
2138 $this->updateFromActivityObject($actor);
2139 } else if ($actor->id) {
2140 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2141 // This isn't what we expect from mainline OStatus person feeds!
2142 // Group feeds go down another path, with different validation...
2143 // Most likely this is a plain ol' blog feed of some kind which
2144 // doesn't match our expectations. We'll take the entry, but ignore
2145 // the <author> info.
2146 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
2148 // Plain <author> without ActivityStreams actor info.
2149 // We'll just ignore this info for now and save the update under the feed's identity.
2160 * Exception indicating we've got a remote reference to a local user,
2161 * not a remote user!
2163 * If we can ue a local profile after all, it's available as $e->profile.
2165 class OStatusShadowException extends Exception
2170 * @param Profile $profile
2171 * @param string $message
2173 function __construct($profile, $message) {
2174 $this->profile = $profile;
2175 parent::__construct($message);