blib/lib/HTML/Defaultify.pm

filter: Statementstmt 12.8% 24 / 187 Branchbran 0.0% 0 / 106 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 26.3% 5 / 19 Podpod 42.8% 6 / 14 totaltotal 10.1% 35 / 345 CC 65 SCAR 44.6
CC
65
Cov
8%
new_inputtag
210.0
extract_default_if_match
132.0
defaultify
110.0
CRAP 86.2
↑ Summary
1 #!/usr/local/bin/perl -w
2 #
3 # HTML::Defaultify-- Pre-fill default values into an existing HTML form.
4 #
5 # The main purpose of this module is the defaultify() routine, which
6 # takes a block of HTML and a hash of default values, and returns that HTML
7 # with all form fields set based on those default values. Default values
8 # (hash elements) may each be given in any of three forms: as a single
9 # scalar, as a list in "\0"-delimited form, or as a reference to an actual
10 # list. If the HTML contains more than one form, you can name which form to
11 # defaultify. Return values are the defaultified block of HTML and a hash of
12 # all unused default values (which may be useful as input to hidden_vars()).
13 # Multiple form fields with the same name are handled correctly. Besides
14 # the main defaultify() routine, this module includes several related
15 # routines which the programmer may find useful.
16 #
17 # This package prefers to have the HTML::Entities module available, but
18 # can improvise without it.
19 #
20 # Copyright (c) 1996, 1997, 2002 James Marshall (james@jmarshall.com).
21 # Adapted from the toolbox htmlutil.pl, which is (c) 1996, 1997 by same.
22 # All rights reserved.
23 #
24 # This program is free software; you can redistribute it and/or modify it
25 # under the same terms as Perl itself.
26 #
27 # Exported by default:
28 # $new_HTML= &defaultify($HTML, \%defaults [, $form_name]) ;
29 # ($new_HTML, $unused_defs)= &defaultify($HTML, \%defaults [, $form_name]) ;
30 #
31 # $my_subset_ref= &subhash(\%hash, @keys_to_include) ;
32 #
33 # Export is allowed:
34 # $hidden_vars= &hidden_vars($unused_defaults_ref) ;
35 # $hidden_vars= &hidden_vars(%unused_defaults) ;
36 # $hidden_tag= &hidden_var($name, $value) ;
37 #
38 # ($tag_name, $attr_ref)= &parse_tag($tag) ;
39 # $new_tag= &build_tag($tag_name, $attr_ref) ;
40 # $new_tag= &build_tag($tag_name, %attr) ;
41 #
42 #
43 # For better documentation, see "perldoc HTML::Defaultify" (or
44 # "perldoc -F this_file_name.pm").
45 #
46 # For the latest, see http://www.jmarshall.com/tools/defaultify/ .
47 #
48  
49 #---- package-definition-related stuff -------------------------------------
50  
51 package HTML::Defaultify ;
52  
53 1 ▶use strict ;
Subroutine BEGIN: called CC=1 SCAR=0.0
54 1 ▶use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS) ;
Subroutine BEGIN: called CC=1 SCAR=0.0
55  
56 1 require Exporter ;
57 1 @ISA= qw(Exporter) ;
58  
59 1 $VERSION= '1.01' ;
60 1 @EXPORT= qw( defaultify subhash ) ;
61 1 @EXPORT_OK= qw( hidden_vars hidden_var parse_tag build_tag ) ;
62  
63 1 %EXPORT_TAGS= (
64 parse => [qw( parse_tag build_tag )],
65 all => [@EXPORT, @EXPORT_OK],
66 ) ;
67  
68  
69 #---- actual package code below --------------------------------------------
70  
71 1 ▶use Carp ;
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 1 ▶use vars qw($HAS_HTML_ENTITIES) ;
Subroutine BEGIN: called CC=1 SCAR=0.0
74  
75 # Load HTML::Entities if available; set $HAS_HTML_ENTITIES accordingly.
76 1 ▶eval 'use HTML::Entities' ;
Subroutine BEGIN: called CC=1 SCAR=0.0
77 1 $HAS_HTML_ENTITIES= ($@ eq '') ;
78  
79  
80 # defaultify()-- takes a chunk of HTML that includes form input fields,
81 # and sets defaults according to the hash sent.
82 # Returns defaultified HTML block, and a reference to a hash of all defaults
83 # that were not used (possibly for use with hidden_vars()).
84 # In scalar context, only returns defaultified HTML block.
85 #
86 # ($new_HTML, $unused_defs)= &defaultify($HTML, $defaults [, $form_name]) ;
87 # $new_HTML= &defaultify($HTML, $defaults [, $form_name]) ;
88 #
89 # $defaults is a reference to a hash of default values. Each default (hash
90 # element) may be a scalar, a list in the form of a "\0"-delimited scalar,
91 # or a reference to a real list.
92 # As a special case, if $defaults is undefined, this routine clears all default
93 # settings from $HTML, even if they were set with tag attributes, etc.
94 # As another special case, if $defaults is a CGI object (from CGI.pm), this
95 # routine uses its existing parameters as the default set, by calling its
96 # Vars() method.
97 # If you have an existing hash instead of a reference, use e.g. \%my_hash .
98 # If $form_name is given, then only the form(s) with that name in $HTML will
99 # be defaultified. Otherwise, all of $HTML will be defaultified.
100 # Tags inside comments or <script> or <style> blocks are not affected.
101 # For a given set of defaults, there may be more than one way to defaultify
102 # a form to return those results, e.g. if several fields have the same
103 # name. This routine tries to generate a reasonable choice in those cases
104 # (one tactic is to populate <select> tags before the others), but it may
105 # not always be the intended choice.
106 # The input HTML must be valid HTML, of course. This routine makes a
107 # reasonable effort to support certain invalid but common HTML, but it
108 # makes no guarantee that all invalid HTML will be handled the same way
109 # that browsers do. If you get unexpected results, check that your input
110 # HTML is valid.
111 # A previous version allowed defaults to be sent as a full hash in the
112 # parameter list, instead of a reference. This feature was removed to
113 # better allow future support of named parameters; in other words, we're
114 # reserving the case of second-parameter-is-not-a-reference for use with
115 # named parameters. Additionally, that previous version would modify the
116 # hash in place if sent as a reference, but it was decided that wasn't the
117 # best API, so now the defaults hash is copied before being used and
118 # modified.
119  
120 0 ▶sub defaultify {
Subroutine defaultify: not called CC=10 SCAR=47.0
Pod documented
121 0 my($HTML, $defaults, $form_name)= @_ ;
122 0 my(@extracts, $i, $marker) ;
123 0 local($_) ;
124  
125 # First, temporarily remove all comments, <script>...</script> blocks,
126 # and <style>...</style> blocks from $HTML, to avoid matching tags
127 # inside them. Replace these extractions with markers, so they can be
128 # restored after defaultification is complete. Somewhat hacky approach,
129 # but works.
130 # Extractions are stored in @extracts, and the markers consist of: a random
131 # string not otherwise in $HTML, plus each extraction's location in
132 # @extracts, plus "\0".
133 # All four kinds of extractions (two comment formats, scripts, and styles)
134 # are handled simultaneously. This correctly handles cases of when
135 # "<script>" is inside a comment, or "<!--" is inside a script, etc.
136 # Note that comments ending with "--\s*>" take precedence over comments
137 # ending with just ">", so they must be the first alternative in the
138 # extraction regex below. The next comment explains the reasoning:
139 # Handling end-of-comments is tricky and varies slightly by browser,
140 # though all try to handle the illegal but common usage of comments
141 # ending with only ">" (they are supposed to end with "-->", with
142 # possible whitespace after the "--"). Netscape and Konqueror seem to
143 # end comments on "-->" if available (Konqueror allows the whitespace),
144 # else the comment ends on the next ">". So to extract comments here,
145 # first extract "<!-- ... --\s*>" blocks, then extract any remaining
146 # comments with "<!-- ... >" . The real solution is to use correct
147 # HTML in the first place, i.e. end comments with "-->".
148 # <script> and <style> blocks are supposed to end on the first "</" string,
149 # but in fact browsers seem to end those blocks at the actual </script>
150 # or </style> tags. This is most likely what the HTML author expects
151 # anyway, though it violates the HTML spec. Worse, browsers vary on
152 # whether they'll end a <script> block on a literal string "</script>"
153 # inside the script code. Balancing all this, for here it's a reasonable
154 # policy to end those blocks on "</script>" and "</style>".
155 # There's a potential problem with the marker: Even if it's not in
156 # $HTML, certain sequences could cause problems. Consider a marker of
157 # "xy1xy", and a comment preceded by "xy1". After the comment->marker
158 # replacement, the string is "xy1xy1xy" and will match too early. But
159 # since we know \d+\0 will always follow the marker, then excluding
160 # digits and \0 from the marker will prevent a wrong match like this.
161 # I'm pretty sure this solves it, but please tell me if you think of
162 # any combinations that could break this.
163  
164 # Generate a random 5-character string. Exclude digits, \0, and
165 # what the hell, "<" and ">".
166 # srand is automatically called in Perl 5.004 and later.
167 0 ▶ do {
Branch: 1 branch
BranchTrueFalseTotal
$HTML =~ /\Q$marker\E/ and do { do { $marker = pack("C5", map({rand(193) + 63;} 1..5)) } } 0 0 0
168 0 $marker= pack("C5", map {rand(193)+63} 1..5) ; # start after ">"
169 } while $HTML=~ /\Q$marker/ ;
170  
171 # Extract comments, <script> blocks, and <style> blocks into @extracts,
172 # replacing them with marker in $HTML. Note the order of the two
173 # comment formats.
174 0 $i= 0 ;
175 0 $HTML=~ s#(<!--.*?--\s*>|<!--.*?>|<\s*script\b.*?<\s*/script\b.*?>|<\s*style\b.*?<\s*/style\b.*?>)#
176 0 push(@extracts, $1), $marker . $i++ . "\0" #sgie ;
177  
178 # $HTML=~ s/(<!--.*?--\s*>)/ push(@comments,$1), $marker . $i++ . "\0" /sge ;
179 # $HTML=~ s/(<!--.*?>)/ push(@comments,$1), $marker . $i++ . "\0" /sge ;
180  
181  
182 # Next, defaultify either the entire $HTML or just one form within it.
183  
184 # If $form_name is given, then only update the form with that name.
185 # This must be done after comments are removed, above.
186 0 ▶ if ($form_name ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($form_name ne '') { } 0 0 0
187 # Here, replace each entire form by either: itself if "name" attribute
188 # doesn't match $form_name, or defaultified self if it does.
189 # Note that the resulting $defaults is saved.
190 # A little inefficient but not bad.
191 0 $HTML=~ s{(<\s*form\b.*?<\s*/form\b.*?>)} {
192 0 my($form)= $1 ; # avoid trouble if $1 gets clobbered
193 ($form, $defaults)= &defaultify($form, $defaults)
194 0 ▶ if (&parse_tag($form))[1]->{'name'} eq $form_name ;
Branch: 1 branch
BranchTrueFalseTotal
if +(&parse_tag($form))[1]->{"name"} eq $form_name 0 0 0
195 0 $form ;
196 }sgie ;
197  
198  
199 # If no form name was passed, defaultify entire $HTML. This is the meat
200 # of the module, always run at least once (possibly recursed into by
201 # substitution above).
202 } else {
203 0 my($radios_done)= {} ; # must initialize to reference to work correctly
204  
205 # First, set $defaults appropriately: make local copy of hash if it's
206 # a normal hash reference, or {} for undef, or croak.
207 0 ▶ if (ref($defaults) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $defaults eq 'HASH') { } 0 0 0
elsif (ref $defaults eq 'CGI') { } 0 0 0
elsif (not defined $defaults) { } 0 0 0
208 0 $defaults= { %$defaults } ;
209  
210 # make local copies of any referenced lists
211 0 foreach (keys %$defaults) {
212 0 ▶ $defaults->{$_}= [ @{$defaults->{$_}} ] if ref($defaults->{$_});
Branch: 1 branch
BranchTrueFalseTotal
if ref $defaults->{$_} 0 0 0
213 }
214  
215 # Special case-- if $defaults is a CGI object, use its Vars() method.
216 # Call in list context with {}, to make copy instead of tied hash.
217 } elsif (ref($defaults) eq 'CGI') {
218 0 $defaults= { $defaults->Vars() } ;
219  
220 # If $defaults is undef, use an empty hash (clears all form fields).
221 } elsif (!defined($defaults)) {
222 0 $defaults= {} ;
223  
224 # Otherwise, croak.
225 } else {
226 0 croak("Second parameter to defaultify() must be hash reference or undef") ;
227 }
228  
229  
230 # Now, replace all form fields with their defaultified versions!
231 # Update all <select><option>...</select>, <input>, and
232 # <textarea>...</textarea> blocks.
233  
234 0 $HTML=~ s#(<\s*select\b.*?<\s*/select\b.*?>)#
235 0 &new_select($1, $defaults) #sgie ;
236  
237 0 $HTML=~ s#(<\s*input\b.*?>)#
238 0 &new_inputtag($1, $defaults, $radios_done) #sgie ;
239  
240 0 $HTML=~ s#(<\s*textarea\b.*?<\s*/textarea\b.*?>)#
241 0 &new_textarea($1, $defaults) #sgie ;
242 }
243  
244  
245 # Finally, replace comments and <script> and <style> blocks back into $HTML.
246 0 $HTML=~ s/\Q$marker\E(\d+)\0/$extracts[$1]/g ;
247  
248  
249 0 ▶ return wantarray ? ($HTML, $defaults) : $HTML ;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 0 0 0
250 }
251  
252  
253  
254 # For the given <input> tag, set the correct default and return corrected tag.
255 # Any default value that is used is removed from %$defaults.
256 # The new tag may vary in attribute capitalization and order.
257 # Radio buttons are special in that only one with a given name may be set in
258 # the same form. Thus, we need to keep track of which radio buttons have
259 # been set, and pass as a parameter if the caller cares about this. The
260 # parameter is a reference to a hash, and the hash is modified in place
261 # when a radio button is set. The parameter is not required.
262 0 ▶sub new_inputtag {
Subroutine new_inputtag: not called CC=14 SCAR=53.5
Pod undocumented
263 0 my($old_tag, $defaults, $radios_done)= @_ ;
264 0 my($tag_name, $attr)= &parse_tag($old_tag) ;
265  
266 # Sanity check
267 0 ▶ croak("new_inputtag() called without <input>")
Branch: 1 branch
BranchTrueFalseTotal
unless lc $tag_name eq "input" 0 0 0
268 unless lc($tag_name) eq 'input' ;
269  
270 # Lowercase type attribute for easier comparisons
271 0 $attr->{'type'}= lc($attr->{'type'}) ;
272  
273 # For text fields, replace value with default value.
274 0 ▶ if (($attr->{'type'} eq '') or $attr->{'type'}=~ /^(text|password)$/i ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($attr->{'type'} eq '' or $attr->{'type'} =~ /^(text|password)$/i) { } 0 0 0
elsif ($attr->{'type'} eq 'checkbox') { } 0 0 0
elsif ($attr->{'type'} eq 'radio') { } 0 0 0
Condition0%0/3
$attr->{"type"} eq "" or $attr->{"type"} =~ /^(text|password)$/i
l!l&&r!l&&!r
000
MC/DC0%0/2
$attr->{"type"} eq "" or $attr->{"type"} =~ /^(text|password)$/i
$attr->{"type"} eq "" $attr->{"type"} =~ /^(text|password)$/i
Truth table0%0/3
A or B
A= $attr->{"type"} eq ""B= $attr->{"type"} =~ /^(text|password)$/i
ABresult
1X1
011
000
275 0 $attr->{'value'}= &extract_default($defaults, $attr->{'name'}) ;
276  
277 # Delete value attribute if it's just set to "".
278 0 ▶ delete($attr->{'value'}) if $attr->{'value'} eq '' ;
Branch: 1 branch
BranchTrueFalseTotal
if $attr->{"value"} eq "" 0 0 0
279  
280 # Some old versions of Perl create $attr->{'type'} above, so remove it.
281 0 ▶ delete($attr->{'type'}) if $attr->{'type'} eq '' ;
Branch: 1 branch
BranchTrueFalseTotal
if $attr->{"type"} eq "" 0 0 0
282  
283 # For checkboxes, set "checked" if value matches default.
284 } elsif ($attr->{'type'} eq 'checkbox') {
285 0 ▶ my($value)= defined($attr->{'value'}) ? $attr->{'value'} : 'on' ;
Branch: 1 branch
BranchTrueFalseTotal
defined $attr->{'value'} ? : 0 0 0
286 $attr->{'checked'}=
287 0 ▶ &extract_default_if_match($defaults, $attr->{'name'}, $value)
Branch: 1 branch
BranchTrueFalseTotal
&extract_default_if_match($defaults, $attr->{'name'}, $value) ? : 0 0 0
288 ? '' : undef ;
289  
290 # For radio buttons, set "checked" if value matches default.
291 # Do not set "checked" if another same-named radio button is already set.
292 } elsif ($attr->{'type'} eq 'radio') {
293 0 ▶ my($value)= defined($attr->{'value'}) ? $attr->{'value'} : 'on' ;
Branch: 1 branch
BranchTrueFalseTotal
defined $attr->{'value'} ? : 0 0 0
294 0 ▶ if ($radios_done->{$attr->{'name'}}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($$radios_done{$attr->{'name'}}) { } 0 0 0
elsif (&extract_default_if_match($defaults, $attr->{'name'}, $value)) { } 0 0 0
295 0 undef($attr->{'checked'}) ;
296  
297 } elsif (&extract_default_if_match($defaults, $attr->{'name'}, $value)) {
298 0 $attr->{'checked'}= '' ;
299 0 ▶ $radios_done->{$attr->{'name'}}= 1 if ref($radios_done) ;
Branch: 1 branch
BranchTrueFalseTotal
if ref $radios_done 0 0 0
300 } else {
301 0 undef($attr->{'checked'}) ;
302 }
303  
304 # For other or unknown <input> field types, return tag unchanged.
305 } else {
306 0 return $old_tag ;
307 }
308  
309 0 return &build_tag($tag_name, $attr) ;
310 }
311  
312  
313  
314 # For the given <textarea>...</textarea> block, set the correct default.
315 # Any default value that is used is removed from %$defaults.
316 # The new tags may vary in attribute capitalization and order.
317 0 ▶sub new_textarea {
Subroutine new_textarea: not called CC=2 SCAR=17.9
Pod undocumented
318 0 my($old_block, $defaults)= @_ ;
319 0 my($tag_name, $attr)= &parse_tag($old_block) ; # parses first tag only
320  
321 # Sanity check
322 0 ▶ croak("new_textarea() called without <textarea>")
Branch: 1 branch
BranchTrueFalseTotal
unless lc $tag_name eq "textarea" 0 0 0
323 unless lc($tag_name) eq 'textarea' ;
324  
325 # Set text between <textarea> and </textarea> to the default.
326 0 my($contents)= &HTMLescape(&extract_default($defaults, $attr->{'name'})) ;
327 0 $old_block=~ s#>.*?<\s*/textarea\b#>$contents</textarea# ;
328  
329 0 return $old_block ;
330 }
331  
332  
333 # For the given <select>...</select> block, set the correct default.
334 # Any default value that is used is removed from %$defaults.
335 # The new tags may vary in attribute capitalization and order.
336 0 ▶sub new_select {
Subroutine new_select: not called CC=5 SCAR=34.0
Pod undocumented
337 0 my($old_block, $defaults)= @_ ;
338 0 my($tag_name, $attr)= &parse_tag($old_block) ; # parses first tag only
339  
340 # Sanity check
341 0 ▶ croak("new_select() called without <select>")
Branch: 1 branch
BranchTrueFalseTotal
unless lc $tag_name eq "select" 0 0 0
342 unless lc($tag_name) eq 'select' ;
343  
344 # Only allow one option to be set unless <select> has "multiple" attribute.
345 # Tricky to update only the first matching option. Here, we split() with
346 # "delimiters", where the delimiters are what we really care about.
347 # The "<option>..." strings are in array elements 1, 3, 5, ....
348 # Note the fourth parameter to new_option() is used to force remaining
349 # options to be unselected after one is set. Kinda hacky, but works.
350 0 my(@options, $i, $is_selected, $is_done) ;
351 0 @options= split( /(<\s*option[^>]*>[^<]*)/i , $old_block) ;
352 0 ▶ for ($i= 1 ; $i<= $#options ; $i+= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $#options) 0 0 0
353 ($options[$i], $is_selected)=
354 0 &new_option($options[$i], $defaults, $attr->{'name'}, $is_done) ;
355 0 ▶ $is_done||= $is_selected && !defined($attr->{'multiple'}) ;
Condition0%0/6
$is_done ||= $is_selected && !defined($attr->{"multiple"})
l!l&&r!l&&!r
000
$is_selected && !defined($attr->{'multiple'})
!ll&&!rl&&r
000
MC/DC0%0/3
$is_done ||= $is_selected && !defined($attr->{"multiple"})
$is_done $is_selected !defined($attr->{'multiple'})
Truth table0%0/4
A ||= B && not(C)
A= $is_doneB= $is_selectedC= !defined($attr->{'multiple'})
ABCresult
1XX1
0111
00X0
0100
356 }
357  
358 # Rejoin the <select> block, including both updated options and any other
359 # text before, after, or interspersed within.
360 0 return join('', @options) ;
361 }
362  
363  
364 # For the given <option>... block, set "selected" as required.
365 # Returns new <option>... block, and a flag indicating whether it was selected.
366 # Any default value that is used is removed from %$defaults.
367 # The new tag may vary in attribute capitalization and order.
368 # An alternate use is to merely remove any selected attribute if
369 # $force_off is set; this is used by new_select().
370 0 ▶sub new_option {
Subroutine new_option: not called CC=6 SCAR=37.4
Pod undocumented
371 0 my($old_block, $defaults, $name, $force_off)= @_ ;
372 0 my($tag_name, $attr)= &parse_tag($old_block) ; # parses first tag only
373 0 my($orig_text, $remainder)= $old_block=~ />([^<]*)(.*)/s ;
374 0 my($is_match) ;
375  
376 # Sanity check
377 0 ▶ croak("new_option() called without <option>")
Branch: 1 branch
BranchTrueFalseTotal
unless lc $tag_name eq "option" 0 0 0
378 unless lc($tag_name) eq 'option' ;
379  
380 # If $force_off is set, then set $is_match=0 .
381 0 ▶ if ($force_off) {
Branch: 2 branches
BranchTrueFalseTotal
if ($force_off) { } 0 0 0
elsif (defined $attr->{'value'}) { } 0 0 0
382 0 $is_match= 0 ;
383  
384 # If "value" attribute exists, then test match using it.
385 } elsif (defined($attr->{'value'})) {
386 0 $is_match= &extract_default_if_match($defaults, $name, $attr->{'value'}) ;
387  
388 # Otherwise, test match using text following <option> tag.
389 # Apparently, Netscape strips leading and trailing blanks before sending
390 # menu selections. Thus, compare with or without leading/trailing blanks.
391 } else {
392 0 my($stripped_text)= $orig_text ;
393 0 $stripped_text=~ s/^\s+|\s+$//g ;
394  
395 # Compare to original or stripped text. Note short-circuit "||".
396 0 ▶ $is_match= &extract_default_if_match($defaults, $name, $orig_text)
Condition0%0/3
&extract_default_if_match($defaults, $name, $orig_text) || &extract_default_if_match($defaults, $name, $stripped_text)
l!l&&r!l&&!r
000
MC/DC0%0/2
&extract_default_if_match($defaults, $name, $orig_text) || &extract_default_if_match($defaults, $name, $stripped_text)
&extract_default_if_match($defaults, $name, $orig_text) &extract_default_if_match($defaults, $name, $stripped_text)
Truth table0%0/3
A || B
A= &extract_default_if_match($defaults, $name, $orig_text)B= &extract_default_if_match($defaults, $name, $stripped_text)
ABresult
1X1
011
000
397 || &extract_default_if_match($defaults, $name, $stripped_text) ;
398 }
399  
400 0 ▶ $attr->{'selected'}= $is_match ? '' : undef ;
Branch: 1 branch
BranchTrueFalseTotal
$is_match ? : 0 0 0
401  
402 0 return (&build_tag($tag_name,$attr) . $orig_text . $remainder, $is_match) ;
403 }
404  
405  
406 #---- extract_default() and extract_default_if_match() ---------------
407  
408 # $is_match= &extract_default_if_match($defaults, $name, $value) ;
409 # $value= &extract_default($defaults, $name) ;
410  
411 # Each default (hash element) may be a scalar, a scalar with a "\0"-delimited
412 # list of strings, or a reference to a list.
413  
414 # Return the default value for the given field name. If there is more than one
415 # default (i.e. a list of values), return the first one. Return undef if
416 # there is no default for the given field.
417 # As a side effect, remove the returned value from the existing default set.
418 0 ▶sub extract_default {
Subroutine extract_default: not called CC=5 SCAR=34.0
Pod undocumented
419 0 my($defaults, $name)= @_ ;
420 0 my($value) ;
421  
422 # Handle the three possible cases of the hash element.
423 # First, handle if it's a reference to a list; ...
424 0 ▶ if (ref($defaults->{$name})) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $defaults->{$name}) { } 0 0 0
elsif ($defaults->{$name} =~ /\0/) { } 0 0 0
425 croak("Default for '$name' is a non-ARRAY reference")
426 0 ▶ unless ref($defaults->{$name}) eq 'ARRAY' ;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $defaults->{$name} eq "ARRAY" 0 0 0
427 0 $value= shift(@{$defaults->{$name}}) ;
428 0 ▶ delete($defaults->{$name}) if @{$defaults->{$name}}==0 ;
Branch: 1 branch
BranchTrueFalseTotal
if @{$defaults->{$name};} == 0 0 0 0
429  
430 # ... else, handle if it's a "\0"-delimited list of strings; ...
431 } elsif ($defaults->{$name}=~ /\0/) {
432 0 ($value, $defaults->{$name})= split(/\0/, $defaults->{$name}, 2) ;
433 # will never need to delete hash element here.
434  
435 # ... else handle case of normal scalar (including undef).
436 } else {
437 0 $value= $defaults->{$name} ;
438 0 delete($defaults->{$name}) ;
439 }
440  
441 0 return $value ;
442 }
443  
444  
445  
446 # Return true iff there is a default for the given field name that matches the
447 # given value (used for things like checkboxes or select menus). Return
448 # undef if there is no default for the given field.
449 # As a side effect, remove the matched value from the existing default set.
450 0 ▶sub extract_default_if_match {
Subroutine extract_default_if_match: not called CC=11 SCAR=48.8
Pod undocumented
451 0 my($defaults, $name, $value)= @_ ;
452 0 my($is_match, $i) ;
453  
454 # Return undef (false) if no defaults are defined for this field.
455 0 ▶ return undef unless defined($defaults->{$name}) ;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $defaults->{$name} 0 0 0
456  
457 # Handle the three possible cases of the hash element.
458 # First, handle if it's a reference to a list; ...
459 0 ▶ if (ref($defaults->{$name})) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $defaults->{$name}) { } 0 0 0
elsif ($defaults->{$name} =~ /\0/) { } 0 0 0
460 croak("Default for '$name' is a non-ARRAY reference")
461 0 ▶ unless ref($defaults->{$name}) eq 'ARRAY' ;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $defaults->{$name} eq "ARRAY" 0 0 0
462 0 foreach $i (0..$#{$defaults->{$name}}) {
463 0 ▶ if ($defaults->{$name}[$i] eq $value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($defaults->{$name}[$i] eq $value) 0 0 0
464 0 $is_match= 1 ;
465 0 splice(@{$defaults->{$name}}, $i, 1) ;
466 0 ▶ delete($defaults->{$name}) if @{$defaults->{$name}}==0 ;
Branch: 1 branch
BranchTrueFalseTotal
if @{$defaults->{$name};} == 0 0 0 0
467 0 last ;
468 }
469 }
470  
471 # ... else, handle if it's a "\0"-delimited list of strings; ...
472 } elsif ($defaults->{$name}=~ /\0/) {
473 # Split into list, then manage like above.
474 # Note that w/o a LIMIT, split() drops trailing '' from the result. :P
475 0 my(@values)= split(/\0/, $defaults->{$name}, length($defaults->{$name})) ;
476 0 foreach $i (0..$#values) {
477 0 ▶ if ($values[$i] eq $value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($values[$i] eq $value) 0 0 0
478 0 $is_match= 1 ;
479 0 splice(@values, $i, 1) ;
480 0 $defaults->{$name}= join("\0", @values) ;
481 # will never need to delete hash element here.
482 0 last ;
483 }
484 }
485  
486 # ... else handle case of normal scalar.
487 } else {
488 0 ▶ if ($defaults->{$name} eq $value) {
Branch: 1 branch
BranchTrueFalseTotal
if ($defaults->{$name} eq $value) 0 0 0
489 0 $is_match= 1 ;
490 0 delete($defaults->{$name}) ;
491 }
492 }
493  
494 0 return $is_match ;
495 }
496  
497  
498 #---- parse_tag() and build_tag() ------------------------------------
499  
500 # Parses an HTML tag into its tagname and attributes.
501 # Parses first tag in string, ignoring all before and after.
502 # Returns tag name and reference to hash of attributes. The hash keys
503 # (attribute names) are lowercased, and the values are de-quoted with
504 # character entity references replaced by their characters where possible.
505 0 ▶sub parse_tag {
Subroutine parse_tag: not called CC=3 SCAR=24.8
Pod documented
506 0 my($tag)= @_ ;
507 0 my($tag_name, $attrs, $attr) ;
508 0 local($_) ;
509  
510 # Remove comments to avoid parsing tag within one.
511 # See defaultify() above for notes about removing comments.
512 0 $tag=~ s/<!--.*?--\s*>//sg ;
513 0 $tag=~ s/<!--.*?>//sg ;
514  
515 # SGML tag and attribute names match "\w[\w.-]*" , except no underscores. Oh well.
516 # Include possible "/" at start.
517 0 ($tag_name,$attrs)= $tag=~ /<\s*(\/?\w[\w.-]*)\s*([^>]*)/ ; # first tag only
518  
519 # Extract name/value (possibly quoted), lowercase name, set $attr->{}.
520 # If quoted, delimited by quotes; if not, delimited by whitespace.
521 0 ▶ $attr->{lc($1)}= &HTMLunescape($+)
Branch: 1 branch
BranchTrueFalseTotal
$attrs =~ s/\s*(\w[\w.-]*)\s*=\s*(([^"']\S*)|"([^"]*)"?|'([^']*)'?)// and do { $$attr{lc $1} = &HTMLunescape($+) } 0 0 0
522 while $attrs=~ s/\s*(\w[\w.-]*)\s*=\s*(([^"']\S*)|"([^"]*)"?|'([^']*)'?)// ;
523  
524 # Now, get remaining non-valued attributes.
525 # Technically, HTML attributes with no value given get a value equal to the
526 # attribute name, e.g. a plain 'selected' means 'selected="selected"' .
527 # However, most browsers seem to treat them as having a value of "",
528 # so *sigh* we'll do that here.
529 0 foreach ($attrs=~ /(\w[\w.-]*)/g) { $attr->{+lc}= '' }
530  
531 0 return($tag_name, $attr) ;
532 }
533  
534  
535 # Build a tag from its name and attributes.
536 # Attributes can be passed as either a hash or a reference to one.
537 0 ▶sub build_tag {
Subroutine build_tag: not called CC=5 SCAR=34.0
Pod documented
538 0 my($tag_name)= shift ;
539 0 my($attr, $attrs) ;
540 0 local($_) ;
541  
542 # passed by reference or by values?
543 0 ▶ $attr= ref($_[0]) ? $_[0] : { @_ } ;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 0 0
544  
545 # Undefined attributes are dropped, and attributes equal to "" are put
546 # in the tag with no value. See note in parse_tag().
547 0 foreach (keys %$attr) {
548 0 ▶ next unless defined($attr->{$_}) ;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $attr->{$_} 0 0 0
549 $attrs.= ( ($attr->{$_} ne '')
550 0 ▶ ? (" $_=\"" . &HTMLescape($attr->{$_}) . '"')
Branch: 1 branch
BranchTrueFalseTotal
$attr->{$_} ne '' ? : 0 0 0
551 : " $_" ) ;
552 }
553
554 0 return "<$tag_name$attrs>" ;
555 }
556  
557  
558 #---- hidden_vars() and hidden_var() ---------------------------------
559  
560 # For the given set of form data, create a block of hidden form variables
561 # that represents that data.
562 # Each hash element represents a field; each hash value can be a scalar, a
563 # "\0"-delimited list of strings, or a reference to a real list.
564 0 ▶sub hidden_vars {
Subroutine hidden_vars: not called CC=9 SCAR=45.0
Pod documented
565 0 my($f, @ret, $ret, $name, $value) ;
566  
567 # First, set the hash of fields we'll use
568 0 ▶ $f= ref($_[0]) ? $_[0] : { @_ } ; # passed by reference or by values?
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 0 0 0
569  
570 # Then, for each field, add one or more <input type=hidden> tags to @ret.
571 # Don't include undefined variables.
572 0 foreach $name (keys %$f) {
573 0 ▶ if (defined($f->{$name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $f->{$name}) 0 0 0
574  
575 # Handle the three possible cases of the hash element.
576 # First, handle if it's a reference to a list; ...
577 0 ▶ if (ref($f->{$name})) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $f->{$name}) { } 0 0 0
elsif ($f->{$name} =~ /\0/) { } 0 0 0
578 0 foreach $value (@{$f->{$name}}) {
579 0 ▶ push(@ret, &hidden_var($name, $value)) if defined($value) ;
Branch: 1 branch
BranchTrueFalseTotal
if defined $value 0 0 0
580 }
581  
582 # ... else, handle if it's a "\0"-delimited list of strings; ...
583 } elsif ($f->{$name}=~ /\0/) {
584 # Note that w/o a LIMIT, split() drops trailing ''. :P
585 # No values here will be undefined.
586 0 push(@ret, map { &hidden_var($name, $_) }
587 0 split(/\0/, $f->{$name}, length($f->{$name}))) ;
588  
589 # ... else handle case of normal scalar.
590 } else {
591 push(@ret, &hidden_var($name, $f->{$name}))
592 0 ▶ if defined($f->{$name}) ;
Branch: 1 branch
BranchTrueFalseTotal
if defined $f->{$name} 0 0 0
593 }
594 }
595 }
596  
597 0 return join("\n", @ret) ;
598 }
599  
600  
601 # Returns an <input type=hidden> tag to represent the given form field.
602 0 ▶sub hidden_var {
Subroutine hidden_var: not called CC=1 SCAR=6.9
Pod documented
603 0 my($name, $value)= @_ ;
604  
605 0 return '<input type=hidden name="' . &HTMLescape($name)
606 . '" value="' . &HTMLescape($value) . "\">" ;
607 }
608  
609  
610 #---- subhash() ------------------------------------------------------
611  
612 # Returns a subset of the referenced hash, consisting of those elements
613 # named by @keys.
614 # Returns a reference to the hash. To get the hash itself, use e.g.
615 # "%my_hash= %{ &subhash(...) }" . We removed the list-context option
616 # of returning the full hash, because this is usually called in a list
617 # context where the hash reference is wanted (such as in a parameter
618 # list to &defaultify() ).
619 # Any elements requested but not present in the input hash will exist
620 # in the result hash, with an undefined value.
621 # How I wish Perl supported a "%hash{@subscripts}" notation for slices!
622 0 ▶sub subhash {
Subroutine subhash: not called CC=1 SCAR=6.9
Pod documented
623 0 my($hashref, @keys)= @_ ;
624 0 my(%ret) ;
625  
626 0 @ret{@keys}= @$hashref{@keys} ; # non-existent elements set to undef
627  
628 # return wantarray ? %ret : \%ret ; # no longer
629 0 return \%ret ;
630 }
631  
632  
633 #---- HTMLescape() and HTMLunescape() --------------------------------
634  
635 # Escape any &"<> chars to &xxx; and return resulting string.
636 # Use HTML::Entities if possible, else do adequate job here.
637 # There is still a slight risk-- if the input here has a character
638 # entity reference that was not properly unescaped before (like if
639 # HTMLunescape() can't use HTML::Entities), then the resulting string
640 # here will be doubly-escaped, e.g. "&amp;xyz;" .
641 0 ▶sub HTMLescape {
Subroutine HTMLescape: not called CC=2 SCAR=17.9
Pod undocumented
642 0 my($s)= @_ ;
643  
644 # If we have the HTML::Entities module, encode using that.
645 0 ▶ return encode_entities($s) if $HAS_HTML_ENTITIES ;
Branch: 1 branch
BranchTrueFalseTotal
if $HTML::Defaultify::HAS_HTML_ENTITIES 0 0 0
646  
647 # Otherwise, do a simplified version that encodes &"<> chars.
648 0 $s=~ s/&/&amp;/g ; # must be before all others
649 0 $s=~ s/"/&quot;/g ;
650 0 $s=~ s/</&lt;/g ;
651 0 $s=~ s/>/&gt;/g ;
652 0 return $s ;
653 }
654  
655  
656 # Unescape any character entity references and return resulting string.
657 # Use HTML::Entities if possible, else do adequate job here.
658 # Possible flaw here-- if there is a character entity reference that this
659 # routine does not handle, then data is lost. For example, input strings
660 # of both "&amp;xyz;" and "&xyz;" result in output of "&xyz;" . This is
661 # only a flaw if "&xyz;" is an actual character entity reference; otherwise,
662 # those two input strings actually represent the same data anyway.
663 0 ▶sub HTMLunescape {
Subroutine HTMLunescape: not called CC=4 SCAR=30.0
Pod undocumented
664 0 my($s)= @_ ;
665  
666 # Original code; mirrors that in HTMLescape().
667 # $s=~ s/&quot;/"/g ;
668 # $s=~ s/&lt;/</g ;
669 # $s=~ s/&gt;/>/g ;
670 # $s=~ s/&amp;/&/g ; # must be after all others
671 # return $s ;
672  
673 # If we have the HTML::Entities module, decode using that.
674 0 ▶ return decode_entities($s) if $HAS_HTML_ENTITIES ;
Branch: 1 branch
BranchTrueFalseTotal
if $HTML::Defaultify::HAS_HTML_ENTITIES 0 0 0
675  
676 # Otherwise, do a simplified version ourselves. Decode &"<> chars
677 # and "&#nnn;" codes; otherwise, leave "&...;" sequences unchanged.
678 0 my(%echar)= ('quot', '"', 'lt', '<', 'gt', '>', 'amp', '&') ;
679 0 $s=~ s/(&([a-zA-Z][a-zA-Z0-9.-]*);?|&#([0-9]+);?)/
680 length($3) ? sprintf("%c",$3)
681 0 ▶ : defined($echar{$2}) ? $echar{$2}
Branch: 2 branches
BranchTrueFalseTotal
length $3 ? : 0 0 0
defined $echar{$2} ? : 0 0 0
682 : $1
683 /ge ;
684 0 return $s ;
685 }
686  
687  
688 #---- end of module! -------------------------------------------------------
689  
690 # return true
691 1 1 ;
692  
693 __END__
↑ Summary