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,
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 $profile = $this->localProfile();
1049 if (!empty($profile)) {
1050 $profile->setOriginal($filename);
1053 $orig = clone($this);
1054 $this->avatar = $url;
1055 $this->update($orig);
1059 * Pull avatar URL from ActivityObject or profile hints
1061 * @param ActivityObject $object
1062 * @param array $hints
1063 * @return mixed URL string or false
1065 public static function getActivityObjectAvatar($object, $hints=array())
1067 if ($object->avatarLinks) {
1069 // Take the exact-size avatar, or the largest avatar, or the first avatar if all sizeless
1070 foreach ($object->avatarLinks as $avatar) {
1071 if ($avatar->width == AVATAR_PROFILE_SIZE && $avatar->height = AVATAR_PROFILE_SIZE) {
1076 if (!$best || $avatar->width > $best->width) {
1081 } else if (array_key_exists('avatar', $hints)) {
1082 return $hints['avatar'];
1088 * Get an appropriate avatar image source URL, if available.
1090 * @param ActivityObject $actor
1091 * @param DOMElement $feed
1094 protected static function getAvatar($actor, $feed)
1098 if ($actor->avatar) {
1099 $url = trim($actor->avatar);
1102 // Check <atom:logo> and <atom:icon> on the feed
1103 $els = $feed->childNodes();
1104 if ($els && $els->length) {
1105 for ($i = 0; $i < $els->length; $i++) {
1106 $el = $els->item($i);
1107 if ($el->namespaceURI == Activity::ATOM) {
1108 if (empty($url) && $el->localName == 'logo') {
1109 $url = trim($el->textContent);
1112 if (empty($icon) && $el->localName == 'icon') {
1113 // Use as a fallback
1114 $icon = trim($el->textContent);
1119 if ($icon && !$url) {
1124 $opts = array('allowed_schemes' => array('http', 'https'));
1125 if (Validate::uri($url, $opts)) {
1130 return Plugin::staticPath('OStatus', 'images/96px-Feed-icon.svg.png');
1134 * Fetch, or build if necessary, an Ostatus_profile for the actor
1135 * in a given Activity Streams activity.
1136 * This should never return null -- you will either get an object or
1137 * an exception will be thrown.
1139 * @param Activity $activity
1140 * @param string $feeduri if we already know the canonical feed URI!
1141 * @param string $salmonuri if we already know the salmon return channel URI
1142 * @return Ostatus_profile
1145 public static function ensureActorProfile($activity, $hints=array())
1147 return self::ensureActivityObjectProfile($activity->actor, $hints);
1151 * Fetch, or build if necessary, an Ostatus_profile for the profile
1152 * in a given Activity Streams object (can be subject, actor, or object).
1153 * This should never return null -- you will either get an object or
1154 * an exception will be thrown.
1156 * @param ActivityObject $object
1157 * @param array $hints additional discovery information passed from higher levels
1158 * @return Ostatus_profile
1161 public static function ensureActivityObjectProfile($object, $hints=array())
1163 $profile = self::getActivityObjectProfile($object);
1165 $profile->updateFromActivityObject($object, $hints);
1167 $profile = self::createActivityObjectProfile($object, $hints);
1173 * @param Activity $activity
1174 * @return mixed matching Ostatus_profile or false if none known
1175 * @throws ServerException if feed info invalid
1177 public static function getActorProfile($activity)
1179 return self::getActivityObjectProfile($activity->actor);
1183 * @param ActivityObject $activity
1184 * @return mixed matching Ostatus_profile or false if none known
1185 * @throws ServerException if feed info invalid
1187 protected static function getActivityObjectProfile($object)
1189 $uri = self::getActivityObjectProfileURI($object);
1190 return Ostatus_profile::staticGet('uri', $uri);
1194 * Get the identifier URI for the remote entity described
1195 * by this ActivityObject. This URI is *not* guaranteed to be
1196 * a resolvable HTTP/HTTPS URL.
1198 * @param ActivityObject $object
1200 * @throws ServerException if feed info invalid
1202 protected static function getActivityObjectProfileURI($object)
1205 if (ActivityUtils::validateUri($object->id)) {
1210 // If the id is missing or invalid (we've seen feeds mistakenly listing
1211 // things like local usernames in that field) then we'll use the profile
1212 // page link, if valid.
1213 if ($object->link && common_valid_http_url($object->link)) {
1214 return $object->link;
1216 // TRANS: Server exception.
1217 throw new ServerException(_m('No author ID URI found.'));
1221 * @fixme validate stuff somewhere
1225 * Create local ostatus_profile and profile/user_group entries for
1226 * the provided remote user or group.
1227 * This should never return null -- you will either get an object or
1228 * an exception will be thrown.
1230 * @param ActivityObject $object
1231 * @param array $hints
1233 * @return Ostatus_profile
1235 protected static function createActivityObjectProfile($object, $hints=array())
1237 $homeuri = $object->id;
1241 common_log(LOG_DEBUG, __METHOD__ . " empty actor profile URI: " . var_export($activity, true));
1242 // TRANS: Exception.
1243 throw new Exception(_m('No profile URI.'));
1246 $user = User::staticGet('uri', $homeuri);
1248 // TRANS: Exception.
1249 throw new Exception(_m('Local user cannot be referenced as remote.'));
1252 if (OStatusPlugin::localGroupFromUrl($homeuri)) {
1253 // TRANS: Exception.
1254 throw new Exception(_m('Local group cannot be referenced as remote.'));
1257 $ptag = Profile_list::staticGet('uri', $homeuri);
1259 $local_user = User::staticGet('id', $ptag->tagger);
1260 if (!empty($local_user)) {
1261 // TRANS: Exception.
1262 throw new Exception(_m('Local list cannot be referenced as remote.'));
1266 if (array_key_exists('feedurl', $hints)) {
1267 $feeduri = $hints['feedurl'];
1269 $discover = new FeedDiscovery();
1270 $feeduri = $discover->discoverFromURL($homeuri);
1273 if (array_key_exists('salmon', $hints)) {
1274 $salmonuri = $hints['salmon'];
1277 $discover = new FeedDiscovery();
1278 $discover->discoverFromFeedURL($hints['feedurl']);
1280 $salmonuri = $discover->getAtomLink(Salmon::NS_REPLIES);
1283 if (array_key_exists('hub', $hints)) {
1284 $huburi = $hints['hub'];
1287 $discover = new FeedDiscovery();
1288 $discover->discoverFromFeedURL($hints['feedurl']);
1290 $huburi = $discover->getHubLink();
1293 if (!$huburi && !common_config('feedsub', 'fallback_hub')) {
1294 // We can only deal with folks with a PuSH hub
1295 throw new FeedSubNoHubException();
1298 $oprofile = new Ostatus_profile();
1300 $oprofile->uri = $homeuri;
1301 $oprofile->feeduri = $feeduri;
1302 $oprofile->salmonuri = $salmonuri;
1304 $oprofile->created = common_sql_now();
1305 $oprofile->modified = common_sql_now();
1307 if ($object->type == ActivityObject::PERSON) {
1308 $profile = new Profile();
1309 $profile->created = common_sql_now();
1310 self::updateProfile($profile, $object, $hints);
1312 $oprofile->profile_id = $profile->insert();
1313 if (!$oprofile->profile_id) {
1314 // TRANS: Server exception.
1315 throw new ServerException(_m('Cannot save local profile.'));
1317 } else if ($object->type == ActivityObject::GROUP) {
1318 $group = new User_group();
1319 $group->uri = $homeuri;
1320 $group->created = common_sql_now();
1321 self::updateGroup($group, $object, $hints);
1323 $oprofile->group_id = $group->insert();
1324 if (!$oprofile->group_id) {
1325 // TRANS: Server exception.
1326 throw new ServerException(_m('Cannot save local profile.'));
1328 } else if ($object->type == ActivityObject::_LIST) {
1329 $ptag = new Profile_list();
1330 $ptag->uri = $homeuri;
1331 $ptag->created = common_sql_now();
1332 self::updatePeopletag($ptag, $object, $hints);
1334 $oprofile->peopletag_id = $ptag->insert();
1335 if (!$oprofile->peopletag_id) {
1336 // TRANS: Server exception.
1337 throw new ServerException(_m('Cannot save local list.'));
1341 $ok = $oprofile->insert();
1344 // TRANS: Server exception.
1345 throw new ServerException(_m('Cannot save OStatus profile.'));
1348 $avatar = self::getActivityObjectAvatar($object, $hints);
1352 $oprofile->updateAvatar($avatar);
1353 } catch (Exception $ex) {
1354 // Profile is saved, but Avatar is messed up. We're
1355 // just going to continue.
1356 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: ". $ex->getMessage());
1364 * Save any updated profile information to our local copy.
1365 * @param ActivityObject $object
1366 * @param array $hints
1368 public function updateFromActivityObject($object, $hints=array())
1370 if ($this->isGroup()) {
1371 $group = $this->localGroup();
1372 self::updateGroup($group, $object, $hints);
1373 } else if ($this->isPeopletag()) {
1374 $ptag = $this->localPeopletag();
1375 self::updatePeopletag($ptag, $object, $hints);
1377 $profile = $this->localProfile();
1378 self::updateProfile($profile, $object, $hints);
1381 $avatar = self::getActivityObjectAvatar($object, $hints);
1382 if ($avatar && !isset($ptag)) {
1384 $this->updateAvatar($avatar);
1385 } catch (Exception $ex) {
1386 common_log(LOG_WARNING, "Exception saving OStatus profile avatar: " . $ex->getMessage());
1391 public static function updateProfile($profile, $object, $hints=array())
1393 $orig = clone($profile);
1395 // Existing nickname is better than nothing.
1397 if (!array_key_exists('nickname', $hints)) {
1398 $hints['nickname'] = $profile->nickname;
1401 $nickname = self::getActivityObjectNickname($object, $hints);
1403 if (!empty($nickname)) {
1404 $profile->nickname = $nickname;
1407 if (!empty($object->title)) {
1408 $profile->fullname = $object->title;
1409 } else if (array_key_exists('fullname', $hints)) {
1410 $profile->fullname = $hints['fullname'];
1413 if (!empty($object->link)) {
1414 $profile->profileurl = $object->link;
1415 } else if (array_key_exists('profileurl', $hints)) {
1416 $profile->profileurl = $hints['profileurl'];
1417 } else if (Validate::uri($object->id, array('allowed_schemes' => array('http', 'https')))) {
1418 $profile->profileurl = $object->id;
1421 $bio = self::getActivityObjectBio($object, $hints);
1424 $profile->bio = $bio;
1427 $location = self::getActivityObjectLocation($object, $hints);
1429 if (!empty($location)) {
1430 $profile->location = $location;
1433 $homepage = self::getActivityObjectHomepage($object, $hints);
1435 if (!empty($homepage)) {
1436 $profile->homepage = $homepage;
1439 if (!empty($object->geopoint)) {
1440 $location = ActivityContext::locationFromPoint($object->geopoint);
1441 if (!empty($location)) {
1442 $profile->lat = $location->lat;
1443 $profile->lon = $location->lon;
1447 // @fixme tags/categories
1448 // @todo tags from categories
1451 common_log(LOG_DEBUG, "Updating OStatus profile $profile->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1452 $profile->update($orig);
1456 protected static function updateGroup($group, $object, $hints=array())
1458 $orig = clone($group);
1460 $group->nickname = self::getActivityObjectNickname($object, $hints);
1461 $group->fullname = $object->title;
1463 if (!empty($object->link)) {
1464 $group->mainpage = $object->link;
1465 } else if (array_key_exists('profileurl', $hints)) {
1466 $group->mainpage = $hints['profileurl'];
1469 // @todo tags from categories
1470 $group->description = self::getActivityObjectBio($object, $hints);
1471 $group->location = self::getActivityObjectLocation($object, $hints);
1472 $group->homepage = self::getActivityObjectHomepage($object, $hints);
1475 common_log(LOG_DEBUG, "Updating OStatus group $group->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1476 $group->update($orig);
1480 protected static function updatePeopletag($tag, $object, $hints=array()) {
1481 $orig = clone($tag);
1483 $tag->tag = $object->title;
1485 if (!empty($object->link)) {
1486 $tag->mainpage = $object->link;
1487 } else if (array_key_exists('profileurl', $hints)) {
1488 $tag->mainpage = $hints['profileurl'];
1491 $tag->description = $object->summary;
1492 $tagger = self::ensureActivityObjectProfile($object->owner);
1493 $tag->tagger = $tagger->profile_id;
1496 common_log(LOG_DEBUG, "Updating OStatus peopletag $tag->id from remote info $object->id: " . var_export($object, true) . var_export($hints, true));
1497 $tag->update($orig);
1501 protected static function getActivityObjectHomepage($object, $hints=array())
1504 $poco = $object->poco;
1506 if (!empty($poco)) {
1507 $url = $poco->getPrimaryURL();
1508 if ($url && $url->type == 'homepage') {
1509 $homepage = $url->value;
1513 // @todo Try for a another PoCo URL?
1518 protected static function getActivityObjectLocation($object, $hints=array())
1522 if (!empty($object->poco) &&
1523 isset($object->poco->address->formatted)) {
1524 $location = $object->poco->address->formatted;
1525 } else if (array_key_exists('location', $hints)) {
1526 $location = $hints['location'];
1529 if (!empty($location)) {
1530 if (mb_strlen($location) > 255) {
1531 $location = mb_substr($note, 0, 255 - 3) . ' … ';
1535 // @todo Try to find location some othe way? Via goerss point?
1540 protected static function getActivityObjectBio($object, $hints=array())
1544 if (!empty($object->poco)) {
1545 $note = $object->poco->note;
1546 } else if (array_key_exists('bio', $hints)) {
1547 $note = $hints['bio'];
1550 if (!empty($note)) {
1551 if (Profile::bioTooLong($note)) {
1552 // XXX: truncate ok?
1553 $bio = mb_substr($note, 0, Profile::maxBio() - 3) . ' … ';
1559 // @todo Try to get bio info some other way?
1564 public static function getActivityObjectNickname($object, $hints=array())
1566 if ($object->poco) {
1567 if (!empty($object->poco->preferredUsername)) {
1568 return common_nicknamize($object->poco->preferredUsername);
1572 if (!empty($object->nickname)) {
1573 return common_nicknamize($object->nickname);
1576 if (array_key_exists('nickname', $hints)) {
1577 return $hints['nickname'];
1580 // Try the profile url (like foo.example.com or example.com/user/foo)
1581 if (!empty($object->link)) {
1582 $profileUrl = $object->link;
1583 } else if (!empty($hints['profileurl'])) {
1584 $profileUrl = $hints['profileurl'];
1587 if (!empty($profileUrl)) {
1588 $nickname = self::nicknameFromURI($profileUrl);
1591 // Try the URI (may be a tag:, http:, acct:, ...
1593 if (empty($nickname)) {
1594 $nickname = self::nicknameFromURI($object->id);
1597 // Try a Webfinger if one was passed (way) down
1599 if (empty($nickname)) {
1600 if (array_key_exists('webfinger', $hints)) {
1601 $nickname = self::nicknameFromURI($hints['webfinger']);
1607 if (empty($nickname)) {
1608 $nickname = common_nicknamize($object->title);
1614 protected static function nicknameFromURI($uri)
1616 if (preg_match('/(\w+):/', $uri, $matches)) {
1617 $protocol = $matches[1];
1622 switch ($protocol) {
1625 if (preg_match("/^$protocol:(.*)?@.*\$/", $uri, $matches)) {
1626 return common_canonical_nickname($matches[1]);
1630 return common_url_to_nickname($uri);
1638 * Look up, and if necessary create, an Ostatus_profile for the remote
1639 * entity with the given webfinger address.
1640 * This should never return null -- you will either get an object or
1641 * an exception will be thrown.
1643 * @param string $addr webfinger address
1644 * @return Ostatus_profile
1645 * @throws Exception on error conditions
1646 * @throws OStatusShadowException if this reference would obscure a local user/group
1648 public static function ensureWebfinger($addr)
1650 // First, try the cache
1652 $uri = self::cacheGet(sprintf('ostatus_profile:webfinger:%s', $addr));
1654 if ($uri !== false) {
1655 if (is_null($uri)) {
1656 // Negative cache entry
1657 // TRANS: Exception.
1658 throw new Exception(_m('Not a valid webfinger address.'));
1660 $oprofile = Ostatus_profile::staticGet('uri', $uri);
1661 if (!empty($oprofile)) {
1666 // Try looking it up
1667 $oprofile = Ostatus_profile::staticGet('uri', 'acct:'.$addr);
1669 if (!empty($oprofile)) {
1670 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1674 // Now, try some discovery
1676 $disco = new Discovery();
1679 $xrd = $disco->lookup($addr);
1680 } catch (Exception $e) {
1681 // Save negative cache entry so we don't waste time looking it up again.
1682 // @fixme distinguish temporary failures?
1683 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), null);
1684 // TRANS: Exception.
1685 throw new Exception(_m('Not a valid webfinger address.'));
1688 $hints = array('webfinger' => $addr);
1690 $dhints = DiscoveryHints::fromXRD($xrd);
1692 $hints = array_merge($hints, $dhints);
1694 // If there's an Hcard, let's grab its info
1695 if (array_key_exists('hcard', $hints)) {
1696 if (!array_key_exists('profileurl', $hints) ||
1697 $hints['hcard'] != $hints['profileurl']) {
1698 $hcardHints = DiscoveryHints::fromHcardUrl($hints['hcard']);
1699 $hints = array_merge($hcardHints, $hints);
1703 // If we got a feed URL, try that
1704 if (array_key_exists('feedurl', $hints)) {
1706 common_log(LOG_INFO, "Discovery on acct:$addr with feed URL " . $hints['feedurl']);
1707 $oprofile = self::ensureFeedURL($hints['feedurl'], $hints);
1708 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1710 } catch (Exception $e) {
1711 common_log(LOG_WARNING, "Failed creating profile from feed URL '$feedUrl': " . $e->getMessage());
1716 // If we got a profile page, try that!
1717 if (array_key_exists('profileurl', $hints)) {
1719 common_log(LOG_INFO, "Discovery on acct:$addr with profile URL $profileUrl");
1720 $oprofile = self::ensureProfileURL($hints['profileurl'], $hints);
1721 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1723 } catch (OStatusShadowException $e) {
1724 // We've ended up with a remote reference to a local user or group.
1725 // @fixme ideally we should be able to say who it was so we can
1726 // go back and refer to it the regular way
1728 } catch (Exception $e) {
1729 common_log(LOG_WARNING, "Failed creating profile from profile URL '$profileUrl': " . $e->getMessage());
1732 // @fixme this means an error discovering from profile page
1733 // may give us a corrupt entry using the webfinger URI, which
1734 // will obscure the correct page-keyed profile later on.
1741 if (array_key_exists('salmon', $hints)) {
1742 $salmonEndpoint = $hints['salmon'];
1744 // An account URL, a salmon endpoint, and a dream? Not much to go
1745 // on, but let's give it a try
1747 $uri = 'acct:'.$addr;
1749 $profile = new Profile();
1751 $profile->nickname = self::nicknameFromUri($uri);
1752 $profile->created = common_sql_now();
1754 if (isset($profileUrl)) {
1755 $profile->profileurl = $profileUrl;
1758 $profile_id = $profile->insert();
1761 common_log_db_error($profile, 'INSERT', __FILE__);
1762 // TRANS: Exception. %s is a webfinger address.
1763 throw new Exception(sprintf(_m('Could not save profile for "%s".'),$addr));
1766 $oprofile = new Ostatus_profile();
1768 $oprofile->uri = $uri;
1769 $oprofile->salmonuri = $salmonEndpoint;
1770 $oprofile->profile_id = $profile_id;
1771 $oprofile->created = common_sql_now();
1773 if (isset($feedUrl)) {
1774 $profile->feeduri = $feedUrl;
1777 $result = $oprofile->insert();
1780 common_log_db_error($oprofile, 'INSERT', __FILE__);
1781 // TRANS: Exception. %s is a webfinger address.
1782 throw new Exception(sprintf(_m('Could not save OStatus profile for "%s".'),$addr));
1785 self::cacheSet(sprintf('ostatus_profile:webfinger:%s', $addr), $oprofile->uri);
1789 // TRANS: Exception. %s is a webfinger address.
1790 throw new Exception(sprintf(_m('Could not find a valid profile for "%s".'),$addr));
1794 * Store the full-length scrubbed HTML of a remote notice to an attachment
1795 * file on our server. We'll link to this at the end of the cropped version.
1797 * @param string $title plaintext for HTML page's title
1798 * @param string $rendered HTML fragment for HTML page's body
1801 function saveHTMLFile($title, $rendered)
1803 $final = sprintf("<!DOCTYPE html>\n" .
1805 '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' .
1806 '<title>%s</title>' .
1808 '<body>%s</body></html>',
1809 htmlspecialchars($title),
1812 $filename = File::filename($this->localProfile(),
1813 'ostatus', // ignored?
1816 $filepath = File::path($filename);
1818 file_put_contents($filepath, $final);
1822 $file->filename = $filename;
1823 $file->url = File::url($filename);
1824 $file->size = filesize($filepath);
1825 $file->date = time();
1826 $file->mimetype = 'text/html';
1828 $file_id = $file->insert();
1830 if ($file_id === false) {
1831 common_log_db_error($file, "INSERT", __FILE__);
1832 // TRANS: Server exception.
1833 throw new ServerException(_m('Could not store HTML content of long post as file.'));
1839 static function ensureProfileURI($uri)
1843 // First, try to query it
1845 $oprofile = Ostatus_profile::staticGet('uri', $uri);
1847 // If unfound, do discovery stuff
1849 if (empty($oprofile)) {
1850 if (preg_match("/^(\w+)\:(.*)/", $uri, $match)) {
1851 $protocol = $match[1];
1852 switch ($protocol) {
1855 $oprofile = Ostatus_profile::ensureProfileURL($uri);
1860 $oprofile = Ostatus_profile::ensureWebfinger($rest);
1863 // TRANS: Server exception.
1864 // TRANS: %1$s is a protocol, %2$s is a URI.
1865 throw new ServerException(sprintf(_m('Unrecognized URI protocol for profile: %1$s (%2$s).'),
1871 // TRANS: Server exception. %s is a URI.
1872 throw new ServerException(sprintf(_m('No URI protocol for profile: %s.'),$uri));
1879 function checkAuthorship($activity)
1881 if ($this->isGroup() || $this->isPeopletag()) {
1882 // A group or propletag feed will contain posts from multiple authors.
1883 $oprofile = self::ensureActorProfile($activity);
1884 if ($oprofile->isGroup() || $oprofile->isPeopletag()) {
1885 // Groups can't post notices in StatusNet.
1886 common_log(LOG_WARNING,
1887 "OStatus: skipping post with group listed ".
1888 "as author: $oprofile->uri in feed from $this->uri");
1892 $actor = $activity->actor;
1894 if (empty($actor)) {
1895 // OK here! assume the default
1896 } else if ($actor->id == $this->uri || $actor->link == $this->uri) {
1897 $this->updateFromActivityObject($actor);
1898 } else if ($actor->id) {
1899 // We have an ActivityStreams actor with an explicit ID that doesn't match the feed owner.
1900 // This isn't what we expect from mainline OStatus person feeds!
1901 // Group feeds go down another path, with different validation...
1902 // Most likely this is a plain ol' blog feed of some kind which
1903 // doesn't match our expectations. We'll take the entry, but ignore
1904 // the <author> info.
1905 common_log(LOG_WARNING, "Got an actor '{$actor->title}' ({$actor->id}) on single-user feed for {$this->uri}");
1907 // Plain <author> without ActivityStreams actor info.
1908 // We'll just ignore this info for now and save the update under the feed's identity.
1919 * Exception indicating we've got a remote reference to a local user,
1920 * not a remote user!
1922 * If we can ue a local profile after all, it's available as $e->profile.
1924 class OStatusShadowException extends Exception
1929 * @param Profile $profile
1930 * @param string $message
1932 function __construct($profile, $message) {
1933 $this->profile = $profile;
1934 parent::__construct($message);