Class: CGI

Inherits:
SimpleDelegator
  • Object
show all
Defined in:
lib/cgi-lib.rb

Constant Summary collapse

CR =
"\015"
LF =
"\012"
EOL =
CR + LF
RFC822_DAYS =
%w[ Sun
RFC822_MONTHS =
%w[ Jan

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input = $stdin) ⇒ CGI

Returns a new instance of CGI.



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/cgi-lib.rb', line 162

def initialize(input = $stdin)

  @inputs = {}
  @cookie = {}

  case ENV['REQUEST_METHOD']
  when "GET"
    ENV['QUERY_STRING'] or ""
  when "POST"
    input.read(Integer(ENV['CONTENT_LENGTH'])) or ""
  else
    read_from_cmdline
  end.split(/[&;]/).each do |x|
    key, val = x.split(/=/,2).collect{|x|CGI::unescape(x)}
    if @inputs.include?(key)
      @inputs[key] += "\0" + (val or "")
    else
      @inputs[key] = (val or "")
    end
  end

  super(@inputs)

  if ENV.has_key?('HTTP_COOKIE') or ENV.has_key?('COOKIE')
    (ENV['HTTP_COOKIE'] or ENV['COOKIE']).split(/; /).each do |x|
      key, val = x.split(/=/,2)
      key = CGI::unescape(key)
      val = val.split(/&/).collect{|x|CGI::unescape(x)}.join("\0")
      if @cookie.include?(key)
        @cookie[key] += "\0" + val
      else
        @cookie[key] = val
      end
    end
  end
end

Instance Attribute Details

Returns the value of attribute cookie



200
201
202
# File 'lib/cgi-lib.rb', line 200

def cookie
  @cookie
end

#inputsObject (readonly)

Returns the value of attribute inputs



199
200
201
# File 'lib/cgi-lib.rb', line 199

def inputs
  @inputs
end

Class Method Details

make raw cookie string



211
212
213
214
215
216
217
# File 'lib/cgi-lib.rb', line 211

def CGI::cookie(options)
  "Set-Cookie: " + options['name'] + '=' + escape(options['value']) +
  (options['domain']  ? '; domain='  + options['domain'] : '') +
  (options['path']    ? '; path='    + options['path']   : '') +
  (options['expires'] ? '; expires=' + rfc1123_date(options['expires']) : '') +
  (options['secure']  ? '; secure' : '')
end

.errorObject

print error message to $> and exit



264
265
266
267
268
269
270
271
# File 'lib/cgi-lib.rb', line 264

def CGI::error
  CGI::message({'title'=>'ERROR', 'body'=>
    CGI::tag("PRE"){
      "ERROR: " + CGI::tag("STRONG"){ escapeHTML($!.to_s) } + "\n" + escapeHTML($@.join("\n"))
    }
  })
  exit
end

.escape(str) ⇒ Object

escape url encode



134
135
136
# File 'lib/cgi-lib.rb', line 134

def CGI::escape(str)
  str.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
end

.escapeHTML(str) ⇒ Object

escape HTML



144
145
146
# File 'lib/cgi-lib.rb', line 144

def CGI::escapeHTML(str)
  str.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
end

.header(*options) ⇒ Object

make HTTP header string



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/cgi-lib.rb', line 220

def CGI::header(*options)
  if defined?(MOD_RUBY)
    options.each{|option|
      option.sub(/(.*?): (.*)/){
        Apache::request.headers_out[$1] = $2
      }
    }
    Apache::request.send_http_header
    ''
  else
    if options.delete("nph") or (ENV['SERVER_SOFTWARE'] =~ /IIS/)
      [(ENV['SERVER_PROTOCOL'] or "HTTP/1.0") + " 200 OK",
       "Date: " + rfc1123_date(Time.now),
       "Server: " + (ENV['SERVER_SOFTWARE'] or ""),
       "Connection: close"] +
      (options.empty? ? ["Content-Type: text/html"] : options)
    else
      options.empty? ? ["Content-Type: text/html"] : options
    end.join(EOL) + EOL + EOL
  end
end

.message(message, title = "",, header = ["Content-Type: text/html"]) ⇒ Object

print message to $>



248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/cgi-lib.rb', line 248

def CGI::message(message, title = "", header = ["Content-Type: text/html"])
  if message.kind_of?(Hash)
    title   = message['title']
    header  = message['header']
    message = message['body']
  end
  CGI::print(*header){
    CGI::tag("HTML"){
      CGI::tag("HEAD"){ CGI.tag("TITLE"){ title } } +
      CGI::tag("BODY"){ message }
    }
  }
  true
end

print HTTP header and string to $>



243
244
245
# File 'lib/cgi-lib.rb', line 243

def CGI::print(*options)
  $>.print CGI::header(*options) + yield.to_s
end

.rfc1123_date(time) ⇒ Object

make rfc1123 date string



126
127
128
129
130
131
# File 'lib/cgi-lib.rb', line 126

def CGI::rfc1123_date(time)
  t = time.clone.gmtime
  return format("%s, %.2d %s %d %.2d:%.2d:%.2d GMT",
              RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
              t.hour, t.min, t.sec)
end

.tag(element, attributes = {}) ⇒ Object

make HTML tag string



203
204
205
206
207
208
# File 'lib/cgi-lib.rb', line 203

def CGI::tag(element, attributes = {})
  "<" + escapeHTML(element) + attributes.collect{|name, value|
    " " + escapeHTML(name) + '="' + escapeHTML(value) + '"'
  }.to_s + ">" +
  (iterator? ? yield.to_s + "</" + escapeHTML(element) + ">" : "")
end

.unescape(str) ⇒ Object

unescape url encoded



139
140
141
# File 'lib/cgi-lib.rb', line 139

def CGI::unescape(str)
  str.gsub(/\+/, ' ').gsub(/%([0-9a-fA-F]{2})/){ [$1.hex].pack("c") }
end

Instance Method Details

#read_from_cmdlineObject

offline mode. read name=value pairs on standard input.



149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/cgi-lib.rb', line 149

def read_from_cmdline
  require "shellwords.rb"
  words = Shellwords.shellwords(
            if not ARGV.empty?
              ARGV.join(' ')
            else
              STDERR.print "(offline mode: enter name=value pairs on standard input)\n" if STDIN.tty?
              readlines.join(' ').gsub(/\n/, '')
            end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26'))

  if words.find{|x| x =~ /=/} then words.join('&') else words.join('+') end
end