From dd1ebb535bc1f8eddec70294b71a6953b1de2519 Mon Sep 17 00:00:00 2001
From: Robin Ward <robin.ward@gmail.com>
Date: Thu, 20 Nov 2014 14:01:48 -0500
Subject: [PATCH] FIX: Could not download exported data on some sites

---
 app/models/topic_link_click.rb       |  6 ++++++
 spec/models/topic_link_click_spec.rb | 21 +++++++++++++++++++++
 2 files changed, 27 insertions(+)

diff --git a/app/models/topic_link_click.rb b/app/models/topic_link_click.rb
index a682808b4..e06ad2ce7 100644
--- a/app/models/topic_link_click.rb
+++ b/app/models/topic_link_click.rb
@@ -31,6 +31,12 @@ class TopicLinkClick < ActiveRecord::Base
     unless link.present?
       return args[:url] if args[:url] =~ /^\//
 
+      begin
+        uri = URI.parse(args[:url])
+        return args[:url] if uri.host == URI.parse(Discourse.base_url).host
+      rescue
+      end
+
       # If we have it somewhere else on the site, just allow the redirect. This is
       # likely due to a onebox of another topic.
       link = TopicLink.find_by(url: args[:url])
diff --git a/spec/models/topic_link_click_spec.rb b/spec/models/topic_link_click_spec.rb
index 9fd7d1f24..e6c91b623 100644
--- a/spec/models/topic_link_click_spec.rb
+++ b/spec/models/topic_link_click_spec.rb
@@ -79,6 +79,27 @@ describe TopicLinkClick do
         end
       end
 
+      context "relative urls" do
+        let(:host) { URI.parse(Discourse.base_url).host }
+
+        it 'returns the url' do
+          url = TopicLinkClick.create_from(url: '/relative-url', post_id: @post.id, ip: '127.0.0.1')
+          url.should == "/relative-url"
+        end
+
+        it 'finds a protocol relative urls with a host' do
+          url = "//#{host}/relative-url"
+          redirect = TopicLinkClick.create_from(url: url)
+          redirect.should == url
+        end
+
+        it "returns the url if it's on our host" do
+          url = "http://#{host}/relative-url"
+          redirect = TopicLinkClick.create_from(url: url)
+          redirect.should == url
+        end
+      end
+
       context 'with a HTTPS version of the same URL' do
         before do
           @url = TopicLinkClick.create_from(url: 'https://twitter.com', topic_id: @topic.id, ip: '127.0.0.3')