request.rb 7.4 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3
module ActionController
  # These methods are available in both the production and test Request objects.
  class AbstractRequest
4
    cattr_accessor :relative_url_root
5

6 7 8 9
    # Returns the hash of environment variables for this request,
    # such as { 'RAILS_ENV' => 'production' }.
    attr_reader :env

D
Initial  
David Heinemeier Hansson 已提交
10 11
    # Returns both GET and POST parameters in a single hash.
    def parameters
12
      @parameters ||= request_parameters.update(query_parameters).update(path_parameters).with_indifferent_access
D
Initial  
David Heinemeier Hansson 已提交
13 14
    end

15
    # Returns the HTTP request method as a lowercase symbol (:get, for example)
D
Initial  
David Heinemeier Hansson 已提交
16
    def method
17
      @request_method ||= @env['REQUEST_METHOD'].downcase.to_sym
D
Initial  
David Heinemeier Hansson 已提交
18 19
    end

20
    # Is this a GET request?  Equivalent to request.method == :get
D
Initial  
David Heinemeier Hansson 已提交
21 22 23 24
    def get?
      method == :get
    end

25
    # Is this a POST request?  Equivalent to request.method == :post
D
Initial  
David Heinemeier Hansson 已提交
26 27 28 29
    def post?
      method == :post
    end

30
    # Is this a PUT request?  Equivalent to request.method == :put
D
Initial  
David Heinemeier Hansson 已提交
31 32 33 34
    def put?
      method == :put
    end

35
    # Is this a DELETE request?  Equivalent to request.method == :delete
D
Initial  
David Heinemeier Hansson 已提交
36 37 38 39
    def delete?
      method == :delete
    end

40
    # Is this a HEAD request?  Equivalent to request.method == :head
41 42 43
    def head?
      method == :head
    end
44

45 46
    # Determine whether the body of a HTTP call is URL-encoded (default)
    # or matches one of the registered param_parsers. 
47 48 49
    #
    # For backward compatibility, the post format is extracted from the
    # X-Post-Data-Format HTTP header if present.
50 51
    def content_type
      return @content_type if @content_type
52

53 54 55 56
      @content_type = @env['CONTENT_TYPE'].to_s.downcase
      
      if @env['HTTP_X_POST_DATA_FORMAT']          
        case @env['HTTP_X_POST_DATA_FORMAT'].downcase.to_sym
57 58 59 60 61 62 63 64 65 66 67 68 69
          when :yaml
            @content_type = 'application/x-yaml'
          when :xml
            @content_type = 'application/xml'
          end
      end

      @content_type = Mime::Type.new(@content_type)
    end

    def accepts
      @accepts ||= (@env['HTTP_ACCEPT'].strip.blank? ? "*/*" : @env['HTTP_ACCEPT']).split(";").collect! do |mime_type| 
        Mime::Type.new(mime_type.strip)
70
      end
71
    end
72

73 74 75
    # Returns true if the request's "X-Requested-With" header contains
    # "XMLHttpRequest". (The Prototype Javascript library sends this header with
    # every Ajax request.)
76
    def xml_http_request?
77
      not /XMLHttpRequest/i.match(@env['HTTP_X_REQUESTED_WITH']).nil?
78 79 80
    end
    alias xhr? :xml_http_request?

D
Initial  
David Heinemeier Hansson 已提交
81 82 83 84 85 86 87
    # Determine originating IP address.  REMOTE_ADDR is the standard
    # but will fail if the user is behind a proxy.  HTTP_CLIENT_IP and/or
    # HTTP_X_FORWARDED_FOR are set by proxies so check for these before
    # falling back to REMOTE_ADDR.  HTTP_X_FORWARDED_FOR may be a comma-
    # delimited list in the case of multiple chained proxies; the first is
    # the originating IP.
    def remote_ip
88
      return @env['HTTP_CLIENT_IP'] if @env.include? 'HTTP_CLIENT_IP'
89

90 91
      if @env.include? 'HTTP_X_FORWARDED_FOR' then
        remote_ips = @env['HTTP_X_FORWARDED_FOR'].split(',').reject do |ip|
92
            ip =~ /^unknown$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\./i
93 94 95
        end

        return remote_ips.first.strip unless remote_ips.empty?
D
Initial  
David Heinemeier Hansson 已提交
96
      end
97

98
      @env['REMOTE_ADDR']
D
Initial  
David Heinemeier Hansson 已提交
99 100
    end

101 102 103
    # Returns the domain part of a host, such as rubyonrails.org in "www.rubyonrails.org". You can specify
    # a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
    def domain(tld_length = 1)
104
      return nil if !/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/.match(host).nil? or host.nil?
105

106
      host.split('.').last(1 + tld_length).join('.')
107 108 109 110 111 112
    end

    # Returns all the subdomains as an array, so ["dev", "www"] would be returned for "dev.www.rubyonrails.org".
    # You can specify a different <tt>tld_length</tt>, such as 2 to catch ["www"] instead of ["www", "rubyonrails"]
    # in "www.rubyonrails.co.uk".
    def subdomains(tld_length = 1)
