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 * @return Notice Notice representing the new (or existing) activity
470 public function processEntry($entry, $feed, $source)
472 $activity = new Activity($entry, $feed);
473 return $this->processActivity($activity, $source);
476 public function processActivity($activity, $source)
480 // The "WithProfile" events were added later.
482 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this, &$notice)) &&
483 Event::handle('StartHandleFeedEntry', array($activity))) {
485 switch ($activity->verb) {
486 case ActivityVerb::POST:
487 // @todo process all activity objects
488 switch ($activity->objects[0]->type) {
489 case ActivityObject::ARTICLE:
490 case ActivityObject::BLOGENTRY:
491 case ActivityObject::NOTE:
492 case ActivityObject::STATUS:
493 case ActivityObject::COMMENT:
495 $notice = $this->processPost($activity, $source);
498 // TRANS: Client exception.
499 throw new ClientException(_m('Cannot handle that kind of post.'));
502 case ActivityVerb::SHARE:
503 $notice = $this->processShare($activity, $source);
506 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
509 Event::handle('EndHandleFeedEntry', array($activity));
510 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this, $notice));
516 public function processShare($activity, $method)
520 $oprofile = $this->checkAuthorship($activity);
522 if (empty($oprofile)) {
523 common_log(LOG_INFO, "No author matched share activity");
527 if (count($activity->objects) != 1) {
528 throw new ClientException(_m("Can only handle share activities with exactly one object."));
531 $shared = $activity->objects[0];
533 if (!($shared instanceof Activity)) {
534 throw new ClientException(_m("Can only handle shared activities."));
537 $other = Ostatus_profile::ensureActivityObjectProfile($shared->actor);
539 // Save the item (or check for a dupe)
541 $sharedNotice = $other->processActivity($shared, $method);
543 if (empty($sharedNotice)) {
544 $sharedId = ($shared->id) ? $shared->id : $shared->objects[0]->id;
545 throw new ClientException(sprintf(_m("Failed to save activity %s"),
549 // The id URI will be used as a unique identifier for for the notice,
550 // protecting against duplicate saves. It isn't required to be a URL;
551 // tag: URIs for instance are found in Google Buzz feeds.
553 $sourceUri = $activity->id;
555 $dupe = Notice::staticGet('uri', $sourceUri);
557 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
561 // We'll also want to save a web link to the original notice, if provided.
564 if ($activity->link) {
565 $sourceUrl = $activity->link;
566 } else if ($activity->link) {
567 $sourceUrl = $activity->link;
568 } else if (preg_match('!^https?://!', $activity->id)) {
569 $sourceUrl = $activity->id;
572 // Use summary as fallback for content
574 if (!empty($activity->content)) {
575 $sourceContent = $activity->content;
576 } else if (!empty($activity->summary)) {
577 $sourceContent = $activity->summary;
578 } else if (!empty($activity->title)) {
579 $sourceContent = $activity->title;
581 // @fixme fetch from $sourceUrl?
582 // TRANS: Client exception. %s is a source URI.
583 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
586 // Get (safe!) HTML and text versions of the content
588 $rendered = $this->purify($sourceContent);
589 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
591 $shortened = common_shorten_links($content);
593 // If it's too long, try using the summary, and make the
594 // HTML an attachment.
598 if (Notice::contentTooLong($shortened)) {
599 $attachment = $this->saveHTMLFile($activity->title, $rendered);
600 $summary = html_entity_decode(strip_tags($activity->summary), ENT_QUOTES, 'UTF-8');
601 if (empty($summary)) {
604 $shortSummary = common_shorten_links($summary);
605 if (Notice::contentTooLong($shortSummary)) {
606 $url = common_shorten_url($sourceUrl);
607 $shortSummary = substr($shortSummary,
609 Notice::maxContent() - (mb_strlen($url) + 2));
610 $content = $shortSummary . ' ' . $url;
612 // We mark up the attachment link specially for the HTML output
613 // so we can fold-out the full version inline.
615 // @todo FIXME i18n: This tooltip will be saved with the site's default language
616 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
617 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
618 $showMoreText = _m('Show more');
619 $attachUrl = common_local_url('attachment',
620 array('attachment' => $attachment->id));
621 $rendered = common_render_text($shortSummary) .
622 '<a href="' . htmlspecialchars($attachUrl) .'"'.
623 ' class="attachment more"' .
624 ' title="'. htmlspecialchars($showMoreText) . '">' .
630 $options = array('is_local' => Notice::REMOTE,
633 'rendered' => $rendered,
634 'replies' => array(),
636 'peopletags' => array(),
639 'repeat_of' => $sharedNotice->id,
640 'scope' => $sharedNotice->scope);
642 // Check for optional attributes...
644 if (!empty($activity->time)) {
645 $options['created'] = common_sql_date($activity->time);
648 if ($activity->context) {
649 // Any individual or group attn: targets?
650 $replies = $activity->context->attention;
651 $options['groups'] = $this->filterReplies($oprofile, $replies);
652 $options['replies'] = $replies;
654 // Maintain direct reply associations
655 // @fixme what about conversation ID?
656 if (!empty($activity->context->replyToID)) {
657 $orig = Notice::staticGet('uri',
658 $activity->context->replyToID);
660 $options['reply_to'] = $orig->id;
664 $location = $activity->context->location;
666 $options['lat'] = $location->lat;
667 $options['lon'] = $location->lon;
668 if ($location->location_id) {
669 $options['location_ns'] = $location->location_ns;
670 $options['location_id'] = $location->location_id;
675 if ($this->isPeopletag()) {
676 $options['peopletags'][] = $this->localPeopletag();
679 // Atom categories <-> hashtags
680 foreach ($activity->categories as $cat) {
682 $term = common_canonical_tag($cat->term);
684 $options['tags'][] = $term;
689 // Atom enclosures -> attachment URLs
690 foreach ($activity->enclosures as $href) {
691 // @fixme save these locally or....?
692 $options['urls'][] = $href;
695 $notice = Notice::saveNew($oprofile->profile_id,
704 * Process an incoming post activity from this remote feed.
705 * @param Activity $activity
706 * @param string $method 'push' or 'salmon'
707 * @return mixed saved Notice or false
708 * @fixme break up this function, it's getting nasty long
710 public function processPost($activity, $method)
714 $oprofile = $this->checkAuthorship($activity);
716 if (empty($oprofile)) {
720 // It's not always an ActivityObject::NOTE, but... let's just say it is.
722 $note = $activity->objects[0];
724 // The id URI will be used as a unique identifier for for the notice,
725 // protecting against duplicate saves. It isn't required to be a URL;
726 // tag: URIs for instance are found in Google Buzz feeds.
727 $sourceUri = $note->id;
728 $dupe = Notice::staticGet('uri', $sourceUri);
730 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
734 // We'll also want to save a web link to the original notice, if provided.
737 $sourceUrl = $note->link;
738 } else if ($activity->link) {
739 $sourceUrl = $activity->link;
740 } else if (preg_match('!^https?://!', $note->id)) {
741 $sourceUrl = $note->id;
744 // Use summary as fallback for content
746 if (!empty($note->content)) {
747 $sourceContent = $note->content;
748 } else if (!empty($note->summary)) {
749 $sourceContent = $note->summary;
750 } else if (!empty($note->title)) {
751 $sourceContent = $note->title;
753 // @fixme fetch from $sourceUrl?
754 // TRANS: Client exception. %s is a source URI.
755 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
758 // Get (safe!) HTML and text versions of the content
760 $rendered = $this->purify($sourceContent);
761 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
763 $shortened = common_shorten_links($content);
765 // If it's too long, try using the summary, and make the
766 // HTML an attachment.
770 if (Notice::contentTooLong($shortened)) {
771 $attachment = $this->saveHTMLFile($note->title, $rendered);
772 $summary = html_entity_decode(strip_tags($note->summary), ENT_QUOTES, 'UTF-8');
773 if (empty($summary)) {
776 $shortSummary = common_shorten_links($summary);
777 if (Notice::contentTooLong($shortSummary)) {
778 $url = common_shorten_url($sourceUrl);
779 $shortSummary = substr($shortSummary,
781 Notice::maxContent() - (mb_strlen($url) + 2));
782 $content = $shortSummary . ' ' . $url;
784 // We mark up the attachment link specially for the HTML output
785 // so we can fold-out the full version inline.
787 // @todo FIXME i18n: This tooltip will be saved with the site's default language
788 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
789 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
790 $showMoreText = _m('Show more');
791 $attachUrl = common_local_url('attachment',
792 array('attachment' => $attachment->id));
793 $rendered = common_render_text($shortSummary) .
794 '<a href="' . htmlspecialchars($attachUrl) .'"'.
795 ' class="attachment more"' .
796 ' title="'. htmlspecialchars($showMoreText) . '">' .
802 $options = array('is_local' => Notice::REMOTE,
805 'rendered' => $rendered,
806 'replies' => array(),
808 'peopletags' => array(),
812 // Check for optional attributes...
814 if (!empty($activity->time)) {
815 $options['created'] = common_sql_date($activity->time);
818 if ($activity->context) {
819 // Any individual or group attn: targets?
820 $replies = $activity->context->attention;
821 $options['groups'] = $this->filterReplies($oprofile, $replies);
822 $options['replies'] = $replies;
824 // Maintain direct reply associations
825 // @fixme what about conversation ID?
826 if (!empty($activity->context->replyToID)) {
827 $orig = Notice::staticGet('uri',
828 $activity->context->replyToID);
830 $options['reply_to'] = $orig->id;
834 $location = $activity->context->location;
836 $options['lat'] = $location->lat;
837 $options['lon'] = $location->lon;
838 if ($location->location_id) {
839 $options['location_ns'] = $location->location_ns;
840 $options['location_id'] = $location->location_id;
845 if ($this->isPeopletag()) {
846 $options['peopletags'][] = $this->localPeopletag();
849 // Atom categories <-> hashtags
850 foreach ($activity->categories as $cat) {
852 $term = common_canonical_tag($cat->term);
854 $options['tags'][] = $term;
859 // Atom enclosures -> attachment URLs
860 foreach ($activity->enclosures as $href) {
861 // @fixme save these locally or....?
862 $options['urls'][] = $href;
866 $saved = Notice::saveNew($oprofile->profile_id,
871 Ostatus_source::saveNew($saved, $this, $method);
872 if (!empty($attachment)) {
873 File_to_post::processNew($attachment->id, $saved->id);
876 } catch (Exception $e) {
877 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
880 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
887 protected function purify($html)
889 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
890 $config = array('safe' => 1,
891 'deny_attribute' => 'id,style,on*');
892 return htmLawed($html, $config);
896 * Filters a list of recipient ID URIs to just those for local delivery.
897 * @param Ostatus_profile local profile of sender
898 * @param array in/out &$attention_uris set of URIs, will be pruned on output
899 * @return array of group IDs
901 protected function filterReplies($sender, &$attention_uris)
903 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', $attention_uris));
906 foreach (array_unique($attention_uris) as $recipient) {
907 // Is the recipient a local user?
908 $user = User::staticGet('uri', $recipient);
910 // @fixme sender verification, spam etc?
911 $replies[] = $recipient;
915 // Is the recipient a local group?
916 // $group = User_group::staticGet('uri', $recipient);
917 $id = OStatusPlugin::localGroupFromUrl($recipient);
919 $group = User_group::staticGet('id', $id);
921 // Deliver to all members of this local group if allowed.
922 $profile = $sender->localProfile();
923 if ($profile->isMember($group)) {
924 $groups[] = $group->id;
926 common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
930 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
934 // Is the recipient a remote user or group?
936 $oprofile = Ostatus_profile::ensureProfileURI($recipient);
937 if ($oprofile->isGroup()) {
938 // Deliver to local members of this remote group.
939 // @fixme sender verification?
940 $groups[] = $oprofile->group_id;
942 // may be canonicalized or something
943 $replies[] = $oprofile->uri;
946 } catch (Exception $e) {
947 // Neither a recognizable local nor remote user!
948 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
952 $attention_uris = $replies;
953 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
954 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
959 * Look up and if necessary create an Ostatus_profile for the remote entity
960 * with the given profile page URL. This should never return null -- you
961 * will either get an object or an exception will be thrown.
963 * @param string $profile_url
964 * @return Ostatus_profile
965 * @throws Exception on various error conditions
966 * @throws OStatusShadowException if this reference would obscure a local user/group
968 public static function ensureProfileURL($profile_url, $hints=array())
970 $oprofile = self::getFromProfileURL($profile_url);
972 if (!empty($oprofile)) {
976 $hints['profileurl'] = $profile_url;
981 $client = new HTTPClient();
982 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
983 $response = $client->get($profile_url);
985 if (!$response->isOk()) {
986 // TRANS: Exception. %s is a profile URL.
987 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
990 // Check if we have a non-canonical URL
992 $finalUrl = $response->getUrl();
994 if ($finalUrl != $profile_url) {
996 $hints['profileurl'] = $finalUrl;
998 $oprofile = self::getFromProfileURL($finalUrl);
1000 if (!empty($oprofile)) {
1005 // Try to get some hCard data
1007 $body = $response->getBody();
1009 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
1011 if (!empty($hcardHints)) {
1012 $hints = array_merge($hints, $hcardHints);
1015 // Check if they've got an LRDD header
1017 $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
1019 if (!empty($lrdd)) {
1021 $xrd = Discovery::fetchXrd($lrdd);
1022 $xrdHints = DiscoveryHints::fromXRD($xrd);
1024 $hints = array_merge($hints, $xrdHints);
1027 // If discovery found a feedurl (probably from LRDD), use it.
1029 if (array_key_exists('feedurl', $hints)) {
1030 return self::ensureFeedURL($hints['feedurl'], $hints);
1033 // Get the feed URL from HTML
1035 $discover = new FeedDiscovery();
1037 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
1039 if (!empty($feedurl)) {
1040 $hints['feedurl'] = $feedurl;
1041 return self::ensureFeedURL($feedurl, $hints);
1044 // TRANS: Exception. %s is a URL.
1045 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
1049 * Look up the Ostatus_profile, if present, for a remote entity with the
1050 * given profile page URL. Will return null for both unknown and invalid
1053 * @return mixed Ostatus_profile or null
1054 * @throws OStatusShadowException for local profiles
1056 static function getFromProfileURL($profile_url)
1058 $profile = Profile::staticGet('profileurl', $profile_url);
1060 if (empty($profile)) {
1064 // Is it a known Ostatus profile?
1066 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
1068 if (!empty($oprofile)) {
1072 // Is it a local user?
1074 $user = User::staticGet('id', $profile->id);
1076 if (!empty($user)) {
1077 // @todo i18n FIXME: use sprintf and add i18n (?)
1078 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
1081 // Continue discovery; it's a remote profile
1082 // for OMB or some other protocol, may also
1089 * Look up and if necessary create an Ostatus_profile for remote entity
1090 * with the given update feed. This should never return null -- you will
1091 * either get an object or an exception will be thrown.
1093 * @return Ostatus_profile
1096 public static function ensureFeedURL($feed_url, $hints=array())
1098 $discover = new FeedDiscovery();
1100 $feeduri = $discover->discoverFromFeedURL($feed_url);
1101 $hints['feedurl'] = $feeduri;
1103 $huburi = $discover->getHubLink();
1104 $hints['hub'] = $huburi;
1105 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1106 $hints['salmon'] = $salmonuri;
1108 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1109 // We can only deal with folks with a PuSH hub
1110 throw new FeedSubNoHubException();
1113 $feedEl = $discover->root;
1115 if ($feedEl->tagName == 'feed') {
1116 return self::ensureAtomFeed($feedEl, $hints);
1117 } else if ($feedEl->tagName == 'channel') {
1118 return self::ensureRssChannel($feedEl, $hints);
1120 throw new FeedSubBadXmlException($feeduri);
1125 * Look up and, if necessary, create an Ostatus_profile for the remote
1126 * profile with the given Atom feed - actually loaded from the feed.
1127 * This should never return null -- you will either get an object or
1128 * an exception will be thrown.
1130 * @param DOMElement $feedEl root element of a loaded Atom feed
1131 * @param array $hints additional discovery information passed from higher levels
1132 * @fixme should this be marked public?
1133 * @return Ostatus_profile
1136 public static function ensureAtomFeed($feedEl, $hints)
1138 $author = ActivityUtils::getFeedAuthor($feedEl);
1140 if (empty($author)) {
1141 // XXX: make some educated guesses here
1142 // TRANS: Feed sub exception.
1143 throw new FeedSubException(_m('Cannot find enough profile '.
1144 'information to make a feed.'));
1147 return self::ensureActivityObjectProfile($author, $hints);
1151 * Look up and, if necessary, create an Ostatus_profile for the remote
1152 * profile with the given RSS feed - actually loaded from the feed.
1153 * This should never return null -- you will either get an object or
1154 * an exception will be thrown.
1156 * @param DOMElement $feedEl root element of a loaded RSS feed
1157 * @param array $hints additional discovery information passed from higher levels
1158 * @fixme should this be marked public?
1159 * @return Ostatus_profile
1162 public static function ensureRssChannel($feedEl, $hints)
1164 // Special-case for Posterous. They have some nice metadata in their
1165 // posterous:author elements. We should use them instead of the channel.
1167 $items = $feedEl->getElementsByTagName('item');
1169 if ($items->length > 0) {
1170 $item = $items->item(0);
1171 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
1172 if (!empty($authorEl)) {
1173 $obj = ActivityObject::fromPosterousAuthor($authorEl);
1174 // Posterous has multiple authors per feed, and multiple feeds
1175 // per author. We check if this is the "main" feed for this author.
1176 if (array_key_exists('profileurl', $hints) &&
1177 !empty($obj->poco) &&
1178 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
1179 return self::ensureActivityObjectProfile($obj, $hints);
1184 // @fixme we should check whether this feed has elements
1185 // with different <author> or <dc:creator> elements, and... I dunno.
1186 // Do something about that.
1188 $obj = ActivityObject::fromRssChannel($feedEl);
1190 return self::ensureActivityObjectProfile($obj, $hints);
1194 * Download and update given avatar image
1196 * @param string $url
1197 * @throws Exception in various failure cases
1199 protected function updateAvatar($url)
1201 if ($url == $this->avatar) {
1202 // We've already got this one.
1205 if (!common_valid_http_url($url)) {
1206 // TRANS: Server exception. %s is a URL.
1207 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1210 if ($this->isGroup()) {
1211 $self = $this->localGroup();
1213 $self = $this->localProfile();
1216 throw new ServerException(sprintf(
1217 // TRANS: Server exception. %s is a URI.
1218 _m('Tried to update avatar for unsaved remote profile %s.'),
1222 // @fixme this should be better encapsulated
1223 // ripped from oauthstore.php (for old OMB client)
1224 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1226 if (!copy($url, $temp_filename)) {
1227 // TRANS: Server exception. %s is a URL.
1228 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1231 if ($this->isGroup()) {
1232 $id = $this->group_id;
1234 $id = $this->profile_id;
1236 // @fixme should we be using different ids?
1237 $imagefile = new ImageFile($id, $temp_filename);
1238 $filename = Avatar::filename($id,
1239 image_type_to_extension($imagefile->type),
1241 common_timestamp());
1242 rename($temp_filename, Avatar::path($filename));
1243 } catch (Exception $e) {
1244 unlink($temp_filename);
1247 // @fixme hardcoded chmod is lame, but seems to be necessary to
1248 // keep from accidentally saving images from command-line (queues)
1249 // that can't be read from web server, which causes hard-to-notice
1250 // problems later on:
1252 // http://status.net/open-source/issues/2663
1253 chmod(Avatar::path($filename), 0644);
1255 $profile = $this->localProfile();
1257 if (!empty($profile)) {
1258 $profile->setOriginal($filename);
1261 $orig = clone($this);
1262 $this->avatar = $url;
1263 $this->update($orig);
1267 * Pull avatar URL from ActivityObject or profile hints
1269 * @param ActivityObject $object
1270 * @param array $hints
1271 * @return mixed URL string or false
1273 public static function getActivityObjectAvatar($object, $hints=array())
1275 if ($object->avatarLinks) {
1277 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1278 foreach ($object->avatarLinks as $avatar) {
1279 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1284 if (!$best || $avatar->width > $best->width) {
1289 } else if (array_key_exists('avatar', $hints)) {
1290 return $hints['avatar'];
1296 * Get an appropriate avatar image source URL, if available.
1298 * @param ActivityObject $actor
1299 * @param DOMElement $feed
1302 protected static function getAvatar($actor, $feed)
1306 if ($actor->avatar) {
1307 $url = trim($actor->avatar);
1310 // Check <atom:logo> and <atom:icon> on the feed
1311 $els = $feed->childNodes();
1312 if ($els && $els->length) {
1313 for ($i = 0; $i < $els->length; $i++) {
1314 $el = $els->item($i);
1315 if ($el->namespaceURI == Activity::ATOM) {
1316 if (empty($url) && $el->localName == 'logo') {
1317 $url = trim($el->textContent);
1320 if (empty($icon) && $el->localName == 'icon') {
1321 // Use as a fallback
1322 $icon = trim($el->textContent);
1327 if ($icon && !$url) {
1332 $opts = array('allowed_schemes' => array('http', 'https'));
1333 if (Validate::uri($url, $opts)) {
1338 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1342 * Fetch, or build if necessary, an Ostatus_profile for the actor
1343 * in a given Activity Streams activity.
1344 * This should never return null -- you will either get an object or
1345 * an exception will be thrown.
1347 * @param Activity $activity
1348 * @param string $feeduri if we already know the canonical feed URI!
1349 * @param string $salmonuri if we already know the salmon return channel URI
1350 * @return Ostatus_profile
1353 public static function ensureActorProfile($activity, $hints=array())
1355 return self::ensureActivityObjectProfile($activity->actor, $hints);
1359 * Fetch, or build if necessary, an Ostatus_profile for the profile
1360 * in a given Activity Streams object (can be subject, actor, or object).
1361 * This should never return null -- you will either get an object or
1362 * an exception will be thrown.
1364 * @param ActivityObject $object
1365 * @param array $hints additional discovery information passed from higher levels
1366 * @return Ostatus_profile
1369 public static function ensureActivityObjectProfile($object, $hints=array())
1371 $profile = self::getActivityObjectProfile($object);
1373 $profile->updateFromActivityObject($object, $hints);
1375 $profile = self::createActivityObjectProfile($object, $hints);
1381 * @param Activity $activity
1382 * @return mixed matching Ostatus_profile or false if none known
1383 * @throws ServerException if feed info invalid
1385 public static function getActorProfile($activity)
1387 return self::getActivityObjectProfile($activity->actor);
1391 * @param ActivityObject $activity
1392 * @return mixed matching Ostatus_profile or false if none known
1393 * @throws ServerException if feed info invalid
1395 protected static function getActivityObjectProfile($object)
1397 $uri = self::getActivityObjectProfileURI($object);
1398 return Ostatus_profile::staticGet('uri', $uri);
1402 * Get the identifier URI for the remote entity described
1403 * by this ActivityObject. This URI is *not* guaranteed to be
1404 * a resolvable HTTP/HTTPS URL.
1406 * @param ActivityObject $object
1408 * @throws ServerException if feed info invalid
1410 protected static function getActivityObjectProfileURI($object)
1413 if (ActivityUtils::validateUri($object->id)) {
1418 // If the id is missing or invalid (we've seen feeds mistakenly listing
1419 // things like local usernames in that field) then we'll use the profile
1420 // page link, if valid.
1421 if ($object->link && common_valid_http_url($object->link)) {
1422 return $object->link;
1424 // TRANS: Server exception.
1425 throw new ServerException(_m('No author ID URI found.'));
1429 * @fixme validate stuff somewhere
1433 * Create local ostatus_profile and profile/user_group entries for
1434 * the provided remote user or group.
1435 * This should never return null -- you will either get an object or
1436 * an exception will be thrown.
1438 * @param ActivityObject $object
1439 * @param array $hints
1441 * @return Ostatus_profile
1443 protected static function createActivityObjectProfile($object, $hints=array())
1445 $homeuri = $object->id;
1449 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1450 // TRANS: Exception.
1451 throw new Exception(_m('No profile URI.'));
1454 $user = User::staticGet('uri', $homeuri);
1456 // TRANS: Exception.
1457 throw new Exception(_m('Local user cannot be referenced as remote.'));
1460 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1461 // TRANS: Exception.
1462 throw new Exception(_m('Local group cannot be referenced as remote.'));
1465 $ptag = Profile_list::staticGet('uri', $homeuri);
1467 $local_user = User::staticGet('id', $ptag->tagger);
1468 if (!empty($local_user)) {
1469 // TRANS: Exception.
1470 throw new Exception(_m('Local list cannot be referenced as remote.'));
1474 if (array_key_exists('feedurl', $hints)) {
1475 $feeduri = $hints['feedurl'];
1477 $discover = new FeedDiscovery();
1478 $feeduri = $discover->discoverFromURL($homeuri);
1481 if (array_key_exists('salmon', $hints)) {
1482 $salmonuri = $hints['salmon'];
1485 $discover = new FeedDiscovery();
1486 $discover->discoverFromFeedURL($hints['feedurl']);
1488 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1491 if (array_key_exists('hub', $hints)) {
1492 $huburi = $hints['hub'];
1495 $discover = new FeedDiscovery();
1496 $discover->discoverFromFeedURL($hints['feedurl']);
1498 $huburi = $discover->getHubLink();
1501 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1502 // We can only deal with folks with a PuSH hub
1503 throw new FeedSubNoHubException();
1506 $oprofile = new Ostatus_profile();
1508 $oprofile->uri = $homeuri;
1509 $oprofile->feeduri = $feeduri;
1510 $oprofile->salmonuri = $salmonuri;
1512 $oprofile->created = common_sql_now();
1513 $oprofile->modified = common_sql_now();
1515 if ($object->type == ActivityObject::PERSON) {
1516 $profile = new Profile();
1517 $profile->created = common_sql_now();
1518 self::updateProfile($profile, $object, $hints);
1520 $oprofile->profile_id = $profile->insert();
1521 if (!$oprofile->profile_id) {
1522 // TRANS: Server exception.
1523 throw new ServerException(_m('Cannot save local profile.'));
1525 } else if ($object->type == ActivityObject::GROUP) {
1526 $group = new User_group();
1527 $group->uri = $homeuri;
1528 $group->created = common_sql_now();
1529 self::updateGroup($group, $object, $hints);
1531 $oprofile->group_id = $group->insert();
1532 if (!$oprofile->group_id) {
1533 // TRANS: Server exception.
1534 throw new ServerException(_m('Cannot save local profile.'));
1536 } else if ($object->type == ActivityObject::_LIST) {
1537 $ptag = new Profile_list();
1538 $ptag->uri = $homeuri;
1539 $ptag->created = common_sql_now();
1540 self::updatePeopletag($ptag, $object, $hints);
1542 $oprofile->peopletag_id = $ptag->insert();
1543 if (!$oprofile->peopletag_id) {
1544 // TRANS: Server exception.
1545 throw new ServerException(_m('Cannot save local list.'));
1549 $ok = $oprofile->insert();
1552 // TRANS: Server exception.
1553 throw new ServerException(_m('Cannot save OStatus profile.'));
1556 $avatar = self::getActivityObjectAvatar($object, $hints);
1560 $oprofile->updateAvatar($avatar);
1561 } catch (Exception $ex) {
1562 // Profile is saved, but Avatar is messed up. We're
1563 // just going to continue.
1564 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1572 * Save any updated profile information to our local copy.
1573 * @param ActivityObject $object
1574 * @param array $hints
1576 public function updateFromActivityObject($object, $hints=array())
1578 if ($this->isGroup()) {
1579 $group = $this->localGroup();
1580 self::updateGroup($group, $object, $hints);
1581 } else if ($this->isPeopletag()) {
1582 $ptag = $this->localPeopletag();
1583 self::updatePeopletag($ptag, $object, $hints);
1585 $profile = $this->localProfile();
1586 self::updateProfile($profile, $object, $hints);
1589 $avatar = self::getActivityObjectAvatar($object, $hints);
1590 if ($avatar && !isset($ptag)) {
1592 $this->updateAvatar($avatar);
1593 } catch (Exception $ex) {
1594 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1599 public static function updateProfile($profile, $object, $hints=array())
1601 $orig = clone($profile);
1603 // Existing nickname is better than nothing.
1605 if (!array_key_exists('nickname', $hints)) {
1606 $hints['nickname'] = $profile->nickname;
1609 $nickname = self::getActivityObjectNickname($object, $hints);
1611 if (!empty($nickname)) {
1612 $profile->nickname = $nickname;
1615 if (!empty($object->title)) {
1616 $profile->fullname = $object->title;
1617 } else if (array_key_exists('fullname', $hints)) {
1618 $profile->fullname = $hints['fullname'];
1621 if (!empty($object->link)) {
1622 $profile->profileurl = $object->link;
1623 } else if (array_key_exists('profileurl', $hints)) {
1624 $profile->profileurl = $hints['profileurl'];
1625 } else if (Validate::uri($object->id, array('allowed_schemes' => array('http', 'https')))) {
1626 $profile->profileurl = $object->id;
1629 $bio = self::getActivityObjectBio($object, $hints);
1632 $profile->bio = $bio;
1635 $location = self::getActivityObjectLocation($object, $hints);
1637 if (!empty($location)) {
1638 $profile->location = $location;
1641 $homepage = self::getActivityObjectHomepage($object, $hints);
1643 if (!empty($homepage)) {
1644 $profile->homepage = $homepage;
1647 if (!empty($object->geopoint)) {
1648 $location = ActivityContext::locationFromPoint($object->geopoint);
1649 if (!empty($location)) {
1650 $profile->lat = $location->lat;
1651 $profile->lon = $location->lon;
1655 // @fixme tags/categories
1656 // @todo tags from categories
1659 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1660 $profile->update($orig);
1664 protected static function updateGroup($group, $object, $hints=array())
1666 $orig = clone($group);
1668 $group->nickname = self::getActivityObjectNickname($object, $hints);
1669 $group->fullname = $object->title;
1671 if (!empty($object->link)) {
1672 $group->mainpage = $object->link;
1673 } else if (array_key_exists('profileurl', $hints)) {
1674 $group->mainpage = $hints['profileurl'];
1677 // @todo tags from categories
1678 $group->description = self::getActivityObjectBio($object, $hints);
1679 $group->location = self::getActivityObjectLocation($object, $hints);
1680 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1683 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1684 $group->update($orig);
1688 protected static function updatePeopletag($tag, $object, $hints=array()) {
1689 $orig = clone($tag);
1691 $tag->tag = $object->title;
1693 if (!empty($object->link)) {
1694 $tag->mainpage = $object->link;
1695 } else if (array_key_exists('profileurl', $hints)) {
1696 $tag->mainpage = $hints['profileurl'];
1699 $tag->description = $object->summary;
1700 $tagger = self::ensureActivityObjectProfile($object->owner);
1701 $tag->tagger = $tagger->profile_id;
1704 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1705 $tag->update($orig);
1709 protected static function getActivityObjectHomepage($object, $hints=array())
1712 $poco = $object->poco;
1714 if (!empty($poco)) {
1715 $url = $poco->getPrimaryURL();
1716 if ($url && $url->type == 'homepage') {
1717 $homepage = $url->value;
1721 // @todo Try for a another PoCo URL?
1726 protected static function getActivityObjectLocation($object, $hints=array())
1730 if (!empty($object->poco) &&
1731 isset($object->poco->address->formatted)) {
1732 $location = $object->poco->address->formatted;
1733 } else if (array_key_exists('location', $hints)) {
1734 $location = $hints['location'];
1737 if (!empty($location)) {
1738 if (mb_strlen($location) > 255) {
1739 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1743 // @todo Try to find location some othe way? Via goerss point?
1748 protected static function getActivityObjectBio($object, $hints=array())
1752 if (!empty($object->poco)) {
1753 $note = $object->poco->note;
1754 } else if (array_key_exists('bio', $hints)) {
1755 $note = $hints['bio'];
1758 if (!empty($note)) {
1759 if (Profile::bioTooLong($note)) {
1760 // XXX: truncate ok?
1761 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1767 // @todo Try to get bio info some other way?
1772 public static function getActivityObjectNickname($object, $hints=array())
1774 if ($object->poco) {
1775 if (!empty($object->poco->preferredUsername)) {
1776 return common_nicknamize($object->poco->preferredUsername);
1780 if (!empty($object->nickname)) {
1781 return common_nicknamize($object->nickname);
1784 if (array_key_exists('nickname', $hints)) {
1785 return $hints['nickname'];
1788 // Try the profile url (like foo.example.com or example.com/user/foo)
1789 if (!empty($object->link)) {
1790 $profileUrl = $object->link;
1791 } else if (!empty($hints['profileurl'])) {
1792 $profileUrl = $hints['profileurl'];
1795 if (!empty($profileUrl)) {
1796 $nickname = self::nicknameFromURI($profileUrl);
1799 // Try the URI (may be a tag:, http:, acct:, ...
1801 if (empty($nickname)) {
1802 $nickname = self::nicknameFromURI($object->id);
1805 // Try a Webfinger if one was passed (way) down
1807 if (empty($nickname)) {
1808 if (array_key_exists('webfinger', $hints)) {
1809 $nickname = self::nicknameFromURI($hints['webfinger']);
1815 if (empty($nickname)) {
1816 $nickname = common_nicknamize($object->title);
1822 protected static function nicknameFromURI($uri)
1824 if (preg_match('/(\w+):/', $uri, $matches)) {
1825 $protocol = $matches[1];
1830 switch ($protocol) {
1833 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1834 return common_canonical_nickname($matches[1]);
1838 return common_url_to_nickname($uri);
1846 * Look up, and if necessary create, an Ostatus_profile for the remote
1847 * entity with the given webfinger address.
1848 * This should never return null -- you will either get an object or
1849 * an exception will be thrown.
1851 * @param string $addr webfinger address
1852 * @return Ostatus_profile
1853 * @throws Exception on error conditions
1854 * @throws OStatusShadowException if this reference would obscure a local user/group
1856 public static function ensureWebfinger($addr)
1858 // First, try the cache
1860 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1862 if ($uri !== false) {
1863 if (is_null($uri)) {
1864 // Negative cache entry
1865 // TRANS: Exception.
1866 throw new Exception(_m('Not a valid webfinger address.'));
1868 $oprofile = Ostatus_profile::staticGet('uri', $uri);
1869 if (!empty($oprofile)) {
1874 // Try looking it up
1875 $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1877 if (!empty($oprofile)) {
1878 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1882 // Now, try some discovery
1884 $disco = new Discovery();
1887 $xrd = $disco->lookup($addr);
1888 } catch (Exception $e) {
1889 // Save negative cache entry so we don't waste time looking it up again.
1890 // @fixme distinguish temporary failures?
1891 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1892 // TRANS: Exception.
1893 throw new Exception(_m('Not a valid webfinger address.'));
1896 $hints = array('webfinger' => $addr);
1898 $dhints = DiscoveryHints::fromXRD($xrd);
1900 $hints = array_merge($hints, $dhints);
1902 // If there's an Hcard, let's grab its info
1903 if (array_key_exists('hcard', $hints)) {
1904 if (!array_key_exists('profileurl', $hints) ||
1905 $hints['hcard'] != $hints['profileurl']) {
1906 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1907 $hints = array_merge($hcardHints, $hints);
1911 // If we got a feed URL, try that
1912 if (array_key_exists('feedurl', $hints)) {
1914 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1915 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1916 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1918 } catch (Exception $e) {
1919 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1924 // If we got a profile page, try that!
1925 if (array_key_exists('profileurl', $hints)) {
1927 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1928 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1929 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1931 } catch (OStatusShadowException $e) {
1932 // We've ended up with a remote reference to a local user or group.
1933 // @fixme ideally we should be able to say who it was so we can
1934 // go back and refer to it the regular way
1936 } catch (Exception $e) {
1937 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1940 // @fixme this means an error discovering from profile page
1941 // may give us a corrupt entry using the webfinger URI, which
1942 // will obscure the correct page-keyed profile later on.
1949 if (array_key_exists('salmon', $hints)) {
1950 $salmonEndpoint = $hints['salmon'];
1952 // An account URL, a salmon endpoint, and a dream? Not much to go
1953 // on, but let's give it a try
1955 $uri = 'acct:'.$addr;
1957 $profile = new Profile();
1959 $profile->nickname = self::nicknameFromUri($uri);
1960 $profile->created = common_sql_now();
1962 if (isset($profileUrl)) {
1963 $profile->profileurl = $profileUrl;
1966 $profile_id = $profile->insert();
1969 common_log_db_error($profile, 'INSERT', __FILE__);
1970 // TRANS: Exception. %s is a webfinger address.
1971 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1974 $oprofile = new Ostatus_profile();
1976 $oprofile->uri = $uri;
1977 $oprofile->salmonuri = $salmonEndpoint;
1978 $oprofile->profile_id = $profile_id;
1979 $oprofile->created = common_sql_now();
1981 if (isset($feedUrl)) {
1982 $profile->feeduri = $feedUrl;
1985 $result = $oprofile->insert();
1988 common_log_db_error($oprofile, 'INSERT', __FILE__);
1989 // TRANS: Exception. %s is a webfinger address.
1990 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1993 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1997 // TRANS: Exception. %s is a webfinger address.
1998 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
2002 * Store the full-length scrubbed HTML of a remote notice to an attachment
2003 * file on our server. We'll link to this at the end of the cropped version.
2005 * @param string $title plaintext for HTML page's title
2006 * @param string $rendered HTML fragment for HTML page's body
2009 function saveHTMLFile($title, $rendered)
2011 $final = sprintf("<!DOCTYPE html>\n" .
2013 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
2014 '<title>%s</title>' .
2016 '<body>%s</body></html>',
2017 htmlspecialchars($title),
2020 $filename = File::filename($this->localProfile(),
2021 'ostatus', // ignored?
2024 $filepath = File::path($filename);
2026 file_put_contents($filepath, $final);
2030 $file->filename = $filename;
2031 $file->url = File::url($filename);
2032 $file->size = filesize($filepath);
2033 $file->date = time();
2034 $file->mimetype = 'text/html';
2036 $file_id = $file->insert();
2038 if ($file_id === false) {
2039 common_log_db_error($file, "INSERT", __FILE__);
2040 // TRANS: Server exception.
2041 throw new ServerException(_m('Could not store HTML content of long post as file.'));
2047 static function ensureProfileURI($uri)
2051 // First, try to query it
2053 $oprofile = Ostatus_profile::staticGet('uri', $uri);
2055 // If unfound, do discovery stuff
2057 if (empty($oprofile)) {
2058 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
2059 $protocol = $match[1];
2060 switch ($protocol) {
2063 $oprofile = Ostatus_profile::ensureProfileURL($uri);
2068 $oprofile = Ostatus_profile::ensureWebfinger($rest);
2071 // TRANS: Server exception.
2072 // TRANS: %1$s is a protocol, %2$s is a URI.
2073 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
2079 // TRANS: Server exception. %s is a URI.
2080 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
2087 function checkAuthorship($activity)
2089 if ($this->isGroup() || $this->isPeopletag()) {
2090 // A group or propletag feed will contain posts from multiple authors.
2091 $oprofile = self::ensureActorProfile($activity);
2092 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
2093 // Groups can't post notices in StatusNet.
2094 common_log(LOG_WARNING,
2095 "OStatus: skipping post with group listed ".
2096 "as author: $oprofile->uri in feed from $this->uri");
2100 $actor = $activity->actor;
2102 if (empty($actor)) {
2103 // OK here! assume the default
2104 } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
2105 $this->updateFromActivityObject($actor);
2106 } else if ($actor->id) {
2107 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
2108 // This isn't what we expect from mainline OStatus person feeds!
2109 // Group feeds go down another path, with different validation...
2110 // Most likely this is a plain ol' blog feed of some kind which
2111 // doesn't match our expectations. We'll take the entry, but ignore
2112 // the <author> info.
2113 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
2115 // Plain <author> without ActivityStreams actor info.
2116 // We'll just ignore this info for now and save the update under the feed's identity.
2127 * Exception indicating we've got a remote reference to a local user,
2128 * not a remote user!
2130 * If we can ue a local profile after all, it's available as $e->profile.
2132 class OStatusShadowException extends Exception
2137 * @param Profile $profile
2138 * @param string $message
2140 function __construct($profile, $message) {
2141 $this->profile = $profile;
2142 parent::__construct($message);