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);
471 if (Event::handle('StartHandleFeedEntryWithProfile', array($activity, $this)) &&
472 Event::handle('StartHandleFeedEntry', array($activity))) {
473 // @todo process all activity objects
474 switch ($activity->objects[0]->type) {
475 case ActivityObject::ARTICLE:
476 case ActivityObject::BLOGENTRY:
477 case ActivityObject::NOTE:
478 case ActivityObject::STATUS:
479 case ActivityObject::COMMENT:
481 if ($activity->verb == ActivityVerb::POST) {
482 $this->processPost($activity, $source);
484 common_log(LOG_INFO, "Ignoring activity with unrecognized verb $activity->verb");
488 // TRANS: Client exception.
489 throw new ClientException(_m('Cannot handle that kind of post.'));
492 Event::handle('EndHandleFeedEntry', array($activity));
493 Event::handle('EndHandleFeedEntryWithProfile', array($activity, $this));
498 * Process an incoming post activity from this remote feed.
499 * @param Activity $activity
500 * @param string $method 'push' or 'salmon'
501 * @return mixed saved Notice or false
502 * @fixme break up this function, it's getting nasty long
504 public function processPost($activity, $method)
506 $oprofile = $this->checkAuthorship($activity);
508 if (empty($oprofile)) {
512 // It's not always an ActivityObject::NOTE, but... let's just say it is.
514 $note = $activity->objects[0];
516 // The id URI will be used as a unique identifier for for the notice,
517 // protecting against duplicate saves. It isn't required to be a URL;
518 // tag: URIs for instance are found in Google Buzz feeds.
519 $sourceUri = $note->id;
520 $dupe = Notice::staticGet('uri', $sourceUri);
522 common_log(LOG_INFO, "OStatus: ignoring duplicate post: $sourceUri");
526 // We'll also want to save a web link to the original notice, if provided.
529 $sourceUrl = $note->link;
530 } else if ($activity->link) {
531 $sourceUrl = $activity->link;
532 } else if (preg_match('!^https?://!', $note->id)) {
533 $sourceUrl = $note->id;
536 // Use summary as fallback for content
538 if (!empty($note->content)) {
539 $sourceContent = $note->content;
540 } else if (!empty($note->summary)) {
541 $sourceContent = $note->summary;
542 } else if (!empty($note->title)) {
543 $sourceContent = $note->title;
545 // @fixme fetch from $sourceUrl?
546 // TRANS: Client exception. %s is a source URI.
547 throw new ClientException(sprintf(_m('No content for notice %s.'),$sourceUri));
550 // Get (safe!) HTML and text versions of the content
552 $rendered = $this->purify($sourceContent);
553 $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
555 $shortened = common_shorten_links($content);
557 // If it's too long, try using the summary, and make the
558 // HTML an attachment.
562 if (Notice::contentTooLong($shortened)) {
563 $attachment = $this->saveHTMLFile($note->title, $rendered);
564 $summary = html_entity_decode(strip_tags($note->summary), ENT_QUOTES, 'UTF-8');
565 if (empty($summary)) {
568 $shortSummary = common_shorten_links($summary);
569 if (Notice::contentTooLong($shortSummary)) {
570 $url = common_shorten_url($sourceUrl);
571 $shortSummary = substr($shortSummary,
573 Notice::maxContent() - (mb_strlen($url) + 2));
574 $content = $shortSummary . ' ' . $url;
576 // We mark up the attachment link specially for the HTML output
577 // so we can fold-out the full version inline.
579 // @todo FIXME i18n: This tooltip will be saved with the site's default language
580 // TRANS: Shown when a notice is longer than supported and/or when attachments are present. At runtime
581 // TRANS: this will usually be replaced with localised text from StatusNet core messages.
582 $showMoreText = _m('Show more');
583 $attachUrl = common_local_url('attachment',
584 array('attachment' => $attachment->id));
585 $rendered = common_render_text($shortSummary) .
586 '<a href="' . htmlspecialchars($attachUrl) .'"'.
587 ' class="attachment more"' .
588 ' title="'. htmlspecialchars($showMoreText) . '">' .
594 $options = array('is_local' => Notice::REMOTE_OMB,
597 'rendered' => $rendered,
598 'replies' => array(),
600 'peopletags' => array(),
604 // Check for optional attributes...
606 if (!empty($activity->time)) {
607 $options['created'] = common_sql_date($activity->time);
610 if ($activity->context) {
611 // Any individual or group attn: targets?
612 $replies = $activity->context->attention;
613 $options['groups'] = $this->filterReplies($oprofile, $replies);
614 $options['replies'] = $replies;
616 // Maintain direct reply associations
617 // @fixme what about conversation ID?
618 if (!empty($activity->context->replyToID)) {
619 $orig = Notice::staticGet('uri',
620 $activity->context->replyToID);
622 $options['reply_to'] = $orig->id;
626 $location = $activity->context->location;
628 $options['lat'] = $location->lat;
629 $options['lon'] = $location->lon;
630 if ($location->location_id) {
631 $options['location_ns'] = $location->location_ns;
632 $options['location_id'] = $location->location_id;
637 if ($this->isPeopletag()) {
638 $options['peopletags'][] = $this->localPeopletag();
641 // Atom categories <-> hashtags
642 foreach ($activity->categories as $cat) {
644 $term = common_canonical_tag($cat->term);
646 $options['tags'][] = $term;
651 // Atom enclosures -> attachment URLs
652 foreach ($activity->enclosures as $href) {
653 // @fixme save these locally or....?
654 $options['urls'][] = $href;
658 $saved = Notice::saveNew($oprofile->profile_id,
663 Ostatus_source::saveNew($saved, $this, $method);
664 if (!empty($attachment)) {
665 File_to_post::processNew($attachment->id, $saved->id);
668 } catch (Exception $e) {
669 common_log(LOG_ERR, "OStatus save of remote message $sourceUri failed: " . $e->getMessage());
672 common_log(LOG_INFO, "OStatus saved remote message $sourceUri as notice id $saved->id");
679 protected function purify($html)
681 require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
682 $config = array('safe' => 1,
683 'deny_attribute' => 'id,style,on*');
684 return htmLawed($html, $config);
688 * Filters a list of recipient ID URIs to just those for local delivery.
689 * @param Ostatus_profile local profile of sender
690 * @param array in/out &$attention_uris set of URIs, will be pruned on output
691 * @return array of group IDs
693 protected function filterReplies($sender, &$attention_uris)
695 common_log(LOG_DEBUG, "Original reply recipients: " . implode(', ', $attention_uris));
698 foreach (array_unique($attention_uris) as $recipient) {
699 // Is the recipient a local user?
700 $user = User::staticGet('uri', $recipient);
702 // @fixme sender verification, spam etc?
703 $replies[] = $recipient;
707 // Is the recipient a local group?
708 // $group = User_group::staticGet('uri', $recipient);
709 $id = OStatusPlugin::localGroupFromUrl($recipient);
711 $group = User_group::staticGet('id', $id);
713 // Deliver to all members of this local group if allowed.
714 $profile = $sender->localProfile();
715 if ($profile->isMember($group)) {
716 $groups[] = $group->id;
718 common_log(LOG_DEBUG, "Skipping reply to local group $group->nickname as sender $profile->id is not a member");
722 common_log(LOG_DEBUG, "Skipping reply to bogus group $recipient");
726 // Is the recipient a remote user or group?
728 $oprofile = Ostatus_profile::ensureProfileURI($recipient);
729 if ($oprofile->isGroup()) {
730 // Deliver to local members of this remote group.
731 // @fixme sender verification?
732 $groups[] = $oprofile->group_id;
734 // may be canonicalized or something
735 $replies[] = $oprofile->uri;
738 } catch (Exception $e) {
739 // Neither a recognizable local nor remote user!
740 common_log(LOG_DEBUG, "Skipping reply to unrecognized profile $recipient: " . $e->getMessage());
744 $attention_uris = $replies;
745 common_log(LOG_DEBUG, "Local reply recipients: " . implode(', ', $replies));
746 common_log(LOG_DEBUG, "Local group recipients: " . implode(', ', $groups));
751 * Look up and if necessary create an Ostatus_profile for the remote entity
752 * with the given profile page URL. This should never return null -- you
753 * will either get an object or an exception will be thrown.
755 * @param string $profile_url
756 * @return Ostatus_profile
757 * @throws Exception on various error conditions
758 * @throws OStatusShadowException if this reference would obscure a local user/group
760 public static function ensureProfileURL($profile_url, $hints=array())
762 $oprofile = self::getFromProfileURL($profile_url);
764 if (!empty($oprofile)) {
768 $hints['profileurl'] = $profile_url;
773 $client = new HTTPClient();
774 $client->setHeader('Accept', 'text/html,application/xhtml+xml');
775 $response = $client->get($profile_url);
777 if (!$response->isOk()) {
778 // TRANS: Exception. %s is a profile URL.
779 throw new Exception(sprintf(_m('Could not reach profile page %s.'),$profile_url));
782 // Check if we have a non-canonical URL
784 $finalUrl = $response->getUrl();
786 if ($finalUrl != $profile_url) {
788 $hints['profileurl'] = $finalUrl;
790 $oprofile = self::getFromProfileURL($finalUrl);
792 if (!empty($oprofile)) {
797 // Try to get some hCard data
799 $body = $response->getBody();
801 $hcardHints = DiscoveryHints::hcardHints($body, $finalUrl);
803 if (!empty($hcardHints)) {
804 $hints = array_merge($hints, $hcardHints);
807 // Check if they've got an LRDD header
809 $lrdd = LinkHeader::getLink($response, 'lrdd', 'application/xrd+xml');
813 $xrd = Discovery::fetchXrd($lrdd);
814 $xrdHints = DiscoveryHints::fromXRD($xrd);
816 $hints = array_merge($hints, $xrdHints);
819 // If discovery found a feedurl (probably from LRDD), use it.
821 if (array_key_exists('feedurl', $hints)) {
822 return self::ensureFeedURL($hints['feedurl'], $hints);
825 // Get the feed URL from HTML
827 $discover = new FeedDiscovery();
829 $feedurl = $discover->discoverFromHTML($finalUrl, $body);
831 if (!empty($feedurl)) {
832 $hints['feedurl'] = $feedurl;
833 return self::ensureFeedURL($feedurl, $hints);
836 // TRANS: Exception. %s is a URL.
837 throw new Exception(sprintf(_m('Could not find a feed URL for profile page %s.'),$finalUrl));
841 * Look up the Ostatus_profile, if present, for a remote entity with the
842 * given profile page URL. Will return null for both unknown and invalid
845 * @return mixed Ostatus_profile or null
846 * @throws OStatusShadowException for local profiles
848 static function getFromProfileURL($profile_url)
850 $profile = Profile::staticGet('profileurl', $profile_url);
852 if (empty($profile)) {
856 // Is it a known Ostatus profile?
858 $oprofile = Ostatus_profile::staticGet('profile_id', $profile->id);
860 if (!empty($oprofile)) {
864 // Is it a local user?
866 $user = User::staticGet('id', $profile->id);
869 // @todo i18n FIXME: use sprintf and add i18n (?)
870 throw new OStatusShadowException($profile, "'$profile_url' is the profile for local user '{$user->nickname}'.");
873 // Continue discovery; it's a remote profile
874 // for OMB or some other protocol, may also
881 * Look up and if necessary create an Ostatus_profile for remote entity
882 * with the given update feed. This should never return null -- you will
883 * either get an object or an exception will be thrown.
885 * @return Ostatus_profile
888 public static function ensureFeedURL($feed_url, $hints=array())
890 $discover = new FeedDiscovery();
892 $feeduri = $discover->discoverFromFeedURL($feed_url);
893 $hints['feedurl'] = $feeduri;
895 $huburi = $discover->getHubLink();
896 $hints['hub'] = $huburi;
897 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
898 $hints['salmon'] = $salmonuri;
900 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
901 // We can only deal with folks with a PuSH hub
902 throw new FeedSubNoHubException();
905 $feedEl = $discover->root;
907 if ($feedEl->tagName == 'feed') {
908 return self::ensureAtomFeed($feedEl, $hints);
909 } else if ($feedEl->tagName == 'channel') {
910 return self::ensureRssChannel($feedEl, $hints);
912 throw new FeedSubBadXmlException($feeduri);
917 * Look up and, if necessary, create an Ostatus_profile for the remote
918 * profile with the given Atom feed - actually loaded from the feed.
919 * This should never return null -- you will either get an object or
920 * an exception will be thrown.
922 * @param DOMElement $feedEl root element of a loaded Atom feed
923 * @param array $hints additional discovery information passed from higher levels
924 * @fixme should this be marked public?
925 * @return Ostatus_profile
928 public static function ensureAtomFeed($feedEl, $hints)
930 $author = ActivityUtils::getFeedAuthor($feedEl);
932 if (empty($author)) {
933 // XXX: make some educated guesses here
934 // TRANS: Feed sub exception.
935 throw new FeedSubException(_m('Cannot find enough profile '.
936 'information to make a feed.'));
939 return self::ensureActivityObjectProfile($author, $hints);
943 * Look up and, if necessary, create an Ostatus_profile for the remote
944 * profile with the given RSS feed - actually loaded from the feed.
945 * This should never return null -- you will either get an object or
946 * an exception will be thrown.
948 * @param DOMElement $feedEl root element of a loaded RSS feed
949 * @param array $hints additional discovery information passed from higher levels
950 * @fixme should this be marked public?
951 * @return Ostatus_profile
954 public static function ensureRssChannel($feedEl, $hints)
956 // Special-case for Posterous. They have some nice metadata in their
957 // posterous:author elements. We should use them instead of the channel.
959 $items = $feedEl->getElementsByTagName('item');
961 if ($items->length > 0) {
962 $item = $items->item(0);
963 $authorEl = ActivityUtils::child($item, ActivityObject::AUTHOR, ActivityObject::POSTEROUS);
964 if (!empty($authorEl)) {
965 $obj = ActivityObject::fromPosterousAuthor($authorEl);
966 // Posterous has multiple authors per feed, and multiple feeds
967 // per author. We check if this is the "main" feed for this author.
968 if (array_key_exists('profileurl', $hints) &&
969 !empty($obj->poco) &&
970 common_url_to_nickname($hints['profileurl']) == $obj->poco->preferredUsername) {
971 return self::ensureActivityObjectProfile($obj, $hints);
976 // @fixme we should check whether this feed has elements
977 // with different <author> or <dc:creator> elements, and... I dunno.
978 // Do something about that.
980 $obj = ActivityObject::fromRssChannel($feedEl);
982 return self::ensureActivityObjectProfile($obj, $hints);
986 * Download and update given avatar image
989 * @throws Exception in various failure cases
991 protected function updateAvatar($url)
993 if ($url == $this->avatar) {
994 // We've already got this one.
997 if (!common_valid_http_url($url)) {
998 // TRANS: Server exception. %s is a URL.
999 throw new ServerException(sprintf(_m('Invalid avatar URL %s.'), $url));
1002 if ($this->isGroup()) {
1003 $self = $this->localGroup();
1005 $self = $this->localProfile();
1008 throw new ServerException(sprintf(
1009 // TRANS: Server exception. %s is a URI.
1010 _m('Tried to update avatar for unsaved remote profile %s.'),
1014 // @fixme this should be better encapsulated
1015 // ripped from oauthstore.php (for old OMB client)
1016 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
1018 if (!copy($url, $temp_filename)) {
1019 // TRANS: Server exception. %s is a URL.
1020 throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
1023 if ($this->isGroup()) {
1024 $id = $this->group_id;
1026 $id = $this->profile_id;
1028 // @fixme should we be using different ids?
1029 $imagefile = new ImageFile($id, $temp_filename);
1030 $filename = Avatar::filename($id,
1031 image_type_to_extension($imagefile->type),
1033 common_timestamp());
1034 rename($temp_filename, Avatar::path($filename));
1035 } catch (Exception $e) {
1036 unlink($temp_filename);
1039 // @fixme hardcoded chmod is lame, but seems to be necessary to
1040 // keep from accidentally saving images from command-line (queues)
1041 // that can't be read from web server, which causes hard-to-notice
1042 // problems later on:
1044 // http://status.net/open-source/issues/2663
1045 chmod(Avatar::path($filename), 0644);
1047 $self->setOriginal($filename);
1049 $orig = clone($this);
1050 $this->avatar = $url;
1051 $this->update($orig);
1055 * Pull avatar URL from ActivityObject or profile hints
1057 * @param ActivityObject $object
1058 * @param array $hints
1059 * @return mixed URL string or false
1061 public static function getActivityObjectAvatar($object, $hints=array())
1063 if ($object->avatarLinks) {
1065 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1066 foreach ($object->avatarLinks as $avatar) {
1067 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1072 if (!$best || $avatar->width > $best->width) {
1077 } else if (array_key_exists('avatar', $hints)) {
1078 return $hints['avatar'];
1084 * Get an appropriate avatar image source URL, if available.
1086 * @param ActivityObject $actor
1087 * @param DOMElement $feed
1090 protected static function getAvatar($actor, $feed)
1094 if ($actor->avatar) {
1095 $url = trim($actor->avatar);
1098 // Check <atom:logo> and <atom:icon> on the feed
1099 $els = $feed->childNodes();
1100 if ($els && $els->length) {
1101 for ($i = 0; $i < $els->length; $i++) {
1102 $el = $els->item($i);
1103 if ($el->namespaceURI == Activity::ATOM) {
1104 if (empty($url) && $el->localName == 'logo') {
1105 $url = trim($el->textContent);
1108 if (empty($icon) && $el->localName == 'icon') {
1109 // Use as a fallback
1110 $icon = trim($el->textContent);
1115 if ($icon && !$url) {
1120 $opts = array('allowed_schemes' => array('http', 'https'));
1121 if (Validate::uri($url, $opts)) {
1126 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1130 * Fetch, or build if necessary, an Ostatus_profile for the actor
1131 * in a given Activity Streams activity.
1132 * This should never return null -- you will either get an object or
1133 * an exception will be thrown.
1135 * @param Activity $activity
1136 * @param string $feeduri if we already know the canonical feed URI!
1137 * @param string $salmonuri if we already know the salmon return channel URI
1138 * @return Ostatus_profile
1141 public static function ensureActorProfile($activity, $hints=array())
1143 return self::ensureActivityObjectProfile($activity->actor, $hints);
1147 * Fetch, or build if necessary, an Ostatus_profile for the profile
1148 * in a given Activity Streams object (can be subject, actor, or object).
1149 * This should never return null -- you will either get an object or
1150 * an exception will be thrown.
1152 * @param ActivityObject $object
1153 * @param array $hints additional discovery information passed from higher levels
1154 * @return Ostatus_profile
1157 public static function ensureActivityObjectProfile($object, $hints=array())
1159 $profile = self::getActivityObjectProfile($object);
1161 $profile->updateFromActivityObject($object, $hints);
1163 $profile = self::createActivityObjectProfile($object, $hints);
1169 * @param Activity $activity
1170 * @return mixed matching Ostatus_profile or false if none known
1171 * @throws ServerException if feed info invalid
1173 public static function getActorProfile($activity)
1175 return self::getActivityObjectProfile($activity->actor);
1179 * @param ActivityObject $activity
1180 * @return mixed matching Ostatus_profile or false if none known
1181 * @throws ServerException if feed info invalid
1183 protected static function getActivityObjectProfile($object)
1185 $uri = self::getActivityObjectProfileURI($object);
1186 return Ostatus_profile::staticGet('uri', $uri);
1190 * Get the identifier URI for the remote entity described
1191 * by this ActivityObject. This URI is *not* guaranteed to be
1192 * a resolvable HTTP/HTTPS URL.
1194 * @param ActivityObject $object
1196 * @throws ServerException if feed info invalid
1198 protected static function getActivityObjectProfileURI($object)
1201 if (ActivityUtils::validateUri($object->id)) {
1206 // If the id is missing or invalid (we've seen feeds mistakenly listing
1207 // things like local usernames in that field) then we'll use the profile
1208 // page link, if valid.
1209 if ($object->link && common_valid_http_url($object->link)) {
1210 return $object->link;
1212 throw new ServerException("No author ID URI found.");
1216 * @fixme validate stuff somewhere
1220 * Create local ostatus_profile and profile/user_group entries for
1221 * the provided remote user or group.
1222 * This should never return null -- you will either get an object or
1223 * an exception will be thrown.
1225 * @param ActivityObject $object
1226 * @param array $hints
1228 * @return Ostatus_profile
1230 protected static function createActivityObjectProfile($object, $hints=array())
1232 $homeuri = $object->id;
1236 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1237 throw new Exception('No profile URI.');
1240 $user = User::staticGet('uri', $homeuri);
1242 // TRANS: Exception.
1243 throw new Exception(_m('Local user cannot be referenced as remote.'));
1246 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1247 // TRANS: Exception.
1248 throw new Exception(_m('Local group cannot be referenced as remote.'));
1251 $ptag = Profile_list::staticGet('uri', $homeuri);
1253 $local_user = User::staticGet('id', $ptag->tagger);
1254 if (!empty($local_user)) {
1255 throw new Exception('Local people tag cannot be referenced as remote.');
1259 if (array_key_exists('feedurl', $hints)) {
1260 $feeduri = $hints['feedurl'];
1262 $discover = new FeedDiscovery();
1263 $feeduri = $discover->discoverFromURL($homeuri);
1266 if (array_key_exists('salmon', $hints)) {
1267 $salmonuri = $hints['salmon'];
1270 $discover = new FeedDiscovery();
1271 $discover->discoverFromFeedURL($hints['feedurl']);
1273 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1276 if (array_key_exists('hub', $hints)) {
1277 $huburi = $hints['hub'];
1280 $discover = new FeedDiscovery();
1281 $discover->discoverFromFeedURL($hints['feedurl']);
1283 $huburi = $discover->getHubLink();
1286 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1287 // We can only deal with folks with a PuSH hub
1288 throw new FeedSubNoHubException();
1291 $oprofile = new Ostatus_profile();
1293 $oprofile->uri = $homeuri;
1294 $oprofile->feeduri = $feeduri;
1295 $oprofile->salmonuri = $salmonuri;
1297 $oprofile->created = common_sql_now();
1298 $oprofile->modified = common_sql_now();
1300 if ($object->type == ActivityObject::PERSON) {
1301 $profile = new Profile();
1302 $profile->created = common_sql_now();
1303 self::updateProfile($profile, $object, $hints);
1305 $oprofile->profile_id = $profile->insert();
1306 if (!$oprofile->profile_id) {
1307 // TRANS: Server exception.
1308 throw new ServerException(_m('Cannot save local profile.'));
1310 } else if ($object->type == ActivityObject::GROUP) {
1311 $group = new User_group();
1312 $group->uri = $homeuri;
1313 $group->created = common_sql_now();
1314 self::updateGroup($group, $object, $hints);
1316 $oprofile->group_id = $group->insert();
1317 if (!$oprofile->group_id) {
1318 // TRANS: Server exception.
1319 throw new ServerException(_m('Cannot save local profile.'));
1321 } else if ($object->type == ActivityObject::_LIST) {
1322 $ptag = new Profile_list();
1323 $ptag->uri = $homeuri;
1324 $ptag->created = common_sql_now();
1325 self::updatePeopletag($ptag, $object, $hints);
1327 $oprofile->peopletag_id = $ptag->insert();
1328 if (!$oprofile->peopletag_id) {
1329 throw new ServerException('Cannot save local people tag.');
1333 $ok = $oprofile->insert();
1336 // TRANS: Server exception.
1337 throw new ServerException(_m('Cannot save OStatus profile.'));
1340 $avatar = self::getActivityObjectAvatar($object, $hints);
1344 $oprofile->updateAvatar($avatar);
1345 } catch (Exception $ex) {
1346 // Profile is saved, but Avatar is messed up. We're
1347 // just going to continue.
1348 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1356 * Save any updated profile information to our local copy.
1357 * @param ActivityObject $object
1358 * @param array $hints
1360 public function updateFromActivityObject($object, $hints=array())
1362 if ($this->isGroup()) {
1363 $group = $this->localGroup();
1364 self::updateGroup($group, $object, $hints);
1365 } else if ($this->isPeopletag()) {
1366 $ptag = $this->localPeopletag();
1367 self::updatePeopletag($ptag, $object, $hints);
1369 $profile = $this->localProfile();
1370 self::updateProfile($profile, $object, $hints);
1373 $avatar = self::getActivityObjectAvatar($object, $hints);
1374 if ($avatar && !isset($ptag)) {
1376 $this->updateAvatar($avatar);
1377 } catch (Exception $ex) {
1378 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1383 public static function updateProfile($profile, $object, $hints=array())
1385 $orig = clone($profile);
1387 // Existing nickname is better than nothing.
1389 if (!array_key_exists('nickname', $hints)) {
1390 $hints['nickname'] = $profile->nickname;
1393 $nickname = self::getActivityObjectNickname($object, $hints);
1395 if (!empty($nickname)) {
1396 $profile->nickname = $nickname;
1399 if (!empty($object->title)) {
1400 $profile->fullname = $object->title;
1401 } else if (array_key_exists('fullname', $hints)) {
1402 $profile->fullname = $hints['fullname'];
1405 if (!empty($object->link)) {
1406 $profile->profileurl = $object->link;
1407 } else if (array_key_exists('profileurl', $hints)) {
1408 $profile->profileurl = $hints['profileurl'];
1409 } else if (Validate::uri($object->id, array('allowed_schemes' => array('http', 'https')))) {
1410 $profile->profileurl = $object->id;
1413 $bio = self::getActivityObjectBio($object, $hints);
1416 $profile->bio = $bio;
1419 $location = self::getActivityObjectLocation($object, $hints);
1421 if (!empty($location)) {
1422 $profile->location = $location;
1425 $homepage = self::getActivityObjectHomepage($object, $hints);
1427 if (!empty($homepage)) {
1428 $profile->homepage = $homepage;
1431 if (!empty($object->geopoint)) {
1432 $location = ActivityContext::locationFromPoint($object->geopoint);
1433 if (!empty($location)) {
1434 $profile->lat = $location->lat;
1435 $profile->lon = $location->lon;
1439 // @fixme tags/categories
1440 // @todo tags from categories
1443 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1444 $profile->update($orig);
1448 protected static function updateGroup($group, $object, $hints=array())
1450 $orig = clone($group);
1452 $group->nickname = self::getActivityObjectNickname($object, $hints);
1453 $group->fullname = $object->title;
1455 if (!empty($object->link)) {
1456 $group->mainpage = $object->link;
1457 } else if (array_key_exists('profileurl', $hints)) {
1458 $group->mainpage = $hints['profileurl'];
1461 // @todo tags from categories
1462 $group->description = self::getActivityObjectBio($object, $hints);
1463 $group->location = self::getActivityObjectLocation($object, $hints);
1464 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1467 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1468 $group->update($orig);
1472 protected static function updatePeopletag($tag, $object, $hints=array()) {
1473 $orig = clone($tag);
1475 $tag->tag = $object->title;
1477 if (!empty($object->link)) {
1478 $tag->mainpage = $object->link;
1479 } else if (array_key_exists('profileurl', $hints)) {
1480 $tag->mainpage = $hints['profileurl'];
1483 $tag->description = $object->summary;
1484 $tagger = self::ensureActivityObjectProfile($object->owner);
1485 $tag->tagger = $tagger->profile_id;
1488 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1489 $tag->update($orig);
1493 protected static function getActivityObjectHomepage($object, $hints=array())
1496 $poco = $object->poco;
1498 if (!empty($poco)) {
1499 $url = $poco->getPrimaryURL();
1500 if ($url && $url->type == 'homepage') {
1501 $homepage = $url->value;
1505 // @todo Try for a another PoCo URL?
1510 protected static function getActivityObjectLocation($object, $hints=array())
1514 if (!empty($object->poco) &&
1515 isset($object->poco->address->formatted)) {
1516 $location = $object->poco->address->formatted;
1517 } else if (array_key_exists('location', $hints)) {
1518 $location = $hints['location'];
1521 if (!empty($location)) {
1522 if (mb_strlen($location) > 255) {
1523 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1527 // @todo Try to find location some othe way? Via goerss point?
1532 protected static function getActivityObjectBio($object, $hints=array())
1536 if (!empty($object->poco)) {
1537 $note = $object->poco->note;
1538 } else if (array_key_exists('bio', $hints)) {
1539 $note = $hints['bio'];
1542 if (!empty($note)) {
1543 if (Profile::bioTooLong($note)) {
1544 // XXX: truncate ok?
1545 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1551 // @todo Try to get bio info some other way?
1556 public static function getActivityObjectNickname($object, $hints=array())
1558 if ($object->poco) {
1559 if (!empty($object->poco->preferredUsername)) {
1560 return common_nicknamize($object->poco->preferredUsername);
1564 if (!empty($object->nickname)) {
1565 return common_nicknamize($object->nickname);
1568 if (array_key_exists('nickname', $hints)) {
1569 return $hints['nickname'];
1572 // Try the profile url (like foo.example.com or example.com/user/foo)
1573 if (!empty($object->link)) {
1574 $profileUrl = $object->link;
1575 } else if (!empty($hints['profileurl'])) {
1576 $profileUrl = $hints['profileurl'];
1579 if (!empty($profileUrl)) {
1580 $nickname = self::nicknameFromURI($profileUrl);
1583 // Try the URI (may be a tag:, http:, acct:, ...
1585 if (empty($nickname)) {
1586 $nickname = self::nicknameFromURI($object->id);
1589 // Try a Webfinger if one was passed (way) down
1591 if (empty($nickname)) {
1592 if (array_key_exists('webfinger', $hints)) {
1593 $nickname = self::nicknameFromURI($hints['webfinger']);
1599 if (empty($nickname)) {
1600 $nickname = common_nicknamize($object->title);
1606 protected static function nicknameFromURI($uri)
1608 if (preg_match('/(\w+):/', $uri, $matches)) {
1609 $protocol = $matches[1];
1614 switch ($protocol) {
1617 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1618 return common_canonical_nickname($matches[1]);
1622 return common_url_to_nickname($uri);
1630 * Look up, and if necessary create, an Ostatus_profile for the remote
1631 * entity with the given webfinger address.
1632 * This should never return null -- you will either get an object or
1633 * an exception will be thrown.
1635 * @param string $addr webfinger address
1636 * @return Ostatus_profile
1637 * @throws Exception on error conditions
1638 * @throws OStatusShadowException if this reference would obscure a local user/group
1640 public static function ensureWebfinger($addr)
1642 // First, try the cache
1644 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1646 if ($uri !== false) {
1647 if (is_null($uri)) {
1648 // Negative cache entry
1649 // TRANS: Exception.
1650 throw new Exception(_m('Not a valid webfinger address.'));
1652 $oprofile = Ostatus_profile::staticGet('uri', $uri);
1653 if (!empty($oprofile)) {
1658 // Try looking it up
1659 $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1661 if (!empty($oprofile)) {
1662 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1666 // Now, try some discovery
1668 $disco = new Discovery();
1671 $xrd = $disco->lookup($addr);
1672 } catch (Exception $e) {
1673 // Save negative cache entry so we don't waste time looking it up again.
1674 // @fixme distinguish temporary failures?
1675 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1676 // TRANS: Exception.
1677 throw new Exception(_m('Not a valid webfinger address.'));
1680 $hints = array('webfinger' => $addr);
1682 $dhints = DiscoveryHints::fromXRD($xrd);
1684 $hints = array_merge($hints, $dhints);
1686 // If there's an Hcard, let's grab its info
1687 if (array_key_exists('hcard', $hints)) {
1688 if (!array_key_exists('profileurl', $hints) ||
1689 $hints['hcard'] != $hints['profileurl']) {
1690 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1691 $hints = array_merge($hcardHints, $hints);
1695 // If we got a feed URL, try that
1696 if (array_key_exists('feedurl', $hints)) {
1698 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1699 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1700 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1702 } catch (Exception $e) {
1703 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1708 // If we got a profile page, try that!
1709 if (array_key_exists('profileurl', $hints)) {
1711 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1712 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1713 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1715 } catch (OStatusShadowException $e) {
1716 // We've ended up with a remote reference to a local user or group.
1717 // @fixme ideally we should be able to say who it was so we can
1718 // go back and refer to it the regular way
1720 } catch (Exception $e) {
1721 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1724 // @fixme this means an error discovering from profile page
1725 // may give us a corrupt entry using the webfinger URI, which
1726 // will obscure the correct page-keyed profile later on.
1733 if (array_key_exists('salmon', $hints)) {
1735 $salmonEndpoint = $hints['salmon'];
1737 // An account URL, a salmon endpoint, and a dream? Not much to go
1738 // on, but let's give it a try
1740 $uri = 'acct:'.$addr;
1742 $profile = new Profile();
1744 $profile->nickname = self::nicknameFromUri($uri);
1745 $profile->created = common_sql_now();
1747 if (isset($profileUrl)) {
1748 $profile->profileurl = $profileUrl;
1751 $profile_id = $profile->insert();
1754 common_log_db_error($profile, 'INSERT', __FILE__);
1755 // TRANS: Exception. %s is a webfinger address.
1756 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1759 $oprofile = new Ostatus_profile();
1761 $oprofile->uri = $uri;
1762 $oprofile->salmonuri = $salmonEndpoint;
1763 $oprofile->profile_id = $profile_id;
1764 $oprofile->created = common_sql_now();
1766 if (isset($feedUrl)) {
1767 $profile->feeduri = $feedUrl;
1770 $result = $oprofile->insert();
1773 common_log_db_error($oprofile, 'INSERT', __FILE__);
1774 // TRANS: Exception. %s is a webfinger address.
1775 throw new Exception(sprintf(_m('Could not save ostatus_profile for "%s".'),$addr));
1778 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1782 // TRANS: Exception. %s is a webfinger address.
1783 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1787 * Store the full-length scrubbed HTML of a remote notice to an attachment
1788 * file on our server. We'll link to this at the end of the cropped version.
1790 * @param string $title plaintext for HTML page's title
1791 * @param string $rendered HTML fragment for HTML page's body
1794 function saveHTMLFile($title, $rendered)
1796 $final = sprintf("<!DOCTYPE html>\n" .
1798 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1799 '<title>%s</title>' .
1801 '<body>%s</body></html>',
1802 htmlspecialchars($title),
1805 $filename = File::filename($this->localProfile(),
1806 'ostatus', // ignored?
1809 $filepath = File::path($filename);
1811 file_put_contents($filepath, $final);
1815 $file->filename = $filename;
1816 $file->url = File::url($filename);
1817 $file->size = filesize($filepath);
1818 $file->date = time();
1819 $file->mimetype = 'text/html';
1821 $file_id = $file->insert();
1823 if ($file_id === false) {
1824 common_log_db_error($file, "INSERT", __FILE__);
1825 // TRANS: Server exception.
1826 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1832 static function ensureProfileURI($uri)
1836 // First, try to query it
1838 $oprofile = Ostatus_profile::staticGet('uri', $uri);
1840 // If unfound, do discovery stuff
1842 if (empty($oprofile)) {
1843 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1844 $protocol = $match[1];
1845 switch ($protocol) {
1848 $oprofile = Ostatus_profile::ensureProfileURL($uri);
1853 $oprofile = Ostatus_profile::ensureWebfinger($rest);
1856 // TRANS: Server exception.
1857 // TRANS: %1$s is a protocol, %2$s is a URI.
1858 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1864 // TRANS: Server exception. %s is a URI.
1865 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1872 function checkAuthorship($activity)
1874 if ($this->isGroup() || $this->isPeopletag()) {
1875 // A group or propletag feed will contain posts from multiple authors.
1876 $oprofile = self::ensureActorProfile($activity);
1877 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1878 // Groups can't post notices in StatusNet.
1879 common_log(LOG_WARNING,
1880 "OStatus: skipping post with group listed ".
1881 "as author: $oprofile->uri in feed from $this->uri");
1885 $actor = $activity->actor;
1887 if (empty($actor)) {
1888 // OK here! assume the default
1889 } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
1890 $this->updateFromActivityObject($actor);
1891 } else if ($actor->id) {
1892 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1893 // This isn't what we expect from mainline OStatus person feeds!
1894 // Group feeds go down another path, with different validation...
1895 // Most likely this is a plain ol' blog feed of some kind which
1896 // doesn't match our expectations. We'll take the entry, but ignore
1897 // the <author> info.
1898 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
1900 // Plain <author> without ActivityStreams actor info.
1901 // We'll just ignore this info for now and save the update under the feed's identity.
1912 * Exception indicating we've got a remote reference to a local user,
1913 * not a remote user!
1915 * If we can ue a local profile after all, it's available as $e->profile.
1917 class OStatusShadowException extends Exception
1922 * @param Profile $profile
1923 * @param string $message
1925 function __construct($profile, $message) {
1926 $this->profile = $profile;
1927 parent::__construct($message);