]> mj.ucw.cz Git - libucw.git/blob - lib/perl/CGI.pm
CGI: Added url_param_escape() which writes spaces as "+".
[libucw.git] / lib / perl / CGI.pm
1 #       Poor Man's CGI Module for Perl
2 #
3 #       (c) 2002--2007 Martin Mares <mj@ucw.cz>
4 #       Slightly modified by Tomas Valla <tom@ucw.cz>
5 #
6 #       This software may be freely distributed and used according to the terms
7 #       of the GNU Lesser General Public License.
8
9 package UCW::CGI;
10
11 use strict;
12 use warnings;
13
14 BEGIN {
15         # The somewhat hairy Perl export mechanism
16         use Exporter();
17         our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
18         $VERSION = 1.0;
19         @ISA = qw(Exporter);
20         @EXPORT = qw(&html_escape &url_escape &url_param_escape &self_ref &self_form);
21         @EXPORT_OK = qw();
22         %EXPORT_TAGS = ();
23 }
24
25 ### Escaping ###
26
27 sub url_escape($) {
28         my $x = shift @_;
29         $x =~ s/([^-\$_.!*'(),0-9A-Za-z\x80-\xff])/"%".unpack('H2',$1)/ge;
30         return $x;
31 }
32
33 sub url_param_escape($) {
34         my $x = shift @_;
35         $x = url_escape($x);
36         $x =~ s/%20/+/g;
37         return $x;
38 }
39
40 sub html_escape($) {
41         my $x = shift @_;
42         $x =~ s/&/&amp;/g;
43         $x =~ s/</&lt;/g;
44         $x =~ s/>/&gt;/g;
45         $x =~ s/"/&quot;/g;
46         return $x;
47 }
48
49 ### Analysing RFC 822 Style Headers ###
50
51 sub rfc822_prepare($) {
52         my $x = shift @_;
53         # Convert all %'s and backslash escapes to %xx escapes
54         $x =~ s/%/%25/g;
55         $x =~ s/\\(.)/"%".unpack("H2",$1)/ge;
56         # Remove all comments, beware, they can be nested (unterminated comments are closed at EOL automatically)
57         while ($x =~ s/^(("[^"]*"|[^"(])*(\([^)]*)*)(\([^()]*(\)|$))/$1 /) { }
58         # Remove quotes and escape dangerous characters inside (again closing at the end automatically)
59         $x =~ s{"([^"]*)("|$)}{my $z=$1; $z =~ s/([^0-9a-zA-Z%_-])/"%".unpack("H2",$1)/ge; $z;}ge;
60         # All control characters are properly escaped, tokens are clearly visible.
61         # Finally remove all unnecessary spaces.
62         $x =~ s/\s+/ /g;
63         $x =~ s/(^ | $)//g;
64         $x =~ s{\s*([()<>@,;:\\"/\[\]?=])\s*}{$1}g;
65         return $x;
66 }
67
68 sub rfc822_deescape($) {
69         my $x = shift @_;
70         $x =~ s/%(..)/pack("H2",$1)/ge;
71         return $x;
72 }
73
74 ### Reading of HTTP headers ###
75
76 sub http_get($) {
77         my $h = shift @_;
78         $h =~ tr/a-z-/A-Z_/;
79         return $ENV{"HTTP_$h"} || $ENV{"$h"};
80 }
81
82 ### Parsing of Arguments ###
83
84 our $arg_table;
85
86 sub parse_arg_string($) {
87         my ($s) = @_;
88         $s =~ s/\s+//;
89         foreach $_ (split /[&:]/,$s) {
90                 (/^([^=]+)=(.*)$/) or next;
91                 my $arg = $arg_table->{$1} or next;
92                 $_ = $2;
93                 s/\+/ /g;
94                 s/%(..)/pack("c",hex $1)/eg;
95                 s/(\r|\n|\t)/ /g;
96                 s/^\s+//;
97                 s/\s+$//;
98                 if (my $rx = $arg->{'check'}) {
99                         if (!/^$rx$/) { $_ = $arg->{'default'}; }
100                 }
101
102                 my $r = ref($arg->{'var'});
103                 if ($r eq 'SCALAR') {
104                         ${$arg->{'var'}} = $_;
105                 } elsif ($r eq 'ARRAY') {
106                         push @{$arg->{'var'}}, $_;
107                 }
108         }
109 }
110
111 sub parse_args($) {
112         $arg_table = shift @_;
113         foreach my $a (values %$arg_table) {
114                 my $r = ref($a->{'var'});
115                 defined($a->{'default'}) or $a->{'default'}="";
116                 if ($r eq 'SCALAR') {
117                         ${$a->{'var'}} = $a->{'default'};
118                 } elsif ($r eq 'ARRAY') {
119                         @{$a->{'var'}} = ();
120                 }
121         }
122         defined $ENV{"GATEWAY_INTERFACE"} or die "Not called as a CGI script";
123         my $method = $ENV{"REQUEST_METHOD"};
124         if ($method eq "GET") {
125                 parse_arg_string($ENV{"QUERY_STRING"});
126         } elsif ($method eq "POST") {
127                 if ($ENV{"CONTENT_TYPE"} =~ /^application\/x-www-form-urlencoded\b/i) {
128                         while (<STDIN>) {
129                                 chomp;
130                                 parse_arg_string($_);
131                         }
132                 } else {
133                         return "Unknown content type for POST data";
134                 }
135         } else {
136                 return "Unknown request method";
137         }
138 }
139
140 ### Generating Self-ref URL's ###
141
142 sub make_out_args($) {
143         my ($overrides) = @_;
144         my $out = {};
145         foreach my $name (keys %$arg_table) {
146                 my $arg = $arg_table->{$name};
147                 defined($arg->{'var'}) || next;
148                 defined($arg->{'pass'}) && !$arg->{'pass'} && !exists $overrides->{$name} && next;
149                 my $value;
150                 if (!defined($value = $overrides->{$name})) {
151                         if (exists $overrides->{$name}) {
152                                 $value = $arg->{'default'};
153                         } else {
154                                 $value = ${$arg->{'var'}};
155                         }
156                 }
157                 if ($value ne $arg->{'default'}) {
158                         $out->{$name} = $value;
159                 }
160         }
161         return $out;
162 }
163
164 sub self_ref(@) {
165         my %h = @_;
166         my $out = make_out_args(\%h);
167         return "?" . join(':', map { "$_=" . url_param_escape($out->{$_}) } sort keys %$out);
168 }
169
170 sub self_form(@) {
171         my %h = @_;
172         my $out = make_out_args(\%h);
173         return join('', map { "<input type=hidden name=$_ value='" . html_escape($out->{$_}) . "'>\n" } sort keys %$out);
174 }
175
176 ### Cookies
177
178 sub cookie_esc($) {
179         my $x = shift @_;
180         if ($x !~ /^[a-zA-Z0-9%]+$/) {
181                 $x =~ s/([\\\"])/\\$1/g;
182                 $x = "\"$x\"";
183         }
184         return $x;
185 }
186
187 sub set_cookie($$@) {
188         my $key = shift @_;
189         my $value = shift @_;
190         my %other = @_;
191         $other{'version'} = 1 unless defined $other{'version'};
192         print "Set-Cookie: $key=", cookie_esc($value);
193         foreach my $k (keys %other) {
194                 print ";$k=", cookie_esc($other{$k});
195         }
196         print "\n";
197 }
198
199 sub parse_cookies() {
200         my $h = http_get("Cookie") or return ();
201         my @cook = ();
202         while (my ($padding,$name,$val,$xx,$rest) = ($h =~ /\s*([,;]\s*)*([^ =]+)=([^ =,;\"]*|\"([^\"\\]|\\.)*\")(\s.*|;.*|$)/)) {
203                 if ($val =~ /^\"/) {
204                         $val =~ s/^\"//;
205                         $val =~ s/\"$//;
206                         $val =~ s/\\(.)/$1/g;
207                 }
208                 push @cook, $name, $val;
209                 $h = $rest;
210         }
211         return @cook;
212 }
213
214 1;  # OK