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 = self::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 ($oprofile instanceof Ostatus_profile) {
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 ($oprofile instanceof Ostatus_profile) {
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);
1066 if (!$profile instanceof Profile) {
1070 // Is it a known Ostatus profile?
1071 $oprofile = Ostatus_profile::getKV('profile_id', $profile->id);
1072 if ($oprofile instanceof Ostatus_profile) {
1076 // Is it a local user?
1077 $user = User::getKV('id', $profile->id);
1078 if ($user instanceof User) {
1079 // @todo i18n FIXME: use sprintf and add i18n (?)
1080 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1083 // Continue discovery; it's a remote profile
1084 // for OMB or some other protocol, may also
1091 * Look up and if necessary create an Ostatus_profile for remote entity
1092 * with the given update feed. This should never return null -- you will
1093 * either get an object or an exception will be thrown.
1095 * @return Ostatus_profile
1098 public static function ensureFeedURL($feed_url, $hints=array())
1100 $discover = new FeedDiscovery();
1102 $feeduri = $discover->discoverFromFeedURL($feed_url);
1103 $hints['feedurl'] = $feeduri;
1105 $huburi = $discover->getHubLink();
1106 $hints['hub'] = $huburi;
1107 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1108 $hints['salmon'] = $salmonuri;
1110 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1111 // We can only deal with folks with a PuSH hub
1112 throw new FeedSubNoHubException();
1115 $feedEl = $discover->root;
1117 if ($feedEl->tagName == 'feed') {
1118 return self::ensureAtomFeed($feedEl, $hints);
1119 } else if ($feedEl->tagName == 'channel') {
1120 return self::ensureRssChannel($feedEl, $hints);
1122 throw new FeedSubBadXmlException($feeduri);
1127 * Look up and, if necessary, create an Ostatus_profile for the remote
1128 * profile with the given Atom feed - actually loaded from the feed.
1129 * This should never return null -- you will either get an object or
1130 * an exception will be thrown.
1132 * @param DOMElement $feedEl root element of a loaded Atom feed
1133 * @param array $hints additional discovery information passed from higher levels
1134 * @todo FIXME: Should this be marked public?
1135 * @return Ostatus_profile
1138 public static function ensureAtomFeed($feedEl, $hints)
1140 $author = ActivityUtils::getFeedAuthor($feedEl);
1142 if (empty($author)) {
1143 // XXX: make some educated guesses here
1144 // TRANS: Feed sub exception.
1145 throw new FeedSubException(_m('Cannot find enough profile '.
1146 'information to make a feed.'));
1149 return self::ensureActivityObjectProfile($author, $hints);
1153 * Look up and, if necessary, create an Ostatus_profile for the remote
1154 * profile with the given RSS feed - actually loaded from the feed.
1155 * This should never return null -- you will either get an object or
1156 * an exception will be thrown.
1158 * @param DOMElement $feedEl root element of a loaded RSS feed
1159 * @param array $hints additional discovery information passed from higher levels
1160 * @todo FIXME: Should this be marked public?
1161 * @return Ostatus_profile
1164 public static function ensureRssChannel($feedEl, $hints)
1166 // Special-case for Posterous. They have some nice metadata in their
1167 // posterous:author elements. We should use them instead of the channel.
1169 $items = $feedEl->getElementsByTagName('item');
1171 if ($items->length > 0) {
1172 $item = $items->item(0);
1173 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1174 if (!empty($authorEl)) {
1175 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1176 // Posterous has multiple authors per feed, and multiple feeds
1177 // per author. We check if this is the "main" feed for this author.
1178 if (array_key_exists('profileurl', $hints) &&
1179 !empty($obj->poco) &&
1180 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1181 return self::ensureActivityObjectProfile($obj, $hints);
1186 // @todo FIXME: We should check whether this feed has elements
1187 // with different <author> or <dc:creator> elements, and... I dunno.
1188 // Do something about that.
1190 $obj = ActivityObject::fromRssChannel($feedEl);
1192 return self::ensureActivityObjectProfile($obj, $hints);
1196 * Download and update given avatar image
1198 * @param string $url
1199 * @throws Exception in various failure cases
1201 protected function updateAvatar($url)
1203 if ($url == $this->avatar) {
1204 // We've already got this one.
1207 if (!common_valid_http_url($url)) {
1208 // TRANS: Server exception. %s is a URL.
1209 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1212 if ($this->isGroup()) {
1213 $self = $this->localGroup();
1215 $self = $this->localProfile();
1218 throw new ServerException(sprintf(
1219 // TRANS: Server exception. %s is a URI.
1220 _m('Tried to update avatar for unsaved remote profile %s.'),
1224 // @todo FIXME: This should be better encapsulated
1225 // ripped from oauthstore.php (for old OMB client)
1226 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1228 if (!copy($url, $temp_filename)) {
1229 // TRANS: Server exception. %s is a URL.
1230 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1233 if ($this->isGroup()) {
1234 $id = $this->group_id;
1236 $id = $this->profile_id;
1238 // @todo FIXME: Should we be using different ids?
1239 $imagefile = new ImageFile($id, $temp_filename);
1240 $filename = Avatar::filename($id,
1241 image_type_to_extension($imagefile->type),
1243 common_timestamp());
1244 rename($temp_filename, Avatar::path($filename));
1245 } catch (Exception $e) {
1246 unlink($temp_filename);
1249 // @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
1250 // keep from accidentally saving images from command-line (queues)
1251 // that can't be read from web server, which causes hard-to-notice
1252 // problems later on:
1254 // http://status.net/open-source/issues/2663
1255 chmod(Avatar::path($filename), 0644);
1257 $self->setOriginal($filename);
1259 $orig = clone($this);
1260 $this->avatar = $url;
1261 $this->update($orig);
1265 * Pull avatar URL from ActivityObject or profile hints
1267 * @param ActivityObject $object
1268 * @param array $hints
1269 * @return mixed URL string or false
1271 public static function getActivityObjectAvatar($object, $hints=array())
1273 if ($object->avatarLinks) {
1275 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1276 foreach ($object->avatarLinks as $avatar) {
1277 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1282 if (!$best || $avatar->width > $best->width) {
1287 } else if (array_key_exists('avatar', $hints)) {
1288 return $hints['avatar'];
1294 * Get an appropriate avatar image source URL, if available.
1296 * @param ActivityObject $actor
1297 * @param DOMElement $feed
1300 protected static function getAvatar($actor, $feed)
1304 if ($actor->avatar) {
1305 $url = trim($actor->avatar);
1308 // Check <atom:logo> and <atom:icon> on the feed
1309 $els = $feed->childNodes();
1310 if ($els && $els->length) {
1311 for ($i = 0; $i < $els->length; $i++) {
1312 $el = $els->item($i);
1313 if ($el->namespaceURI == Activity::ATOM) {
1314 if (empty($url) && $el->localName == 'logo') {
1315 $url = trim($el->textContent);
1318 if (empty($icon) && $el->localName == 'icon') {
1319 // Use as a fallback
1320 $icon = trim($el->textContent);
1325 if ($icon && !$url) {
1330 $opts = array('allowed_schemes' => array('http', 'https'));
1331 if (common_valid_http_url($url)) {
1336 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1340 * Fetch, or build if necessary, an Ostatus_profile for the actor
1341 * in a given Activity Streams activity.
1342 * This should never return null -- you will either get an object or
1343 * an exception will be thrown.
1345 * @param Activity $activity
1346 * @param string $feeduri if we already know the canonical feed URI!
1347 * @param string $salmonuri if we already know the salmon return channel URI
1348 * @return Ostatus_profile
1351 public static function ensureActorProfile($activity, $hints=array())
1353 return self::ensureActivityObjectProfile($activity->actor, $hints);
1357 * Fetch, or build if necessary, an Ostatus_profile for the profile
1358 * in a given Activity Streams object (can be subject, actor, or object).
1359 * This should never return null -- you will either get an object or
1360 * an exception will be thrown.
1362 * @param ActivityObject $object
1363 * @param array $hints additional discovery information passed from higher levels
1364 * @return Ostatus_profile
1367 public static function ensureActivityObjectProfile($object, $hints=array())
1369 $profile = self::getActivityObjectProfile($object);
1371 $profile->updateFromActivityObject($object, $hints);
1373 $profile = self::createActivityObjectProfile($object, $hints);
1379 * @param Activity $activity
1380 * @return mixed matching Ostatus_profile or false if none known
1381 * @throws ServerException if feed info invalid
1383 public static function getActorProfile($activity)
1385 return self::getActivityObjectProfile($activity->actor);
1389 * @param ActivityObject $activity
1390 * @return mixed matching Ostatus_profile or false if none known
1391 * @throws ServerException if feed info invalid
1393 protected static function getActivityObjectProfile($object)
1395 $uri = self::getActivityObjectProfileURI($object);
1396 return Ostatus_profile::getKV('uri', $uri);
1400 * Get the identifier URI for the remote entity described
1401 * by this ActivityObject. This URI is *not* guaranteed to be
1402 * a resolvable HTTP/HTTPS URL.
1404 * @param ActivityObject $object
1406 * @throws ServerException if feed info invalid
1408 protected static function getActivityObjectProfileURI($object)
1411 if (ActivityUtils::validateUri($object->id)) {
1416 // If the id is missing or invalid (we've seen feeds mistakenly listing
1417 // things like local usernames in that field) then we'll use the profile
1418 // page link, if valid.
1419 if ($object->link && common_valid_http_url($object->link)) {
1420 return $object->link;
1422 // TRANS: Server exception.
1423 throw new ServerException(_m('No author ID URI found.'));
1427 * @todo FIXME: Validate stuff somewhere.
1431 * Create local ostatus_profile and profile/user_group entries for
1432 * the provided remote user or group.
1433 * This should never return null -- you will either get an object or
1434 * an exception will be thrown.
1436 * @param ActivityObject $object
1437 * @param array $hints
1439 * @return Ostatus_profile
1441 protected static function createActivityObjectProfile($object, $hints=array())
1443 $homeuri = $object->id;
1447 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1448 // TRANS: Exception.
1449 throw new Exception(_m('No profile URI.'));
1452 $user = User::getKV('uri', $homeuri);
1454 // TRANS: Exception.
1455 throw new Exception(_m('Local user cannot be referenced as remote.'));
1458 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1459 // TRANS: Exception.
1460 throw new Exception(_m('Local group cannot be referenced as remote.'));
1463 $ptag = Profile_list::getKV('uri', $homeuri);
1465 $local_user = User::getKV('id', $ptag->tagger);
1466 if (!empty($local_user)) {
1467 // TRANS: Exception.
1468 throw new Exception(_m('Local list cannot be referenced as remote.'));
1472 if (array_key_exists('feedurl', $hints)) {
1473 $feeduri = $hints['feedurl'];
1475 $discover = new FeedDiscovery();
1476 $feeduri = $discover->discoverFromURL($homeuri);
1479 if (array_key_exists('salmon', $hints)) {
1480 $salmonuri = $hints['salmon'];
1483 $discover = new FeedDiscovery();
1484 $discover->discoverFromFeedURL($hints['feedurl']);
1486 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1489 if (array_key_exists('hub', $hints)) {
1490 $huburi = $hints['hub'];
1493 $discover = new FeedDiscovery();
1494 $discover->discoverFromFeedURL($hints['feedurl']);
1496 $huburi = $discover->getHubLink();
1499 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1500 // We can only deal with folks with a PuSH hub
1501 throw new FeedSubNoHubException();
1504 $oprofile = new Ostatus_profile();
1506 $oprofile->uri = $homeuri;
1507 $oprofile->feeduri = $feeduri;
1508 $oprofile->salmonuri = $salmonuri;
1510 $oprofile->created = common_sql_now();
1511 $oprofile->modified = common_sql_now();
1513 if ($object->type == ActivityObject::PERSON) {
1514 $profile = new Profile();
1515 $profile->created = common_sql_now();
1516 self::updateProfile($profile, $object, $hints);
1518 $oprofile->profile_id = $profile->insert();
1519 if ($oprofile->profile_id === false) {
1520 // TRANS: Server exception.
1521 throw new ServerException(_m('Cannot save local profile.'));
1523 } else if ($object->type == ActivityObject::GROUP) {
1524 $profile = new Profile();
1525 $profile->query('BEGIN');
1527 $group = new User_group();
1528 $group->uri = $homeuri;
1529 $group->created = common_sql_now();
1530 self::updateGroup($group, $object, $hints);
1532 // TODO: We should do this directly in User_group->insert()!
1533 // currently it's duplicated in User_group->update()
1534 // AND User_group->register()!!!
1535 $fields = array(/*group field => profile field*/
1536 'nickname' => 'nickname',
1537 'fullname' => 'fullname',
1538 'mainpage' => 'profileurl',
1539 'homepage' => 'homepage',
1540 'description' => 'bio',
1541 'location' => 'location',
1542 'created' => 'created',
1543 'modified' => 'modified',
1545 foreach ($fields as $gf=>$pf) {
1546 $profile->$pf = $group->$gf;
1548 $profile_id = $profile->insert();
1549 if ($profile_id === false) {
1550 $profile->query('ROLLBACK');
1551 throw new ServerException(_('Profile insertion failed.'));
1554 $group->profile_id = $profile_id;
1556 $oprofile->group_id = $group->insert();
1557 if ($oprofile->group_id === false) {
1558 $profile->query('ROLLBACK');
1559 // TRANS: Server exception.
1560 throw new ServerException(_m('Cannot save local profile.'));
1563 $profile->query('COMMIT');
1564 } else if ($object->type == ActivityObject::_LIST) {
1565 $ptag = new Profile_list();
1566 $ptag->uri = $homeuri;
1567 $ptag->created = common_sql_now();
1568 self::updatePeopletag($ptag, $object, $hints);
1570 $oprofile->peopletag_id = $ptag->insert();
1571 if ($oprofile->peopletag_id === false) {
1572 // TRANS: Server exception.
1573 throw new ServerException(_m('Cannot save local list.'));
1577 $ok = $oprofile->insert();
1579 if ($ok === false) {
1580 // TRANS: Server exception.
1581 throw new ServerException(_m('Cannot save OStatus profile.'));
1584 $avatar = self::getActivityObjectAvatar($object, $hints);
1588 $oprofile->updateAvatar($avatar);
1589 } catch (Exception $ex) {
1590 // Profile is saved, but Avatar is messed up. We're
1591 // just going to continue.
1592 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1600 * Save any updated profile information to our local copy.
1601 * @param ActivityObject $object
1602 * @param array $hints
1604 public function updateFromActivityObject($object, $hints=array())
1606 if ($this->isGroup()) {
1607 $group = $this->localGroup();
1608 self::updateGroup($group, $object, $hints);
1609 } else if ($this->isPeopletag()) {
1610 $ptag = $this->localPeopletag();
1611 self::updatePeopletag($ptag, $object, $hints);
1613 $profile = $this->localProfile();
1614 self::updateProfile($profile, $object, $hints);
1617 $avatar = self::getActivityObjectAvatar($object, $hints);
1618 if ($avatar && !isset($ptag)) {
1620 $this->updateAvatar($avatar);
1621 } catch (Exception $ex) {
1622 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1627 public static function updateProfile($profile, $object, $hints=array())
1629 $orig = clone($profile);
1631 // Existing nickname is better than nothing.
1633 if (!array_key_exists('nickname', $hints)) {
1634 $hints['nickname'] = $profile->nickname;
1637 $nickname = self::getActivityObjectNickname($object, $hints);
1639 if (!empty($nickname)) {
1640 $profile->nickname = $nickname;
1643 if (!empty($object->title)) {
1644 $profile->fullname = $object->title;
1645 } else if (array_key_exists('fullname', $hints)) {
1646 $profile->fullname = $hints['fullname'];
1649 if (!empty($object->link)) {
1650 $profile->profileurl = $object->link;
1651 } else if (array_key_exists('profileurl', $hints)) {
1652 $profile->profileurl = $hints['profileurl'];
1653 } else if (common_valid_http_url($object->id)) {
1654 $profile->profileurl = $object->id;
1657 $bio = self::getActivityObjectBio($object, $hints);
1660 $profile->bio = $bio;
1663 $location = self::getActivityObjectLocation($object, $hints);
1665 if (!empty($location)) {
1666 $profile->location = $location;
1669 $homepage = self::getActivityObjectHomepage($object, $hints);
1671 if (!empty($homepage)) {
1672 $profile->homepage = $homepage;
1675 if (!empty($object->geopoint)) {
1676 $location = ActivityContext::locationFromPoint($object->geopoint);
1677 if (!empty($location)) {
1678 $profile->lat = $location->lat;
1679 $profile->lon = $location->lon;
1683 // @todo FIXME: tags/categories
1684 // @todo tags from categories
1687 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1688 $profile->update($orig);
1692 protected static function updateGroup(User_group $group, $object, $hints=array())
1694 $orig = clone($group);
1696 $group->nickname = self::getActivityObjectNickname($object, $hints);
1697 $group->fullname = $object->title;
1699 if (!empty($object->link)) {
1700 $group->mainpage = $object->link;
1701 } else if (array_key_exists('profileurl', $hints)) {
1702 $group->mainpage = $hints['profileurl'];
1705 // @todo tags from categories
1706 $group->description = self::getActivityObjectBio($object, $hints);
1707 $group->location = self::getActivityObjectLocation($object, $hints);
1708 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1710 if ($group->id) { // If no id, we haven't called insert() yet, so don't run update()
1711 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1712 $group->update($orig);
1716 protected static function updatePeopletag($tag, $object, $hints=array()) {
1717 $orig = clone($tag);
1719 $tag->tag = $object->title;
1721 if (!empty($object->link)) {
1722 $tag->mainpage = $object->link;
1723 } else if (array_key_exists('profileurl', $hints)) {
1724 $tag->mainpage = $hints['profileurl'];
1727 $tag->description = $object->summary;
1728 $tagger = self::ensureActivityObjectProfile($object->owner);
1729 $tag->tagger = $tagger->profile_id;
1732 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1733 $tag->update($orig);
1737 protected static function getActivityObjectHomepage($object, $hints=array())
1740 $poco = $object->poco;
1742 if (!empty($poco)) {
1743 $url = $poco->getPrimaryURL();
1744 if ($url && $url->type == 'homepage') {
1745 $homepage = $url->value;
1749 // @todo Try for a another PoCo URL?
1754 protected static function getActivityObjectLocation($object, $hints=array())
1758 if (!empty($object->poco) &&
1759 isset($object->poco->address->formatted)) {
1760 $location = $object->poco->address->formatted;
1761 } else if (array_key_exists('location', $hints)) {
1762 $location = $hints['location'];
1765 if (!empty($location)) {
1766 if (mb_strlen($location) > 255) {
1767 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1771 // @todo Try to find location some othe way? Via goerss point?
1776 protected static function getActivityObjectBio($object, $hints=array())
1780 if (!empty($object->poco)) {
1781 $note = $object->poco->note;
1782 } else if (array_key_exists('bio', $hints)) {
1783 $note = $hints['bio'];
1786 if (!empty($note)) {
1787 if (Profile::bioTooLong($note)) {
1788 // XXX: truncate ok?
1789 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1795 // @todo Try to get bio info some other way?
1800 public static function getActivityObjectNickname($object, $hints=array())
1802 if ($object->poco) {
1803 if (!empty($object->poco->preferredUsername)) {
1804 return common_nicknamize($object->poco->preferredUsername);
1808 if (!empty($object->nickname)) {
1809 return common_nicknamize($object->nickname);
1812 if (array_key_exists('nickname', $hints)) {
1813 return $hints['nickname'];
1816 // Try the profile url (like foo.example.com or example.com/user/foo)
1817 if (!empty($object->link)) {
1818 $profileUrl = $object->link;
1819 } else if (!empty($hints['profileurl'])) {
1820 $profileUrl = $hints['profileurl'];
1823 if (!empty($profileUrl)) {
1824 $nickname = self::nicknameFromURI($profileUrl);
1827 // Try the URI (may be a tag:, http:, acct:, ...
1829 if (empty($nickname)) {
1830 $nickname = self::nicknameFromURI($object->id);
1833 // Try a Webfinger if one was passed (way) down
1835 if (empty($nickname)) {
1836 if (array_key_exists('webfinger', $hints)) {
1837 $nickname = self::nicknameFromURI($hints['webfinger']);
1843 if (empty($nickname)) {
1844 $nickname = common_nicknamize($object->title);
1850 protected static function nicknameFromURI($uri)
1852 if (preg_match('/(\w+):/', $uri, $matches)) {
1853 $protocol = $matches[1];
1858 switch ($protocol) {
1861 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1862 return common_canonical_nickname($matches[1]);
1866 return common_url_to_nickname($uri);
1874 * Look up, and if necessary create, an Ostatus_profile for the remote
1875 * entity with the given webfinger address.
1876 * This should never return null -- you will either get an object or
1877 * an exception will be thrown.
1879 * @param string $addr webfinger address
1880 * @return Ostatus_profile
1881 * @throws Exception on error conditions
1882 * @throws OStatusShadowException if this reference would obscure a local user/group
1884 public static function ensureWebfinger($addr)
1886 // First, try the cache
1888 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1890 if ($uri !== false) {
1891 if (is_null($uri)) {
1892 // Negative cache entry
1893 // TRANS: Exception.
1894 throw new Exception(_m('Not a valid webfinger address.'));
1896 $oprofile = Ostatus_profile::getKV('uri', $uri);
1897 if ($oprofile instanceof Ostatus_profile) {
1902 // Try looking it up
1903 $oprofile = Ostatus_profile::getKV('uri', 'acct:'.$addr);
1905 if ($oprofile instanceof Ostatus_profile) {
1906 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1910 // Now, try some discovery
1912 $disco = new Discovery();
1915 $xrd = $disco->lookup($addr);
1916 } catch (Exception $e) {
1917 // Save negative cache entry so we don't waste time looking it up again.
1918 // @todo FIXME: Distinguish temporary failures?
1919 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1920 // TRANS: Exception.
1921 throw new Exception(_m('Not a valid webfinger address.'));
1924 $hints = array('webfinger' => $addr);
1926 $dhints = DiscoveryHints::fromXRD($xrd);
1928 $hints = array_merge($hints, $dhints);
1930 // If there's an Hcard, let's grab its info
1931 if (array_key_exists('hcard', $hints)) {
1932 if (!array_key_exists('profileurl', $hints) ||
1933 $hints['hcard'] != $hints['profileurl']) {
1934 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1935 $hints = array_merge($hcardHints, $hints);
1939 // If we got a feed URL, try that
1940 if (array_key_exists('feedurl', $hints)) {
1942 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1943 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1944 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1946 } catch (Exception $e) {
1947 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1952 // If we got a profile page, try that!
1953 if (array_key_exists('profileurl', $hints)) {
1955 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1956 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1957 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1959 } catch (OStatusShadowException $e) {
1960 // We've ended up with a remote reference to a local user or group.
1961 // @todo FIXME: Ideally we should be able to say who it was so we can
1962 // go back and refer to it the regular way
1964 } catch (Exception $e) {
1965 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1968 // @todo FIXME: This means an error discovering from profile page
1969 // may give us a corrupt entry using the webfinger URI, which
1970 // will obscure the correct page-keyed profile later on.
1977 if (array_key_exists('salmon', $hints)) {
1978 $salmonEndpoint = $hints['salmon'];
1980 // An account URL, a salmon endpoint, and a dream? Not much to go
1981 // on, but let's give it a try
1983 $uri = 'acct:'.$addr;
1985 $profile = new Profile();
1987 $profile->nickname = self::nicknameFromUri($uri);
1988 $profile->created = common_sql_now();
1990 if (isset($profileUrl)) {
1991 $profile->profileurl = $profileUrl;
1994 $profile_id = $profile->insert();
1996 if ($profile_id === false) {
1997 common_log_db_error($profile, 'INSERT', __FILE__);
1998 // TRANS: Exception. %s is a webfinger address.
1999 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
2002 $oprofile = new Ostatus_profile();
2004 $oprofile->uri = $uri;
2005 $oprofile->salmonuri = $salmonEndpoint;
2006 $oprofile->profile_id = $profile_id;
2007 $oprofile->created = common_sql_now();
2009 if (isset($feedUrl)) {
2010 $profile->feeduri = $feedUrl;
2013 $result = $oprofile->insert();
2015 if ($result === false) {
2016 common_log_db_error($oprofile, 'INSERT', __FILE__);
2017 // TRANS: Exception. %s is a webfinger address.
2018 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
2021 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
2025 // TRANS: Exception. %s is a webfinger address.
2026 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2030 * Store the full-length scrubbed HTML of a remote notice to an attachment
2031 * file on our server. We'll link to this at the end of the cropped version.
2033 * @param string $title plaintext for HTML page's title
2034 * @param string $rendered HTML fragment for HTML page's body
2037 function saveHTMLFile($title, $rendered)
2039 $final = sprintf("<!DOCTYPE html>\n" .
2041 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2042 '<title>%s</title>' .
2044 '<body>%s</body></html>',
2045 htmlspecialchars($title),
2048 $filename = File::filename($this->localProfile(),
2049 'ostatus', // ignored?
2052 $filepath = File::path($filename);
2054 file_put_contents($filepath, $final);
2058 $file->filename = $filename;
2059 $file->url = File::url($filename);
2060 $file->size = filesize($filepath);
2061 $file->date = time();
2062 $file->mimetype = 'text/html';
2064 $file_id = $file->insert();
2066 if ($file_id === false) {
2067 common_log_db_error($file, "INSERT", __FILE__);
2068 // TRANS: Server exception.
2069 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2075 static function ensureProfileURI($uri)
2079 // First, try to query it
2081 $oprofile = Ostatus_profile::getKV('uri', $uri);
2083 if ($oprofile instanceof Ostatus_profile) {
2087 // If unfound, do discovery stuff
2088 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2089 $protocol = $match[1];
2090 switch ($protocol) {
2093 $oprofile = Ostatus_profile::ensureProfileURL($uri);
2098 $oprofile = Ostatus_profile::ensureWebfinger($rest);
2101 // TRANS: Server exception.
2102 // TRANS: %1$s is a protocol, %2$s is a URI.
2103 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2109 // TRANS: Server exception. %s is a URI.
2110 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2116 function checkAuthorship($activity)
2118 if ($this->isGroup() || $this->isPeopletag()) {
2119 // A group or propletag feed will contain posts from multiple authors.
2120 $oprofile = self::ensureActorProfile($activity);
2121 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2122 // Groups can't post notices in StatusNet.
2123 common_log(LOG_WARNING,
2124 "OStatus: skipping post with group listed ".
2125 "as author: $oprofile->uri in feed from $this->uri");
2129 $actor = $activity->actor;
2131 if (empty($actor)) {
2132 // OK here! assume the default
2133 } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
2134 $this->updateFromActivityObject($actor);
2135 } else if ($actor->id) {
2136 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2137 // This isn't what we expect from mainline OStatus person feeds!
2138 // Group feeds go down another path, with different validation...
2139 // Most likely this is a plain ol' blog feed of some kind which
2140 // doesn't match our expectations. We'll take the entry, but ignore
2141 // the <author> info.
2142 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
2144 // Plain <author> without ActivityStreams actor info.
2145 // We'll just ignore this info for now and save the update under the feed's identity.
2156 * Exception indicating we've got a remote reference to a local user,
2157 * not a remote user!
2159 * If we can ue a local profile after all, it's available as $e->profile.
2161 class OStatusShadowException extends Exception
2166 * @param Profile $profile
2167 * @param string $message
2169 function __construct($profile, $message) {
2170 $this->profile = $profile;
2171 parent::__construct($message);