sketch of json sugar
[catagits/Web-Simple.git] / lib / Web / Dispatch / ParamParser.pm
1 package Web::Dispatch::ParamParser;
2
3 use strict;
4 use warnings FATAL => 'all';
5
6 use Encode 'decode_utf8';
7
8 sub UNPACKED_QUERY () { __PACKAGE__.'.unpacked_query' }
9 sub UNPACKED_BODY () { __PACKAGE__.'.unpacked_body' }
10 sub UNPACKED_BODY_OBJECT () { __PACKAGE__.'.unpacked_body_object' }
11 sub UNPACKED_UPLOADS () { __PACKAGE__.'.unpacked_uploads' }
12 sub ORIG_ENV () { 'Web::Dispatch.original_env' }
13
14 sub get_unpacked_query_from {
15   return ($_[0]->{+ORIG_ENV}||$_[0])->{+UNPACKED_QUERY} ||= do {
16     _unpack_params($_[0]->{QUERY_STRING})
17   };
18 }
19
20 sub get_unpacked_body_from {
21   return ($_[0]->{+ORIG_ENV}||$_[0])->{+UNPACKED_BODY} ||= do {
22     my $ct = lc($_[0]->{CONTENT_TYPE}||'');
23     if (!$_[0]->{CONTENT_LENGTH}) {
24       {}
25     } elsif (index($ct, 'application/x-www-form-urlencoded') >= 0) {
26       $_[0]->{'psgi.input'}->read(my $buf, $_[0]->{CONTENT_LENGTH});
27       _unpack_params($buf);
28     } elsif (index($ct, 'multipart/form-data') >= 0) {
29       my $p = get_unpacked_body_object_from($_[0])->param;
30       # forcible arrayification (functional, $p does not belong to us,
31       # do NOT replace this with a side-effect ridden "simpler" version)
32       +{
33         map +(ref($p->{$_}) eq 'ARRAY'
34                ? ($_ => $p->{$_})
35                : ($_ => [ $p->{$_} ])
36              ), keys %$p
37       };
38     } elsif (index($ct, 'application/json') >= 0) {
39       $_[0]->{'psgi.input'}->read(my $buf, $_[0]->{CONTENT_LENGTH});
40       require JSON::MaybeXS;
41       if (my $data = eval {
42         my %data = %{JSON::MaybeXS::decode_json($buf)};
43         +{ map +($_ => [ $data{$_} ]), keys %data };
44       }) {
45         $data
46       } else {
47         {}
48       }
49     } else {
50       {}
51     }
52   };
53 }
54
55 sub get_unpacked_body_object_from {
56   # we may have no object at all - so use a single element arrayref for ||=
57   return (($_[0]->{+ORIG_ENV}||$_[0])->{+UNPACKED_BODY_OBJECT} ||= do {
58     if (!$_[0]->{CONTENT_LENGTH}) {
59       [ undef ]
60     } elsif (index(lc($_[0]->{CONTENT_TYPE}||''),'multipart/form-data')==-1) {
61       [ undef ]
62     } else {
63       [ _make_http_body($_[0]) ]
64     }
65   })->[0];
66 }
67
68 sub get_unpacked_uploads_from {
69   $_[0]->{+UNPACKED_UPLOADS} ||= do {
70     require Web::Dispatch::Upload; require HTTP::Headers;
71     my ($final, $reason) = (
72       {}, "field %s exists with value %s but body was not multipart/form-data"
73     );
74     if (my $body = get_unpacked_body_object_from($_[0])) {
75       my $u = $body->upload;
76       $reason = "field %s exists with value %s but was not an upload";
77       foreach my $k (keys %$u) {
78         foreach my $v (ref($u->{$k}) eq 'ARRAY' ? @{$u->{$k}} : $u->{$k}) {
79           push(@{$final->{$k}||=[]}, Web::Dispatch::Upload->new(
80             %{$v},
81             headers => HTTP::Headers->new($v->{headers})
82           ));
83         }
84       }
85     }
86     my $b = get_unpacked_body_from($_[0]);
87     foreach my $k (keys %$b) {
88       next if $final->{$k};
89       foreach my $v (@{$b->{$k}}) {
90         next unless $v;
91         push(@{$final->{$k}||=[]}, Web::Dispatch::NotAnUpload->new(
92           filename => $v,
93           reason => sprintf($reason, $k, $v)
94         ));
95       }
96     }
97     $final;
98   };
99 }
100
101 {
102   # shamelessly stolen from HTTP::Body::UrlEncoded by Christian Hansen
103
104   my $DECODE = qr/%([0-9a-fA-F]{2})/;
105
106   my %hex_chr;
107
108   foreach my $num ( 0 .. 255 ) {
109     my $h = sprintf "%02X", $num;
110     $hex_chr{ lc $h } = $hex_chr{ uc $h } = chr $num;
111   }
112
113   sub _unpack_params {
114     my %unpack;
115     (my $params = $_[0]) =~ s/\+/ /g;
116     my ($name, $value);
117     foreach my $pair (split(/[&;](?:\s+)?/, $params)) {
118       next unless (($name, $value) = split(/=/, $pair, 2)) == 2;
119
120       s/$DECODE/$hex_chr{$1}/gs for ($name, $value);
121       $_ = decode_utf8 $_ for ($name, $value);
122
123       push(@{$unpack{$name}||=[]}, $value);
124     }
125     \%unpack;
126   }
127 }
128
129 {
130   # shamelessly stolen from Plack::Request by miyagawa
131
132   sub _make_http_body {
133
134     # Can't actually do this yet, since Plack::Request deletes the
135     # header structure out of the uploads in its copy of the body.
136     # I suspect I need to supply miyagawa with a failing test.
137
138     #if (my $plack_body = $_[0]->{'plack.request.http.body'}) {
139     #  # Plack already constructed one; probably wasteful to do it again
140     #  return $plack_body;
141     #}
142
143     require HTTP::Body;
144     my $body = HTTP::Body->new(@{$_[0]}{qw(CONTENT_TYPE CONTENT_LENGTH)});
145     $body->cleanup(1);
146     my $spin = 0;
147     my $input = $_[0]->{'psgi.input'};
148     my $cl = $_[0]->{CONTENT_LENGTH};
149     while ($cl) {
150       $input->read(my $chunk, $cl < 8192 ? $cl : 8192);
151       my $read = length $chunk;
152       $cl -= $read;
153       $body->add($chunk);
154
155       if ($read == 0 && $spin++ > 2000) {
156         require Carp;
157         Carp::croak("Bad Content-Length: maybe client disconnect? ($cl bytes remaining)");
158       }
159     }
160     return $body;
161   }
162 }
163
164 1;