113
      return [] unless host
114
      parts = host.split('.')
115
      parts[0..-(tld_length+2)]
116 117
    end

118 119 120
    # Receive the raw post data.
    # This is useful for services such as REST, XMLRPC and SOAP
    # which communicate over HTTP POST but don't use the traditional parameter format.
121
    def raw_post
122
      @env['RAW_POST_DATA']
123
    end
124

125 126
    # Returns the request URI correctly, taking into account the idiosyncracies
    # of the various servers.
D
Initial  
David Heinemeier Hansson 已提交
127
    def request_uri
128
      if uri = @env['REQUEST_URI']
129
        (%r{^\w+\://[^/]+(/.*|$)$} =~ uri) ? $1 : uri # Remove domain, which webrick puts into the request_uri.
130
      else  # REQUEST_URI is blank under IIS - get this from PATH_INFO and SCRIPT_NAME
131 132
        script_filename = @env['SCRIPT_NAME'].to_s.match(%r{[^/]+$})
        uri = @env['PATH_INFO']
133
        uri = uri.sub(/#{script_filename}\//, '') unless script_filename.nil?
134
        unless (env_qs = @env['QUERY_STRING']).nil? || env_qs.empty?
135 136 137
          uri << '?' << env_qs
        end
        uri
138
      end
139
    end
D
Initial  
David Heinemeier Hansson 已提交
140

141
    # Return 'https://' if this is an SSL request and 'http://' otherwise.
D
Initial  
David Heinemeier Hansson 已提交
142
    def protocol
143
      ssl? ? 'https://' : 'http://'
D
Initial  
David Heinemeier Hansson 已提交
144 145
    end

146
    # Is this an SSL request?
147
    def ssl?
148
      @env['HTTPS'] == 'on' || @env['HTTP_X_FORWARDED_PROTO'] == 'https'
149
    end
150

151
    # Returns the interpreted path to requested resource after all the installation directory of this application was taken into account
D
Initial  
David Heinemeier Hansson 已提交
152
    def path
153
      path = (uri = request_uri) ? uri.split('?').first : ''
154

155
      # Cut off the path to the installation directory if given
156 157 158 159
      root = relative_url_root
      path[0, root.length] = '' if root
      path || ''
    end
160

161 162 163
    # Returns the path minus the web server relative installation directory.
    # This method returns nil unless the web server is apache.
    def relative_url_root
164
      @@relative_url_root ||= server_software == 'apache' ? @env["SCRIPT_NAME"].to_s.sub(/\/dispatch\.(fcgi|rb|cgi)$/, '') : ''
D
Initial  
David Heinemeier Hansson 已提交
165 166
    end

167
    # Returns the port number of this request as an integer.
D
Initial  
David Heinemeier Hansson 已提交
168
    def port
169
      @port_as_int ||= @env['SERVER_PORT'].to_i
D
Initial  
David Heinemeier Hansson 已提交
170
    end
171

172 173 174 175 176 177 178
    # Returns the standard port number for this request's protocol
    def standard_port
      case protocol
        when 'https://' then 443
        else 80
      end
    end
D
Initial  
David Heinemeier Hansson 已提交
179

180 181
    # Returns a port suffix like ":8080" if the port number of this request
    # is not the default HTTP port 80 or HTTPS port 443.
182
    def port_string
183
      (port == standard_port) ? '' : ":#{port}"
184 185
    end

186 187
    # Returns a host:port string for this request, such as example.com or
    # example.com:8080.
D
Initial  
David Heinemeier Hansson 已提交
188
    def host_with_port
189
      host + port_string
D
Initial  
David Heinemeier Hansson 已提交
190
    end
191

192 193
    def path_parameters=(parameters)
      @path_parameters = parameters
194 195
      @symbolized_path_parameters = @parameters = nil
    end
196

197 198
    def symbolized_path_parameters
      @symbolized_path_parameters ||= path_parameters.symbolize_keys
199
    end
D
Initial  
David Heinemeier Hansson 已提交
200

201 202 203
    def path_parameters
      @path_parameters ||= {}
    end
204 205

    # Returns the lowercase name of the HTTP server software.
206
    def server_software
207
      (@env['SERVER_SOFTWARE'] && /^([a-zA-Z]+)/ =~ @env['SERVER_SOFTWARE']) ? $1.downcase : nil
208
    end
209

D
Initial  
David Heinemeier Hansson 已提交
210 211 212
    #--
    # Must be implemented in the concrete request
    #++
213
    def query_parameters #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
214 215
    end

216
    def request_parameters #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
217 218
    end

219 220
    # Returns the host for this request, such as example.com.
    def host
D
Initial  
David Heinemeier Hansson 已提交
221 222
    end

223
    def cookies #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
224 225
    end

226
    def session #:nodoc:
D
Initial  
David Heinemeier Hansson 已提交
227 228
    end

229 230 231 232
    def session=(session) #:nodoc:
      @session = session
    end

233
    def reset_session #:nodoc:
234
    end
D
Initial  
David Heinemeier Hansson 已提交
235 236
  end
end