-
Notifications
You must be signed in to change notification settings - Fork 0
/
cgi.rb
1949 lines (1610 loc) · 51 KB
/
cgi.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
=begin
== NAME
cgi.rb - cgi support library
Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
Copyright (C) 2000 Information-technology Promotion Agency, Japan
Wakou Aoyama <[email protected]>
== EXAMPLE
=== GET FORM VALUES
require "cgi"
cgi = CGI.new
values = cgi['field_name'] # <== array of 'field_name'
# if not 'field_name' included, then return [].
fields = cgi.keys # <== array of field names
# returns true if form has 'field_name'
cgi.has_key?('field_name')
cgi.has_key?('field_name')
cgi.include?('field_name')
=== GET FORM VALUES AS HASH
require "cgi"
cgi = CGI.new
params = cgi.params
cgi.params is a hash.
cgi.params['new_field_name'] = ["value"] # add new param
cgi.params['field_name'] = ["new_value"] # change value
cgi.params.delete('field_name') # delete param
cgi.params.clear # delete all params
=== SAVE FORM VALUES TO FILE
require "pstore"
db = PStore.new("query.db")
db.transaction do
db["params"] = cgi.params
end
=== RESTORE FORM VALUES FROM FILE
require "pstore"
db = PStore.new("query.db")
db.transaction do
cgi.params = db["params"]
end
=== GET MULTIPART FORM VALUES
require "cgi"
cgi = CGI.new
values = cgi['field_name'] # <== array of 'field_name'
values[0].read # <== body of values[0]
values[0].local_path # <== path to local file of values[0]
values[0].original_filename # <== original filename of values[0]
values[0].content_type # <== content_type of values[0]
and values[0] has Tempfile class methods.
(Tempfile class object has File class methods)
=== GET COOKIE VALUES
require "cgi"
cgi = CGI.new
values = cgi.cookies['name'] # <== array of 'name'
# if not 'name' included, then return [].
names = cgi.cookies.keys # <== array of cookie names
and cgi.cookies is a hash.
=== GET COOKIE OBJECTS
require "cgi"
cgi = CGI.new
for name, cookie in cgi.cookies
cookie.expires = Time.now + 30
end
cgi.out("cookie" => cgi.cookies){"string"}
cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... }
require "cgi"
cgi = CGI.new
cgi.cookies['name'].expires = Time.now + 30
cgi.out("cookie" => cgi.cookies['name']){"string"}
and see MAKE COOKIE OBJECT.
=== GET ENVIRONMENT VALUE
require "cgi"
cgi = CGI.new
value = cgi.auth_type
# ENV["AUTH_TYPE"]
see http://www.w3.org/CGI/
AUTH_TYPE CONTENT_LENGTH CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST REMOTE_IDENT
REMOTE_USER REQUEST_METHOD SCRIPT_NAME SERVER_NAME SERVER_PORT
SERVER_PROTOCOL SERVER_SOFTWARE
content_length and server_port return Integer. and the others return String.
and HTTP_COOKIE, HTTP_COOKIE2
value = cgi.raw_cookie
# ENV["HTTP_COOKIE"]
value = cgi.raw_cookie2
# ENV["HTTP_COOKIE2"]
and other HTTP_*
value = cgi.accept
# ENV["HTTP_ACCEPT"]
value = cgi.accept_charset
# ENV["HTTP_ACCEPT_CHARSET"]
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING HTTP_ACCEPT_LANGUAGE
HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST HTTP_NEGOTIATE HTTP_PRAGMA
HTTP_REFERER HTTP_USER_AGENT
=== PRINT HTTP HEADER AND HTML STRING TO $DEFAULT_OUTPUT ($>)
require "cgi"
cgi = CGI.new("html3") # add HTML generation methods
cgi.out() do
cgi.html() do
cgi.head{ cgi.title{"TITLE"} } +
cgi.body() do
cgi.form() do
cgi.textarea("get_text") +
cgi.br +
cgi.submit
end +
cgi.pre() do
CGI::escapeHTML(
"params: " + cgi.params.inspect + "\n" +
"cookies: " + cgi.cookies.inspect + "\n" +
ENV.collect() do |key, value|
key + " --> " + value + "\n"
end.join("")
)
end
end
end
end
# add HTML generation methods
CGI.new("html3") # html3.2
CGI.new("html4") # html4.01 (Strict)
CGI.new("html4Tr") # html4.01 Transitional
CGI.new("html4Fr") # html4.01 Frameset
=end
raise "Please, use ruby1.5.4 or later." if RUBY_VERSION < "1.5.4"
require 'English'
class CGI
CR = "\015"
LF = "\012"
EOL = CR + LF
REVISION = '$Id$'
NEEDS_BINMODE = true if /WIN/ni.match(RUBY_PLATFORM)
PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'}
HTTP_STATUS = {
"OK" => "200 OK",
"PARTIAL_CONTENT" => "206 Partial Content",
"MULTIPLE_CHOICES" => "300 Multiple Choices",
"MOVED" => "301 Moved Permanently",
"REDIRECT" => "302 Found",
"NOT_MODIFIED" => "304 Not Modified",
"BAD_REQUEST" => "400 Bad Request",
"AUTH_REQUIRED" => "401 Authorization Required",
"FORBIDDEN" => "403 Forbidden",
"NOT_FOUND" => "404 Not Found",
"METHOD_NOT_ALLOWED" => "405 Method Not Allowed",
"NOT_ACCEPTABLE" => "406 Not Acceptable",
"LENGTH_REQUIRED" => "411 Length Required",
"PRECONDITION_FAILED" => "412 Rrecondition Failed",
"SERVER_ERROR" => "500 Internal Server Error",
"NOT_IMPLEMENTED" => "501 Method Not Implemented",
"BAD_GATEWAY" => "502 Bad Gateway",
"VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates"
}
RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ]
RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ]
def env_table
ENV
end
def stdinput
$stdin
end
def stdoutput
$DEFAULT_OUTPUT
end
private :env_table, :stdinput, :stdoutput
=begin
== METHODS
=end
=begin
=== ESCAPE URL ENCODE
url_encoded_string = CGI::escape("string")
=end
def CGI::escape(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase
end.tr(' ', '+')
end
=begin
=== UNESCAPE URL ENCODED
string = CGI::unescape("url encoded string")
=end
def CGI::unescape(string)
string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do
[$1.delete('%')].pack('H*')
end
end
=begin
=== ESCAPE HTML &\"<>
CGI::escapeHTML("string")
=end
def CGI::escapeHTML(string)
string.gsub(/&/n, '&').gsub(/\"/n, '"').gsub(/>/n, '>').gsub(/</n, '<')
end
=begin
=== UNESCAPE HTML
CGI::unescapeHTML("HTML escaped string")
=end
def CGI::unescapeHTML(string)
string.gsub(/&(.*?);/n) do
match = $1.dup
case match
when /\Aamp\z/ni then '&'
when /\Aquot\z/ni then '"'
when /\Agt\z/ni then '>'
when /\Alt\z/ni then '<'
when /\A#0*(\d+)\z/n then
if Integer($1) < 256
Integer($1).chr
else
if Integer($1) < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
[Integer($1)].pack("U")
else
"&##{$1};"
end
end
when /\A#x([0-9a-f]+)\z/ni then
if $1.hex < 256
$1.hex.chr
else
if $1.hex < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U)
[$1.hex].pack("U")
else
"&#x#{$1};"
end
end
else
"&#{match};"
end
end
end
=begin
=== ESCAPE ELEMENT
print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG")
# "<BR><A HREF="url"></A>"
print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"])
# "<BR><A HREF="url"></A>"
=end
def CGI::escapeElement(string, *elements)
elements = elements[0] if elements[0].kind_of?(Array)
unless elements.empty?
string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
CGI::escapeHTML($&)
end
else
string
end
end
=begin
=== UNESCAPE ELEMENT
print CGI::unescapeElement(
CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
# "<BR><A HREF="url"></A>"
print CGI::unescapeElement(
CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
# "<BR><A HREF="url"></A>"
=end
def CGI::unescapeElement(string, *elements)
elements = elements[0] if elements[0].kind_of?(Array)
unless elements.empty?
string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do
CGI::unescapeHTML($&)
end
else
string
end
end
=begin
=== MAKE RFC1123 DATE STRING
CGI::rfc1123_date(Time.now)
# Sat, 01 Jan 2000 00:00:00 GMT
=end
def CGI::rfc1123_date(time)
t = time.clone.gmtime
return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT",
RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year,
t.hour, t.min, t.sec)
end
=begin
=== MAKE HTTP HEADER STRING
header
# Content-Type: text/html
header("text/plain")
# Content-Type: text/plain
header({"nph" => true,
"status" => "OK", # == "200 OK"
# "status" => "200 GOOD",
"server" => ENV['SERVER_SOFTWARE'],
"connection" => "close",
"type" => "text/html",
"charset" => "iso-2022-jp",
# Content-Type: text/html; charset=iso-2022-jp
"language" => "ja",
"expires" => Time.now + 30,
"cookie" => [cookie1, cookie2],
"my_header1" => "my_value"
"my_header2" => "my_value"})
header will not convert charset.
status:
"OK" --> "200 OK"
"PARTIAL_CONTENT" --> "206 Partial Content"
"MULTIPLE_CHOICES" --> "300 Multiple Choices"
"MOVED" --> "301 Moved Permanently"
"REDIRECT" --> "302 Found"
"NOT_MODIFIED" --> "304 Not Modified"
"BAD_REQUEST" --> "400 Bad Request"
"AUTH_REQUIRED" --> "401 Authorization Required"
"FORBIDDEN" --> "403 Forbidden"
"NOT_FOUND" --> "404 Not Found"
"METHOD_NOT_ALLOWED" --> "405 Method Not Allowed"
"NOT_ACCEPTABLE" --> "406 Not Acceptable"
"LENGTH_REQUIRED" --> "411 Length Required"
"PRECONDITION_FAILED" --> "412 Rrecondition Failed"
"SERVER_ERROR" --> "500 Internal Server Error"
"NOT_IMPLEMENTED" --> "501 Method Not Implemented"
"BAD_GATEWAY" --> "502 Bad Gateway"
"VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates"
=end
def header(options = "text/html")
buf = ""
case options
when String
options = { "type" => options }
when Hash
options = options.dup
end
unless options.has_key?("type")
options["type"] = "text/html"
end
if options.has_key?("charset")
options["type"] += "; charset=" + options.delete("charset")
end
options.delete("nph") if defined?(MOD_RUBY)
if options.delete("nph") or /IIS/n.match(env_table['SERVER_SOFTWARE'])
buf += (env_table["SERVER_PROTOCOL"] or "HTTP/1.0") + " " +
(HTTP_STATUS[options["status"]] or options["status"] or "200 OK") +
EOL +
"Date: " + CGI::rfc1123_date(Time.now) + EOL
unless options.has_key?("server")
options["server"] = (env_table['SERVER_SOFTWARE'] or "")
end
unless options.has_key?("connection")
options["connection"] = "close"
end
options.delete("status")
end
if options.has_key?("status")
buf += "Status: " +
(HTTP_STATUS[options["status"]] or options["status"]) + EOL
options.delete("status")
end
if options.has_key?("server")
buf += "Server: " + options.delete("server") + EOL
end
if options.has_key?("connection")
buf += "Connection: " + options.delete("connection") + EOL
end
buf += "Content-Type: " + options.delete("type") + EOL
if options.has_key?("length")
buf += "Content-Length: " + options.delete("length").to_s + EOL
end
if options.has_key?("language")
buf += "Content-Language: " + options.delete("language") + EOL
end
if options.has_key?("expires")
buf += "Expires: " + CGI::rfc1123_date( options.delete("expires") ) + EOL
end
if options.has_key?("cookie")
if options["cookie"].kind_of?(String) or
options["cookie"].kind_of?(Cookie)
buf += "Set-Cookie: " + options.delete("cookie").to_s + EOL
elsif options["cookie"].kind_of?(Array)
options.delete("cookie").each{|cookie|
buf += "Set-Cookie: " + cookie.to_s + EOL
}
elsif options["cookie"].kind_of?(Hash)
options.delete("cookie").each_value{|cookie|
buf += "Set-Cookie: " + cookie.to_s + EOL
}
end
end
if @output_cookies
for cookie in @output_cookies
buf += "Set-Cookie: " + cookie.to_s + EOL
end
end
options.each{|key, value|
buf += key + ": " + value + EOL
}
if defined?(MOD_RUBY)
table = Apache::request.headers_out
buf.scan(/([^:]+): (.+)#{EOL}/n){ |name, value|
$stderr.printf("name:%s value:%s\n", name, value) if $DEBUG
case name
when 'Set-Cookie'
table.add($1, $2)
when /^status$/ni
Apache::request.status_line = value
Apache::request.status = value.to_i
when /^content-type$/ni
Apache::request.content_type = value
when /^content-encoding$/ni
Apache::request.content_encoding = value
when /^location$/ni
if Apache::request.status == 200
Apache::request.status = 302
end
Apache::request.headers_out[name] = value
else
Apache::request.headers_out[name] = value
end
}
Apache::request.send_http_header
''
else
buf + EOL
end
end # header()
=begin
=== PRINT HTTP HEADER AND STRING TO $DEFAULT_OUTPUT ($>)
cgi = CGI.new
cgi.out{ "string" }
# Content-Type: text/html
# Content-Length: 6
#
# string
cgi.out("text/plain"){ "string" }
# Content-Type: text/plain
# Content-Length: 6
#
# string
cgi.out({"nph" => true,
"status" => "OK", # == "200 OK"
"server" => ENV['SERVER_SOFTWARE'],
"connection" => "close",
"type" => "text/html",
"charset" => "iso-2022-jp",
# Content-Type: text/html; charset=iso-2022-jp
"language" => "ja",
"expires" => Time.now + (3600 * 24 * 30),
"cookie" => [cookie1, cookie2],
"my_header1" => "my_value",
"my_header2" => "my_value"}){ "string" }
if "HEAD" == REQUEST_METHOD then output only HTTP header.
if charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then
convert string charset, and set language to "ja".
=end
def out(options = "text/html")
options = { "type" => options } if options.kind_of?(String)
content = yield
if options.has_key?("charset")
require "nkf"
case options["charset"]
when /iso-2022-jp/ni
content = NKF::nkf('-j', content)
options["language"] = "ja" unless options.has_key?("language")
when /euc-jp/ni
content = NKF::nkf('-e', content)
options["language"] = "ja" unless options.has_key?("language")
when /shift_jis/ni
content = NKF::nkf('-s', content)
options["language"] = "ja" unless options.has_key?("language")
end
end
options["length"] = content.length.to_s
output = stdoutput
output.binmode if defined? output.binmode
output.print header(options)
output.print content unless "HEAD" == env_table['REQUEST_METHOD']
end
=begin
=== PRINT
cgi = CGI.new
cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print
=end
def print(*options)
stdoutput.print(*options)
end
=begin
=== MAKE COOKIE OBJECT
cookie1 = CGI::Cookie::new("name", "value1", "value2", ...)
cookie1 = CGI::Cookie::new({"name" => "name", "value" => "value"})
cookie1 = CGI::Cookie::new({'name' => 'name',
'value' => ['value1', 'value2', ...],
'path' => 'path', # optional
'domain' => 'domain', # optional
'expires' => Time.now, # optional
'secure' => true # optional
})
cgi.out({"cookie" => [cookie1, cookie2]}){ "string" }
name = cookie1.name
values = cookie1.value
path = cookie1.path
domain = cookie1.domain
expires = cookie1.expires
secure = cookie1.secure
cookie1.name = 'name'
cookie1.value = ['value1', 'value2', ...]
cookie1.path = 'path'
cookie1.domain = 'domain'
cookie1.expires = Time.now + 30
cookie1.secure = true
=end
require "delegate"
class Cookie < SimpleDelegator
def initialize(name = "", *value)
options = if name.kind_of?(String)
{ "name" => name, "value" => value }
else
name
end
unless options.has_key?("name")
raise ArgumentError, "`name' required"
end
@name = options["name"]
@value = Array(options["value"])
# simple support for IE
if options["path"]
@path = options["path"]
else
%r|^(.*/)|.match(ENV["SCRIPT_NAME"])
@path = ($1 or "")
end
@domain = options["domain"]
@expires = options["expires"]
@secure = options["secure"] == true ? true : false
super(@value)
end
attr_accessor("name", "value", "path", "domain", "expires")
attr_reader("secure")
def secure=(val)
@secure = val if val == true or val == false
@secure
end
def to_s
buf = ""
buf += @name + '='
if @value.kind_of?(String)
buf += CGI::escape(@value)
else
buf += @value.collect{|v| CGI::escape(v) }.join("&")
end
if @domain
buf += '; domain=' + @domain
end
if @path
buf += '; path=' + @path
end
if @expires
buf += '; expires=' + CGI::rfc1123_date(@expires)
end
if @secure == true
buf += '; secure'
end
buf
end
end # class Cookie
=begin
=== PARSE RAW COOKIE STRING
cookies = CGI::Cookie::parse("raw_cookie_string")
# { "name1" => cookie1, "name2" => cookie2, ... }
=end
def Cookie::parse(raw_cookie)
cookies = Hash.new([])
return cookies unless raw_cookie
raw_cookie.split('; ').each do |pairs|
name, values = pairs.split('=',2)
name = CGI::unescape(name)
values ||= ""
values = values.split('&').collect{|v| CGI::unescape(v) }
unless cookies.has_key?(name)
cookies[name] = Cookie::new({ "name" => name, "value" => values })
end
end
cookies
end
=begin
=== PARSE QUERY STRING
params = CGI::parse("query_string")
# {"name1" => ["value1", "value2", ...],
# "name2" => ["value1", "value2", ...], ... }
=end
def CGI::parse(query)
params = Hash.new([])
query.split(/[&;]/n).each do |pairs|
key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) }
if params.has_key?(key)
params[key].push(value)
else
params[key] = [value]
end
end
params
end
module QueryExtension
for env in %w[ CONTENT_LENGTH SERVER_PORT ]
eval( <<-END )
def #{env.sub(/^HTTP_/n, '').downcase}
env_table["#{env}"] && Integer(env_table["#{env}"])
end
END
end
for env in %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO
PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST
REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME
SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE
HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST
HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ]
eval( <<-END )
def #{env.sub(/^HTTP_/n, '').downcase}
env_table["#{env}"]
end
END
end
def raw_cookie
env_table["HTTP_COOKIE"]
end
def raw_cookie2
env_table["HTTP_COOKIE2"]
end
attr_accessor("cookies")
attr("params")
def params=(hash)
@params.clear
@params.update(hash)
end
def param(name)
@params[name].join("\0")
end
def read_multipart(boundary, content_length)
params = Hash.new([])
boundary = "--" + boundary
buf = ""
bufsize = 10 * 1024
# start multipart/form-data
stdinput.binmode
boundary_size = boundary.size + EOL.size
content_length -= boundary_size
status = stdinput.read(boundary_size)
if nil == status
raise EOFError, "no content body"
end
require "tempfile"
until -1 == content_length
head = nil
body = Tempfile.new("CGI")
body.binmode
until head and /#{boundary}(?:#{EOL}|--)/n.match(buf)
if (not head) and /#{EOL}#{EOL}/n.match(buf)
buf = buf.sub(/\A((?:.|\n)*?#{EOL})#{EOL}/n) do
head = $1.dup
""
end
next
end
if head and ( (EOL + boundary + EOL).size < buf.size )
body.print buf[0 ... (buf.size - (EOL + boundary + EOL).size)]
buf[0 ... (buf.size - (EOL + boundary + EOL).size)] = ""
end
c = if bufsize < content_length
stdinput.read(bufsize) or ''
else
stdinput.read(content_length) or ''
end
buf += c
content_length -= c.size
end
buf = buf.sub(/\A((?:.|\n)*?)(?:#{EOL})?#{boundary}(#{EOL}|--)/n) do
body.print $1
if "--" == $2
content_length = -1
end
""
end
body.rewind
eval <<-END
def body.local_path
#{body.path.dump}
end
END
/Content-Disposition:.* filename="?([^\";]*)"?/ni.match(head)
eval <<-END
def body.original_filename
#{
filename = ($1 or "").dup
if /Mac/ni.match(env_table['HTTP_USER_AGENT']) and
/Mozilla/ni.match(env_table['HTTP_USER_AGENT']) and
(not /MSIE/ni.match(env_table['HTTP_USER_AGENT']))
CGI::unescape(filename)
else
filename
end.dump.untaint
}.taint
end
END
/Content-Type: (.*)/ni.match(head)
eval <<-END
def body.content_type
#{($1 or "").dump.untaint}.taint
end
END
/Content-Disposition:.* name="?([^\";]*)"?/ni.match(head)
name = $1.dup
if params.has_key?(name)
params[name].push(body)
else
params[name] = [body]
end
end
params
end # read_multipart
private :read_multipart
# offline mode. read name=value pairs on standard input.
def read_from_cmdline
require "shellwords"
string = unless ARGV.empty?
ARGV.join(' ')
else
if STDIN.tty?
STDERR.print(
%|(offline mode: enter name=value pairs on standard input)\n|
)
end
readlines.join(' ').gsub(/\n/n, '')
end.gsub(/\\=/n, '%3D').gsub(/\\&/n, '%26')
words = Shellwords.shellwords(string)
if words.find{|x| /=/n.match(x) }
words.join('&')
else
words.join('+')
end
end
private :read_from_cmdline
def initialize_query()
if ("POST" == env_table['REQUEST_METHOD']) and
%r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n.match(env_table['CONTENT_TYPE'])
boundary = $1.dup
@params = read_multipart(boundary, Integer(env_table['CONTENT_LENGTH']))
else
@params = CGI::parse(
case env_table['REQUEST_METHOD']
when "GET", "HEAD"
if defined?(MOD_RUBY)
Apache::request.args or ""
else
env_table['QUERY_STRING'] or ""
end
when "POST"
stdinput.binmode
stdinput.read(Integer(env_table['CONTENT_LENGTH'])) or ''
else
read_from_cmdline
end
)
end
@cookies = CGI::Cookie::parse((env_table['HTTP_COOKIE'] or env_table['COOKIE']))
end
private :initialize_query
def [](*args)
@params[*args]
end
def keys(*args)
@params.keys(*args)
end
def has_key?(*args)
@params.has_key?(*args)
end
alias key? has_key?
alias include? has_key?
end # QueryExtension
=begin
=== HTML PRETTY FORMAT
print CGI::pretty("<HTML><BODY></BODY></HTML>")
# <HTML>
# <BODY>
# </BODY>
# </HTML>
print CGI::pretty("<HTML><BODY></BODY></HTML>", "\t")
# <HTML>
# <BODY>
# </BODY>
# </HTML>
=end
def CGI::pretty(string, shift = " ")
lines = string.gsub(/(?!\A)<(?:.|\n)*?>/n, "\n\\0").gsub(/<(?:.|\n)*?>(?!\n)/n, "\\0\n")
end_pos = 0
while end_pos = lines.index(/^<\/(\w+)/n, end_pos)
element = $1.dup
start_pos = lines.rindex(/^\s*<#{element}/ni, end_pos)
lines[start_pos ... end_pos] = "__" + lines[start_pos ... end_pos].gsub(/\n(?!\z)/n, "\n" + shift) + "__"
end
lines.gsub(/^((?:#{Regexp::quote(shift)})*)__(?=<\/?\w)/n, '\1')
end
=begin
== HTML ELEMENTS
cgi = CGI.new("html3") # add HTML generation methods
cgi.element
cgi.element{ "string" }
cgi.element({ "ATTRIBUTE1" => "value1", "ATTRIBUTE2" => "value2" })
cgi.element({ "ATTRIBUTE1" => "value1", "ATTRIBUTE2" => "value2" }){ "string" }
# add HTML generation methods
CGI.new("html3") # html3.2
CGI.new("html4") # html4.0 (Strict)
CGI.new("html4Tr") # html4.0 Transitional
CGI.new("html4Fr") # html4.0 Frameset
=end
module TagMaker
# - -
def nn_element_def(element)