home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / ruby / 1.8 / cgi.rb < prev    next >
Encoding:
Ruby Source  |  2007-03-07  |  73.5 KB  |  2,302 lines

  1. # cgi.rb - cgi support library
  2. # Copyright (C) 2000  Network Applied Communication Laboratory, Inc.
  3. # Copyright (C) 2000  Information-technology Promotion Agency, Japan
  4. #
  5. # Author: Wakou Aoyama <wakou@ruby-lang.org>
  6. #
  7. # Documentation: Wakou Aoyama (RDoc'd and embellished by William Webber) 
  8. # == Overview
  9. #
  10. # The Common Gateway Interface (CGI) is a simple protocol
  11. # for passing an HTTP request from a web server to a
  12. # standalone program, and returning the output to the web
  13. # browser.  Basically, a CGI program is called with the
  14. # parameters of the request passed in either in the
  15. # environment (GET) or via $stdin (POST), and everything
  16. # it prints to $stdout is returned to the client.
  17. # This file holds the +CGI+ class.  This class provides
  18. # functionality for retrieving HTTP request parameters,
  19. # managing cookies, and generating HTML output.  See the
  20. # class documentation for more details and examples of use.
  21. #
  22. # The file cgi/session.rb provides session management
  23. # functionality; see that file for more details.
  24. #
  25. # See http://www.w3.org/CGI/ for more information on the CGI
  26. # protocol.
  27.  
  28. raise "Please, use ruby 1.5.4 or later." if RUBY_VERSION < "1.5.4"
  29.  
  30. require 'English'
  31.  
  32. # CGI class.  See documentation for the file cgi.rb for an overview
  33. # of the CGI protocol.
  34. #
  35. # == Introduction
  36. #
  37. # CGI is a large class, providing several categories of methods, many of which
  38. # are mixed in from other modules.  Some of the documentation is in this class,
  39. # some in the modules CGI::QueryExtension and CGI::HtmlExtension.  See
  40. # CGI::Cookie for specific information on handling cookies, and cgi/session.rb
  41. # (CGI::Session) for information on sessions.
  42. #
  43. # For queries, CGI provides methods to get at environmental variables,
  44. # parameters, cookies, and multipart request data.  For responses, CGI provides
  45. # methods for writing output and generating HTML.
  46. #
  47. # Read on for more details.  Examples are provided at the bottom.
  48. #
  49. # == Queries
  50. #
  51. # The CGI class dynamically mixes in parameter and cookie-parsing
  52. # functionality,  environmental variable access, and support for
  53. # parsing multipart requests (including uploaded files) from the
  54. # CGI::QueryExtension module.
  55. #
  56. # === Environmental Variables
  57. #
  58. # The standard CGI environmental variables are available as read-only
  59. # attributes of a CGI object.  The following is a list of these variables:
  60. #
  61. #
  62. #   AUTH_TYPE               HTTP_HOST          REMOTE_IDENT
  63. #   CONTENT_LENGTH          HTTP_NEGOTIATE     REMOTE_USER
  64. #   CONTENT_TYPE            HTTP_PRAGMA        REQUEST_METHOD
  65. #   GATEWAY_INTERFACE       HTTP_REFERER       SCRIPT_NAME
  66. #   HTTP_ACCEPT             HTTP_USER_AGENT    SERVER_NAME
  67. #   HTTP_ACCEPT_CHARSET     PATH_INFO          SERVER_PORT
  68. #   HTTP_ACCEPT_ENCODING    PATH_TRANSLATED    SERVER_PROTOCOL
  69. #   HTTP_ACCEPT_LANGUAGE    QUERY_STRING       SERVER_SOFTWARE
  70. #   HTTP_CACHE_CONTROL      REMOTE_ADDR
  71. #   HTTP_FROM               REMOTE_HOST
  72. #
  73. #
  74. # For each of these variables, there is a corresponding attribute with the
  75. # same name, except all lower case and without a preceding HTTP_.  
  76. # +content_length+ and +server_port+ are integers; the rest are strings.
  77. #
  78. # === Parameters
  79. #
  80. # The method #params() returns a hash of all parameters in the request as
  81. # name/value-list pairs, where the value-list is an Array of one or more
  82. # values.  The CGI object itself also behaves as a hash of parameter names 
  83. # to values, but only returns a single value (as a String) for each 
  84. # parameter name.
  85. #
  86. # For instance, suppose the request contains the parameter 
  87. # "favourite_colours" with the multiple values "blue" and "green".  The
  88. # following behaviour would occur:
  89. #
  90. #   cgi.params["favourite_colours"]  # => ["blue", "green"]
  91. #   cgi["favourite_colours"]         # => "blue"
  92. #
  93. # If a parameter does not exist, the former method will return an empty
  94. # array, the latter an empty string.  The simplest way to test for existence
  95. # of a parameter is by the #has_key? method.
  96. #
  97. # === Cookies
  98. #
  99. # HTTP Cookies are automatically parsed from the request.  They are available
  100. # from the #cookies() accessor, which returns a hash from cookie name to
  101. # CGI::Cookie object.
  102. #
  103. # === Multipart requests
  104. #
  105. # If a request's method is POST and its content type is multipart/form-data, 
  106. # then it may contain uploaded files.  These are stored by the QueryExtension
  107. # module in the parameters of the request.  The parameter name is the name
  108. # attribute of the file input field, as usual.  However, the value is not
  109. # a string, but an IO object, either an IOString for small files, or a
  110. # Tempfile for larger ones.  This object also has the additional singleton
  111. # methods:
  112. #
  113. # #local_path():: the path of the uploaded file on the local filesystem
  114. # #original_filename():: the name of the file on the client computer
  115. # #content_type():: the content type of the file
  116. #
  117. # == Responses
  118. #
  119. # The CGI class provides methods for sending header and content output to
  120. # the HTTP client, and mixes in methods for programmatic HTML generation
  121. # from CGI::HtmlExtension and CGI::TagMaker modules.  The precise version of HTML
  122. # to use for HTML generation is specified at object creation time.
  123. #
  124. # === Writing output
  125. #
  126. # The simplest way to send output to the HTTP client is using the #out() method.
  127. # This takes the HTTP headers as a hash parameter, and the body content
  128. # via a block.  The headers can be generated as a string using the #header()
  129. # method.  The output stream can be written directly to using the #print()
  130. # method.
  131. #
  132. # === Generating HTML
  133. #
  134. # Each HTML element has a corresponding method for generating that
  135. # element as a String.  The name of this method is the same as that
  136. # of the element, all lowercase.  The attributes of the element are 
  137. # passed in as a hash, and the body as a no-argument block that evaluates
  138. # to a String.  The HTML generation module knows which elements are
  139. # always empty, and silently drops any passed-in body.  It also knows
  140. # which elements require matching closing tags and which don't.  However,
  141. # it does not know what attributes are legal for which elements.
  142. #
  143. # There are also some additional HTML generation methods mixed in from
  144. # the CGI::HtmlExtension module.  These include individual methods for the
  145. # different types of form inputs, and methods for elements that commonly
  146. # take particular attributes where the attributes can be directly specified
  147. # as arguments, rather than via a hash.
  148. #
  149. # == Examples of use
  150. # === Get form values
  151. #   require "cgi"
  152. #   cgi = CGI.new
  153. #   value = cgi['field_name']   # <== value string for 'field_name'
  154. #     # if not 'field_name' included, then return "".
  155. #   fields = cgi.keys            # <== array of field names
  156. #   # returns true if form has 'field_name'
  157. #   cgi.has_key?('field_name')
  158. #   cgi.has_key?('field_name')
  159. #   cgi.include?('field_name')
  160. # CAUTION! cgi['field_name'] returned an Array with the old 
  161. # cgi.rb(included in ruby 1.6)
  162. # === Get form values as hash
  163. #   require "cgi"
  164. #   cgi = CGI.new
  165. #   params = cgi.params
  166. # cgi.params is a hash.
  167. #   cgi.params['new_field_name'] = ["value"]  # add new param
  168. #   cgi.params['field_name'] = ["new_value"]  # change value
  169. #   cgi.params.delete('field_name')           # delete param
  170. #   cgi.params.clear                          # delete all params
  171. # === Save form values to file
  172. #   require "pstore"
  173. #   db = PStore.new("query.db")
  174. #   db.transaction do
  175. #     db["params"] = cgi.params
  176. #   end
  177. # === Restore form values from file
  178. #   require "pstore"
  179. #   db = PStore.new("query.db")
  180. #   db.transaction do
  181. #     cgi.params = db["params"]
  182. #   end
  183. # === Get multipart form values
  184. #   require "cgi"
  185. #   cgi = CGI.new
  186. #   value = cgi['field_name']   # <== value string for 'field_name'
  187. #   value.read                  # <== body of value
  188. #   value.local_path            # <== path to local file of value
  189. #   value.original_filename     # <== original filename of value
  190. #   value.content_type          # <== content_type of value
  191. # and value has StringIO or Tempfile class methods.
  192. # === Get cookie values
  193. #   require "cgi"
  194. #   cgi = CGI.new
  195. #   values = cgi.cookies['name']  # <== array of 'name'
  196. #     # if not 'name' included, then return [].
  197. #   names = cgi.cookies.keys      # <== array of cookie names
  198. # and cgi.cookies is a hash.
  199. # === Get cookie objects
  200. #   require "cgi"
  201. #   cgi = CGI.new
  202. #   for name, cookie in cgi.cookies
  203. #     cookie.expires = Time.now + 30
  204. #   end
  205. #   cgi.out("cookie" => cgi.cookies) {"string"}
  206. #   cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
  207. #   require "cgi"
  208. #   cgi = CGI.new
  209. #   cgi.cookies['name'].expires = Time.now + 30
  210. #   cgi.out("cookie" => cgi.cookies['name']) {"string"}
  211. # === Print http header and html string to $DEFAULT_OUTPUT ($>)
  212. #   require "cgi"
  213. #   cgi = CGI.new("html3")  # add HTML generation methods
  214. #   cgi.out() do
  215. #     cgi.html() do
  216. #       cgi.head{ cgi.title{"TITLE"} } +
  217. #       cgi.body() do
  218. #         cgi.form() do
  219. #           cgi.textarea("get_text") +
  220. #           cgi.br +
  221. #           cgi.submit
  222. #         end +
  223. #         cgi.pre() do
  224. #           CGI::escapeHTML(
  225. #             "params: " + cgi.params.inspect + "\n" +
  226. #             "cookies: " + cgi.cookies.inspect + "\n" +
  227. #             ENV.collect() do |key, value|
  228. #               key + " --> " + value + "\n"
  229. #             end.join("")
  230. #           )
  231. #         end
  232. #       end
  233. #     end
  234. #   end
  235. #   # add HTML generation methods
  236. #   CGI.new("html3")    # html3.2
  237. #   CGI.new("html4")    # html4.01 (Strict)
  238. #   CGI.new("html4Tr")  # html4.01 Transitional
  239. #   CGI.new("html4Fr")  # html4.01 Frameset
  240. #
  241. class CGI
  242.  
  243.   # :stopdoc:
  244.  
  245.   # String for carriage return
  246.   CR  = "\015"
  247.  
  248.   # String for linefeed
  249.   LF  = "\012"
  250.  
  251.   # Standard internet newline sequence
  252.   EOL = CR + LF
  253.  
  254.   REVISION = '$Id: cgi.rb,v 1.68.2.17 2006/09/04 07:36:49 matz Exp $' #:nodoc:
  255.  
  256.   NEEDS_BINMODE = true if /WIN/ni.match(RUBY_PLATFORM) 
  257.  
  258.   # Path separators in different environments.
  259.   PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'}
  260.  
  261.   # HTTP status codes.
  262.   HTTP_STATUS = {
  263.     "OK"                  => "200 OK",
  264.     "PARTIAL_CONTENT"     => "206 Partial Content",
  265.     "MULTIPLE_CHOICES"    => "300 Multiple Choices",
  266.     "MOVED"               => "301 Moved Permanently",
  267.     "REDIRECT"            => "302 Found",
  268.     "NOT_MODIFIED"        => "304 Not Modified",
  269.     "BAD_REQUEST"         => "400 Bad Request",
  270.     "AUTH_REQUIRED"       => "401 Authorization Required",
  271.     "FORBIDDEN"           => "403 Forbidden",
  272.     "NOT_FOUND"           => "404 Not Found",
  273.     "METHOD_NOT_ALLOWED"  => "405 Method Not Allowed",
  274.     "NOT_ACCEPTABLE"      => "406 Not Acceptable",
  275.     "LENGTH_REQUIRED"     => "411 Length Required",
  276.     "PRECONDITION_FAILED" => "412 Rrecondition Failed",
  277.     "SERVER_ERROR"        => "500 Internal Server Error",
  278.     "NOT_IMPLEMENTED"     => "501 Method Not Implemented",
  279.     "BAD_GATEWAY"         => "502 Bad Gateway",
  280.     "VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates"
  281.   }
  282.  
  283.   # Abbreviated day-of-week names specified by RFC 822
  284.   RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ]
  285.  
  286.   # Abbreviated month names specified by RFC 822
  287.   RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]
  288.  
  289.   # :startdoc:
  290.  
  291.   def env_table 
  292.     ENV
  293.   end
  294.  
  295.   def stdinput
  296.     $stdin
  297.   end
  298.  
  299.   def stdoutput
  300.     $DEFAULT_OUTPUT
  301.   end
  302.  
  303.   private :env_table, :stdinput, :stdoutput
  304.  
  305.   # URL-encode a string.
  306.   #   url_encoded_string = CGI::escape("'Stop!' said Fred")
  307.   #      # => "%27Stop%21%27+said+Fred"
  308.   def CGI::escape(string)
  309.     string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
  310.       '%' + $1.unpack('H2' * $1.size).join('%').upcase
  311.     end.tr(' ', '+')
  312.   end
  313.  
  314.  
  315.   # URL-decode a string.
  316.   #   string = CGI::unescape("%27Stop%21%27+said+Fred")
  317.   #      # => "'Stop!' said Fred"
  318.   def CGI::unescape(string)
  319.     string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
  320.       [$1.delete('%')].pack('H*')
  321.     end
  322.   end
  323.  
  324.  
  325.   # Escape special characters in HTML, namely &\"<>
  326.   #   CGI::escapeHTML('Usage: foo "bar" <baz>')
  327.   #      # => "Usage: foo "bar" <baz>"
  328.   def CGI::escapeHTML(string)
  329.     string.gsub(/&/n, '&').gsub(/\"/n, '"').gsub(/>/n, '>').gsub(/</n, '<')
  330.   end
  331.  
  332.  
  333.   # Unescape a string that has been HTML-escaped
  334.   #   CGI::unescapeHTML("Usage: foo "bar" <baz>")
  335.   #      # => "Usage: foo \"bar\" <baz>"
  336.   def CGI::unescapeHTML(string)
  337.     string.gsub(/&(.*?);/n) do
  338.       match = $1.dup
  339.       case match
  340.       when /\Aamp\z/ni           then '&'
  341.       when /\Aquot\z/ni          then '"'
  342.       when /\Agt\z/ni            then '>'
  343.       when /\Alt\z/ni            then '<'
  344.       when /\A#0*(\d+)\z/n       then
  345.         if Integer($1) < 256
  346.           Integer($1).chr
  347.         else
  348.           if Integer($1) < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
  349.             [Integer($1)].pack("U")
  350.           else
  351.             "&##{$1};"
  352.           end
  353.         end
  354.       when /\A#x([0-9a-f]+)\z/ni then
  355.         if $1.hex < 256
  356.           $1.hex.chr
  357.         else
  358.           if $1.hex < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
  359.             [$1.hex].pack("U")
  360.           else
  361.             "&#x#{$1};"
  362.           end
  363.         end
  364.       else
  365.         "&#{match};"
  366.       end
  367.     end
  368.   end
  369.  
  370.  
  371.   # Escape only the tags of certain HTML elements in +string+.
  372.   #
  373.   # Takes an element or elements or array of elements.  Each element
  374.   # is specified by the name of the element, without angle brackets.
  375.   # This matches both the start and the end tag of that element.
  376.   # The attribute list of the open tag will also be escaped (for
  377.   # instance, the double-quotes surrounding attribute values).
  378.   #
  379.   #   print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
  380.   #     # "<BR><A HREF="url"></A>"
  381.   #
  382.   #   print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
  383.   #     # "<BR><A HREF="url"></A>"
  384.   def CGI::escapeElement(string, *elements)
  385.     elements = elements[0] if elements[0].kind_of?(Array)
  386.     unless elements.empty?
  387.       string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
  388.         CGI::escapeHTML($&)
  389.       end
  390.     else
  391.       string
  392.     end
  393.   end
  394.  
  395.  
  396.   # Undo escaping such as that done by CGI::escapeElement()
  397.   #
  398.   #   print CGI::unescapeElement(
  399.   #           CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
  400.   #     # "<BR><A HREF="url"></A>"
  401.   # 
  402.   #   print CGI::unescapeElement(
  403.   #           CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
  404.   #     # "<BR><A HREF="url"></A>"
  405.   def CGI::unescapeElement(string, *elements)
  406.     elements = elements[0] if elements[0].kind_of?(Array)
  407.     unless elements.empty?
  408.       string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
  409.         CGI::unescapeHTML($&)
  410.       end
  411.     else
  412.       string
  413.     end
  414.   end
  415.  
  416.  
  417.   # Format a +Time+ object as a String using the format specified by RFC 1123.
  418.   #
  419.   #   CGI::rfc1123_date(Time.now)
  420.   #     # Sat, 01 Jan 2000 00:00:00 GMT
  421.   def CGI::rfc1123_date(time)
  422.     t = time.clone.gmtime
  423.     return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
  424.                 RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
  425.                 t.hour, t.min, t.sec)
  426.   end
  427.  
  428.  
  429.   # Create an HTTP header block as a string.
  430.   #
  431.   # Includes the empty line that ends the header block.
  432.   #
  433.   # +options+ can be a string specifying the Content-Type (defaults
  434.   # to text/html), or a hash of header key/value pairs.  The following
  435.   # header keys are recognized:
  436.   #
  437.   # type:: the Content-Type header.  Defaults to "text/html"
  438.   # charset:: the charset of the body, appended to the Content-Type header.
  439.   # nph:: a boolean value.  If true, prepend protocol string and status code, and
  440.   #       date; and sets default values for "server" and "connection" if not
  441.   #       explicitly set.
  442.   # status:: the HTTP status code, returned as the Status header.  See the
  443.   #          list of available status codes below.
  444.   # server:: the server software, returned as the Server header.
  445.   # connection:: the connection type, returned as the Connection header (for 
  446.   #              instance, "close".
  447.   # length:: the length of the content that will be sent, returned as the
  448.   #          Content-Length header.
  449.   # language:: the language of the content, returned as the Content-Language
  450.   #            header.
  451.   # expires:: the time on which the current content expires, as a +Time+
  452.   #           object, returned as the Expires header.
  453.   # cookie:: a cookie or cookies, returned as one or more Set-Cookie headers.
  454.   #          The value can be the literal string of the cookie; a CGI::Cookie
  455.   #          object; an Array of literal cookie strings or Cookie objects; or a 
  456.   #          hash all of whose values are literal cookie strings or Cookie objects.
  457.   #          These cookies are in addition to the cookies held in the
  458.   #          @output_cookies field.
  459.   #
  460.   # Other header lines can also be set; they are appended as key: value.
  461.   # 
  462.   #   header
  463.   #     # Content-Type: text/html
  464.   # 
  465.   #   header("text/plain")
  466.   #     # Content-Type: text/plain
  467.   # 
  468.   #   header("nph"        => true,
  469.   #          "status"     => "OK",  # == "200 OK"
  470.   #            # "status"     => "200 GOOD",
  471.   #          "server"     => ENV['SERVER_SOFTWARE'],
  472.   #          "connection" => "close",
  473.   #          "type"       => "text/html",
  474.   #          "charset"    => "iso-2022-jp",
  475.   #            # Content-Type: text/html; charset=iso-2022-jp
  476.   #          "length"     => 103,
  477.   #          "language"   => "ja",
  478.   #          "expires"    => Time.now + 30,
  479.   #          "cookie"     => [cookie1, cookie2],
  480.   #          "my_header1" => "my_value"
  481.   #          "my_header2" => "my_value")
  482.   # 
  483.   # The status codes are:
  484.   # 
  485.   #   "OK"                  --> "200 OK"
  486.   #   "PARTIAL_CONTENT"     --> "206 Partial Content"
  487.   #   "MULTIPLE_CHOICES"    --> "300 Multiple Choices"
  488.   #   "MOVED"               --> "301 Moved Permanently"
  489.   #   "REDIRECT"            --> "302 Found"
  490.   #   "NOT_MODIFIED"        --> "304 Not Modified"
  491.   #   "BAD_REQUEST"         --> "400 Bad Request"
  492.   #   "AUTH_REQUIRED"       --> "401 Authorization Required"
  493.   #   "FORBIDDEN"           --> "403 Forbidden"
  494.   #   "NOT_FOUND"           --> "404 Not Found"
  495.   #   "METHOD_NOT_ALLOWED"  --> "405 Method Not Allowed"
  496.   #   "NOT_ACCEPTABLE"      --> "406 Not Acceptable"
  497.   #   "LENGTH_REQUIRED"     --> "411 Length Required"
  498.   #   "PRECONDITION_FAILED" --> "412 Precondition Failed"
  499.   #   "SERVER_ERROR"        --> "500 Internal Server Error"
  500.   #   "NOT_IMPLEMENTED"     --> "501 Method Not Implemented"
  501.   #   "BAD_GATEWAY"         --> "502 Bad Gateway"
  502.   #   "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates"
  503.   # 
  504.   # This method does not perform charset conversion. 
  505.   #
  506.   def header(options = "text/html")
  507.  
  508.     buf = ""
  509.  
  510.     case options
  511.     when String
  512.       options = { "type" => options }
  513.     when Hash
  514.       options = options.dup
  515.     end
  516.  
  517.     unless options.has_key?("type")
  518.       options["type"] = "text/html"
  519.     end
  520.  
  521.     if options.has_key?("charset")
  522.       options["type"] += "; charset=" + options.delete("charset")
  523.     end
  524.  
  525.     options.delete("nph") if defined?(MOD_RUBY)
  526.     if options.delete("nph") or /IIS/n.match(env_table['SERVER_SOFTWARE'])
  527.       buf += (env_table["SERVER_PROTOCOL"] or "HTTP/1.0")  + " " +
  528.              (HTTP_STATUS[options["status"]] or options["status"] or "200 OK") +
  529.              EOL +
  530.              "Date: " + CGI::rfc1123_date(Time.now) + EOL
  531.  
  532.       unless options.has_key?("server")
  533.         options["server"] = (env_table['SERVER_SOFTWARE'] or "")
  534.       end
  535.  
  536.       unless options.has_key?("connection")
  537.         options["connection"] = "close"
  538.       end
  539.  
  540.       options.delete("status")
  541.     end
  542.  
  543.     if options.has_key?("status")
  544.       buf += "Status: " +
  545.              (HTTP_STATUS[options["status"]] or options["status"]) + EOL
  546.       options.delete("status")
  547.     end
  548.  
  549.     if options.has_key?("server")
  550.       buf += "Server: " + options.delete("server") + EOL
  551.     end
  552.  
  553.     if options.has_key?("connection")
  554.       buf += "Connection: " + options.delete("connection") + EOL
  555.     end
  556.  
  557.     buf += "Content-Type: " + options.delete("type") + EOL
  558.  
  559.     if options.has_key?("length")
  560.       buf += "Content-Length: " + options.delete("length").to_s + EOL
  561.     end
  562.  
  563.     if options.has_key?("language")
  564.       buf += "Content-Language: " + options.delete("language") + EOL
  565.     end
  566.  
  567.     if options.has_key?("expires")
  568.       buf += "Expires: " + CGI::rfc1123_date( options.delete("expires") ) + EOL
  569.     end
  570.  
  571.     if options.has_key?("cookie")
  572.       if options["cookie"].kind_of?(String) or
  573.            options["cookie"].kind_of?(Cookie)
  574.         buf += "Set-Cookie: " + options.delete("cookie").to_s + EOL
  575.       elsif options["cookie"].kind_of?(Array)
  576.         options.delete("cookie").each{|cookie|
  577.           buf += "Set-Cookie: " + cookie.to_s + EOL
  578.         }
  579.       elsif options["cookie"].kind_of?(Hash)
  580.         options.delete("cookie").each_value{|cookie|
  581.           buf += "Set-Cookie: " + cookie.to_s + EOL
  582.         }
  583.       end
  584.     end
  585.     if @output_cookies
  586.       for cookie in @output_cookies
  587.         buf += "Set-Cookie: " + cookie.to_s + EOL
  588.       end
  589.     end
  590.  
  591.     options.each{|key, value|
  592.       buf += key + ": " + value.to_s + EOL
  593.     }
  594.  
  595.     if defined?(MOD_RUBY)
  596.       table = Apache::request.headers_out
  597.       buf.scan(/([^:]+): (.+)#{EOL}/n){ |name, value|
  598.         warn sprintf("name:%s value:%s\n", name, value) if $DEBUG
  599.         case name
  600.         when 'Set-Cookie'
  601.           table.add(name, value)
  602.         when /^status$/ni
  603.           Apache::request.status_line = value
  604.           Apache::request.status = value.to_i
  605.         when /^content-type$/ni
  606.           Apache::request.content_type = value
  607.         when /^content-encoding$/ni
  608.           Apache::request.content_encoding = value
  609.         when /^location$/ni
  610.       if Apache::request.status == 200
  611.         Apache::request.status = 302
  612.       end
  613.           Apache::request.headers_out[name] = value
  614.         else
  615.           Apache::request.headers_out[name] = value
  616.         end
  617.       }
  618.       Apache::request.send_http_header
  619.       ''
  620.     else
  621.       buf + EOL
  622.     end
  623.  
  624.   end # header()
  625.  
  626.  
  627.   # Print an HTTP header and body to $DEFAULT_OUTPUT ($>)
  628.   #
  629.   # The header is provided by +options+, as for #header().
  630.   # The body of the document is that returned by the passed-
  631.   # in block.  This block takes no arguments.  It is required.
  632.   #
  633.   #   cgi = CGI.new
  634.   #   cgi.out{ "string" }
  635.   #     # Content-Type: text/html
  636.   #     # Content-Length: 6
  637.   #     #
  638.   #     # string
  639.   # 
  640.   #   cgi.out("text/plain") { "string" }
  641.   #     # Content-Type: text/plain
  642.   #     # Content-Length: 6
  643.   #     #
  644.   #     # string
  645.   # 
  646.   #   cgi.out("nph"        => true,
  647.   #           "status"     => "OK",  # == "200 OK"
  648.   #           "server"     => ENV['SERVER_SOFTWARE'],
  649.   #           "connection" => "close",
  650.   #           "type"       => "text/html",
  651.   #           "charset"    => "iso-2022-jp",
  652.   #             # Content-Type: text/html; charset=iso-2022-jp
  653.   #           "language"   => "ja",
  654.   #           "expires"    => Time.now + (3600 * 24 * 30),
  655.   #           "cookie"     => [cookie1, cookie2],
  656.   #           "my_header1" => "my_value",
  657.   #           "my_header2" => "my_value") { "string" }
  658.   # 
  659.   # Content-Length is automatically calculated from the size of
  660.   # the String returned by the content block.
  661.   #
  662.   # If ENV['REQUEST_METHOD'] == "HEAD", then only the header
  663.   # is outputted (the content block is still required, but it
  664.   # is ignored).
  665.   # 
  666.   # If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then
  667.   # the content is converted to this charset, and the language is set 
  668.   # to "ja".
  669.   def out(options = "text/html") # :yield:
  670.  
  671.     options = { "type" => options } if options.kind_of?(String)
  672.     content = yield
  673.  
  674.     if options.has_key?("charset")
  675.       require "nkf"
  676.       case options["charset"]
  677.       when /iso-2022-jp/ni
  678.         content = NKF::nkf('-m0 -x -j', content)
  679.         options["language"] = "ja" unless options.has_key?("language")
  680.       when /euc-jp/ni
  681.         content = NKF::nkf('-m0 -x -e', content)
  682.         options["language"] = "ja" unless options.has_key?("language")
  683.       when /shift_jis/ni
  684.         content = NKF::nkf('-m0 -x -s', content)
  685.         options["language"] = "ja" unless options.has_key?("language")
  686.       end
  687.     end
  688.  
  689.     options["length"] = content.length.to_s
  690.     output = stdoutput
  691.     output.binmode if defined? output.binmode
  692.     output.print header(options)
  693.     output.print content unless "HEAD" == env_table['REQUEST_METHOD']
  694.   end
  695.  
  696.  
  697.   # Print an argument or list of arguments to the default output stream
  698.   #
  699.   #   cgi = CGI.new
  700.   #   cgi.print    # default:  cgi.print == $DEFAULT_OUTPUT.print
  701.   def print(*options)
  702.     stdoutput.print(*options)
  703.   end
  704.  
  705.   require "delegate"
  706.  
  707.   # Class representing an HTTP cookie.
  708.   #
  709.   # In addition to its specific fields and methods, a Cookie instance
  710.   # is a delegator to the array of its values.
  711.   #
  712.   # See RFC 2965.
  713.   #
  714.   # == Examples of use
  715.   #   cookie1 = CGI::Cookie::new("name", "value1", "value2", ...)
  716.   #   cookie1 = CGI::Cookie::new("name" => "name", "value" => "value")
  717.   #   cookie1 = CGI::Cookie::new('name'    => 'name',
  718.   #                              'value'   => ['value1', 'value2', ...],
  719.   #                              'path'    => 'path',   # optional
  720.   #                              'domain'  => 'domain', # optional
  721.   #                              'expires' => Time.now, # optional
  722.   #                              'secure'  => true      # optional
  723.   #                             )
  724.   # 
  725.   #   cgi.out("cookie" => [cookie1, cookie2]) { "string" }
  726.   # 
  727.   #   name    = cookie1.name
  728.   #   values  = cookie1.value
  729.   #   path    = cookie1.path
  730.   #   domain  = cookie1.domain
  731.   #   expires = cookie1.expires
  732.   #   secure  = cookie1.secure
  733.   # 
  734.   #   cookie1.name    = 'name'
  735.   #   cookie1.value   = ['value1', 'value2', ...]
  736.   #   cookie1.path    = 'path'
  737.   #   cookie1.domain  = 'domain'
  738.   #   cookie1.expires = Time.now + 30
  739.   #   cookie1.secure  = true
  740.   class Cookie < DelegateClass(Array)
  741.  
  742.     # Create a new CGI::Cookie object.
  743.     #
  744.     # The contents of the cookie can be specified as a +name+ and one
  745.     # or more +value+ arguments.  Alternatively, the contents can
  746.     # be specified as a single hash argument.  The possible keywords of
  747.     # this hash are as follows:
  748.     #
  749.     # name:: the name of the cookie.  Required.
  750.     # value:: the cookie's value or list of values.
  751.     # path:: the path for which this cookie applies.  Defaults to the
  752.     #        base directory of the CGI script.
  753.     # domain:: the domain for which this cookie applies.
  754.     # expires:: the time at which this cookie expires, as a +Time+ object.
  755.     # secure:: whether this cookie is a secure cookie or not (default to
  756.     #          false).  Secure cookies are only transmitted to HTTPS 
  757.     #          servers.
  758.     #
  759.     # These keywords correspond to attributes of the cookie object.
  760.     def initialize(name = "", *value)
  761.       options = if name.kind_of?(String)
  762.                   { "name" => name, "value" => value }
  763.                 else
  764.                   name
  765.                 end
  766.       unless options.has_key?("name")
  767.         raise ArgumentError, "`name' required"
  768.       end
  769.  
  770.       @name = options["name"]
  771.       @value = Array(options["value"])
  772.       # simple support for IE
  773.       if options["path"]
  774.         @path = options["path"]
  775.       else
  776.         %r|^(.*/)|.match(ENV["SCRIPT_NAME"])
  777.         @path = ($1 or "")
  778.       end
  779.       @domain = options["domain"]
  780.       @expires = options["expires"]
  781.       @secure = options["secure"] == true ? true : false
  782.  
  783.       super(@value)
  784.     end
  785.  
  786.     attr_accessor("name", "value", "path", "domain", "expires")
  787.     attr_reader("secure")
  788.  
  789.     # Set whether the Cookie is a secure cookie or not.
  790.     #
  791.     # +val+ must be a boolean.
  792.     def secure=(val)
  793.       @secure = val if val == true or val == false
  794.       @secure
  795.     end
  796.  
  797.     # Convert the Cookie to its string representation.
  798.     def to_s
  799.       buf = ""
  800.       buf += @name + '='
  801.  
  802.       if @value.kind_of?(String)
  803.         buf += CGI::escape(@value)
  804.       else
  805.         buf += @value.collect{|v| CGI::escape(v) }.join("&")
  806.       end
  807.  
  808.       if @domain
  809.         buf += '; domain=' + @domain
  810.       end
  811.  
  812.       if @path
  813.         buf += '; path=' + @path
  814.       end
  815.  
  816.       if @expires
  817.         buf += '; expires=' + CGI::rfc1123_date(@expires)
  818.       end
  819.  
  820.       if @secure == true
  821.         buf += '; secure'
  822.       end
  823.  
  824.       buf
  825.     end
  826.  
  827.   end # class Cookie
  828.  
  829.  
  830.   # Parse a raw cookie string into a hash of cookie-name=>Cookie
  831.   # pairs.
  832.   #
  833.   #   cookies = CGI::Cookie::parse("raw_cookie_string")
  834.   #     # { "name1" => cookie1, "name2" => cookie2, ... }
  835.   #
  836.   def Cookie::parse(raw_cookie)
  837.     cookies = Hash.new([])
  838.     return cookies unless raw_cookie
  839.  
  840.     raw_cookie.split(/[;,]\s?/).each do |pairs|
  841.       name, values = pairs.split('=',2)
  842.       next unless name and values
  843.       name = CGI::unescape(name)
  844.       values ||= ""
  845.       values = values.split('&').collect{|v| CGI::unescape(v) }
  846.       if cookies.has_key?(name)
  847.         values = cookies[name].value + values
  848.       end
  849.       cookies[name] = Cookie::new({ "name" => name, "value" => values })
  850.     end
  851.  
  852.     cookies
  853.   end
  854.  
  855.   # Parse an HTTP query string into a hash of key=>value pairs.
  856.   #
  857.   #   params = CGI::parse("query_string")
  858.   #     # {"name1" => ["value1", "value2", ...],
  859.   #     #  "name2" => ["value1", "value2", ...], ... }
  860.   #
  861.   def CGI::parse(query)
  862.     params = Hash.new([].freeze)
  863.  
  864.     query.split(/[&;]/n).each do |pairs|
  865.       key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
  866.       if params.has_key?(key)
  867.         params[key].push(value)
  868.       else
  869.         params[key] = [value]
  870.       end
  871.     end
  872.  
  873.     params
  874.   end
  875.  
  876.   # Mixin module. It provides the follow functionality groups:
  877.   #
  878.   # 1. Access to CGI environment variables as methods.  See 
  879.   #    documentation to the CGI class for a list of these variables.
  880.   #
  881.   # 2. Access to cookies, including the cookies attribute.
  882.   #
  883.   # 3. Access to parameters, including the params attribute, and overloading
  884.   #    [] to perform parameter value lookup by key.
  885.   #
  886.   # 4. The initialize_query method, for initialising the above
  887.   #    mechanisms, handling multipart forms, and allowing the
  888.   #    class to be used in "offline" mode.
  889.   #
  890.   module QueryExtension
  891.  
  892.     %w[ CONTENT_LENGTH SERVER_PORT ].each do |env|
  893.       define_method(env.sub(/^HTTP_/n, '').downcase) do
  894.         (val = env_table[env]) && Integer(val)
  895.       end
  896.     end
  897.  
  898.     %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
  899.         PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST
  900.         REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME
  901.         SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE
  902.  
  903.         HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
  904.         HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
  905.         HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env|
  906.       define_method(env.sub(/^HTTP_/n, '').downcase) do
  907.         env_table[env]
  908.       end
  909.     end
  910.  
  911.     # Get the raw cookies as a string.
  912.     def raw_cookie
  913.       env_table["HTTP_COOKIE"]
  914.     end
  915.  
  916.     # Get the raw RFC2965 cookies as a string.
  917.     def raw_cookie2
  918.       env_table["HTTP_COOKIE2"]
  919.     end
  920.  
  921.     # Get the cookies as a hash of cookie-name=>Cookie pairs.
  922.     attr_accessor("cookies")
  923.  
  924.     # Get the parameters as a hash of name=>values pairs, where
  925.     # values is an Array.
  926.     attr("params")
  927.  
  928.     # Set all the parameters.
  929.     def params=(hash)
  930.       @params.clear
  931.       @params.update(hash)
  932.     end
  933.  
  934.     def read_multipart(boundary, content_length)
  935.       params = Hash.new([])
  936.       boundary = "--" + boundary
  937.       quoted_boundary = Regexp.quote(boundary, "n")
  938.       buf = ""
  939.       bufsize = 10 * 1024
  940.       boundary_end=""
  941.  
  942.       # start multipart/form-data
  943.       stdinput.binmode if defined? stdinput.binmode
  944.       boundary_size = boundary.size + EOL.size
  945.       content_length -= boundary_size
  946.       status = stdinput.read(boundary_size)
  947.       if nil == status
  948.         raise EOFError, "no content body"
  949.       elsif boundary + EOL != status
  950.         raise EOFError, "bad content body"
  951.       end
  952.  
  953.       loop do
  954.         head = nil
  955.         if 10240 < content_length
  956.           require "tempfile"
  957.           body = Tempfile.new("CGI")
  958.         else
  959.           begin
  960.             require "stringio"
  961.             body = StringIO.new
  962.           rescue LoadError
  963.             require "tempfile"
  964.             body = Tempfile.new("CGI")
  965.           end
  966.         end
  967.         body.binmode if defined? body.binmode
  968.  
  969.         until head and /#{quoted_boundary}(?:#{EOL}|--)/n.match(buf)
  970.  
  971.           if (not head) and /#{EOL}#{EOL}/n.match(buf)
  972.             buf = buf.sub(/\A((?:.|\n)*?#{EOL})#{EOL}/n) do
  973.               head = $1.dup
  974.               ""
  975.             end
  976.             next
  977.           end
  978.  
  979.           if head and ( (EOL + boundary + EOL).size < buf.size )
  980.             body.print buf[0 ... (buf.size - (EOL + boundary + EOL).size)]
  981.             buf[0 ... (buf.size - (EOL + boundary + EOL).size)] = ""
  982.           end
  983.  
  984.           c = if bufsize < content_length
  985.                 stdinput.read(bufsize)
  986.               else
  987.                 stdinput.read(content_length)
  988.               end
  989.           if c.nil? || c.empty?
  990.             raise EOFError, "bad content body"
  991.           end
  992.           buf.concat(c)
  993.           content_length -= c.size
  994.         end
  995.  
  996.         buf = buf.sub(/\A((?:.|\n)*?)(?:[\r\n]{1,2})?#{quoted_boundary}([\r\n]{1,2}|--)/n) do
  997.           body.print $1
  998.           if "--" == $2
  999.             content_length = -1
  1000.           end
  1001.          boundary_end = $2.dup
  1002.           ""
  1003.         end
  1004.  
  1005.         body.rewind
  1006.  
  1007.         /Content-Disposition:.* filename="?([^\";]*)"?/ni.match(head)
  1008.     filename = ($1 or "")
  1009.     if /Mac/ni.match(env_table['HTTP_USER_AGENT']) and
  1010.         /Mozilla/ni.match(env_table['HTTP_USER_AGENT']) and
  1011.         (not /MSIE/ni.match(env_table['HTTP_USER_AGENT']))
  1012.       filename = CGI::unescape(filename)
  1013.     end
  1014.         
  1015.         /Content-Type: (.*)/ni.match(head)
  1016.         content_type = ($1 or "")
  1017.  
  1018.         (class << body; self; end).class_eval do
  1019.           alias local_path path
  1020.           define_method(:original_filename) {filename.dup.taint}
  1021.           define_method(:content_type) {content_type.dup.taint}
  1022.         end
  1023.  
  1024.         /Content-Disposition:.* name="?([^\";]*)"?/ni.match(head)
  1025.         name = $1.dup
  1026.  
  1027.         if params.has_key?(name)
  1028.           params[name].push(body)
  1029.         else
  1030.           params[name] = [body]
  1031.         end
  1032.         break if buf.size == 0
  1033.         break if content_length === -1
  1034.       end
  1035.       raise EOFError, "bad boundary end of body part" unless boundary_end=~/--/
  1036.  
  1037.       params
  1038.     end # read_multipart
  1039.     private :read_multipart
  1040.  
  1041.     # offline mode. read name=value pairs on standard input.
  1042.     def read_from_cmdline
  1043.       require "shellwords"
  1044.  
  1045.       string = unless ARGV.empty?
  1046.         ARGV.join(' ')
  1047.       else
  1048.         if STDIN.tty?
  1049.           STDERR.print(
  1050.             %|(offline mode: enter name=value pairs on standard input)\n|
  1051.           )
  1052.         end
  1053.         readlines.join(' ').gsub(/\n/n, '')
  1054.       end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26')
  1055.  
  1056.       words = Shellwords.shellwords(string)
  1057.  
  1058.       if words.find{|x| /=/n.match(x) }
  1059.         words.join('&')
  1060.       else
  1061.         words.join('+')
  1062.       end
  1063.     end
  1064.     private :read_from_cmdline
  1065.  
  1066.     # Initialize the data from the query.
  1067.     #
  1068.     # Handles multipart forms (in particular, forms that involve file uploads).
  1069.     # Reads query parameters in the @params field, and cookies into @cookies.
  1070.     def initialize_query()
  1071.       if ("POST" == env_table['REQUEST_METHOD']) and
  1072.          %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n.match(env_table['CONTENT_TYPE'])
  1073.         boundary = $1.dup
  1074.         @multipart = true
  1075.         @params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
  1076.       else
  1077.         @multipart = false
  1078.         @params = CGI::parse(
  1079.                     case env_table['REQUEST_METHOD']
  1080.                     when "GET", "HEAD"
  1081.                       if defined?(MOD_RUBY)
  1082.                         Apache::request.args or ""
  1083.                       else
  1084.                         env_table['QUERY_STRING'] or ""
  1085.                       end
  1086.                     when "POST"
  1087.                       stdinput.binmode if defined? stdinput.binmode
  1088.                       stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
  1089.                     else
  1090.                       read_from_cmdline
  1091.                     end
  1092.                   )
  1093.       end
  1094.  
  1095.       @cookies = CGI::Cookie::parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
  1096.     end
  1097.     private :initialize_query
  1098.  
  1099.     def multipart?
  1100.       @multipart
  1101.     end
  1102.  
  1103.     module Value    # :nodoc:
  1104.       def set_params(params)
  1105.         @params = params
  1106.       end
  1107.       def [](idx, *args)
  1108.         if args.size == 0
  1109.           warn "#{caller(1)[0]}:CAUTION! cgi['key'] == cgi.params['key'][0]; if want Array, use cgi.params['key']"
  1110.           @params[idx]
  1111.         else
  1112.           super[idx,*args]
  1113.         end
  1114.       end
  1115.       def first
  1116.         warn "#{caller(1)[0]}:CAUTION! cgi['key'] == cgi.params['key'][0]; if want Array, use cgi.params['key']"
  1117.         self
  1118.       end
  1119.       alias last first
  1120.       def to_a
  1121.         @params || [self]
  1122.       end
  1123.       alias to_ary to_a       # to be rhs of multiple assignment
  1124.     end
  1125.  
  1126.     # Get the value for the parameter with a given key.
  1127.     #
  1128.     # If the parameter has multiple values, only the first will be 
  1129.     # retrieved; use #params() to get the array of values.
  1130.     def [](key)
  1131.       params = @params[key]
  1132.       value = params[0]
  1133.       if @multipart
  1134.         if value
  1135.           return value
  1136.         elsif defined? StringIO
  1137.           StringIO.new("")
  1138.         else
  1139.           Tempfile.new("CGI")
  1140.         end
  1141.       else
  1142.         str = if value then value.dup else "" end
  1143.         str.extend(Value)
  1144.         str.set_params(params)
  1145.         str
  1146.       end
  1147.     end
  1148.  
  1149.     # Return all parameter keys as an array.
  1150.     def keys(*args)
  1151.       @params.keys(*args)
  1152.     end
  1153.  
  1154.     # Returns true if a given parameter key exists in the query.
  1155.     def has_key?(*args)
  1156.       @params.has_key?(*args)
  1157.     end
  1158.     alias key? has_key?
  1159.     alias include? has_key?
  1160.  
  1161.   end # QueryExtension
  1162.  
  1163.  
  1164.   # Prettify (indent) an HTML string.
  1165.   #
  1166.   # +string+ is the HTML string to indent.  +shift+ is the indentation
  1167.   # unit to use; it defaults to two spaces.
  1168.   #
  1169.   #   print CGI::pretty("<HTML><BODY></BODY></HTML>")
  1170.   #     # <HTML>
  1171.   #     #   <BODY>
  1172.   #     #   </BODY>
  1173.   #     # </HTML>
  1174.   # 
  1175.   #   print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
  1176.   #     # <HTML>
  1177.   #     #         <BODY>
  1178.   #     #         </BODY>
  1179.   #     # </HTML>
  1180.   #
  1181.   def CGI::pretty(string, shift = "  ")
  1182.     lines = string.gsub(/(?!\A)<(?:.|\n)*?>/n, "\n\\0").gsub(/<(?:.|\n)*?>(?!\n)/n, "\\0\n")
  1183.     end_pos = 0
  1184.     while end_pos = lines.index(/^<\/(\w+)/n, end_pos)
  1185.       element = $1.dup
  1186.       start_pos = lines.rindex(/^\s*<#{element}/ni, end_pos)
  1187.       lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/n, "\n" + shift) + "__"
  1188.     end
  1189.     lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/n, '\1')
  1190.   end
  1191.  
  1192.  
  1193.   # Base module for HTML-generation mixins.
  1194.   #
  1195.   # Provides methods for code generation for tags following
  1196.   # the various DTD element types.
  1197.   module TagMaker # :nodoc:
  1198.  
  1199.     # Generate code for an element with required start and end tags.
  1200.     #
  1201.     #   - -
  1202.     def nn_element_def(element)
  1203.       nOE_element_def(element, <<-END)
  1204.           if block_given?
  1205.             yield.to_s
  1206.           else
  1207.             ""
  1208.           end +
  1209.           "</#{element.upcase}>"
  1210.       END
  1211.     end
  1212.  
  1213.     # Generate code for an empty element.
  1214.     #
  1215.     #   - O EMPTY
  1216.     def nOE_element_def(element, append = nil)
  1217.       s = <<-END
  1218.           "<#{element.upcase}" + attributes.collect{|name, value|
  1219.             next unless value
  1220.             " " + CGI::escapeHTML(name) +
  1221.             if true == value
  1222.               ""
  1223.             else
  1224.               '="' + CGI::escapeHTML(value) + '"'
  1225.             end
  1226.           }.to_s + ">"
  1227.       END
  1228.       s.sub!(/\Z/, " +") << append if append
  1229.       s
  1230.     end
  1231.  
  1232.     # Generate code for an element for which the end (and possibly the
  1233.     # start) tag is optional.
  1234.     #
  1235.     #   O O or - O
  1236.     def nO_element_def(element)
  1237.       nOE_element_def(element, <<-END)
  1238.           if block_given?
  1239.             yield.to_s + "</#{element.upcase}>"
  1240.           else
  1241.             ""
  1242.           end
  1243.       END
  1244.     end
  1245.  
  1246.   end # TagMaker
  1247.  
  1248.  
  1249.   #
  1250.   # Mixin module providing HTML generation methods.
  1251.   #
  1252.   # For example,
  1253.   #   cgi.a("http://www.example.com") { "Example" }
  1254.   #     # => "<A HREF=\"http://www.example.com\">Example</A>"
  1255.   #
  1256.   # Modules Http3, Http4, etc., contain more basic HTML-generation methods
  1257.   # (:title, :center, etc.).
  1258.   #
  1259.   # See class CGI for a detailed example. 
  1260.   #
  1261.   module HtmlExtension
  1262.  
  1263.  
  1264.     # Generate an Anchor element as a string.
  1265.     #
  1266.     # +href+ can either be a string, giving the URL
  1267.     # for the HREF attribute, or it can be a hash of
  1268.     # the element's attributes.
  1269.     #
  1270.     # The body of the element is the string returned by the no-argument
  1271.     # block passed in.
  1272.     #
  1273.     #   a("http://www.example.com") { "Example" }
  1274.     #     # => "<A HREF=\"http://www.example.com\">Example</A>"
  1275.     #
  1276.     #   a("HREF" => "http://www.example.com", "TARGET" => "_top") { "Example" }
  1277.     #     # => "<A HREF=\"http://www.example.com\" TARGET=\"_top\">Example</A>"
  1278.     #
  1279.     def a(href = "") # :yield:
  1280.       attributes = if href.kind_of?(String)
  1281.                      { "HREF" => href }
  1282.                    else
  1283.                      href
  1284.                    end
  1285.       if block_given?
  1286.         super(attributes){ yield }
  1287.       else
  1288.         super(attributes)
  1289.       end
  1290.     end
  1291.  
  1292.     # Generate a Document Base URI element as a String. 
  1293.     #
  1294.     # +href+ can either by a string, giving the base URL for the HREF
  1295.     # attribute, or it can be a has of the element's attributes.
  1296.     #
  1297.     # The passed-in no-argument block is ignored.
  1298.     #
  1299.     #   base("http://www.example.com/cgi")
  1300.     #     # => "<BASE HREF=\"http://www.example.com/cgi\">"
  1301.     def base(href = "") # :yield:
  1302.       attributes = if href.kind_of?(String)
  1303.                      { "HREF" => href }
  1304.                    else
  1305.                      href
  1306.                    end
  1307.       if block_given?
  1308.         super(attributes){ yield }
  1309.       else
  1310.         super(attributes)
  1311.       end
  1312.     end
  1313.  
  1314.     # Generate a BlockQuote element as a string.
  1315.     #
  1316.     # +cite+ can either be a string, give the URI for the source of
  1317.     # the quoted text, or a hash, giving all attributes of the element,
  1318.     # or it can be omitted, in which case the element has no attributes.
  1319.     #
  1320.     # The body is provided by the passed-in no-argument block
  1321.     #
  1322.     #   blockquote("http://www.example.com/quotes/foo.html") { "Foo!" }
  1323.     #     #=> "<BLOCKQUOTE CITE=\"http://www.example.com/quotes/foo.html\">Foo!</BLOCKQUOTE>
  1324.     def blockquote(cite = nil)  # :yield:
  1325.       attributes = if cite.kind_of?(String)
  1326.                      { "CITE" => cite }
  1327.                    else
  1328.                      cite or ""
  1329.                    end
  1330.       if block_given?
  1331.         super(attributes){ yield }
  1332.       else
  1333.         super(attributes)
  1334.       end
  1335.     end
  1336.  
  1337.  
  1338.     # Generate a Table Caption element as a string.
  1339.     #
  1340.     # +align+ can be a string, giving the alignment of the caption
  1341.     # (one of top, bottom, left, or right).  It can be a hash of
  1342.     # all the attributes of the element.  Or it can be omitted.
  1343.     #
  1344.     # The body of the element is provided by the passed-in no-argument block.
  1345.     #
  1346.     #   caption("left") { "Capital Cities" }
  1347.     #     # => <CAPTION ALIGN=\"left\">Capital Cities</CAPTION>
  1348.     def caption(align = nil) # :yield:
  1349.       attributes = if align.kind_of?(String)
  1350.                      { "ALIGN" => align }
  1351.                    else
  1352.                      align or ""
  1353.                    end
  1354.       if block_given?
  1355.         super(attributes){ yield }
  1356.       else
  1357.         super(attributes)
  1358.       end
  1359.     end
  1360.  
  1361.  
  1362.     # Generate a Checkbox Input element as a string.
  1363.     #
  1364.     # The attributes of the element can be specified as three arguments,
  1365.     # +name+, +value+, and +checked+.  +checked+ is a boolean value;
  1366.     # if true, the CHECKED attribute will be included in the element.
  1367.     #
  1368.     # Alternatively, the attributes can be specified as a hash.
  1369.     #
  1370.     #   checkbox("name")
  1371.     #     # = checkbox("NAME" => "name")
  1372.     # 
  1373.     #   checkbox("name", "value")
  1374.     #     # = checkbox("NAME" => "name", "VALUE" => "value")
  1375.     # 
  1376.     #   checkbox("name", "value", true)
  1377.     #     # = checkbox("NAME" => "name", "VALUE" => "value", "CHECKED" => true)
  1378.     def checkbox(name = "", value = nil, checked = nil)
  1379.       attributes = if name.kind_of?(String)
  1380.                      { "TYPE" => "checkbox", "NAME" => name,
  1381.                        "VALUE" => value, "CHECKED" => checked }
  1382.                    else
  1383.                      name["TYPE"] = "checkbox"
  1384.                      name
  1385.                    end
  1386.       input(attributes)
  1387.     end
  1388.  
  1389.     # Generate a sequence of checkbox elements, as a String.
  1390.     #
  1391.     # The checkboxes will all have the same +name+ attribute.
  1392.     # Each checkbox is followed by a label.
  1393.     # There will be one checkbox for each value.  Each value
  1394.     # can be specified as a String, which will be used both
  1395.     # as the value of the VALUE attribute and as the label
  1396.     # for that checkbox.  A single-element array has the
  1397.     # same effect.
  1398.     #
  1399.     # Each value can also be specified as a three-element array.
  1400.     # The first element is the VALUE attribute; the second is the
  1401.     # label; and the third is a boolean specifying whether this
  1402.     # checkbox is CHECKED.
  1403.     #
  1404.     # Each value can also be specified as a two-element
  1405.     # array, by omitting either the value element (defaults
  1406.     # to the same as the label), or the boolean checked element
  1407.     # (defaults to false).
  1408.     #
  1409.     #   checkbox_group("name", "foo", "bar", "baz")
  1410.     #     # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
  1411.     #     # <INPUT TYPE="checkbox" NAME="name" VALUE="bar">bar
  1412.     #     # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
  1413.     # 
  1414.     #   checkbox_group("name", ["foo"], ["bar", true], "baz")
  1415.     #     # <INPUT TYPE="checkbox" NAME="name" VALUE="foo">foo
  1416.     #     # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="bar">bar
  1417.     #     # <INPUT TYPE="checkbox" NAME="name" VALUE="baz">baz
  1418.     # 
  1419.     #   checkbox_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
  1420.     #     # <INPUT TYPE="checkbox" NAME="name" VALUE="1">Foo
  1421.     #     # <INPUT TYPE="checkbox" CHECKED NAME="name" VALUE="2">Bar
  1422.     #     # <INPUT TYPE="checkbox" NAME="name" VALUE="Baz">Baz
  1423.     # 
  1424.     #   checkbox_group("NAME" => "name",
  1425.     #                    "VALUES" => ["foo", "bar", "baz"])
  1426.     # 
  1427.     #   checkbox_group("NAME" => "name",
  1428.     #                    "VALUES" => [["foo"], ["bar", true], "baz"])
  1429.     # 
  1430.     #   checkbox_group("NAME" => "name",
  1431.     #                    "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
  1432.     def checkbox_group(name = "", *values)
  1433.       if name.kind_of?(Hash)
  1434.         values = name["VALUES"]
  1435.         name = name["NAME"]
  1436.       end
  1437.       values.collect{|value|
  1438.         if value.kind_of?(String)
  1439.           checkbox(name, value) + value
  1440.         else
  1441.           if value[value.size - 1] == true
  1442.             checkbox(name, value[0], true) +
  1443.             value[value.size - 2]
  1444.           else
  1445.             checkbox(name, value[0]) +
  1446.             value[value.size - 1]
  1447.           end
  1448.         end
  1449.       }.to_s
  1450.     end
  1451.  
  1452.  
  1453.     # Generate an File Upload Input element as a string.
  1454.     #
  1455.     # The attributes of the element can be specified as three arguments,
  1456.     # +name+, +size+, and +maxlength+.  +maxlength+ is the maximum length
  1457.     # of the file's _name_, not of the file's _contents_.
  1458.     #
  1459.     # Alternatively, the attributes can be specified as a hash.
  1460.     #
  1461.     # See #multipart_form() for forms that include file uploads.
  1462.     #
  1463.     #   file_field("name")
  1464.     #     # <INPUT TYPE="file" NAME="name" SIZE="20">
  1465.     # 
  1466.     #   file_field("name", 40)
  1467.     #     # <INPUT TYPE="file" NAME="name" SIZE="40">
  1468.     # 
  1469.     #   file_field("name", 40, 100)
  1470.     #     # <INPUT TYPE="file" NAME="name" SIZE="40" MAXLENGTH="100">
  1471.     # 
  1472.     #   file_field("NAME" => "name", "SIZE" => 40)
  1473.     #     # <INPUT TYPE="file" NAME="name" SIZE="40">
  1474.     def file_field(name = "", size = 20, maxlength = nil)
  1475.       attributes = if name.kind_of?(String)
  1476.                      { "TYPE" => "file", "NAME" => name,
  1477.                        "SIZE" => size.to_s }
  1478.                    else
  1479.                      name["TYPE"] = "file"
  1480.                      name
  1481.                    end
  1482.       attributes["MAXLENGTH"] = maxlength.to_s if maxlength
  1483.       input(attributes)
  1484.     end
  1485.  
  1486.  
  1487.     # Generate a Form element as a string.
  1488.     #
  1489.     # +method+ should be either "get" or "post", and defaults to the latter.
  1490.     # +action+ defaults to the current CGI script name.  +enctype+
  1491.     # defaults to "application/x-www-form-urlencoded".  
  1492.     #
  1493.     # Alternatively, the attributes can be specified as a hash.
  1494.     #
  1495.     # See also #multipart_form() for forms that include file uploads.
  1496.     #
  1497.     #   form{ "string" }
  1498.     #     # <FORM METHOD="post" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
  1499.     # 
  1500.     #   form("get") { "string" }
  1501.     #     # <FORM METHOD="get" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
  1502.     # 
  1503.     #   form("get", "url") { "string" }
  1504.     #     # <FORM METHOD="get" ACTION="url" ENCTYPE="application/x-www-form-urlencoded">string</FORM>
  1505.     # 
  1506.     #   form("METHOD" => "post", "ENCTYPE" => "enctype") { "string" }
  1507.     #     # <FORM METHOD="post" ENCTYPE="enctype">string</FORM>
  1508.     def form(method = "post", action = script_name, enctype = "application/x-www-form-urlencoded")
  1509.       attributes = if method.kind_of?(String)
  1510.                      { "METHOD" => method, "ACTION" => action,
  1511.                        "ENCTYPE" => enctype } 
  1512.                    else
  1513.                      unless method.has_key?("METHOD")
  1514.                        method["METHOD"] = "post"
  1515.                      end
  1516.                      unless method.has_key?("ENCTYPE")
  1517.                        method["ENCTYPE"] = enctype
  1518.                      end
  1519.                      method
  1520.                    end
  1521.       if block_given?
  1522.         body = yield
  1523.       else
  1524.         body = ""
  1525.       end
  1526.       if @output_hidden
  1527.         body += @output_hidden.collect{|k,v|
  1528.           "<INPUT TYPE=\"HIDDEN\" NAME=\"#{k}\" VALUE=\"#{v}\">"
  1529.         }.to_s
  1530.       end
  1531.       super(attributes){body}
  1532.     end
  1533.  
  1534.     # Generate a Hidden Input element as a string.
  1535.     #
  1536.     # The attributes of the element can be specified as two arguments,
  1537.     # +name+ and +value+.
  1538.     #
  1539.     # Alternatively, the attributes can be specified as a hash.
  1540.     #
  1541.     #   hidden("name")
  1542.     #     # <INPUT TYPE="hidden" NAME="name">
  1543.     # 
  1544.     #   hidden("name", "value")
  1545.     #     # <INPUT TYPE="hidden" NAME="name" VALUE="value">
  1546.     # 
  1547.     #   hidden("NAME" => "name", "VALUE" => "reset", "ID" => "foo")
  1548.     #     # <INPUT TYPE="hidden" NAME="name" VALUE="value" ID="foo">
  1549.     def hidden(name = "", value = nil)
  1550.       attributes = if name.kind_of?(String)
  1551.                      { "TYPE" => "hidden", "NAME" => name, "VALUE" => value }
  1552.                    else
  1553.                      name["TYPE"] = "hidden"
  1554.                      name
  1555.                    end
  1556.       input(attributes)
  1557.     end
  1558.  
  1559.     # Generate a top-level HTML element as a string.
  1560.     #
  1561.     # The attributes of the element are specified as a hash.  The
  1562.     # pseudo-attribute "PRETTY" can be used to specify that the generated
  1563.     # HTML string should be indented.  "PRETTY" can also be specified as
  1564.     # a string as the sole argument to this method.  The pseudo-attribute
  1565.     # "DOCTYPE", if given, is used as the leading DOCTYPE SGML tag; it
  1566.     # should include the entire text of this tag, including angle brackets.
  1567.     #
  1568.     # The body of the html element is supplied as a block.
  1569.     # 
  1570.     #   html{ "string" }
  1571.     #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML>string</HTML>
  1572.     # 
  1573.     #   html("LANG" => "ja") { "string" }
  1574.     #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><HTML LANG="ja">string</HTML>
  1575.     # 
  1576.     #   html("DOCTYPE" => false) { "string" }
  1577.     #     # <HTML>string</HTML>
  1578.     # 
  1579.     #   html("DOCTYPE" => '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">') { "string" }
  1580.     #     # <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN"><HTML>string</HTML>
  1581.     # 
  1582.     #   html("PRETTY" => "  ") { "<BODY></BODY>" }
  1583.     #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
  1584.     #     # <HTML>
  1585.     #     #   <BODY>
  1586.     #     #   </BODY>
  1587.     #     # </HTML>
  1588.     # 
  1589.     #   html("PRETTY" => "\t") { "<BODY></BODY>" }
  1590.     #     # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
  1591.     #     # <HTML>
  1592.     #     #         <BODY>
  1593.     #     #         </BODY>
  1594.     #     # </HTML>
  1595.     # 
  1596.     #   html("PRETTY") { "<BODY></BODY>" }
  1597.     #     # = html("PRETTY" => "  ") { "<BODY></BODY>" }
  1598.     # 
  1599.     #   html(if $VERBOSE then "PRETTY" end) { "HTML string" }
  1600.     #
  1601.     def html(attributes = {}) # :yield:
  1602.       if nil == attributes
  1603.         attributes = {}
  1604.       elsif "PRETTY" == attributes
  1605.         attributes = { "PRETTY" => true }
  1606.       end
  1607.       pretty = attributes.delete("PRETTY")
  1608.       pretty = "  " if true == pretty
  1609.       buf = ""
  1610.  
  1611.       if attributes.has_key?("DOCTYPE")
  1612.         if attributes["DOCTYPE"]
  1613.           buf += attributes.delete("DOCTYPE")
  1614.         else
  1615.           attributes.delete("DOCTYPE")
  1616.         end
  1617.       else
  1618.         buf += doctype
  1619.       end
  1620.  
  1621.       if block_given?
  1622.         buf += super(attributes){ yield }
  1623.       else
  1624.         buf += super(attributes)
  1625.       end
  1626.  
  1627.       if pretty
  1628.         CGI::pretty(buf, pretty)
  1629.       else
  1630.         buf
  1631.       end
  1632.  
  1633.     end
  1634.  
  1635.     # Generate an Image Button Input element as a string.
  1636.     #
  1637.     # +src+ is the URL of the image to use for the button.  +name+ 
  1638.     # is the input name.  +alt+ is the alternative text for the image.
  1639.     #
  1640.     # Alternatively, the attributes can be specified as a hash.
  1641.     # 
  1642.     #   image_button("url")
  1643.     #     # <INPUT TYPE="image" SRC="url">
  1644.     # 
  1645.     #   image_button("url", "name", "string")
  1646.     #     # <INPUT TYPE="image" SRC="url" NAME="name" ALT="string">
  1647.     # 
  1648.     #   image_button("SRC" => "url", "ATL" => "strng")
  1649.     #     # <INPUT TYPE="image" SRC="url" ALT="string">
  1650.     def image_button(src = "", name = nil, alt = nil)
  1651.       attributes = if src.kind_of?(String)
  1652.                      { "TYPE" => "image", "SRC" => src, "NAME" => name,
  1653.                        "ALT" => alt }
  1654.                    else
  1655.                      src["TYPE"] = "image"
  1656.                      src["SRC"] ||= ""
  1657.                      src
  1658.                    end
  1659.       input(attributes)
  1660.     end
  1661.  
  1662.  
  1663.     # Generate an Image element as a string.
  1664.     #
  1665.     # +src+ is the URL of the image.  +alt+ is the alternative text for
  1666.     # the image.  +width+ is the width of the image, and +height+ is
  1667.     # its height.
  1668.     #
  1669.     # Alternatively, the attributes can be specified as a hash.
  1670.     #
  1671.     #   img("src", "alt", 100, 50)
  1672.     #     # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
  1673.     # 
  1674.     #   img("SRC" => "src", "ALT" => "alt", "WIDTH" => 100, "HEIGHT" => 50)
  1675.     #     # <IMG SRC="src" ALT="alt" WIDTH="100" HEIGHT="50">
  1676.     def img(src = "", alt = "", width = nil, height = nil)
  1677.       attributes = if src.kind_of?(String)
  1678.                      { "SRC" => src, "ALT" => alt }
  1679.                    else
  1680.                      src
  1681.                    end
  1682.       attributes["WIDTH"] = width.to_s if width
  1683.       attributes["HEIGHT"] = height.to_s if height
  1684.       super(attributes)
  1685.     end
  1686.  
  1687.  
  1688.     # Generate a Form element with multipart encoding as a String.
  1689.     #
  1690.     # Multipart encoding is used for forms that include file uploads.
  1691.     #
  1692.     # +action+ is the action to perform.  +enctype+ is the encoding
  1693.     # type, which defaults to "multipart/form-data".
  1694.     #
  1695.     # Alternatively, the attributes can be specified as a hash.
  1696.     #
  1697.     #   multipart_form{ "string" }
  1698.     #     # <FORM METHOD="post" ENCTYPE="multipart/form-data">string</FORM>
  1699.     # 
  1700.     #   multipart_form("url") { "string" }
  1701.     #     # <FORM METHOD="post" ACTION="url" ENCTYPE="multipart/form-data">string</FORM>
  1702.     def multipart_form(action = nil, enctype = "multipart/form-data")
  1703.       attributes = if action == nil
  1704.                      { "METHOD" => "post", "ENCTYPE" => enctype } 
  1705.                    elsif action.kind_of?(String)
  1706.                      { "METHOD" => "post", "ACTION" => action,
  1707.                        "ENCTYPE" => enctype } 
  1708.                    else
  1709.                      unless action.has_key?("METHOD")
  1710.                        action["METHOD"] = "post"
  1711.                      end
  1712.                      unless action.has_key?("ENCTYPE")
  1713.                        action["ENCTYPE"] = enctype
  1714.                      end
  1715.                      action
  1716.                    end
  1717.       if block_given?
  1718.         form(attributes){ yield }
  1719.       else
  1720.         form(attributes)
  1721.       end
  1722.     end
  1723.  
  1724.  
  1725.     # Generate a Password Input element as a string.
  1726.     #
  1727.     # +name+ is the name of the input field.  +value+ is its default
  1728.     # value.  +size+ is the size of the input field display.  +maxlength+
  1729.     # is the maximum length of the inputted password.
  1730.     #
  1731.     # Alternatively, attributes can be specified as a hash.
  1732.     #
  1733.     #   password_field("name")
  1734.     #     # <INPUT TYPE="password" NAME="name" SIZE="40">
  1735.     # 
  1736.     #   password_field("name", "value")
  1737.     #     # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="40">
  1738.     # 
  1739.     #   password_field("password", "value", 80, 200)
  1740.     #     # <INPUT TYPE="password" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
  1741.     # 
  1742.     #   password_field("NAME" => "name", "VALUE" => "value")
  1743.     #     # <INPUT TYPE="password" NAME="name" VALUE="value">
  1744.     def password_field(name = "", value = nil, size = 40, maxlength = nil)
  1745.       attributes = if name.kind_of?(String)
  1746.                      { "TYPE" => "password", "NAME" => name,
  1747.                        "VALUE" => value, "SIZE" => size.to_s }
  1748.                    else
  1749.                      name["TYPE"] = "password"
  1750.                      name
  1751.                    end
  1752.       attributes["MAXLENGTH"] = maxlength.to_s if maxlength
  1753.       input(attributes)
  1754.     end
  1755.  
  1756.     # Generate a Select element as a string.
  1757.     #
  1758.     # +name+ is the name of the element.  The +values+ are the options that
  1759.     # can be selected from the Select menu.  Each value can be a String or
  1760.     # a one, two, or three-element Array.  If a String or a one-element
  1761.     # Array, this is both the value of that option and the text displayed for
  1762.     # it.  If a three-element Array, the elements are the option value, displayed
  1763.     # text, and a boolean value specifying whether this option starts as selected.
  1764.     # The two-element version omits either the option value (defaults to the same
  1765.     # as the display text) or the boolean selected specifier (defaults to false).
  1766.     #
  1767.     # The attributes and options can also be specified as a hash.  In this
  1768.     # case, options are specified as an array of values as described above,
  1769.     # with the hash key of "VALUES".
  1770.     #
  1771.     #   popup_menu("name", "foo", "bar", "baz")
  1772.     #     # <SELECT NAME="name">
  1773.     #     #   <OPTION VALUE="foo">foo</OPTION>
  1774.     #     #   <OPTION VALUE="bar">bar</OPTION>
  1775.     #     #   <OPTION VALUE="baz">baz</OPTION>
  1776.     #     # </SELECT>
  1777.     # 
  1778.     #   popup_menu("name", ["foo"], ["bar", true], "baz")
  1779.     #     # <SELECT NAME="name">
  1780.     #     #   <OPTION VALUE="foo">foo</OPTION>
  1781.     #     #   <OPTION VALUE="bar" SELECTED>bar</OPTION>
  1782.     #     #   <OPTION VALUE="baz">baz</OPTION>
  1783.     #     # </SELECT>
  1784.     # 
  1785.     #   popup_menu("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
  1786.     #     # <SELECT NAME="name">
  1787.     #     #   <OPTION VALUE="1">Foo</OPTION>
  1788.     #     #   <OPTION SELECTED VALUE="2">Bar</OPTION>
  1789.     #     #   <OPTION VALUE="Baz">Baz</OPTION>
  1790.     #     # </SELECT>
  1791.     # 
  1792.     #   popup_menu("NAME" => "name", "SIZE" => 2, "MULTIPLE" => true,
  1793.     #               "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
  1794.     #     # <SELECT NAME="name" MULTIPLE SIZE="2">
  1795.     #     #   <OPTION VALUE="1">Foo</OPTION>
  1796.     #     #   <OPTION SELECTED VALUE="2">Bar</OPTION>
  1797.     #     #   <OPTION VALUE="Baz">Baz</OPTION>
  1798.     #     # </SELECT>
  1799.     def popup_menu(name = "", *values)
  1800.  
  1801.       if name.kind_of?(Hash)
  1802.         values   = name["VALUES"]
  1803.         size     = name["SIZE"].to_s if name["SIZE"]
  1804.         multiple = name["MULTIPLE"]
  1805.         name     = name["NAME"]
  1806.       else
  1807.         size = nil
  1808.         multiple = nil
  1809.       end
  1810.  
  1811.       select({ "NAME" => name, "SIZE" => size,
  1812.                "MULTIPLE" => multiple }){
  1813.         values.collect{|value|
  1814.           if value.kind_of?(String)
  1815.             option({ "VALUE" => value }){ value }
  1816.           else
  1817.             if value[value.size - 1] == true
  1818.               option({ "VALUE" => value[0], "SELECTED" => true }){
  1819.                 value[value.size - 2]
  1820.               }
  1821.             else
  1822.               option({ "VALUE" => value[0] }){
  1823.                 value[value.size - 1]
  1824.               }
  1825.             end
  1826.           end
  1827.         }.to_s
  1828.       }
  1829.  
  1830.     end
  1831.  
  1832.     # Generates a radio-button Input element.
  1833.     #
  1834.     # +name+ is the name of the input field.  +value+ is the value of
  1835.     # the field if checked.  +checked+ specifies whether the field
  1836.     # starts off checked.
  1837.     #
  1838.     # Alternatively, the attributes can be specified as a hash.
  1839.     #
  1840.     #   radio_button("name", "value")
  1841.     #     # <INPUT TYPE="radio" NAME="name" VALUE="value">
  1842.     # 
  1843.     #   radio_button("name", "value", true)
  1844.     #     # <INPUT TYPE="radio" NAME="name" VALUE="value" CHECKED>
  1845.     # 
  1846.     #   radio_button("NAME" => "name", "VALUE" => "value", "ID" => "foo")
  1847.     #     # <INPUT TYPE="radio" NAME="name" VALUE="value" ID="foo">
  1848.     def radio_button(name = "", value = nil, checked = nil)
  1849.       attributes = if name.kind_of?(String)
  1850.                      { "TYPE" => "radio", "NAME" => name,
  1851.                        "VALUE" => value, "CHECKED" => checked }
  1852.                    else
  1853.                      name["TYPE"] = "radio"
  1854.                      name
  1855.                    end
  1856.       input(attributes)
  1857.     end
  1858.  
  1859.     # Generate a sequence of radio button Input elements, as a String.
  1860.     #
  1861.     # This works the same as #checkbox_group().  However, it is not valid
  1862.     # to have more than one radiobutton in a group checked.
  1863.     # 
  1864.     #   radio_group("name", "foo", "bar", "baz")
  1865.     #     # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
  1866.     #     # <INPUT TYPE="radio" NAME="name" VALUE="bar">bar
  1867.     #     # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
  1868.     # 
  1869.     #   radio_group("name", ["foo"], ["bar", true], "baz")
  1870.     #     # <INPUT TYPE="radio" NAME="name" VALUE="foo">foo
  1871.     #     # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="bar">bar
  1872.     #     # <INPUT TYPE="radio" NAME="name" VALUE="baz">baz
  1873.     # 
  1874.     #   radio_group("name", ["1", "Foo"], ["2", "Bar", true], "Baz")
  1875.     #     # <INPUT TYPE="radio" NAME="name" VALUE="1">Foo
  1876.     #     # <INPUT TYPE="radio" CHECKED NAME="name" VALUE="2">Bar
  1877.     #     # <INPUT TYPE="radio" NAME="name" VALUE="Baz">Baz
  1878.     # 
  1879.     #   radio_group("NAME" => "name",
  1880.     #                 "VALUES" => ["foo", "bar", "baz"])
  1881.     # 
  1882.     #   radio_group("NAME" => "name",
  1883.     #                 "VALUES" => [["foo"], ["bar", true], "baz"])
  1884.     # 
  1885.     #   radio_group("NAME" => "name",
  1886.     #                 "VALUES" => [["1", "Foo"], ["2", "Bar", true], "Baz"])
  1887.     def radio_group(name = "", *values)
  1888.       if name.kind_of?(Hash)
  1889.         values = name["VALUES"]
  1890.         name = name["NAME"]
  1891.       end
  1892.       values.collect{|value|
  1893.         if value.kind_of?(String)
  1894.           radio_button(name, value) + value
  1895.         else
  1896.           if value[value.size - 1] == true
  1897.             radio_button(name, value[0], true) +
  1898.             value[value.size - 2]
  1899.           else
  1900.             radio_button(name, value[0]) +
  1901.             value[value.size - 1]
  1902.           end
  1903.         end
  1904.       }.to_s
  1905.     end
  1906.  
  1907.     # Generate a reset button Input element, as a String.
  1908.     #
  1909.     # This resets the values on a form to their initial values.  +value+
  1910.     # is the text displayed on the button. +name+ is the name of this button.
  1911.     #
  1912.     # Alternatively, the attributes can be specified as a hash.
  1913.     #
  1914.     #   reset
  1915.     #     # <INPUT TYPE="reset">
  1916.     # 
  1917.     #   reset("reset")
  1918.     #     # <INPUT TYPE="reset" VALUE="reset">
  1919.     # 
  1920.     #   reset("VALUE" => "reset", "ID" => "foo")
  1921.     #     # <INPUT TYPE="reset" VALUE="reset" ID="foo">
  1922.     def reset(value = nil, name = nil)
  1923.       attributes = if (not value) or value.kind_of?(String)
  1924.                      { "TYPE" => "reset", "VALUE" => value, "NAME" => name }
  1925.                    else
  1926.                      value["TYPE"] = "reset"
  1927.                      value
  1928.                    end
  1929.       input(attributes)
  1930.     end
  1931.  
  1932.     alias scrolling_list popup_menu
  1933.  
  1934.     # Generate a submit button Input element, as a String.
  1935.     #
  1936.     # +value+ is the text to display on the button.  +name+ is the name
  1937.     # of the input.
  1938.     #
  1939.     # Alternatively, the attributes can be specified as a hash.
  1940.     #
  1941.     #   submit
  1942.     #     # <INPUT TYPE="submit">
  1943.     # 
  1944.     #   submit("ok")
  1945.     #     # <INPUT TYPE="submit" VALUE="ok">
  1946.     # 
  1947.     #   submit("ok", "button1")
  1948.     #     # <INPUT TYPE="submit" VALUE="ok" NAME="button1">
  1949.     # 
  1950.     #   submit("VALUE" => "ok", "NAME" => "button1", "ID" => "foo")
  1951.     #     # <INPUT TYPE="submit" VALUE="ok" NAME="button1" ID="foo">
  1952.     def submit(value = nil, name = nil)
  1953.       attributes = if (not value) or value.kind_of?(String)
  1954.                      { "TYPE" => "submit", "VALUE" => value, "NAME" => name }
  1955.                    else
  1956.                      value["TYPE"] = "submit"
  1957.                      value
  1958.                    end
  1959.       input(attributes)
  1960.     end
  1961.  
  1962.     # Generate a text field Input element, as a String.
  1963.     #
  1964.     # +name+ is the name of the input field.  +value+ is its initial
  1965.     # value.  +size+ is the size of the input area.  +maxlength+
  1966.     # is the maximum length of input accepted.
  1967.     #
  1968.     # Alternatively, the attributes can be specified as a hash.
  1969.     #
  1970.     #   text_field("name")
  1971.     #     # <INPUT TYPE="text" NAME="name" SIZE="40">
  1972.     # 
  1973.     #   text_field("name", "value")
  1974.     #     # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="40">
  1975.     # 
  1976.     #   text_field("name", "value", 80)
  1977.     #     # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80">
  1978.     # 
  1979.     #   text_field("name", "value", 80, 200)
  1980.     #     # <INPUT TYPE="text" NAME="name" VALUE="value" SIZE="80" MAXLENGTH="200">
  1981.     # 
  1982.     #   text_field("NAME" => "name", "VALUE" => "value")
  1983.     #     # <INPUT TYPE="text" NAME="name" VALUE="value">
  1984.     def text_field(name = "", value = nil, size = 40, maxlength = nil)
  1985.       attributes = if name.kind_of?(String)
  1986.                      { "TYPE" => "text", "NAME" => name, "VALUE" => value,
  1987.                        "SIZE" => size.to_s }
  1988.                    else
  1989.                      name["TYPE"] = "text"
  1990.                      name
  1991.                    end
  1992.       attributes["MAXLENGTH"] = maxlength.to_s if maxlength
  1993.       input(attributes)
  1994.     end
  1995.  
  1996.     # Generate a TextArea element, as a String.
  1997.     #
  1998.     # +name+ is the name of the textarea.  +cols+ is the number of
  1999.     # columns and +rows+ is the number of rows in the display.
  2000.     #
  2001.     # Alternatively, the attributes can be specified as a hash.
  2002.     #
  2003.     # The body is provided by the passed-in no-argument block
  2004.     #
  2005.     #   textarea("name")
  2006.     #      # = textarea("NAME" => "name", "COLS" => 70, "ROWS" => 10)
  2007.     #
  2008.     #   textarea("name", 40, 5)
  2009.     #      # = textarea("NAME" => "name", "COLS" => 40, "ROWS" => 5)
  2010.     def textarea(name = "", cols = 70, rows = 10)  # :yield:
  2011.       attributes = if name.kind_of?(String)
  2012.                      { "NAME" => name, "COLS" => cols.to_s,
  2013.                        "ROWS" => rows.to_s }
  2014.                    else
  2015.                      name
  2016.                    end
  2017.       if block_given?
  2018.         super(attributes){ yield }
  2019.       else
  2020.         super(attributes)
  2021.       end
  2022.     end
  2023.  
  2024.   end # HtmlExtension
  2025.  
  2026.  
  2027.   # Mixin module for HTML version 3 generation methods.
  2028.   module Html3 # :nodoc:
  2029.  
  2030.     # The DOCTYPE declaration for this version of HTML
  2031.     def doctype
  2032.       %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">|
  2033.     end
  2034.  
  2035.     # Initialise the HTML generation methods for this version.
  2036.     def element_init
  2037.       extend TagMaker
  2038.       methods = ""
  2039.       # - -
  2040.       for element in %w[ A TT I B U STRIKE BIG SMALL SUB SUP EM STRONG
  2041.           DFN CODE SAMP KBD VAR CITE FONT ADDRESS DIV center MAP
  2042.           APPLET PRE XMP LISTING DL OL UL DIR MENU SELECT table TITLE
  2043.           STYLE SCRIPT H1 H2 H3 H4 H5 H6 TEXTAREA FORM BLOCKQUOTE
  2044.           CAPTION ]
  2045.         methods += <<-BEGIN + nn_element_def(element) + <<-END
  2046.           def #{element.downcase}(attributes = {})
  2047.         BEGIN
  2048.           end
  2049.         END
  2050.       end
  2051.  
  2052.       # - O EMPTY
  2053.       for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
  2054.           ISINDEX META ]
  2055.         methods += <<-BEGIN + nOE_element_def(element) + <<-END
  2056.           def #{element.downcase}(attributes = {})
  2057.         BEGIN
  2058.           end
  2059.         END
  2060.       end
  2061.  
  2062.       # O O or - O
  2063.       for element in %w[ HTML HEAD BODY P PLAINTEXT DT DD LI OPTION tr
  2064.           th td ]
  2065.         methods += <<-BEGIN + nO_element_def(element) + <<-END
  2066.           def #{element.downcase}(attributes = {})
  2067.         BEGIN
  2068.           end
  2069.         END
  2070.       end
  2071.       eval(methods)
  2072.     end
  2073.  
  2074.   end # Html3
  2075.  
  2076.  
  2077.   # Mixin module for HTML version 4 generation methods.
  2078.   module Html4 # :nodoc:
  2079.  
  2080.     # The DOCTYPE declaration for this version of HTML
  2081.     def doctype
  2082.       %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">|
  2083.     end
  2084.  
  2085.     # Initialise the HTML generation methods for this version.
  2086.     def element_init
  2087.       extend TagMaker
  2088.       methods = ""
  2089.       # - -
  2090.       for element in %w[ TT I B BIG SMALL EM STRONG DFN CODE SAMP KBD
  2091.         VAR CITE ABBR ACRONYM SUB SUP SPAN BDO ADDRESS DIV MAP OBJECT
  2092.         H1 H2 H3 H4 H5 H6 PRE Q INS DEL DL OL UL LABEL SELECT OPTGROUP
  2093.         FIELDSET LEGEND BUTTON TABLE TITLE STYLE SCRIPT NOSCRIPT
  2094.         TEXTAREA FORM A BLOCKQUOTE CAPTION ]
  2095.         methods += <<-BEGIN + nn_element_def(element) + <<-END
  2096.           def #{element.downcase}(attributes = {})
  2097.         BEGIN
  2098.           end
  2099.         END
  2100.       end
  2101.  
  2102.       # - O EMPTY
  2103.       for element in %w[ IMG BASE BR AREA LINK PARAM HR INPUT COL META ]
  2104.         methods += <<-BEGIN + nOE_element_def(element) + <<-END
  2105.           def #{element.downcase}(attributes = {})
  2106.         BEGIN
  2107.           end
  2108.         END
  2109.       end
  2110.  
  2111.       # O O or - O
  2112.       for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
  2113.           COLGROUP TR TH TD HEAD]
  2114.         methods += <<-BEGIN + nO_element_def(element) + <<-END
  2115.           def #{element.downcase}(attributes = {})
  2116.         BEGIN
  2117.           end
  2118.         END
  2119.       end
  2120.       eval(methods)
  2121.     end
  2122.  
  2123.   end # Html4
  2124.  
  2125.  
  2126.   # Mixin module for HTML version 4 transitional generation methods.
  2127.   module Html4Tr # :nodoc:
  2128.  
  2129.     # The DOCTYPE declaration for this version of HTML
  2130.     def doctype
  2131.       %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">|
  2132.     end
  2133.  
  2134.     # Initialise the HTML generation methods for this version.
  2135.     def element_init
  2136.       extend TagMaker
  2137.       methods = ""
  2138.       # - -
  2139.       for element in %w[ TT I B U S STRIKE BIG SMALL EM STRONG DFN
  2140.           CODE SAMP KBD VAR CITE ABBR ACRONYM FONT SUB SUP SPAN BDO
  2141.           ADDRESS DIV CENTER MAP OBJECT APPLET H1 H2 H3 H4 H5 H6 PRE Q
  2142.           INS DEL DL OL UL DIR MENU LABEL SELECT OPTGROUP FIELDSET
  2143.           LEGEND BUTTON TABLE IFRAME NOFRAMES TITLE STYLE SCRIPT
  2144.           NOSCRIPT TEXTAREA FORM A BLOCKQUOTE CAPTION ]
  2145.         methods += <<-BEGIN + nn_element_def(element) + <<-END
  2146.           def #{element.downcase}(attributes = {})
  2147.         BEGIN
  2148.           end
  2149.         END
  2150.       end
  2151.  
  2152.       # - O EMPTY
  2153.       for element in %w[ IMG BASE BASEFONT BR AREA LINK PARAM HR INPUT
  2154.           COL ISINDEX META ]
  2155.         methods += <<-BEGIN + nOE_element_def(element) + <<-END
  2156.           def #{element.downcase}(attributes = {})
  2157.         BEGIN
  2158.           end
  2159.         END
  2160.       end
  2161.  
  2162.       # O O or - O
  2163.       for element in %w[ HTML BODY P DT DD LI OPTION THEAD TFOOT TBODY
  2164.           COLGROUP TR TH TD HEAD ]
  2165.         methods += <<-BEGIN + nO_element_def(element) + <<-END
  2166.           def #{element.downcase}(attributes = {})
  2167.         BEGIN
  2168.           end
  2169.         END
  2170.       end
  2171.       eval(methods)
  2172.     end
  2173.  
  2174.   end # Html4Tr
  2175.  
  2176.  
  2177.   # Mixin module for generating HTML version 4 with framesets.
  2178.   module Html4Fr # :nodoc:
  2179.  
  2180.     # The DOCTYPE declaration for this version of HTML
  2181.     def doctype
  2182.       %|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">|
  2183.     end
  2184.  
  2185.     # Initialise the HTML generation methods for this version.
  2186.     def element_init
  2187.       methods = ""
  2188.       # - -
  2189.       for element in %w[ FRAMESET ]
  2190.         methods += <<-BEGIN + nn_element_def(element) + <<-END
  2191.           def #{element.downcase}(attributes = {})
  2192.         BEGIN
  2193.           end
  2194.         END
  2195.       end
  2196.  
  2197.       # - O EMPTY
  2198.       for element in %w[ FRAME ]
  2199.         methods += <<-BEGIN + nOE_element_def(element) + <<-END
  2200.           def #{element.downcase}(attributes = {})
  2201.         BEGIN
  2202.           end
  2203.         END
  2204.       end
  2205.       eval(methods)
  2206.     end
  2207.  
  2208.   end # Html4Fr
  2209.  
  2210.  
  2211.   # Creates a new CGI instance.
  2212.   #
  2213.   # +type+ specifies which version of HTML to load the HTML generation
  2214.   # methods for.  The following versions of HTML are supported:
  2215.   #
  2216.   # html3:: HTML 3.x
  2217.   # html4:: HTML 4.0
  2218.   # html4Tr:: HTML 4.0 Transitional
  2219.   # html4Fr:: HTML 4.0 with Framesets
  2220.   #
  2221.   # If not specified, no HTML generation methods will be loaded.
  2222.   #
  2223.   # If the CGI object is not created in a standard CGI call environment
  2224.   # (that is, it can't locate REQUEST_METHOD in its environment), then
  2225.   # it will run in "offline" mode.  In this mode, it reads its parameters
  2226.   # from the command line or (failing that) from standard input.  Otherwise,
  2227.   # cookies and other parameters are parsed automatically from the standard
  2228.   # CGI locations, which varies according to the REQUEST_METHOD.
  2229.   def initialize(type = "query")
  2230.     if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
  2231.       Apache.request.setup_cgi_env
  2232.     end
  2233.  
  2234.     extend QueryExtension
  2235.     @multipart = false
  2236.     if defined?(CGI_PARAMS)
  2237.       warn "do not use CGI_PARAMS and CGI_COOKIES"
  2238.       @params = CGI_PARAMS.dup
  2239.       @cookies = CGI_COOKIES.dup
  2240.     else
  2241.       initialize_query()  # set @params, @cookies
  2242.     end
  2243.     @output_cookies = nil
  2244.     @output_hidden = nil
  2245.  
  2246.     case type
  2247.     when "html3"
  2248.       extend Html3
  2249.       element_init()
  2250.       extend HtmlExtension
  2251.     when "html4"
  2252.       extend Html4
  2253.       element_init()
  2254.       extend HtmlExtension
  2255.     when "html4Tr"
  2256.       extend Html4Tr
  2257.       element_init()
  2258.       extend HtmlExtension
  2259.     when "html4Fr"
  2260.       extend Html4Tr
  2261.       element_init()
  2262.       extend Html4Fr
  2263.       element_init()
  2264.       extend HtmlExtension
  2265.     end
  2266.   end
  2267.  
  2268. end   # class CGI
  2269.