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>
29 class Ostatus_profile extends Managed_DataObject
31 public $__table = 'ostatus_profile';
41 public $avatar; // remote URL of the last avatar we saved
46 public /*static*/ function staticGet($k, $v=null)
48 return parent::staticGet(__CLASS__, $k, $v);
52 * Return table definition for Schema setup and DB_DataObject usage.
54 * @return array array of column definitions
56 static function schemaDef()
60 'uri' => array('type' => 'varchar', 'length' => 255, 'not null' => true),
61 'profile_id' => array('type' => 'integer'),
62 'group_id' => array('type' => 'integer'),
63 'peopletag_id' => array('type' => 'integer'),
64 'feeduri' => array('type' => 'varchar', 'length' => 255),
65 'salmonuri' => array('type' => 'varchar', 'length' => 255),
66 'avatar' => array('type' => 'text'),
67 'created' => array('type' => 'datetime', 'not null' => true),
68 'modified' => array('type' => 'datetime', 'not null' => true),
70 'primary key' => array('uri'),
71 'unique keys' => array(
72 'ostatus_profile_profile_id_idx' => array('profile_id'),
73 'ostatus_profile_group_id_idx' => array('group_id'),
74 'ostatus_profile_peopletag_id_idx' => array('peopletag_id'),
75 'ostatus_profile_feeduri_idx' => array('feeduri'),
77 'foreign keys' => array(
78 'ostatus_profile_profile_id_fkey' => array('profile', array('profile_id' => 'id')),
79 'ostatus_profile_group_id_fkey' => array('user_group', array('group_id' => 'id')),
80 'ostatus_profile_peopletag_id_fkey' => array('profile_list', array('peopletag_id' => 'id')),
86 * Fetch the StatusNet-side profile for this feed
89 public function localProfile()
91 if ($this->profile_id) {
92 return Profile::staticGet('id', $this->profile_id);
98 * Fetch the StatusNet-side profile for this feed
101 public function localGroup()
103 if ($this->group_id) {
104 return User_group::staticGet('id', $this->group_id);
110 * Fetch the StatusNet-side peopletag for this feed
113 public function localPeopletag()
115 if ($this->peopletag_id) {
116 return Profile_list::staticGet('id', $this->peopletag_id);
122 * Returns an ActivityObject describing this remote user or group profile.
123 * Can then be used to generate Atom chunks.
125 * @return ActivityObject
127 function asActivityObject()
129 if ($this->isGroup()) {
130 return ActivityObject::fromGroup($this->localGroup());
131 } else if ($this->isPeopletag()) {
132 return ActivityObject::fromPeopletag($this->localPeopletag());
134 return ActivityObject::fromProfile($this->localProfile());
139 * Returns an XML string fragment with profile information as an
140 * Activity Streams noun object with the given element type.
142 * Assumes that 'activity' namespace has been previously defined.
144 * @fixme replace with wrappers on asActivityObject when it's got everything.
146 * @param string $element one of 'actor', 'subject', 'object', 'target'
149 function asActivityNoun($element)
151 if ($this->isGroup()) {
152 $noun = ActivityObject::fromGroup($this->localGroup());
153 return $noun->asString('activity:' . $element);
154 } else if ($this->isPeopletag()) {
155 $noun = ActivityObject::fromPeopletag($this->localPeopletag());
156 return $noun->asString('activity:' . $element);
158 $noun = ActivityObject::fromProfile($this->localProfile());
159 return $noun->asString('activity:' . $element);
164 * @return boolean true if this is a remote group
168 if ($this->profile_id || $this->peopletag_id && !$this->group_id) {
170 } else if ($this->group_id && !$this->profile_id && !$this->peopletag_id) {
172 } else if ($this->group_id && ($this->profile_id || $this->peopletag_id)) {
173 // TRANS: Server exception. %s is a URI
174 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->uri));
176 // TRANS: Server exception. %s is a URI
177 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->uri));
182 * @return boolean true if this is a remote peopletag
184 function isPeopletag()
186 if ($this->profile_id || $this->group_id && !$this->peopletag_id) {
188 } else if ($this->peopletag_id && !$this->profile_id && !$this->group_id) {
190 } else if ($this->peopletag_id && ($this->profile_id || $this->group_id)) {
191 // TRANS: Server exception. %s is a URI
192 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: Two or more IDs set for %s.'), $this->uri));
194 // TRANS: Server exception. %s is a URI
195 throw new ServerException(sprintf(_m('Invalid ostatus_profile state: All IDs empty for %s.'), $this->uri));
200 * Send a subscription request to the hub for this feed.
201 * The hub will later send us a confirmation POST to /main/push/callback.
203 * @return bool true on success, false on failure
204 * @throws ServerException if feed state is not valid
206 public function subscribe()
208 $feedsub = FeedSub::ensureFeed($this->feeduri);
209 if ($feedsub->sub_state == 'active') {
210 // Active subscription, we don't need to do anything.
213 // Inactive or we got left in an inconsistent state.
214 // Run a subscription request to make sure we're current!
215 return $feedsub->subscribe();
220 * Check if this remote profile has any active local subscriptions, and
221 * if not drop the PuSH subscription feed.
223 * @return bool true on success, false on failure
225 public function unsubscribe() {
226 $this->garbageCollect();
230 * Check if this remote profile has any active local subscriptions, and
231 * if not drop the PuSH subscription feed.
235 public function garbageCollect()
237 $feedsub = FeedSub::staticGet('uri', $this->feeduri);
238 return $feedsub->garbageCollect();
242 * Check if this remote profile has any active local subscriptions, so the
243 * PuSH subscription layer can decide if it can drop the feed.
245 * This gets called via the FeedSubSubscriberCount event when running
246 * FeedSub::garbageCollect().
250 public function subscriberCount()
252 if ($this->isGroup()) {
253 $members = $this->localGroup()->getMembers(0, 1);
254 $count = $members->N;
255 } else if ($this->isPeopletag()) {
256 $subscribers = $this->localPeopletag()->getSubscribers(0, 1);
257 $count = $subscribers->N;
259 $profile = $this->localProfile();
260 $count = $profile->subscriberCount();
261 if ($profile->hasLocalTags()) {
265 common_log(LOG_INFO, __METHOD__ . " SUB COUNT BEFORE: $count");
267 // Other plugins may be piggybacking on OStatus without having
268 // an active group or user-to-user subscription we know about.
269 Event::handle('Ostatus_profileSubscriberCount', array($this, &$count));
270 common_log(LOG_INFO, __METHOD__ . " SUB COUNT AFTER: $count");
276 * Send an Activity Streams notification to the remote Salmon endpoint,
279 * @param Profile $actor Actor who did the activity
280 * @param string $verb Activity::SUBSCRIBE or Activity::JOIN
281 * @param Object $object object of the action; must define asActivityNoun($tag)
283 public function notify($actor, $verb, $object=null, $target=null)
285 if (!($actor instanceof Profile)) {
286 $type = gettype($actor);
287 if ($type == 'object') {
288 $type = get_class($actor);
290 // TRANS: Server exception.
291 // TRANS: %1$s is the method name the exception occured in, %2$s is the actor type.
292 throw new ServerException(sprintf(_m('Invalid actor passed to %1$s: %2$s.'),__METHOD__,$type));
294 if ($object == null) {
297 if ($this->salmonuri) {
299 $id = TagURI::mint('%s:%s:%s',
302 common_date_iso8601(time()));
304 // @fixme consolidate all these NS settings somewhere
305 $attributes = array('xmlns' => Activity::ATOM,
306 'xmlns:activity' => 'http://activitystrea.ms/spec/1.0/',
307 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0',
308 'xmlns:georss' => 'http://www.georss.org/georss',
309 'xmlns:ostatus' => 'http://ostatus.org/schema/1.0',
310 'xmlns:poco' => 'http://portablecontacts.net/spec/1.0',
311 'xmlns:media' => 'http://purl.org/syndication/atommedia');
313 $entry = new XMLStringer();
314 $entry->elementStart('entry', $attributes);
315 $entry->element('id', null, $id);
316 $entry->element('title', null, $text);
317 $entry->element('summary', null, $text);
318 $entry->element('published', null, common_date_w3dtf(common_sql_now()));
320 $entry->element('activity:verb', null, $verb);
321 $entry->raw($actor->asAtomAuthor());
322 $entry->raw($actor->asActivityActor());
323 $entry->raw($object->asActivityNoun('object'));
324 if ($target != null) {
325 $entry->raw($target->asActivityNoun('target'));
327 $entry->elementEnd('entry');
329 $xml = $entry->getString();
330 common_log(LOG_INFO, "Posting to Salmon endpoint $this->salmonuri: $xml");
332 $salmon = new Salmon(); // ?
333 return $salmon->post($this->salmonuri, $xml, $actor);
339 * Send a Salmon notification ping immediately, and confirm that we got
340 * an acceptable response from the remote site.
342 * @param mixed $entry XML string, Notice, or Activity
343 * @param Profile $actor
344 * @return boolean success
346 public function notifyActivity($entry, $actor)
348 if ($this->salmonuri) {
349 $salmon = new Salmon();
350 return $salmon->post($this->salmonuri, $this->notifyPrepXml($entry), $actor);
357 * Queue a Salmon notification for later. If queues are disabled we'll
358 * send immediately but won't get the return value.
360 * @param mixed $entry XML string, Notice, or Activity
361 * @return boolean success
363 public function notifyDeferred($entry, $actor)
365 if ($this->salmonuri) {
366 $data = array('salmonuri' => $this->salmonuri,
367 'entry' => $this->notifyPrepXml($entry),
368 'actor' => $actor->id);
370 $qm = QueueManager::get();
371 return $qm->enqueue($data, 'salmon');
377 protected function notifyPrepXml($entry)
379 $preamble = '<?xml version="1.0" encoding="UTF-8" ?' . '>';
380 if (is_string($entry)) {
382 } else if ($entry instanceof Activity) {
383 return $preamble . $entry->asString(true);
384 } else if ($entry instanceof Notice) {
385 return $preamble . $entry->asAtomEntry(true, true);
387 // TRANS: Server exception.
388 throw new ServerException(_m('Invalid type passed to Ostatus_profile::notify. It must be XML string or Activity entry.'));
392 function getBestName()
394 if ($this->isGroup()) {
395 return $this->localGroup()->getBestName();
396 } else if ($this->isPeopletag()) {
397 return $this->localPeopletag()->getBestName();
399 return $this->localProfile()->getBestName();
404 * Read and post notices for updates from the feed.
405 * Currently assumes that all items in the feed are new,
406 * coming from a PuSH hub.
408 * @param DOMDocument $doc
409 * @param string $source identifier ("push")
411 public function processFeed(DOMDocument $doc, $source)
413 $feed = $doc->documentElement;
415 if ($feed->localName == 'feed' && $feed->namespaceURI == Activity::ATOM) {
416 $this->processAtomFeed($feed, $source);
417 } else if ($feed->localName == 'rss') { // @fixme check namespace
418 $this->processRssFeed($feed, $source);
421 throw new Exception(_m('Unknown feed format.'));
425 public function processAtomFeed(DOMElement $feed, $source)
427 $entries = $feed->getElementsByTagNameNS(Activity::ATOM, 'entry');
428 if ($entries->length == 0) {
429 common_log(LOG_ERR, __METHOD__ . ": no entries in feed update, ignoring");
433 for ($i = 0; $i < $entries->length; $i++) {
434 $entry = $entries->item($i);
435 $this->processEntry($entry, $feed, $source);
439 public function processRssFeed(DOMElement $rss, $source)
441 $channels = $rss->getElementsByTagName('channel');
443 if ($channels->length == 0) {
445 throw new Exception(_m('RSS feed without a channel.'));
446 } else if ($channels->length > 1) {
447 common_log(LOG_WARNING, __METHOD__ . ": more than one channel in an RSS feed");
450 $channel = $channels->item(0);
452 $items = $channel->getElementsByTagName('item');
454 for ($i = 0; $i < $items->length; $i++) {
455 $item = $items->item($i);
456 $this->processEntry($item, $channel, $source);
461 * Process a posted entry from this feed source.
463 * @param DOMElement $entry
464 * @param DOMElement $feed for context
465 * @param string $source identifier ("push" or "salmon")
467 public function processEntry($entry, $feed, $source)
469 $activity = new Activity($entry, $feed);
470 $this->processActivity($activity, $source);
473 public function processActivity($activity, $source)
475 // The "WithProfile" events were added later.
477 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this)) &&
478 Event::handle('StartHandleFeedEntry', array($activity))) {
480 switch ($activity->verb) {
481 case ActivityVerb::POST:
482 // @todo process all activity objects
483 switch ($activity->objects[0]->type) {
484 case ActivityObject::ARTICLE:
485 case ActivityObject::BLOGENTRY:
486 case ActivityObject::NOTE:
487 case ActivityObject::STATUS:
488 case ActivityObject::COMMENT:
490 $this->processPost($activity, $source);
493 // TRANS: Client exception.
494 throw new ClientException(_m('Cannot handle that kind of post.'));
497 case ActivityVerb::SHARE:
498 $result = $this->processShare($activity, $source);
501 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
504 Event::handle('EndHandleFeedEntry', array($activity));
505 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this));
509 public function processShare($activity, $method)
511 $oprofile = $this->checkAuthorship($activity);
513 if (empty($oprofile)) {
514 common_log(LOG_INFO, "No author matched share activity");
518 if (count($activity->objects) != 1) {
519 throw new ClientException(_m("Can only handle share activities with exactly one object."));
522 $shared = $activity->objects[0];
524 if (!($shared instanceof Activity)) {
525 throw new ClientException(_m("Can only handle shared activities."));
528 $other = Ostatus_profile::ensureActivityObjectProfile($shared->actor);
530 // Save the item (or check for a dupe)
532 $other->processActivity($shared, $method);
534 // XXX: process*() should return the new or existing notice. They don't, so we have to
535 // go fishing for it now.
537 $sharedId = ($shared->id) ? $shared->id : $shared->objects[0]->id;
539 $sharedNotice = Notice::staticGet('uri', $sharedId);
541 if (empty($sharedNotice)) {
542 throw new ClientException(sprintf(_m("Failed to save activity %s"),
546 // The id URI will be used as a unique identifier for for the notice,
547 // protecting against duplicate saves. It isn't required to be a URL;
548 // tag: URIs for instance are found in Google Buzz feeds.
550 $sourceUri = $activity->id;
552 $dupe = Notice::staticGet('uri', $sourceUri);
554 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
558 // We'll also want to save a web link to the original notice, if provided.
561 if ($activity->link) {
562 $sourceUrl = $activity->link;
563 } else if ($activity->link) {
564 $sourceUrl = $activity->link;
565 } else if (preg_match('!^https?://!', $activity->id)) {
566 $sourceUrl = $activity->id;
569 // Use summary as fallback for content
571 if (!empty($activity->content)) {
572 $sourceContent = $activity->content;
573 } else if (!empty($activity->summary)) {
574 $sourceContent = $activity->summary;
575 } else if (!empty($activity->title)) {
576 $sourceContent = $activity->title;
578 // @fixme fetch from $sourceUrl?
579 // TRANS: Client exception. %s is a source URI.
580 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
583 // Get (safe!) HTML and text versions of the content
585 $rendered = $this->purify($sourceContent);
586 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
588 $shortened = common_shorten_links($content);
590 // If it's too long, try using the summary, and make the
591 // HTML an attachment.
595 if (Notice::contentTooLong($shortened)) {
596 $attachment = $this->saveHTMLFile($activity->title, $rendered);
597 $summary = html_entity_decode(strip_tags($activity->summary), ENT_QUOTES, 'UTF-8');
598 if (empty($summary)) {
601 $shortSummary = common_shorten_links($summary);
602 if (Notice::contentTooLong($shortSummary)) {
603 $url = common_shorten_url($sourceUrl);
604 $shortSummary = substr($shortSummary,
606 Notice::maxContent() - (mb_strlen($url) + 2));
607 $content = $shortSummary . ' ' . $url;
609 // We mark up the attachment link specially for the HTML output
610 // so we can fold-out the full version inline.
612 // @todo FIXME i18n: This tooltip will be saved with the site's default language
613 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
614 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
615 $showMoreText = _m('Show more');
616 $attachUrl = common_local_url('attachment',
617 array('attachment' => $attachment->id));
618 $rendered = common_render_text($shortSummary) .
619 '<a href="' . htmlspecialchars($attachUrl) .'"'.
620 ' class="attachment more"' .
621 ' title="'. htmlspecialchars($showMoreText) . '">' .
627 $options = array('is_local' => Notice::REMOTE,
630 'rendered' => $rendered,
631 'replies' => array(),
633 'peopletags' => array(),
636 'repeat_of' => $sharedNotice->id,
637 'scope' => $sharedNotice->scope);
639 // Check for optional attributes...
641 if (!empty($activity->time)) {
642 $options['created'] = common_sql_date($activity->time);
645 if ($activity->context) {
646 // Any individual or group attn: targets?
647 $replies = $activity->context->attention;
648 $options['groups'] = $this->filterReplies($oprofile, $replies);
649 $options['replies'] = $replies;
651 // Maintain direct reply associations
652 // @fixme what about conversation ID?
653 if (!empty($activity->context->replyToID)) {
654 $orig = Notice::staticGet('uri',
655 $activity->context->replyToID);
657 $options['reply_to'] = $orig->id;
661 $location = $activity->context->location;
663 $options['lat'] = $location->lat;
664 $options['lon'] = $location->lon;
665 if ($location->location_id) {
666 $options['location_ns'] = $location->location_ns;
667 $options['location_id'] = $location->location_id;
672 if ($this->isPeopletag()) {
673 $options['peopletags'][] = $this->localPeopletag();
676 // Atom categories <-> hashtags
677 foreach ($activity->categories as $cat) {
679 $term = common_canonical_tag($cat->term);
681 $options['tags'][] = $term;
686 // Atom enclosures -> attachment URLs
687 foreach ($activity->enclosures as $href) {
688 // @fixme save these locally or....?
689 $options['urls'][] = $href;
692 return Notice::saveNew($oprofile->profile_id,
699 * Process an incoming post activity from this remote feed.
700 * @param Activity $activity
701 * @param string $method 'push' or 'salmon'
702 * @return mixed saved Notice or false
703 * @fixme break up this function, it's getting nasty long
705 public function processPost($activity, $method)
707 $oprofile = $this->checkAuthorship($activity);
709 if (empty($oprofile)) {
713 // It's not always an ActivityObject::NOTE, but... let's just say it is.
715 $note = $activity->objects[0];
717 // The id URI will be used as a unique identifier for for the notice,
718 // protecting against duplicate saves. It isn't required to be a URL;
719 // tag: URIs for instance are found in Google Buzz feeds.
720 $sourceUri = $note->id;
721 $dupe = Notice::staticGet('uri', $sourceUri);
723 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
727 // We'll also want to save a web link to the original notice, if provided.
730 $sourceUrl = $note->link;
731 } else if ($activity->link) {
732 $sourceUrl = $activity->link;
733 } else if (preg_match('!^https?://!', $note->id)) {
734 $sourceUrl = $note->id;
737 // Use summary as fallback for content
739 if (!empty($note->content)) {
740 $sourceContent = $note->content;
741 } else if (!empty($note->summary)) {
742 $sourceContent = $note->summary;
743 } else if (!empty($note->title)) {
744 $sourceContent = $note->title;
746 // @fixme fetch from $sourceUrl?
747 // TRANS: Client exception. %s is a source URI.
748 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
751 // Get (safe!) HTML and text versions of the content
753 $rendered = $this->purify($sourceContent);
754 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
756 $shortened = common_shorten_links($content);
758 // If it's too long, try using the summary, and make the
759 // HTML an attachment.
763 if (Notice::contentTooLong($shortened)) {
764 $attachment = $this->saveHTMLFile($note->title, $rendered);
765 $summary = html_entity_decode(strip_tags($note->summary), ENT_QUOTES, 'UTF-8');
766 if (empty($summary)) {
769 $shortSummary = common_shorten_links($summary);
770 if (Notice::contentTooLong($shortSummary)) {
771 $url = common_shorten_url($sourceUrl);
772 $shortSummary = substr($shortSummary,
774 Notice::maxContent() - (mb_strlen($url) + 2));
775 $content = $shortSummary . ' ' . $url;
777 // We mark up the attachment link specially for the HTML output
778 // so we can fold-out the full version inline.
780 // @todo FIXME i18n: This tooltip will be saved with the site's default language
781 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
782 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
783 $showMoreText = _m('Show more');
784 $attachUrl = common_local_url('attachment',
785 array('attachment' => $attachment->id));
786 $rendered = common_render_text($shortSummary) .
787 '<a href="' . htmlspecialchars($attachUrl) .'"'.
788 ' class="attachment more"' .
789 ' title="'. htmlspecialchars($showMoreText) . '">' .
795 $options = array('is_local' => Notice::REMOTE,
798 'rendered' => $rendered,
799 'replies' => array(),
801 'peopletags' => array(),
805 // Check for optional attributes...
807 if (!empty($activity->time)) {
808 $options['created'] = common_sql_date($activity->time);
811 if ($activity->context) {
812 // Any individual or group attn: targets?
813 $replies = $activity->context->attention;
814 $options['groups'] = $this->filterReplies($oprofile, $replies);
815 $options['replies'] = $replies;
817 // Maintain direct reply associations
818 // @fixme what about conversation ID?
819 if (!empty($activity->context->replyToID)) {
820 $orig = Notice::staticGet('uri',
821 $activity->context->replyToID);
823 $options['reply_to'] = $orig->id;
827 $location = $activity->context->location;
829 $options['lat'] = $location->lat;
830 $options['lon'] = $location->lon;
831 if ($location->location_id) {
832 $options['location_ns'] = $location->location_ns;
833 $options['location_id'] = $location->location_id;
838 if ($this->isPeopletag()) {
839 $options['peopletags'][] = $this->localPeopletag();
842 // Atom categories <-> hashtags
843 foreach ($activity->categories as $cat) {
845 $term = common_canonical_tag($cat->term);
847 $options['tags'][] = $term;
852 // Atom enclosures -> attachment URLs
853 foreach ($activity->enclosures as $href) {
854 // @fixme save these locally or....?
855 $options['urls'][] = $href;
859 $saved = Notice::saveNew($oprofile->profile_id,
864 Ostatus_source::saveNew($saved, $this, $method);
865 if (!empty($attachment)) {
866 File_to_post::processNew($attachment->id, $saved->id);
869 } catch (Exception $e) {
870 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
873 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
880 protected function purify($html)
882 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
883 $config = array('safe' => 1,
884 'deny_attribute' => 'id,style,on*');
885 return htmLawed($html, $config);
889 * Filters a list of recipient ID URIs to just those for local delivery.
890 * @param Ostatus_profile local profile of sender
891 * @param array in/out &$attention_uris set of URIs, will be pruned on output
892 * @return array of group IDs
894 protected function filterReplies($sender, &$attention_uris)
896 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', $attention_uris));
899 foreach (array_unique($attention_uris) as $recipient) {
900 // Is the recipient a local user?
901 $user = User::staticGet('uri', $recipient);
903 // @fixme sender verification, spam etc?
904 $replies[] = $recipient;
908 // Is the recipient a local group?
909 // $group = User_group::staticGet('uri', $recipient);
910 $id = OStatusPlugin::localGroupFromUrl($recipient);
912 $group = User_group::staticGet('id', $id);
914 // Deliver to all members of this local group if allowed.
915 $profile = $sender->localProfile();
916 if ($profile->isMember($group)) {
917 $groups[] = $group->id;
919 common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
923 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
927 // Is the recipient a remote user or group?
929 $oprofile = Ostatus_profile::ensureProfileURI($recipient);
930 if ($oprofile->isGroup()) {
931 // Deliver to local members of this remote group.
932 // @fixme sender verification?
933 $groups[] = $oprofile->group_id;
935 // may be canonicalized or something
936 $replies[] = $oprofile->uri;
939 } catch (Exception $e) {
940 // Neither a recognizable local nor remote user!
941 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
945 $attention_uris = $replies;
946 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
947 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
952 * Look up and if necessary create an Ostatus_profile for the remote entity
953 * with the given profile page URL. This should never return null -- you
954 * will either get an object or an exception will be thrown.
956 * @param string $profile_url
957 * @return Ostatus_profile
958 * @throws Exception on various error conditions
959 * @throws OStatusShadowException if this reference would obscure a local user/group
961 public static function ensureProfileURL($profile_url, $hints=array())
963 $oprofile = self::getFromProfileURL($profile_url);
965 if (!empty($oprofile)) {
969 $hints['profileurl'] = $profile_url;
974 $client = new HTTPClient();
975 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
976 $response = $client->get($profile_url);
978 if (!$response->isOk()) {
979 // TRANS: Exception. %s is a profile URL.
980 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
983 // Check if we have a non-canonical URL
985 $finalUrl = $response->getUrl();
987 if ($finalUrl != $profile_url) {
989 $hints['profileurl'] = $finalUrl;
991 $oprofile = self::getFromProfileURL($finalUrl);
993 if (!empty($oprofile)) {
998 // Try to get some hCard data
1000 $body = $response->getBody();
1002 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1004 if (!empty($hcardHints)) {
1005 $hints = array_merge($hints, $hcardHints);
1008 // Check if they've got an LRDD header
1010 $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
1012 if (!empty($lrdd)) {
1014 $xrd = Discovery::fetchXrd($lrdd);
1015 $xrdHints = DiscoveryHints::fromXRD($xrd);
1017 $hints = array_merge($hints, $xrdHints);
1020 // If discovery found a feedurl (probably from LRDD), use it.
1022 if (array_key_exists('feedurl', $hints)) {
1023 return self::ensureFeedURL($hints['feedurl'], $hints);
1026 // Get the feed URL from HTML
1028 $discover = new FeedDiscovery();
1030 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1032 if (!empty($feedurl)) {
1033 $hints['feedurl'] = $feedurl;
1034 return self::ensureFeedURL($feedurl, $hints);
1037 // TRANS: Exception. %s is a URL.
1038 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1042 * Look up the Ostatus_profile, if present, for a remote entity with the
1043 * given profile page URL. Will return null for both unknown and invalid
1046 * @return mixed Ostatus_profile or null
1047 * @throws OStatusShadowException for local profiles
1049 static function getFromProfileURL($profile_url)
1051 $profile = Profile::staticGet('profileurl', $profile_url);
1053 if (empty($profile)) {
1057 // Is it a known Ostatus profile?
1059 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1061 if (!empty($oprofile)) {
1065 // Is it a local user?
1067 $user = User::staticGet('id', $profile->id);
1069 if (!empty($user)) {
1070 // @todo i18n FIXME: use sprintf and add i18n (?)
1071 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1074 // Continue discovery; it's a remote profile
1075 // for OMB or some other protocol, may also
1082 * Look up and if necessary create an Ostatus_profile for remote entity
1083 * with the given update feed. This should never return null -- you will
1084 * either get an object or an exception will be thrown.
1086 * @return Ostatus_profile
1089 public static function ensureFeedURL($feed_url, $hints=array())
1091 $discover = new FeedDiscovery();
1093 $feeduri = $discover->discoverFromFeedURL($feed_url);
1094 $hints['feedurl'] = $feeduri;
1096 $huburi = $discover->getHubLink();
1097 $hints['hub'] = $huburi;
1098 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1099 $hints['salmon'] = $salmonuri;
1101 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1102 // We can only deal with folks with a PuSH hub
1103 throw new FeedSubNoHubException();
1106 $feedEl = $discover->root;
1108 if ($feedEl->tagName == 'feed') {
1109 return self::ensureAtomFeed($feedEl, $hints);
1110 } else if ($feedEl->tagName == 'channel') {
1111 return self::ensureRssChannel($feedEl, $hints);
1113 throw new FeedSubBadXmlException($feeduri);
1118 * Look up and, if necessary, create an Ostatus_profile for the remote
1119 * profile with the given Atom feed - actually loaded from the feed.
1120 * This should never return null -- you will either get an object or
1121 * an exception will be thrown.
1123 * @param DOMElement $feedEl root element of a loaded Atom feed
1124 * @param array $hints additional discovery information passed from higher levels
1125 * @fixme should this be marked public?
1126 * @return Ostatus_profile
1129 public static function ensureAtomFeed($feedEl, $hints)
1131 $author = ActivityUtils::getFeedAuthor($feedEl);
1133 if (empty($author)) {
1134 // XXX: make some educated guesses here
1135 // TRANS: Feed sub exception.
1136 throw new FeedSubException(_m('Cannot find enough profile '.
1137 'information to make a feed.'));
1140 return self::ensureActivityObjectProfile($author, $hints);
1144 * Look up and, if necessary, create an Ostatus_profile for the remote
1145 * profile with the given RSS feed - actually loaded from the feed.
1146 * This should never return null -- you will either get an object or
1147 * an exception will be thrown.
1149 * @param DOMElement $feedEl root element of a loaded RSS feed
1150 * @param array $hints additional discovery information passed from higher levels
1151 * @fixme should this be marked public?
1152 * @return Ostatus_profile
1155 public static function ensureRssChannel($feedEl, $hints)
1157 // Special-case for Posterous. They have some nice metadata in their
1158 // posterous:author elements. We should use them instead of the channel.
1160 $items = $feedEl->getElementsByTagName('item');
1162 if ($items->length > 0) {
1163 $item = $items->item(0);
1164 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1165 if (!empty($authorEl)) {
1166 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1167 // Posterous has multiple authors per feed, and multiple feeds
1168 // per author. We check if this is the "main" feed for this author.
1169 if (array_key_exists('profileurl', $hints) &&
1170 !empty($obj->poco) &&
1171 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1172 return self::ensureActivityObjectProfile($obj, $hints);
1177 // @fixme we should check whether this feed has elements
1178 // with different <author> or <dc:creator> elements, and... I dunno.
1179 // Do something about that.
1181 $obj = ActivityObject::fromRssChannel($feedEl);
1183 return self::ensureActivityObjectProfile($obj, $hints);
1187 * Download and update given avatar image
1189 * @param string $url
1190 * @throws Exception in various failure cases
1192 protected function updateAvatar($url)
1194 if ($url == $this->avatar) {
1195 // We've already got this one.
1198 if (!common_valid_http_url($url)) {
1199 // TRANS: Server exception. %s is a URL.
1200 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1203 if ($this->isGroup()) {
1204 $self = $this->localGroup();
1206 $self = $this->localProfile();
1209 throw new ServerException(sprintf(
1210 // TRANS: Server exception. %s is a URI.
1211 _m('Tried to update avatar for unsaved remote profile %s.'),
1215 // @fixme this should be better encapsulated
1216 // ripped from oauthstore.php (for old OMB client)
1217 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1219 if (!copy($url, $temp_filename)) {
1220 // TRANS: Server exception. %s is a URL.
1221 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1224 if ($this->isGroup()) {
1225 $id = $this->group_id;
1227 $id = $this->profile_id;
1229 // @fixme should we be using different ids?
1230 $imagefile = new ImageFile($id, $temp_filename);
1231 $filename = Avatar::filename($id,
1232 image_type_to_extension($imagefile->type),
1234 common_timestamp());
1235 rename($temp_filename, Avatar::path($filename));
1236 } catch (Exception $e) {
1237 unlink($temp_filename);
1240 // @fixme hardcoded chmod is lame, but seems to be necessary to
1241 // keep from accidentally saving images from command-line (queues)
1242 // that can't be read from web server, which causes hard-to-notice
1243 // problems later on:
1245 // http://status.net/open-source/issues/2663
1246 chmod(Avatar::path($filename), 0644);
1248 $profile = $this->localProfile();
1250 if (!empty($profile)) {
1251 $profile->setOriginal($filename);
1254 $orig = clone($this);
1255 $this->avatar = $url;
1256 $this->update($orig);
1260 * Pull avatar URL from ActivityObject or profile hints
1262 * @param ActivityObject $object
1263 * @param array $hints
1264 * @return mixed URL string or false
1266 public static function getActivityObjectAvatar($object, $hints=array())
1268 if ($object->avatarLinks) {
1270 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1271 foreach ($object->avatarLinks as $avatar) {
1272 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1277 if (!$best || $avatar->width > $best->width) {
1282 } else if (array_key_exists('avatar', $hints)) {
1283 return $hints['avatar'];
1289 * Get an appropriate avatar image source URL, if available.
1291 * @param ActivityObject $actor
1292 * @param DOMElement $feed
1295 protected static function getAvatar($actor, $feed)
1299 if ($actor->avatar) {
1300 $url = trim($actor->avatar);
1303 // Check <atom:logo> and <atom:icon> on the feed
1304 $els = $feed->childNodes();
1305 if ($els && $els->length) {
1306 for ($i = 0; $i < $els->length; $i++) {
1307 $el = $els->item($i);
1308 if ($el->namespaceURI == Activity::ATOM) {
1309 if (empty($url) && $el->localName == 'logo') {
1310 $url = trim($el->textContent);
1313 if (empty($icon) && $el->localName == 'icon') {
1314 // Use as a fallback
1315 $icon = trim($el->textContent);
1320 if ($icon && !$url) {
1325 $opts = array('allowed_schemes' => array('http', 'https'));
1326 if (Validate::uri($url, $opts)) {
1331 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1335 * Fetch, or build if necessary, an Ostatus_profile for the actor
1336 * in a given Activity Streams activity.
1337 * This should never return null -- you will either get an object or
1338 * an exception will be thrown.
1340 * @param Activity $activity
1341 * @param string $feeduri if we already know the canonical feed URI!
1342 * @param string $salmonuri if we already know the salmon return channel URI
1343 * @return Ostatus_profile
1346 public static function ensureActorProfile($activity, $hints=array())
1348 return self::ensureActivityObjectProfile($activity->actor, $hints);
1352 * Fetch, or build if necessary, an Ostatus_profile for the profile
1353 * in a given Activity Streams object (can be subject, actor, or object).
1354 * This should never return null -- you will either get an object or
1355 * an exception will be thrown.
1357 * @param ActivityObject $object
1358 * @param array $hints additional discovery information passed from higher levels
1359 * @return Ostatus_profile
1362 public static function ensureActivityObjectProfile($object, $hints=array())
1364 $profile = self::getActivityObjectProfile($object);
1366 $profile->updateFromActivityObject($object, $hints);
1368 $profile = self::createActivityObjectProfile($object, $hints);
1374 * @param Activity $activity
1375 * @return mixed matching Ostatus_profile or false if none known
1376 * @throws ServerException if feed info invalid
1378 public static function getActorProfile($activity)
1380 return self::getActivityObjectProfile($activity->actor);
1384 * @param ActivityObject $activity
1385 * @return mixed matching Ostatus_profile or false if none known
1386 * @throws ServerException if feed info invalid
1388 protected static function getActivityObjectProfile($object)
1390 $uri = self::getActivityObjectProfileURI($object);
1391 return Ostatus_profile::staticGet('uri', $uri);
1395 * Get the identifier URI for the remote entity described
1396 * by this ActivityObject. This URI is *not* guaranteed to be
1397 * a resolvable HTTP/HTTPS URL.
1399 * @param ActivityObject $object
1401 * @throws ServerException if feed info invalid
1403 protected static function getActivityObjectProfileURI($object)
1406 if (ActivityUtils::validateUri($object->id)) {
1411 // If the id is missing or invalid (we've seen feeds mistakenly listing
1412 // things like local usernames in that field) then we'll use the profile
1413 // page link, if valid.
1414 if ($object->link && common_valid_http_url($object->link)) {
1415 return $object->link;
1417 // TRANS: Server exception.
1418 throw new ServerException(_m('No author ID URI found.'));
1422 * @fixme validate stuff somewhere
1426 * Create local ostatus_profile and profile/user_group entries for
1427 * the provided remote user or group.
1428 * This should never return null -- you will either get an object or
1429 * an exception will be thrown.
1431 * @param ActivityObject $object
1432 * @param array $hints
1434 * @return Ostatus_profile
1436 protected static function createActivityObjectProfile($object, $hints=array())
1438 $homeuri = $object->id;
1442 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1443 // TRANS: Exception.
1444 throw new Exception(_m('No profile URI.'));
1447 $user = User::staticGet('uri', $homeuri);
1449 // TRANS: Exception.
1450 throw new Exception(_m('Local user cannot be referenced as remote.'));
1453 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1454 // TRANS: Exception.
1455 throw new Exception(_m('Local group cannot be referenced as remote.'));
1458 $ptag = Profile_list::staticGet('uri', $homeuri);
1460 $local_user = User::staticGet('id', $ptag->tagger);
1461 if (!empty($local_user)) {
1462 // TRANS: Exception.
1463 throw new Exception(_m('Local list cannot be referenced as remote.'));
1467 if (array_key_exists('feedurl', $hints)) {
1468 $feeduri = $hints['feedurl'];
1470 $discover = new FeedDiscovery();
1471 $feeduri = $discover->discoverFromURL($homeuri);
1474 if (array_key_exists('salmon', $hints)) {
1475 $salmonuri = $hints['salmon'];
1478 $discover = new FeedDiscovery();
1479 $discover->discoverFromFeedURL($hints['feedurl']);
1481 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1484 if (array_key_exists('hub', $hints)) {
1485 $huburi = $hints['hub'];
1488 $discover = new FeedDiscovery();
1489 $discover->discoverFromFeedURL($hints['feedurl']);
1491 $huburi = $discover->getHubLink();
1494 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1495 // We can only deal with folks with a PuSH hub
1496 throw new FeedSubNoHubException();
1499 $oprofile = new Ostatus_profile();
1501 $oprofile->uri = $homeuri;
1502 $oprofile->feeduri = $feeduri;
1503 $oprofile->salmonuri = $salmonuri;
1505 $oprofile->created = common_sql_now();
1506 $oprofile->modified = common_sql_now();
1508 if ($object->type == ActivityObject::PERSON) {
1509 $profile = new Profile();
1510 $profile->created = common_sql_now();
1511 self::updateProfile($profile, $object, $hints);
1513 $oprofile->profile_id = $profile->insert();
1514 if (!$oprofile->profile_id) {
1515 // TRANS: Server exception.
1516 throw new ServerException(_m('Cannot save local profile.'));
1518 } else if ($object->type == ActivityObject::GROUP) {
1519 $group = new User_group();
1520 $group->uri = $homeuri;
1521 $group->created = common_sql_now();
1522 self::updateGroup($group, $object, $hints);
1524 $oprofile->group_id = $group->insert();
1525 if (!$oprofile->group_id) {
1526 // TRANS: Server exception.
1527 throw new ServerException(_m('Cannot save local profile.'));
1529 } else if ($object->type == ActivityObject::_LIST) {
1530 $ptag = new Profile_list();
1531 $ptag->uri = $homeuri;
1532 $ptag->created = common_sql_now();
1533 self::updatePeopletag($ptag, $object, $hints);
1535 $oprofile->peopletag_id = $ptag->insert();
1536 if (!$oprofile->peopletag_id) {
1537 // TRANS: Server exception.
1538 throw new ServerException(_m('Cannot save local list.'));
1542 $ok = $oprofile->insert();
1545 // TRANS: Server exception.
1546 throw new ServerException(_m('Cannot save OStatus profile.'));
1549 $avatar = self::getActivityObjectAvatar($object, $hints);
1553 $oprofile->updateAvatar($avatar);
1554 } catch (Exception $ex) {
1555 // Profile is saved, but Avatar is messed up. We're
1556 // just going to continue.
1557 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1565 * Save any updated profile information to our local copy.
1566 * @param ActivityObject $object
1567 * @param array $hints
1569 public function updateFromActivityObject($object, $hints=array())
1571 if ($this->isGroup()) {
1572 $group = $this->localGroup();
1573 self::updateGroup($group, $object, $hints);
1574 } else if ($this->isPeopletag()) {
1575 $ptag = $this->localPeopletag();
1576 self::updatePeopletag($ptag, $object, $hints);
1578 $profile = $this->localProfile();
1579 self::updateProfile($profile, $object, $hints);
1582 $avatar = self::getActivityObjectAvatar($object, $hints);
1583 if ($avatar && !isset($ptag)) {
1585 $this->updateAvatar($avatar);
1586 } catch (Exception $ex) {
1587 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1592 public static function updateProfile($profile, $object, $hints=array())
1594 $orig = clone($profile);
1596 // Existing nickname is better than nothing.
1598 if (!array_key_exists('nickname', $hints)) {
1599 $hints['nickname'] = $profile->nickname;
1602 $nickname = self::getActivityObjectNickname($object, $hints);
1604 if (!empty($nickname)) {
1605 $profile->nickname = $nickname;
1608 if (!empty($object->title)) {
1609 $profile->fullname = $object->title;
1610 } else if (array_key_exists('fullname', $hints)) {
1611 $profile->fullname = $hints['fullname'];
1614 if (!empty($object->link)) {
1615 $profile->profileurl = $object->link;
1616 } else if (array_key_exists('profileurl', $hints)) {
1617 $profile->profileurl = $hints['profileurl'];
1618 } else if (Validate::uri($object->id, array('allowed_schemes' => array('http', 'https')))) {
1619 $profile->profileurl = $object->id;
1622 $bio = self::getActivityObjectBio($object, $hints);
1625 $profile->bio = $bio;
1628 $location = self::getActivityObjectLocation($object, $hints);
1630 if (!empty($location)) {
1631 $profile->location = $location;
1634 $homepage = self::getActivityObjectHomepage($object, $hints);
1636 if (!empty($homepage)) {
1637 $profile->homepage = $homepage;
1640 if (!empty($object->geopoint)) {
1641 $location = ActivityContext::locationFromPoint($object->geopoint);
1642 if (!empty($location)) {
1643 $profile->lat = $location->lat;
1644 $profile->lon = $location->lon;
1648 // @fixme tags/categories
1649 // @todo tags from categories
1652 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1653 $profile->update($orig);
1657 protected static function updateGroup($group, $object, $hints=array())
1659 $orig = clone($group);
1661 $group->nickname = self::getActivityObjectNickname($object, $hints);
1662 $group->fullname = $object->title;
1664 if (!empty($object->link)) {
1665 $group->mainpage = $object->link;
1666 } else if (array_key_exists('profileurl', $hints)) {
1667 $group->mainpage = $hints['profileurl'];
1670 // @todo tags from categories
1671 $group->description = self::getActivityObjectBio($object, $hints);
1672 $group->location = self::getActivityObjectLocation($object, $hints);
1673 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1676 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1677 $group->update($orig);
1681 protected static function updatePeopletag($tag, $object, $hints=array()) {
1682 $orig = clone($tag);
1684 $tag->tag = $object->title;
1686 if (!empty($object->link)) {
1687 $tag->mainpage = $object->link;
1688 } else if (array_key_exists('profileurl', $hints)) {
1689 $tag->mainpage = $hints['profileurl'];
1692 $tag->description = $object->summary;
1693 $tagger = self::ensureActivityObjectProfile($object->owner);
1694 $tag->tagger = $tagger->profile_id;
1697 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1698 $tag->update($orig);
1702 protected static function getActivityObjectHomepage($object, $hints=array())
1705 $poco = $object->poco;
1707 if (!empty($poco)) {
1708 $url = $poco->getPrimaryURL();
1709 if ($url && $url->type == 'homepage') {
1710 $homepage = $url->value;
1714 // @todo Try for a another PoCo URL?
1719 protected static function getActivityObjectLocation($object, $hints=array())
1723 if (!empty($object->poco) &&
1724 isset($object->poco->address->formatted)) {
1725 $location = $object->poco->address->formatted;
1726 } else if (array_key_exists('location', $hints)) {
1727 $location = $hints['location'];
1730 if (!empty($location)) {
1731 if (mb_strlen($location) > 255) {
1732 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1736 // @todo Try to find location some othe way? Via goerss point?
1741 protected static function getActivityObjectBio($object, $hints=array())
1745 if (!empty($object->poco)) {
1746 $note = $object->poco->note;
1747 } else if (array_key_exists('bio', $hints)) {
1748 $note = $hints['bio'];
1751 if (!empty($note)) {
1752 if (Profile::bioTooLong($note)) {
1753 // XXX: truncate ok?
1754 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1760 // @todo Try to get bio info some other way?
1765 public static function getActivityObjectNickname($object, $hints=array())
1767 if ($object->poco) {
1768 if (!empty($object->poco->preferredUsername)) {
1769 return common_nicknamize($object->poco->preferredUsername);
1773 if (!empty($object->nickname)) {
1774 return common_nicknamize($object->nickname);
1777 if (array_key_exists('nickname', $hints)) {
1778 return $hints['nickname'];
1781 // Try the profile url (like foo.example.com or example.com/user/foo)
1782 if (!empty($object->link)) {
1783 $profileUrl = $object->link;
1784 } else if (!empty($hints['profileurl'])) {
1785 $profileUrl = $hints['profileurl'];
1788 if (!empty($profileUrl)) {
1789 $nickname = self::nicknameFromURI($profileUrl);
1792 // Try the URI (may be a tag:, http:, acct:, ...
1794 if (empty($nickname)) {
1795 $nickname = self::nicknameFromURI($object->id);
1798 // Try a Webfinger if one was passed (way) down
1800 if (empty($nickname)) {
1801 if (array_key_exists('webfinger', $hints)) {
1802 $nickname = self::nicknameFromURI($hints['webfinger']);
1808 if (empty($nickname)) {
1809 $nickname = common_nicknamize($object->title);
1815 protected static function nicknameFromURI($uri)
1817 if (preg_match('/(\w+):/', $uri, $matches)) {
1818 $protocol = $matches[1];
1823 switch ($protocol) {
1826 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1827 return common_canonical_nickname($matches[1]);
1831 return common_url_to_nickname($uri);
1839 * Look up, and if necessary create, an Ostatus_profile for the remote
1840 * entity with the given webfinger address.
1841 * This should never return null -- you will either get an object or
1842 * an exception will be thrown.
1844 * @param string $addr webfinger address
1845 * @return Ostatus_profile
1846 * @throws Exception on error conditions
1847 * @throws OStatusShadowException if this reference would obscure a local user/group
1849 public static function ensureWebfinger($addr)
1851 // First, try the cache
1853 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1855 if ($uri !== false) {
1856 if (is_null($uri)) {
1857 // Negative cache entry
1858 // TRANS: Exception.
1859 throw new Exception(_m('Not a valid webfinger address.'));
1861 $oprofile = Ostatus_profile::staticGet('uri', $uri);
1862 if (!empty($oprofile)) {
1867 // Try looking it up
1868 $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1870 if (!empty($oprofile)) {
1871 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1875 // Now, try some discovery
1877 $disco = new Discovery();
1880 $xrd = $disco->lookup($addr);
1881 } catch (Exception $e) {
1882 // Save negative cache entry so we don't waste time looking it up again.
1883 // @fixme distinguish temporary failures?
1884 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1885 // TRANS: Exception.
1886 throw new Exception(_m('Not a valid webfinger address.'));
1889 $hints = array('webfinger' => $addr);
1891 $dhints = DiscoveryHints::fromXRD($xrd);
1893 $hints = array_merge($hints, $dhints);
1895 // If there's an Hcard, let's grab its info
1896 if (array_key_exists('hcard', $hints)) {
1897 if (!array_key_exists('profileurl', $hints) ||
1898 $hints['hcard'] != $hints['profileurl']) {
1899 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1900 $hints = array_merge($hcardHints, $hints);
1904 // If we got a feed URL, try that
1905 if (array_key_exists('feedurl', $hints)) {
1907 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1908 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1909 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1911 } catch (Exception $e) {
1912 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1917 // If we got a profile page, try that!
1918 if (array_key_exists('profileurl', $hints)) {
1920 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1921 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1922 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1924 } catch (OStatusShadowException $e) {
1925 // We've ended up with a remote reference to a local user or group.
1926 // @fixme ideally we should be able to say who it was so we can
1927 // go back and refer to it the regular way
1929 } catch (Exception $e) {
1930 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1933 // @fixme this means an error discovering from profile page
1934 // may give us a corrupt entry using the webfinger URI, which
1935 // will obscure the correct page-keyed profile later on.
1942 if (array_key_exists('salmon', $hints)) {
1943 $salmonEndpoint = $hints['salmon'];
1945 // An account URL, a salmon endpoint, and a dream? Not much to go
1946 // on, but let's give it a try
1948 $uri = 'acct:'.$addr;
1950 $profile = new Profile();
1952 $profile->nickname = self::nicknameFromUri($uri);
1953 $profile->created = common_sql_now();
1955 if (isset($profileUrl)) {
1956 $profile->profileurl = $profileUrl;
1959 $profile_id = $profile->insert();
1962 common_log_db_error($profile, 'INSERT', __FILE__);
1963 // TRANS: Exception. %s is a webfinger address.
1964 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1967 $oprofile = new Ostatus_profile();
1969 $oprofile->uri = $uri;
1970 $oprofile->salmonuri = $salmonEndpoint;
1971 $oprofile->profile_id = $profile_id;
1972 $oprofile->created = common_sql_now();
1974 if (isset($feedUrl)) {
1975 $profile->feeduri = $feedUrl;
1978 $result = $oprofile->insert();
1981 common_log_db_error($oprofile, 'INSERT', __FILE__);
1982 // TRANS: Exception. %s is a webfinger address.
1983 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1986 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1990 // TRANS: Exception. %s is a webfinger address.
1991 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1995 * Store the full-length scrubbed HTML of a remote notice to an attachment
1996 * file on our server. We'll link to this at the end of the cropped version.
1998 * @param string $title plaintext for HTML page's title
1999 * @param string $rendered HTML fragment for HTML page's body
2002 function saveHTMLFile($title, $rendered)
2004 $final = sprintf("<!DOCTYPE html>\n" .
2006 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2007 '<title>%s</title>' .
2009 '<body>%s</body></html>',
2010 htmlspecialchars($title),
2013 $filename = File::filename($this->localProfile(),
2014 'ostatus', // ignored?
2017 $filepath = File::path($filename);
2019 file_put_contents($filepath, $final);
2023 $file->filename = $filename;
2024 $file->url = File::url($filename);
2025 $file->size = filesize($filepath);
2026 $file->date = time();
2027 $file->mimetype = 'text/html';
2029 $file_id = $file->insert();
2031 if ($file_id === false) {
2032 common_log_db_error($file, "INSERT", __FILE__);
2033 // TRANS: Server exception.
2034 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2040 static function ensureProfileURI($uri)
2044 // First, try to query it
2046 $oprofile = Ostatus_profile::staticGet('uri', $uri);
2048 // If unfound, do discovery stuff
2050 if (empty($oprofile)) {
2051 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2052 $protocol = $match[1];
2053 switch ($protocol) {
2056 $oprofile = Ostatus_profile::ensureProfileURL($uri);
2061 $oprofile = Ostatus_profile::ensureWebfinger($rest);
2064 // TRANS: Server exception.
2065 // TRANS: %1$s is a protocol, %2$s is a URI.
2066 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2072 // TRANS: Server exception. %s is a URI.
2073 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2080 function checkAuthorship($activity)
2082 if ($this->isGroup() || $this->isPeopletag()) {
2083 // A group or propletag feed will contain posts from multiple authors.
2084 $oprofile = self::ensureActorProfile($activity);
2085 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2086 // Groups can't post notices in StatusNet.
2087 common_log(LOG_WARNING,
2088 "OStatus: skipping post with group listed ".
2089 "as author: $oprofile->uri in feed from $this->uri");
2093 $actor = $activity->actor;
2095 if (empty($actor)) {
2096 // OK here! assume the default
2097 } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
2098 $this->updateFromActivityObject($actor);
2099 } else if ($actor->id) {
2100 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2101 // This isn't what we expect from mainline OStatus person feeds!
2102 // Group feeds go down another path, with different validation...
2103 // Most likely this is a plain ol' blog feed of some kind which
2104 // doesn't match our expectations. We'll take the entry, but ignore
2105 // the <author> info.
2106 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
2108 // Plain <author> without ActivityStreams actor info.
2109 // We'll just ignore this info for now and save the update under the feed's identity.
2120 * Exception indicating we've got a remote reference to a local user,
2121 * not a remote user!
2123 * If we can ue a local profile after all, it's available as $e->profile.
2125 class OStatusShadowException extends Exception
2130 * @param Profile $profile
2131 * @param string $message
2133 function __construct($profile, $message) {
2134 $this->profile = $profile;
2135 parent::__construct($message);