?????????? ????????? - ??????????????? - /home/agenciai/public_html/cd38d8/HTML.zip
???????
PK #L�[�x�\ \ Template.pmnu �[��� package HTML::Template; $HTML::Template::VERSION = '2.97'; =head1 NAME HTML::Template - Perl module to use HTML-like templating language =head1 SYNOPSIS First you make a template - this is just a normal HTML file with a few extra tags, the simplest being C<< <TMPL_VAR> >> For example, test.tmpl: <html> <head><title>Test Template</title></head> <body> My Home Directory is <TMPL_VAR NAME=HOME> <p> My Path is set to <TMPL_VAR NAME=PATH> </body> </html> Now you can use it in a small CGI program: #!/usr/bin/perl -w use HTML::Template; # open the html template my $template = HTML::Template->new(filename => 'test.tmpl'); # fill in some parameters $template->param(HOME => $ENV{HOME}); $template->param(PATH => $ENV{PATH}); # send the obligatory Content-Type and print the template output print "Content-Type: text/html\n\n", $template->output; If all is well in the universe this should show something like this in your browser when visiting the CGI: My Home Directory is /home/some/directory My Path is set to /bin;/usr/bin =head1 DESCRIPTION This module attempts to make using HTML templates simple and natural. It extends standard HTML with a few new HTML-esque tags - C<< <TMPL_VAR> >> C<< <TMPL_LOOP> >>, C<< <TMPL_INCLUDE> >>, C<< <TMPL_IF> >>, C<< <TMPL_ELSE> >> and C<< <TMPL_UNLESS> >>. The file written with HTML and these new tags is called a template. It is usually saved separate from your script - possibly even created by someone else! Using this module you fill in the values for the variables, loops and branches declared in the template. This allows you to separate design - the HTML - from the data, which you generate in the Perl script. This module is licensed under the same terms as Perl. See the LICENSE section below for more details. =head1 TUTORIAL If you're new to HTML::Template, I suggest you start with the introductory article available on Perl Monks: http://www.perlmonks.org/?node_id=65642 =head1 FAQ Please see L<HTML::Template::FAQ> =head1 MOTIVATION It is true that there are a number of packages out there to do HTML templates. On the one hand you have things like L<HTML::Embperl> which allows you freely mix Perl with HTML. On the other hand lie home-grown variable substitution solutions. Hopefully the module can find a place between the two. One advantage of this module over a full L<HTML::Embperl>-esque solution is that it enforces an important divide - design and programming. By limiting the programmer to just using simple variables and loops in the HTML, the template remains accessible to designers and other non-perl people. The use of HTML-esque syntax goes further to make the format understandable to others. In the future this similarity could be used to extend existing HTML editors/analyzers to support HTML::Template. An advantage of this module over home-grown tag-replacement schemes is the support for loops. In my work I am often called on to produce tables of data in html. Producing them using simplistic HTML templates results in programs containing lots of HTML since the HTML itself cannot represent loops. The introduction of loop statements in the HTML simplifies this situation considerably. The designer can layout a single row and the programmer can fill it in as many times as necessary - all they must agree on is the parameter names. For all that, I think the best thing about this module is that it does just one thing and it does it quickly and carefully. It doesn't try to replace Perl and HTML, it just augments them to interact a little better. And it's pretty fast. =head1 THE TAGS =head2 TMPL_VAR <TMPL_VAR NAME="PARAMETER_NAME"> The C<< <TMPL_VAR> >> tag is very simple. For each C<< <TMPL_VAR> >> tag in the template you call: $template->param(PARAMETER_NAME => "VALUE") When the template is output the C<< <TMPL_VAR> >> is replaced with the VALUE text you specified. If you don't set a parameter it just gets skipped in the output. You can also specify the value of the parameter as a code reference in order to have "lazy" variables. These sub routines will only be referenced if the variables are used. See L<LAZY VALUES> for more information. =head3 Attributes The following "attributes" can also be specified in template var tags: =over =item * escape This allows you to escape the value before it's put into the output. This is useful when you want to use a TMPL_VAR in a context where those characters would cause trouble. For example: <input name=param type=text value="<TMPL_VAR PARAM>"> If you called C<param()> with a value like C<sam"my> you'll get in trouble with HTML's idea of a double-quote. On the other hand, if you use C<escape=html>, like this: <input name=param type=text value="<TMPL_VAR PARAM ESCAPE=HTML>"> You'll get what you wanted no matter what value happens to be passed in for param. The following escape values are supported: =over =item * html Replaces the following characters with their HTML entity equivalent: C<&>, C<">, C<'>, C<< < >>, C<< > >> =item * js Escapes (with a backslash) the following characters: C<\>, C<'>, C<">, C<\n>, C<\r> =item * url URL escapes any ASCII characters except for letters, numbers, C<_>, C<.> and C<->. =item * none Performs no escaping. This is the default, but it's useful to be able to explicitly turn off escaping if you are using the C<default_escape> option. =back =item * default With this attribute you can assign a default value to a variable. For example, this will output "the devil gave me a taco" if the C<who> variable is not set. <TMPL_VAR WHO DEFAULT="the devil"> gave me a taco. =back =head2 TMPL_LOOP <TMPL_LOOP NAME="LOOP_NAME"> ... </TMPL_LOOP> The C<< <TMPL_LOOP> >> tag is a bit more complicated than C<< <TMPL_VAR> >>. The C<< <TMPL_LOOP> >> tag allows you to delimit a section of text and give it a name. Inside this named loop you place C<< <TMPL_VAR> >>s. Now you pass to C<param()> a list (an array ref) of parameter assignments (hash refs) for this loop. The loop iterates over the list and produces output from the text block for each pass. Unset parameters are skipped. Here's an example: In the template: <TMPL_LOOP NAME=EMPLOYEE_INFO> Name: <TMPL_VAR NAME=NAME> <br> Job: <TMPL_VAR NAME=JOB> <p> </TMPL_LOOP> In your Perl code: $template->param( EMPLOYEE_INFO => [{name => 'Sam', job => 'programmer'}, {name => 'Steve', job => 'soda jerk'}] ); print $template->output(); The output is: Name: Sam Job: programmer Name: Steve Job: soda jerk As you can see above the C<< <TMPL_LOOP> >> takes a list of variable assignments and then iterates over the loop body producing output. Often you'll want to generate a C<< <TMPL_LOOP> >>'s contents programmatically. Here's an example of how this can be done (many other ways are possible!): # a couple of arrays of data to put in a loop: my @words = qw(I Am Cool); my @numbers = qw(1 2 3); my @loop_data = (); # initialize an array to hold your loop while (@words and @numbers) { my %row_data; # get a fresh hash for the row data # fill in this row $row_data{WORD} = shift @words; $row_data{NUMBER} = shift @numbers; # the crucial step - push a reference to this row into the loop! push(@loop_data, \%row_data); } # finally, assign the loop data to the loop param, again with a reference: $template->param(THIS_LOOP => \@loop_data); The above example would work with a template like: <TMPL_LOOP NAME="THIS_LOOP"> Word: <TMPL_VAR NAME="WORD"> Number: <TMPL_VAR NAME="NUMBER"> </TMPL_LOOP> It would produce output like: Word: I Number: 1 Word: Am Number: 2 Word: Cool Number: 3 C<< <TMPL_LOOP> >>s within C<< <TMPL_LOOP> >>s are fine and work as you would expect. If the syntax for the C<param()> call has you stumped, here's an example of a param call with one nested loop: $template->param( LOOP => [ { name => 'Bobby', nicknames => [{name => 'the big bad wolf'}, {name => 'He-Man'}], }, ], ); Basically, each C<< <TMPL_LOOP> >> gets an array reference. Inside the array are any number of hash references. These hashes contain the name=>value pairs for a single pass over the loop template. Inside a C<< <TMPL_LOOP> >>, the only variables that are usable are the ones from the C<< <TMPL_LOOP> >>. The variables in the outer blocks are not visible within a template loop. For the computer-science geeks among you, a C<< <TMPL_LOOP> >> introduces a new scope much like a perl subroutine call. If you want your variables to be global you can use C<global_vars> option to C<new()> described below. =head2 TMPL_INCLUDE <TMPL_INCLUDE NAME="filename.tmpl"> This tag includes a template directly into the current template at the point where the tag is found. The included template contents are used exactly as if its contents were physically included in the master template. The file specified can be an absolute path (beginning with a '/' under Unix, for example). If it isn't absolute, the path to the enclosing file is tried first. After that the path in the environment variable C<HTML_TEMPLATE_ROOT> is tried, if it exists. Next, the "path" option is consulted, first as-is and then with C<HTML_TEMPLATE_ROOT> prepended if available. As a final attempt, the filename is passed to C<open()> directly. See below for more information on C<HTML_TEMPLATE_ROOT> and the C<path> option to C<new()>. As a protection against infinitely recursive includes, an arbitrary limit of 10 levels deep is imposed. You can alter this limit with the C<max_includes> option. See the entry for the C<max_includes> option below for more details. =head2 TMPL_IF <TMPL_IF NAME="PARAMETER_NAME"> ... </TMPL_IF> The C<< <TMPL_IF> >> tag allows you to include or not include a block of the template based on the value of a given parameter name. If the parameter is given a value that is true for Perl - like '1' - then the block is included in the output. If it is not defined, or given a false value - like '0' - then it is skipped. The parameters are specified the same way as with C<< <TMPL_VAR> >>. Example Template: <TMPL_IF NAME="BOOL"> Some text that only gets displayed if BOOL is true! </TMPL_IF> Now if you call C<< $template->param(BOOL => 1) >> then the above block will be included by output. C<< <TMPL_IF> </TMPL_IF> >> blocks can include any valid HTML::Template construct - C<VAR>s and C<LOOP>s and other C<IF>/C<ELSE> blocks. Note, however, that intersecting a C<< <TMPL_IF> >> and a C<< <TMPL_LOOP> >> is invalid. Not going to work: <TMPL_IF BOOL> <TMPL_LOOP SOME_LOOP> </TMPL_IF> </TMPL_LOOP> If the name of a C<< <TMPL_LOOP> >> is used in a C<< <TMPL_IF> >>, the C<IF> block will output if the loop has at least one row. Example: <TMPL_IF LOOP_ONE> This will output if the loop is not empty. </TMPL_IF> <TMPL_LOOP LOOP_ONE> .... </TMPL_LOOP> WARNING: Much of the benefit of HTML::Template is in decoupling your Perl and HTML. If you introduce numerous cases where you have C<TMPL_IF>s and matching Perl C<if>s, you will create a maintenance problem in keeping the two synchronized. I suggest you adopt the practice of only using C<TMPL_IF> if you can do so without requiring a matching C<if> in your Perl code. =head2 TMPL_ELSE <TMPL_IF NAME="PARAMETER_NAME"> ... <TMPL_ELSE> ... </TMPL_IF> You can include an alternate block in your C<< <TMPL_IF> >> block by using C<< <TMPL_ELSE> >>. NOTE: You still end the block with C<< </TMPL_IF> >>, not C<< </TMPL_ELSE> >>! Example: <TMPL_IF BOOL> Some text that is included only if BOOL is true <TMPL_ELSE> Some text that is included only if BOOL is false </TMPL_IF> =head2 TMPL_UNLESS <TMPL_UNLESS NAME="PARAMETER_NAME"> ... </TMPL_UNLESS> This tag is the opposite of C<< <TMPL_IF> >>. The block is output if the C<PARAMETER_NAME> is set false or not defined. You can use C<< <TMPL_ELSE> >> with C<< <TMPL_UNLESS> >> just as you can with C<< <TMPL_IF> >>. Example: <TMPL_UNLESS BOOL> Some text that is output only if BOOL is FALSE. <TMPL_ELSE> Some text that is output only if BOOL is TRUE. </TMPL_UNLESS> If the name of a C<< <TMPL_LOOP> >> is used in a C<< <TMPL_UNLESS> >>, the C<< <UNLESS> >> block output if the loop has zero rows. <TMPL_UNLESS LOOP_ONE> This will output if the loop is empty. </TMPL_UNLESS> <TMPL_LOOP LOOP_ONE> .... </TMPL_LOOP> =cut =head2 NOTES HTML::Template's tags are meant to mimic normal HTML tags. However, they are allowed to "break the rules". Something like: <img src="<TMPL_VAR IMAGE_SRC>"> is not really valid HTML, but it is a perfectly valid use and will work as planned. The C<NAME=> in the tag is optional, although for extensibility's sake I recommend using it. Example - C<< <TMPL_LOOP LOOP_NAME> >> is acceptable. If you're a fanatic about valid HTML and would like your templates to conform to valid HTML syntax, you may optionally type template tags in the form of HTML comments. This may be of use to HTML authors who would like to validate their templates' HTML syntax prior to HTML::Template processing, or who use DTD-savvy editing tools. <!-- TMPL_VAR NAME=PARAM1 --> In order to realize a dramatic savings in bandwidth, the standard (non-comment) tags will be used throughout this documentation. =head1 METHODS =head2 new Call C<new()> to create a new Template object: my $template = HTML::Template->new( filename => 'file.tmpl', option => 'value', ); You must call C<new()> with at least one C<name => value> pair specifying how to access the template text. You can use C<< filename => 'file.tmpl' >> to specify a filename to be opened as the template. Alternately you can use: my $t = HTML::Template->new( scalarref => $ref_to_template_text, option => 'value', ); and my $t = HTML::Template->new( arrayref => $ref_to_array_of_lines, option => 'value', ); These initialize the template from in-memory resources. In almost every case you'll want to use the filename parameter. If you're worried about all the disk access from reading a template file just use mod_perl and the cache option detailed below. You can also read the template from an already opened filehandle, either traditionally as a glob or as a L<FileHandle>: my $t = HTML::Template->new(filehandle => *FH, option => 'value'); The four C<new()> calling methods can also be accessed as below, if you prefer. my $t = HTML::Template->new_file('file.tmpl', option => 'value'); my $t = HTML::Template->new_scalar_ref($ref_to_template_text, option => 'value'); my $t = HTML::Template->new_array_ref($ref_to_array_of_lines, option => 'value'); my $t = HTML::Template->new_filehandle($fh, option => 'value'); And as a final option, for those that might prefer it, you can call new as: my $t = HTML::Template->new( type => 'filename', source => 'file.tmpl', ); Which works for all three of the source types. If the environment variable C<HTML_TEMPLATE_ROOT> is set and your filename doesn't begin with "/", then the path will be relative to the value of c<HTML_TEMPLATE_ROOT>. B<Example> - if the environment variable C<HTML_TEMPLATE_ROOT> is set to F</home/sam> and I call C<< HTML::Template->new() >> with filename set to "sam.tmpl", HTML::Template will try to open F</home/sam/sam.tmpl> to access the template file. You can also affect the search path for files with the C<path> option to C<new()> - see below for more information. You can modify the Template object's behavior with C<new()>. The options are available: =head3 Error Detection Options =over =item * die_on_bad_params If set to 0 the module will let you call: $template->param(param_name => 'value') even if 'param_name' doesn't exist in the template body. Defaults to 1. =item * force_untaint If set to 1 the module will not allow you to set unescaped parameters with tainted values. If set to 2 you will have to untaint all parameters, including ones with the escape attribute. This option makes sure you untaint everything so you don't accidentally introduce e.g. cross-site-scripting (XSS) vulnerabilities. Requires taint mode. Defaults to 0. =item * strict - if set to 0 the module will allow things that look like they might be TMPL_* tags to get by without dieing. Example: <TMPL_HUH NAME=ZUH> Would normally cause an error, but if you call new with C<< strict => 0 >> HTML::Template will ignore it. Defaults to 1. =item * vanguard_compatibility_mode If set to 1 the module will expect to see C<< <TMPL_VAR> >>s that look like C<%NAME%> in addition to the standard syntax. Also sets C<die_on_bad_params => 0>. If you're not at Vanguard Media trying to use an old format template don't worry about this one. Defaults to 0. =back =head3 Caching Options =over =item * cache If set to 1 the module will cache in memory the parsed templates based on the filename parameter, the modification date of the file and the options passed to C<new()>. This only applies to templates opened with the filename parameter specified, not scalarref or arrayref templates. Caching also looks at the modification times of any files included using C<< <TMPL_INCLUDE> >> tags, but again, only if the template is opened with filename parameter. This is mainly of use in a persistent environment like Apache/mod_perl. It has absolutely no benefit in a normal CGI environment since the script is unloaded from memory after every request. For a cache that does work for a non-persistent environment see the C<shared_cache> option below. My simplistic testing shows that using cache yields a 90% performance increase under mod_perl. Cache defaults to 0. =item * shared_cache If set to 1 the module will store its cache in shared memory using the L<IPC::SharedCache> module (available from CPAN). The effect of this will be to maintain a single shared copy of each parsed template for all instances of HTML::Template on the same machine to use. This can be a significant reduction in memory usage in an environment with a single machine but multiple servers. As an example, on one of our systems we use 4MB of template cache and maintain 25 httpd processes - shared_cache results in saving almost 100MB! Of course, some reduction in speed versus normal caching is to be expected. Another difference between normal caching and shared_cache is that shared_cache will work in a non-persistent environment (like normal CGI) - normal caching is only useful in a persistent environment like Apache/mod_perl. By default HTML::Template uses the IPC key 'TMPL' as a shared root segment (0x4c504d54 in hex), but this can be changed by setting the C<ipc_key> C<new()> parameter to another 4-character or integer key. Other options can be used to affect the shared memory cache correspond to L<IPC::SharedCache> options - C<ipc_mode>, C<ipc_segment_size> and C<ipc_max_size>. See L<IPC::SharedCache> for a description of how these work - in most cases you shouldn't need to change them from the defaults. For more information about the shared memory cache system used by HTML::Template see L<IPC::SharedCache>. =item * double_cache If set to 1 the module will use a combination of C<shared_cache> and normal cache mode for the best possible caching. Of course, it also uses the most memory of all the cache modes. All the same ipc_* options that work with C<shared_cache> apply to C<double_cache> as well. Defaults to 0. =item * blind_cache If set to 1 the module behaves exactly as with normal caching but does not check to see if the file has changed on each request. This option should be used with caution, but could be of use on high-load servers. My tests show C<blind_cache> performing only 1 to 2 percent faster than cache under mod_perl. B<NOTE>: Combining this option with shared_cache can result in stale templates stuck permanently in shared memory! =item * file_cache If set to 1 the module will store its cache in a file using the L<Storable> module. It uses no additional memory, and my simplistic testing shows that it yields a 50% performance advantage. Like C<shared_cache>, it will work in a non-persistent environments (like CGI). Default is 0. If you set this option you must set the C<file_cache_dir> option. See below for details. B<NOTE>: L<Storable> uses C<flock()> to ensure safe access to cache files. Using C<file_cache> on a system or filesystem (like NFS) without C<flock()> support is dangerous. =item * file_cache_dir Sets the directory where the module will store the cache files if C<file_cache> is enabled. Your script will need write permissions to this directory. You'll also need to make sure the sufficient space is available to store the cache files. =item * file_cache_dir_mode Sets the file mode for newly created C<file_cache> directories and subdirectories. Defaults to "0700" for security but this may be inconvenient if you do not have access to the account running the webserver. =item * double_file_cache If set to 1 the module will use a combination of C<file_cache> and normal C<cache> mode for the best possible caching. The file_cache_* options that work with file_cache apply to C<double_file_cache> as well. Defaults to 0. =item * cache_lazy_vars The option tells HTML::Template to cache the values returned from code references used for C<TMPL_VAR>s. See L<LAZY VALUES> for details. =item * cache_lazy_loops The option tells HTML::Template to cache the values returned from code references used for C<TMPL_LOOP>s. See L<LAZY VALUES> for details. =back =head3 Filesystem Options =over =item * path You can set this variable with a list of paths to search for files specified with the C<filename> option to C<new()> and for files included with the C<< <TMPL_INCLUDE> >> tag. This list is only consulted when the filename is relative. The C<HTML_TEMPLATE_ROOT> environment variable is always tried first if it exists. Also, if C<HTML_TEMPLATE_ROOT> is set then an attempt will be made to prepend C<HTML_TEMPLATE_ROOT> onto paths in the path array. In the case of a C<< <TMPL_INCLUDE> >> file, the path to the including file is also tried before path is consulted. Example: my $template = HTML::Template->new( filename => 'file.tmpl', path => ['/path/to/templates', '/alternate/path'], ); B<NOTE>: the paths in the path list must be expressed as UNIX paths, separated by the forward-slash character ('/'). =item * search_path_on_include If set to a true value the module will search from the top of the array of paths specified by the path option on every C<< <TMPL_INCLUDE> >> and use the first matching template found. The normal behavior is to look only in the current directory for a template to include. Defaults to 0. =item * utf8 Setting this to true tells HTML::Template to treat your template files as UTF-8 encoded. This will apply to any file's passed to C<new()> or any included files. It won't do anything special to scalars templates passed to C<new()> since you should be doing the encoding on those yourself. my $template = HTML::Template->new( filename => 'umlauts_are_awesome.tmpl', utf8 => 1, ); Most templates are either ASCII (the default) or UTF-8 encoded Unicode. But if you need some other encoding other than these 2, look at the C<open_mode> option. B<NOTE>: The C<utf8> and C<open_mode> options cannot be used at the same time. =item * open_mode You can set this option to an opening mode with which all template files will be opened. For example, if you want to use a template that is UTF-16 encoded unicode: my $template = HTML::Template->new( filename => 'file.tmpl', open_mode => '<:encoding(UTF-16)', ); That way you can force a different encoding (than the default ASCII or UTF-8), CR/LF properties etc. on the template files. See L<PerlIO> for details. B<NOTE>: this only works in perl 5.7.1 and above. B<NOTE>: you have to supply an opening mode that actually permits reading from the file handle. B<NOTE>: The C<utf8> and C<open_mode> options cannot be used at the same time. =back =head3 Debugging Options =over =item * debug If set to 1 the module will write random debugging information to STDERR. Defaults to 0. =item * stack_debug If set to 1 the module will use Data::Dumper to print out the contents of the parse_stack to STDERR. Defaults to 0. =item * cache_debug If set to 1 the module will send information on cache loads, hits and misses to STDERR. Defaults to 0. =item * shared_cache_debug If set to 1 the module will turn on the debug option in L<IPC::SharedCache>. Defaults to 0. =item * memory_debug If set to 1 the module will send information on cache memory usage to STDERR. Requires the L<GTop> module. Defaults to 0. =back =head3 Miscellaneous Options =over =item * associate This option allows you to inherit the parameter values from other objects. The only requirement for the other object is that it have a C<param()> method that works like HTML::Template's C<param()>. A good candidate would be a L<CGI> query object. Example: my $query = CGI->new; my $template = HTML::Template->new( filename => 'template.tmpl', associate => $query, ); Now, C<< $template->output() >> will act as though $template->param(form_field => $cgi->param('form_field')); had been specified for each key/value pair that would be provided by the C<< $cgi->param() >> method. Parameters you set directly take precedence over associated parameters. You can specify multiple objects to associate by passing an anonymous array to the associate option. They are searched for parameters in the order they appear: my $template = HTML::Template->new( filename => 'template.tmpl', associate => [$query, $other_obj], ); B<NOTE>: The parameter names are matched in a case-insensitive manner. If you have two parameters in a CGI object like 'NAME' and 'Name' one will be chosen randomly by associate. This behavior can be changed by the C<case_sensitive> option. =item * case_sensitive Setting this option to true causes HTML::Template to treat template variable names case-sensitively. The following example would only set one parameter without the C<case_sensitive> option: my $template = HTML::Template->new( filename => 'template.tmpl', case_sensitive => 1 ); $template->param( FieldA => 'foo', fIELDa => 'bar', ); This option defaults to off. B<NOTE>: with C<case_sensitive> and C<loop_context_vars> the special loop variables are available in lower-case only. =item * loop_context_vars When this parameter is set to true (it is false by default) extra variables that depend on the loop's context are made available inside a loop. These are: =over =item * __first__ Value that is true for the first iteration of the loop and false every other time. =item * __last__ Value that is true for the last iteration of the loop and false every other time. =item * __inner__ Value that is true for the every iteration of the loop except for the first and last. =item * __outer__ Value that is true for the first and last iterations of the loop. =item * __odd__ Value that is true for the every odd iteration of the loop. =item * __even__ Value that is true for the every even iteration of the loop. =item * __counter__ An integer (starting from 1) whose value increments for each iteration of the loop. =item * __index__ An integer (starting from 0) whose value increments for each iteration of the loop. =back Just like any other C<TMPL_VAR>s these variables can be used in C<< <TMPL_IF> >>, C<< <TMPL_UNLESS> >> and C<< <TMPL_ELSE> >> to control how a loop is output. Example: <TMPL_LOOP NAME="FOO"> <TMPL_IF NAME="__first__"> This only outputs on the first pass. </TMPL_IF> <TMPL_IF NAME="__odd__"> This outputs every other pass, on the odd passes. </TMPL_IF> <TMPL_UNLESS NAME="__odd__"> This outputs every other pass, on the even passes. </TMPL_UNLESS> <TMPL_IF NAME="__inner__"> This outputs on passes that are neither first nor last. </TMPL_IF> This is pass number <TMPL_VAR NAME="__counter__">. <TMPL_IF NAME="__last__"> This only outputs on the last pass. </TMPL_IF> </TMPL_LOOP> One use of this feature is to provide a "separator" similar in effect to the perl function C<join()>. Example: <TMPL_LOOP FRUIT> <TMPL_IF __last__> and </TMPL_IF> <TMPL_VAR KIND><TMPL_UNLESS __last__>, <TMPL_ELSE>.</TMPL_UNLESS> </TMPL_LOOP> Would output something like: Apples, Oranges, Brains, Toes, and Kiwi. Given an appropriate C<param()> call, of course. B<NOTE>: A loop with only a single pass will get both C<__first__> and C<__last__> set to true, but not C<__inner__>. =item * no_includes Set this option to 1 to disallow the C<< <TMPL_INCLUDE> >> tag in the template file. This can be used to make opening untrusted templates B<slightly> less dangerous. Defaults to 0. =item * max_includes Set this variable to determine the maximum depth that includes can reach. Set to 10 by default. Including files to a depth greater than this value causes an error message to be displayed. Set to 0 to disable this protection. =item * die_on_missing_include If true, then HTML::Template will die if it can't find a file for a C<< <TMPL_INCLUDE> >>. This defaults to true. =item * global_vars Normally variables declared outside a loop are not available inside a loop. This option makes C<< <TMPL_VAR> >>s like global variables in Perl - they have unlimited scope. This option also affects C<< <TMPL_IF> >> and C<< <TMPL_UNLESS> >>. Example: This is a normal variable: <TMPL_VAR NORMAL>.<P> <TMPL_LOOP NAME=FROOT_LOOP> Here it is inside the loop: <TMPL_VAR NORMAL><P> </TMPL_LOOP> Normally this wouldn't work as expected, since C<< <TMPL_VAR NORMAL> >>'s value outside the loop is not available inside the loop. The global_vars option also allows you to access the values of an enclosing loop within an inner loop. For example, in this loop the inner loop will have access to the value of C<OUTER_VAR> in the correct iteration: <TMPL_LOOP OUTER_LOOP> OUTER: <TMPL_VAR OUTER_VAR> <TMPL_LOOP INNER_LOOP> INNER: <TMPL_VAR INNER_VAR> INSIDE OUT: <TMPL_VAR OUTER_VAR> </TMPL_LOOP> </TMPL_LOOP> One side-effect of C<global_vars> is that variables you set with C<param()> that might otherwise be ignored when C<die_on_bad_params> is off will stick around. This is necessary to allow inner loops to access values set for outer loops that don't directly use the value. B<NOTE>: C<global_vars> is not C<global_loops> (which does not exist). That means that loops you declare at one scope are not available inside other loops even when C<global_vars> is on. =item * filter This option allows you to specify a filter for your template files. A filter is a subroutine that will be called after HTML::Template reads your template file but before it starts parsing template tags. In the most simple usage, you simply assign a code reference to the filter parameter. This subroutine will receive a single argument - a reference to a string containing the template file text. Here is an example that accepts templates with tags that look like C<!!!ZAP_VAR FOO!!!> and transforms them into HTML::Template tags: my $filter = sub { my $text_ref = shift; $$text_ref =~ s/!!!ZAP_(.*?)!!!/<TMPL_$1>/g; }; # open zap.tmpl using the above filter my $template = HTML::Template->new( filename => 'zap.tmpl', filter => $filter, ); More complicated usages are possible. You can request that your filter receives the template text as an array of lines rather than as a single scalar. To do that you need to specify your filter using a hash-ref. In this form you specify the filter using the C<sub> key and the desired argument format using the C<format> key. The available formats are C<scalar> and C<array>. Using the C<array> format will incur a performance penalty but may be more convenient in some situations. my $template = HTML::Template->new( filename => 'zap.tmpl', filter => { sub => $filter, format => 'array', } ); You may also have multiple filters. This allows simple filters to be combined for more elaborate functionality. To do this you specify an array of filters. The filters are applied in the order they are specified. my $template = HTML::Template->new( filename => 'zap.tmpl', filter => [ { sub => \&decompress, format => 'scalar', }, { sub => \&remove_spaces, format => 'array', }, ] ); The specified filters will be called for any C<TMPL_INCLUDE>ed files just as they are for the main template file. =item * default_escape Set this parameter to a valid escape type (see the C<escape> option) and HTML::Template will apply the specified escaping to all variables unless they declare a different escape in the template. =back =cut use integer; # no floating point math so far! use strict; # and no funny business, either. use Carp; # generate better errors with more context use File::Spec; # generate paths that work on all platforms use Digest::MD5 qw(md5_hex); # generate cache keys use Scalar::Util qw(tainted); # define accessor constants used to improve readability of array # accesses into "objects". I used to use 'use constant' but that # seems to cause occasional irritating warnings in older Perls. package HTML::Template::LOOP; sub TEMPLATE_HASH () { 0 } sub PARAM_SET () { 1 } package HTML::Template::COND; sub VARIABLE () { 0 } sub VARIABLE_TYPE () { 1 } sub VARIABLE_TYPE_VAR () { 0 } sub VARIABLE_TYPE_LOOP () { 1 } sub JUMP_IF_TRUE () { 2 } sub JUMP_ADDRESS () { 3 } sub WHICH () { 4 } sub UNCONDITIONAL_JUMP () { 5 } sub IS_ELSE () { 6 } sub WHICH_IF () { 0 } sub WHICH_UNLESS () { 1 } # back to the main package scope. package HTML::Template; my %OPTIONS; # set the default options BEGIN { %OPTIONS = ( debug => 0, stack_debug => 0, timing => 0, search_path_on_include => 0, cache => 0, blind_cache => 0, file_cache => 0, file_cache_dir => '', file_cache_dir_mode => 0700, force_untaint => 0, cache_debug => 0, shared_cache_debug => 0, memory_debug => 0, die_on_bad_params => 1, vanguard_compatibility_mode => 0, associate => [], path => [], strict => 1, loop_context_vars => 0, max_includes => 10, shared_cache => 0, double_cache => 0, double_file_cache => 0, ipc_key => 'TMPL', ipc_mode => 0666, ipc_segment_size => 65536, ipc_max_size => 0, global_vars => 0, no_includes => 0, case_sensitive => 0, filter => [], open_mode => '', utf8 => 0, cache_lazy_vars => 0, cache_lazy_loops => 0, die_on_missing_include => 1, ); } # open a new template and return an object handle sub new { my $pkg = shift; my $self; { my %hash; $self = bless(\%hash, $pkg); } # the options hash my $options = {}; $self->{options} = $options; # set default parameters in options hash %$options = %OPTIONS; # load in options supplied to new() $options = _load_supplied_options([@_], $options); # blind_cache = 1 implies cache = 1 $options->{blind_cache} and $options->{cache} = 1; # shared_cache = 1 implies cache = 1 $options->{shared_cache} and $options->{cache} = 1; # file_cache = 1 implies cache = 1 $options->{file_cache} and $options->{cache} = 1; # double_cache is a combination of shared_cache and cache. $options->{double_cache} and $options->{cache} = 1; $options->{double_cache} and $options->{shared_cache} = 1; # double_file_cache is a combination of file_cache and cache. $options->{double_file_cache} and $options->{cache} = 1; $options->{double_file_cache} and $options->{file_cache} = 1; # vanguard_compatibility_mode implies die_on_bad_params = 0 $options->{vanguard_compatibility_mode} and $options->{die_on_bad_params} = 0; # handle the "type", "source" parameter format (does anyone use it?) if (exists($options->{type})) { exists($options->{source}) or croak("HTML::Template->new() called with 'type' parameter set, but no 'source'!"); ( $options->{type} eq 'filename' or $options->{type} eq 'scalarref' or $options->{type} eq 'arrayref' or $options->{type} eq 'filehandle' ) or croak("HTML::Template->new() : type parameter must be set to 'filename', 'arrayref', 'scalarref' or 'filehandle'!"); $options->{$options->{type}} = $options->{source}; delete $options->{type}; delete $options->{source}; } # make sure taint mode is on if force_untaint flag is set if ($options->{force_untaint}) { if ($] < 5.008000) { warn("HTML::Template->new() : 'force_untaint' option needs at least Perl 5.8.0!"); } elsif (!${^TAINT}) { croak("HTML::Template->new() : 'force_untaint' option set but perl does not run in taint mode!"); } } # associate should be an array of one element if it's not # already an array. if (ref($options->{associate}) ne 'ARRAY') { $options->{associate} = [$options->{associate}]; } # path should be an array if it's not already if (ref($options->{path}) ne 'ARRAY') { $options->{path} = [$options->{path}]; } # filter should be an array if it's not already if (ref($options->{filter}) ne 'ARRAY') { $options->{filter} = [$options->{filter}]; } # make sure objects in associate area support param() foreach my $object (@{$options->{associate}}) { defined($object->can('param')) or croak("HTML::Template->new called with associate option, containing object of type " . ref($object) . " which lacks a param() method!"); } # check for syntax errors: my $source_count = 0; exists($options->{filename}) and $source_count++; exists($options->{filehandle}) and $source_count++; exists($options->{arrayref}) and $source_count++; exists($options->{scalarref}) and $source_count++; if ($source_count != 1) { croak( "HTML::Template->new called with multiple (or no) template sources specified! A valid call to new() has exactly one filename => 'file' OR exactly one scalarref => \\\$scalar OR exactly one arrayref => \\\@array OR exactly one filehandle => \*FH" ); } # check that cache options are not used with non-cacheable templates croak "Cannot have caching when template source is not file" if grep { exists($options->{$_}) } qw( filehandle arrayref scalarref) and grep { $options->{$_} } qw( cache blind_cache file_cache shared_cache double_cache double_file_cache ); # check that filenames aren't empty if (exists($options->{filename})) { croak("HTML::Template->new called with empty filename parameter!") unless length $options->{filename}; } # do some memory debugging - this is best started as early as possible if ($options->{memory_debug}) { # memory_debug needs GTop eval { require GTop; }; croak("Could not load GTop. You must have GTop installed to use HTML::Template in memory_debug mode. The error was: $@") if ($@); $self->{gtop} = GTop->new(); $self->{proc_mem} = $self->{gtop}->proc_mem($$); print STDERR "\n### HTML::Template Memory Debug ### START ", $self->{proc_mem}->size(), "\n"; } if ($options->{file_cache}) { # make sure we have a file_cache_dir option croak("You must specify the file_cache_dir option if you want to use file_cache.") unless length $options->{file_cache_dir}; # file_cache needs some extra modules loaded eval { require Storable; }; croak( "Could not load Storable. You must have Storable installed to use HTML::Template in file_cache mode. The error was: $@" ) if ($@); } if ($options->{shared_cache}) { # shared_cache needs some extra modules loaded eval { require IPC::SharedCache; }; croak( "Could not load IPC::SharedCache. You must have IPC::SharedCache installed to use HTML::Template in shared_cache mode. The error was: $@" ) if ($@); # initialize the shared cache my %cache; tie %cache, 'IPC::SharedCache', ipc_key => $options->{ipc_key}, load_callback => [\&_load_shared_cache, $self], validate_callback => [\&_validate_shared_cache, $self], debug => $options->{shared_cache_debug}, ipc_mode => $options->{ipc_mode}, max_size => $options->{ipc_max_size}, ipc_segment_size => $options->{ipc_segment_size}; $self->{cache} = \%cache; } if ($options->{default_escape}) { $options->{default_escape} = uc $options->{default_escape}; unless ($options->{default_escape} =~ /^(NONE|HTML|URL|JS)$/i) { croak( "HTML::Template->new(): Invalid setting for default_escape - '$options->{default_escape}'. Valid values are 'none', 'html', 'url', or 'js'." ); } } # no 3 args form of open before perl 5.7.1 if ($options->{open_mode} && $] < 5.007001) { croak("HTML::Template->new(): open_mode cannot be used in Perl < 5.7.1"); } if($options->{utf8}) { croak("HTML::Template->new(): utf8 cannot be used in Perl < 5.7.1") if $] < 5.007001; croak("HTML::Template->new(): utf8 and open_mode cannot be used at the same time") if $options->{open_mode}; # utf8 is just a short-cut for a common open_mode $options->{open_mode} = '<:encoding(utf8)'; } print STDERR "### HTML::Template Memory Debug ### POST CACHE INIT ", $self->{proc_mem}->size(), "\n" if $options->{memory_debug}; # initialize data structures $self->_init; print STDERR "### HTML::Template Memory Debug ### POST _INIT CALL ", $self->{proc_mem}->size(), "\n" if $options->{memory_debug}; # drop the shared cache - leaving out this step results in the # template object evading garbage collection since the callbacks in # the shared cache tie hold references to $self! This was not easy # to find, by the way. delete $self->{cache} if $options->{shared_cache}; return $self; } sub _load_supplied_options { my $argsref = shift; my $options = shift; for (my $x = 0 ; $x < @{$argsref} ; $x += 2) { defined(${$argsref}[($x + 1)]) or croak("HTML::Template->new() called with odd number of option parameters - should be of the form option => value"); $options->{lc(${$argsref}[$x])} = ${$argsref}[($x + 1)]; } return $options; } # an internally used new that receives its parse_stack and param_map as input sub _new_from_loop { my $pkg = shift; my $self; { my %hash; $self = bless(\%hash, $pkg); } # the options hash my $options = { debug => $OPTIONS{debug}, stack_debug => $OPTIONS{stack_debug}, die_on_bad_params => $OPTIONS{die_on_bad_params}, associate => [@{$OPTIONS{associate}}], loop_context_vars => $OPTIONS{loop_context_vars}, }; $self->{options} = $options; $options = _load_supplied_options([@_], $options); $self->{param_map} = $options->{param_map}; $self->{parse_stack} = $options->{parse_stack}; delete($options->{param_map}); delete($options->{parse_stack}); return $self; } # a few shortcuts to new(), of possible use... sub new_file { my $pkg = shift; return $pkg->new('filename', @_); } sub new_filehandle { my $pkg = shift; return $pkg->new('filehandle', @_); } sub new_array_ref { my $pkg = shift; return $pkg->new('arrayref', @_); } sub new_scalar_ref { my $pkg = shift; return $pkg->new('scalarref', @_); } # initializes all the object data structures, either from cache or by # calling the appropriate routines. sub _init { my $self = shift; my $options = $self->{options}; if ($options->{double_cache}) { # try the normal cache, return if we have it. $self->_fetch_from_cache(); return if (defined $self->{param_map} and defined $self->{parse_stack}); # try the shared cache $self->_fetch_from_shared_cache(); # put it in the local cache if we got it. $self->_commit_to_cache() if (defined $self->{param_map} and defined $self->{parse_stack}); } elsif ($options->{double_file_cache}) { # try the normal cache, return if we have it. $self->_fetch_from_cache(); return if (defined $self->{param_map}); # try the file cache $self->_fetch_from_file_cache(); # put it in the local cache if we got it. $self->_commit_to_cache() if (defined $self->{param_map}); } elsif ($options->{shared_cache}) { # try the shared cache $self->_fetch_from_shared_cache(); } elsif ($options->{file_cache}) { # try the file cache $self->_fetch_from_file_cache(); } elsif ($options->{cache}) { # try the normal cache $self->_fetch_from_cache(); } # if we got a cache hit, return return if (defined $self->{param_map}); # if we're here, then we didn't get a cached copy, so do a full # init. $self->_init_template(); $self->_parse(); # now that we have a full init, cache the structures if caching is # on. shared cache is already cool. if ($options->{file_cache}) { $self->_commit_to_file_cache(); } $self->_commit_to_cache() if ( ($options->{cache} and not $options->{shared_cache} and not $options->{file_cache}) or ($options->{double_cache}) or ($options->{double_file_cache})); } # Caching subroutines - they handle getting and validating cache # records from either the in-memory or shared caches. # handles the normal in memory cache use vars qw( %CACHE ); sub _fetch_from_cache { my $self = shift; my $options = $self->{options}; # return if there's no file here my $filepath = $self->_find_file($options->{filename}); return unless (defined($filepath)); $options->{filepath} = $filepath; # return if there's no cache entry for this key my $key = $self->_cache_key(); return unless exists($CACHE{$key}); # validate the cache my $mtime = $self->_mtime($filepath); if (defined $mtime) { # return if the mtime doesn't match the cache if (defined($CACHE{$key}{mtime}) and ($mtime != $CACHE{$key}{mtime})) { $options->{cache_debug} and print STDERR "CACHE MISS : $filepath : $mtime\n"; return; } # if the template has includes, check each included file's mtime # and return if different if (exists($CACHE{$key}{included_mtimes})) { foreach my $filename (keys %{$CACHE{$key}{included_mtimes}}) { next unless defined($CACHE{$key}{included_mtimes}{$filename}); my $included_mtime = (stat($filename))[9]; if ($included_mtime != $CACHE{$key}{included_mtimes}{$filename}) { $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### CACHE MISS : $filepath : INCLUDE $filename : $included_mtime\n"; return; } } } } # got a cache hit! $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### CACHE HIT : $filepath => $key\n"; $self->{param_map} = $CACHE{$key}{param_map}; $self->{parse_stack} = $CACHE{$key}{parse_stack}; exists($CACHE{$key}{included_mtimes}) and $self->{included_mtimes} = $CACHE{$key}{included_mtimes}; # clear out values from param_map from last run $self->_normalize_options(); $self->clear_params(); } sub _commit_to_cache { my $self = shift; my $options = $self->{options}; my $key = $self->_cache_key(); my $filepath = $options->{filepath}; $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### CACHE LOAD : $filepath => $key\n"; $options->{blind_cache} or $CACHE{$key}{mtime} = $self->_mtime($filepath); $CACHE{$key}{param_map} = $self->{param_map}; $CACHE{$key}{parse_stack} = $self->{parse_stack}; exists($self->{included_mtimes}) and $CACHE{$key}{included_mtimes} = $self->{included_mtimes}; } # create a cache key from a template object. The cache key includes # the full path to the template and options which affect template # loading. sub _cache_key { my $self = shift; my $options = $self->{options}; # assemble pieces of the key my @key = ($options->{filepath}); push(@key, @{$options->{path}}); push(@key, $options->{search_path_on_include} || 0); push(@key, $options->{loop_context_vars} || 0); push(@key, $options->{global_vars} || 0); push(@key, $options->{open_mode} || 0); # compute the md5 and return it return md5_hex(@key); } # generates MD5 from filepath to determine filename for cache file sub _get_cache_filename { my ($self, $filepath) = @_; # get a cache key $self->{options}{filepath} = $filepath; my $hash = $self->_cache_key(); # ... and build a path out of it. Using the first two characters # gives us 255 buckets. This means you can have 255,000 templates # in the cache before any one directory gets over a few thousand # files in it. That's probably pretty good for this planet. If not # then it should be configurable. if (wantarray) { return (substr($hash, 0, 2), substr($hash, 2)); } else { return File::Spec->join($self->{options}{file_cache_dir}, substr($hash, 0, 2), substr($hash, 2)); } } # handles the file cache sub _fetch_from_file_cache { my $self = shift; my $options = $self->{options}; # return if there's no cache entry for this filename my $filepath = $self->_find_file($options->{filename}); return unless defined $filepath; my $cache_filename = $self->_get_cache_filename($filepath); return unless -e $cache_filename; eval { $self->{record} = Storable::lock_retrieve($cache_filename); }; croak("HTML::Template::new() - Problem reading cache file $cache_filename (file_cache => 1) : $@") if $@; croak("HTML::Template::new() - Problem reading cache file $cache_filename (file_cache => 1) : $!") unless defined $self->{record}; ($self->{mtime}, $self->{included_mtimes}, $self->{param_map}, $self->{parse_stack}) = @{$self->{record}}; $options->{filepath} = $filepath; # validate the cache my $mtime = $self->_mtime($filepath); if (defined $mtime) { # return if the mtime doesn't match the cache if (defined($self->{mtime}) and ($mtime != $self->{mtime})) { $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### FILE CACHE MISS : $filepath : $mtime\n"; ($self->{mtime}, $self->{included_mtimes}, $self->{param_map}, $self->{parse_stack}) = (undef, undef, undef, undef); return; } # if the template has includes, check each included file's mtime # and return if different if (exists($self->{included_mtimes})) { foreach my $filename (keys %{$self->{included_mtimes}}) { next unless defined($self->{included_mtimes}{$filename}); my $included_mtime = (stat($filename))[9]; if ($included_mtime != $self->{included_mtimes}{$filename}) { $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### FILE CACHE MISS : $filepath : INCLUDE $filename : $included_mtime\n"; ($self->{mtime}, $self->{included_mtimes}, $self->{param_map}, $self->{parse_stack}) = (undef, undef, undef, undef); return; } } } } # got a cache hit! $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### FILE CACHE HIT : $filepath\n"; # clear out values from param_map from last run $self->_normalize_options(); $self->clear_params(); } sub _commit_to_file_cache { my $self = shift; my $options = $self->{options}; my $filepath = $options->{filepath}; if (not defined $filepath) { $filepath = $self->_find_file($options->{filename}); confess("HTML::Template->new() : Cannot open included file $options->{filename} : file not found.") unless defined($filepath); $options->{filepath} = $filepath; } my ($cache_dir, $cache_file) = $self->_get_cache_filename($filepath); $cache_dir = File::Spec->join($options->{file_cache_dir}, $cache_dir); if (not -d $cache_dir) { if (not -d $options->{file_cache_dir}) { mkdir($options->{file_cache_dir}, $options->{file_cache_dir_mode}) or croak("HTML::Template->new() : can't mkdir $options->{file_cache_dir} (file_cache => 1): $!"); } mkdir($cache_dir, $options->{file_cache_dir_mode}) or croak("HTML::Template->new() : can't mkdir $cache_dir (file_cache => 1): $!"); } $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### FILE CACHE LOAD : $options->{filepath}\n"; my $result; eval { $result = Storable::lock_store([$self->{mtime}, $self->{included_mtimes}, $self->{param_map}, $self->{parse_stack}], scalar File::Spec->join($cache_dir, $cache_file)); }; croak("HTML::Template::new() - Problem writing cache file $cache_dir/$cache_file (file_cache => 1) : $@") if $@; croak("HTML::Template::new() - Problem writing cache file $cache_dir/$cache_file (file_cache => 1) : $!") unless defined $result; } # Shared cache routines. sub _fetch_from_shared_cache { my $self = shift; my $options = $self->{options}; my $filepath = $self->_find_file($options->{filename}); return unless defined $filepath; # fetch from the shared cache. $self->{record} = $self->{cache}{$filepath}; ($self->{mtime}, $self->{included_mtimes}, $self->{param_map}, $self->{parse_stack}) = @{$self->{record}} if defined($self->{record}); $options->{cache_debug} and defined($self->{record}) and print STDERR "### HTML::Template Cache Debug ### CACHE HIT : $filepath\n"; # clear out values from param_map from last run $self->_normalize_options(), $self->clear_params() if (defined($self->{record})); delete($self->{record}); return $self; } sub _validate_shared_cache { my ($self, $filename, $record) = @_; my $options = $self->{options}; $options->{shared_cache_debug} and print STDERR "### HTML::Template Cache Debug ### SHARED CACHE VALIDATE : $filename\n"; return 1 if $options->{blind_cache}; my ($c_mtime, $included_mtimes, $param_map, $parse_stack) = @$record; # if the modification time has changed return false my $mtime = $self->_mtime($filename); if ( defined $mtime and defined $c_mtime and $mtime != $c_mtime) { $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### SHARED CACHE MISS : $filename : $mtime\n"; return 0; } # if the template has includes, check each included file's mtime # and return false if different if (defined $mtime and defined $included_mtimes) { foreach my $fname (keys %$included_mtimes) { next unless defined($included_mtimes->{$fname}); if ($included_mtimes->{$fname} != (stat($fname))[9]) { $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### SHARED CACHE MISS : $filename : INCLUDE $fname\n"; return 0; } } } # all done - return true return 1; } sub _load_shared_cache { my ($self, $filename) = @_; my $options = $self->{options}; my $cache = $self->{cache}; $self->_init_template(); $self->_parse(); $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### SHARED CACHE LOAD : $options->{filepath}\n"; print STDERR "### HTML::Template Memory Debug ### END CACHE LOAD ", $self->{proc_mem}->size(), "\n" if $options->{memory_debug}; return [$self->{mtime}, $self->{included_mtimes}, $self->{param_map}, $self->{parse_stack}]; } # utility function - given a filename performs documented search and # returns a full path or undef if the file cannot be found. sub _find_file { my ($self, $filename, $extra_path) = @_; my $options = $self->{options}; my $filepath; # first check for a full path return File::Spec->canonpath($filename) if (File::Spec->file_name_is_absolute($filename) and (-e $filename)); # try the extra_path if one was specified if (defined($extra_path)) { $extra_path->[$#{$extra_path}] = $filename; $filepath = File::Spec->canonpath(File::Spec->catfile(@$extra_path)); return File::Spec->canonpath($filepath) if -e $filepath; } # try pre-prending HTML_Template_Root if (defined($ENV{HTML_TEMPLATE_ROOT})) { $filepath = File::Spec->catfile($ENV{HTML_TEMPLATE_ROOT}, $filename); return File::Spec->canonpath($filepath) if -e $filepath; } # try "path" option list.. foreach my $path (@{$options->{path}}) { $filepath = File::Spec->catfile($path, $filename); return File::Spec->canonpath($filepath) if -e $filepath; } # try even a relative path from the current directory... return File::Spec->canonpath($filename) if -e $filename; # try "path" option list with HTML_TEMPLATE_ROOT prepended... if (defined($ENV{HTML_TEMPLATE_ROOT})) { foreach my $path (@{$options->{path}}) { $filepath = File::Spec->catfile($ENV{HTML_TEMPLATE_ROOT}, $path, $filename); return File::Spec->canonpath($filepath) if -e $filepath; } } return undef; } # utility function - computes the mtime for $filename sub _mtime { my ($self, $filepath) = @_; my $options = $self->{options}; return (undef) if ($options->{blind_cache}); # make sure it still exists in the filesystem (-r $filepath) or Carp::confess("HTML::Template : template file $filepath does not exist or is unreadable."); # get the modification time return (stat(_))[9]; } # utility function - enforces new() options across LOOPs that have # come from a cache. Otherwise they would have stale options hashes. sub _normalize_options { my $self = shift; my $options = $self->{options}; my @pstacks = ($self->{parse_stack}); while (@pstacks) { my $pstack = pop(@pstacks); foreach my $item (@$pstack) { next unless (ref($item) eq 'HTML::Template::LOOP'); foreach my $template (values %{$item->[HTML::Template::LOOP::TEMPLATE_HASH]}) { # must be the same list as the call to _new_from_loop... $template->{options}{debug} = $options->{debug}; $template->{options}{stack_debug} = $options->{stack_debug}; $template->{options}{die_on_bad_params} = $options->{die_on_bad_params}; $template->{options}{case_sensitive} = $options->{case_sensitive}; $template->{options}{parent_global_vars} = $options->{parent_global_vars}; push(@pstacks, $template->{parse_stack}); } } } } # initialize the template buffer sub _init_template { my $self = shift; my $options = $self->{options}; print STDERR "### HTML::Template Memory Debug ### START INIT_TEMPLATE ", $self->{proc_mem}->size(), "\n" if $options->{memory_debug}; if (exists($options->{filename})) { my $filepath = $options->{filepath}; if (not defined $filepath) { $filepath = $self->_find_file($options->{filename}); confess("HTML::Template->new() : Cannot open included file $options->{filename} : file not found.") unless defined($filepath); # we'll need this for future reference - to call stat() for example. $options->{filepath} = $filepath; } # use the open_mode if we have one if (my $mode = $options->{open_mode}) { open(TEMPLATE, $mode, $filepath) || confess("HTML::Template->new() : Cannot open included file $filepath with mode $mode: $!"); } else { open(TEMPLATE, $filepath) or confess("HTML::Template->new() : Cannot open included file $filepath : $!"); } $self->{mtime} = $self->_mtime($filepath); # read into scalar, note the mtime for the record $self->{template} = ""; while (read(TEMPLATE, $self->{template}, 10240, length($self->{template}))) { } close(TEMPLATE); } elsif (exists($options->{scalarref})) { # copy in the template text $self->{template} = ${$options->{scalarref}}; delete($options->{scalarref}); } elsif (exists($options->{arrayref})) { # if we have an array ref, join and store the template text $self->{template} = join("", @{$options->{arrayref}}); delete($options->{arrayref}); } elsif (exists($options->{filehandle})) { # just read everything in in one go local $/ = undef; $self->{template} = readline($options->{filehandle}); delete($options->{filehandle}); } else { confess("HTML::Template : Need to call new with filename, filehandle, scalarref or arrayref parameter specified."); } print STDERR "### HTML::Template Memory Debug ### END INIT_TEMPLATE ", $self->{proc_mem}->size(), "\n" if $options->{memory_debug}; # handle filters if necessary $self->_call_filters(\$self->{template}) if @{$options->{filter}}; return $self; } # handle calling user defined filters sub _call_filters { my $self = shift; my $template_ref = shift; my $options = $self->{options}; my ($format, $sub); foreach my $filter (@{$options->{filter}}) { croak("HTML::Template->new() : bad value set for filter parameter - must be a code ref or a hash ref.") unless ref $filter; # translate into CODE->HASH $filter = {'format' => 'scalar', 'sub' => $filter} if (ref $filter eq 'CODE'); if (ref $filter eq 'HASH') { $format = $filter->{'format'}; $sub = $filter->{'sub'}; # check types and values croak( "HTML::Template->new() : bad value set for filter parameter - hash must contain \"format\" key and \"sub\" key.") unless defined $format and defined $sub; croak("HTML::Template->new() : bad value set for filter parameter - \"format\" must be either 'array' or 'scalar'") unless $format eq 'array' or $format eq 'scalar'; croak("HTML::Template->new() : bad value set for filter parameter - \"sub\" must be a code ref") unless ref $sub and ref $sub eq 'CODE'; # catch errors eval { if ($format eq 'scalar') { # call $sub->($template_ref); } else { # modulate my @array = map { $_ . "\n" } split("\n", $$template_ref); # call $sub->(\@array); # demodulate $$template_ref = join("", @array); } }; croak("HTML::Template->new() : fatal error occurred during filter call: $@") if $@; } else { croak("HTML::Template->new() : bad value set for filter parameter - must be code ref or hash ref"); } } # all done return $template_ref; } # _parse sifts through a template building up the param_map and # parse_stack structures. # # The end result is a Template object that is fully ready for # output(). sub _parse { my $self = shift; my $options = $self->{options}; $options->{debug} and print STDERR "### HTML::Template Debug ### In _parse:\n"; # setup the stacks and maps - they're accessed by typeglobs that # reference the top of the stack. They are masked so that a loop # can transparently have its own versions. use vars qw(@pstack %pmap @ifstack @ucstack %top_pmap); local (*pstack, *ifstack, *pmap, *ucstack, *top_pmap); # the pstack is the array of scalar refs (plain text from the # template file), VARs, LOOPs, IFs and ELSEs that output() works on # to produce output. Looking at output() should make it clear what # _parse is trying to accomplish. my @pstacks = ([]); *pstack = $pstacks[0]; $self->{parse_stack} = $pstacks[0]; # the pmap binds names to VARs, LOOPs and IFs. It allows param() to # access the right variable. NOTE: output() does not look at the # pmap at all! my @pmaps = ({}); *pmap = $pmaps[0]; *top_pmap = $pmaps[0]; $self->{param_map} = $pmaps[0]; # the ifstack is a temporary stack containing pending ifs and elses # waiting for a /if. my @ifstacks = ([]); *ifstack = $ifstacks[0]; # the ucstack is a temporary stack containing conditions that need # to be bound to param_map entries when their block is finished. # This happens when a conditional is encountered before any other # reference to its NAME. Since a conditional can reference VARs and # LOOPs it isn't possible to make the link right away. my @ucstacks = ([]); *ucstack = $ucstacks[0]; # the loopstack is another temp stack for closing loops. unlike # those above it doesn't get scoped inside loops, therefore it # doesn't need the typeglob magic. my @loopstack = (); # the fstack is a stack of filenames and counters that keeps track # of which file we're in and where we are in it. This allows # accurate error messages even inside included files! # fcounter, fmax and fname are aliases for the current file's info use vars qw($fcounter $fname $fmax); local (*fcounter, *fname, *fmax); my @fstack = ([$options->{filepath} || "/fake/path/for/non/file/template", 1, scalar @{[$self->{template} =~ m/(\n)/g]} + 1]); (*fname, *fcounter, *fmax) = \(@{$fstack[0]}); my $NOOP = HTML::Template::NOOP->new(); my $ESCAPE = HTML::Template::ESCAPE->new(); my $JSESCAPE = HTML::Template::JSESCAPE->new(); my $URLESCAPE = HTML::Template::URLESCAPE->new(); # all the tags that need NAMEs: my %need_names = map { $_ => 1 } qw(TMPL_VAR TMPL_LOOP TMPL_IF TMPL_UNLESS TMPL_INCLUDE); # variables used below that don't need to be my'd in the loop my ($name, $which, $escape, $default); # handle the old vanguard format $options->{vanguard_compatibility_mode} and $self->{template} =~ s/%([-\w\/\.+]+)%/<TMPL_VAR NAME=$1>/g; # now split up template on '<', leaving them in my @chunks = split(m/(?=<)/, $self->{template}); # all done with template delete $self->{template}; # loop through chunks, filling up pstack my $last_chunk = $#chunks; CHUNK: for (my $chunk_number = 0 ; $chunk_number <= $last_chunk ; $chunk_number++) { next unless defined $chunks[$chunk_number]; my $chunk = $chunks[$chunk_number]; # a general regex to match any and all TMPL_* tags if ( $chunk =~ /^< (?:!--\s*)? ( \/?tmpl_ (?: (?:var) | (?:loop) | (?:if) | (?:else) | (?:unless) | (?:include) ) ) # $1 => $which - start of the tag \s* # DEFAULT attribute (?: default \s*=\s* (?: "([^">]*)" # $2 => double-quoted DEFAULT value " | '([^'>]*)' # $3 => single-quoted DEFAULT value | ([^\s=>]*) # $4 => unquoted DEFAULT value ) )? \s* # ESCAPE attribute (?: escape \s*=\s* (?: ( (?:["']?0["']?)| (?:["']?1["']?)| (?:["']?html["']?) | (?:["']?url["']?) | (?:["']?js["']?) | (?:["']?none["']?) ) # $5 => ESCAPE on ) )* # allow multiple ESCAPEs \s* # DEFAULT attribute (?: default \s*=\s* (?: "([^">]*)" # $6 => double-quoted DEFAULT value " | '([^'>]*)' # $7 => single-quoted DEFAULT value | ([^\s=>]*) # $8 => unquoted DEFAULT value ) )? \s* # NAME attribute (?: (?: name \s*=\s*)? (?: "([^">]*)" # $9 => double-quoted NAME value " | '([^'>]*)' # $10 => single-quoted NAME value | ([^\s=>]*) # $11 => unquoted NAME value ) )? \s* # DEFAULT attribute (?: default \s*=\s* (?: "([^">]*)" # $12 => double-quoted DEFAULT value " | '([^'>]*)' # $13 => single-quoted DEFAULT value | ([^\s=>]*) # $14 => unquoted DEFAULT value ) )? \s* # ESCAPE attribute (?: escape \s*=\s* (?: ( (?:["']?0["']?)| (?:["']?1["']?)| (?:["']?html["']?) | (?:["']?url["']?) | (?:["']?js["']?) | (?:["']?none["']?) ) # $15 => ESCAPE on ) )* # allow multiple ESCAPEs \s* # DEFAULT attribute (?: default \s*=\s* (?: "([^">]*)" # $16 => double-quoted DEFAULT value " | '([^'>]*)' # $17 => single-quoted DEFAULT value | ([^\s=>]*) # $18 => unquoted DEFAULT value ) )? \s* (?:--)?\/?> (.*) # $19 => $post - text that comes after the tag $/isx ) { $which = uc($1); # which tag is it $escape = defined $5 ? $5 : defined $15 ? $15 : (defined $options->{default_escape} && $which eq 'TMPL_VAR') ? $options->{default_escape} : 0; # escape set? # what name for the tag? undef for a /tag at most, one of the # following three will be defined $name = defined $9 ? $9 : defined $10 ? $10 : defined $11 ? $11 : undef; # is there a default? $default = defined $2 ? $2 : defined $3 ? $3 : defined $4 ? $4 : defined $6 ? $6 : defined $7 ? $7 : defined $8 ? $8 : defined $12 ? $12 : defined $13 ? $13 : defined $14 ? $14 : defined $16 ? $16 : defined $17 ? $17 : defined $18 ? $18 : undef; my $post = $19; # what comes after on the line # allow mixed case in filenames, otherwise flatten $name = lc($name) unless (not defined $name or $which eq 'TMPL_INCLUDE' or $options->{case_sensitive}); # die if we need a name and didn't get one die "HTML::Template->new() : No NAME given to a $which tag at $fname : line $fcounter." if ($need_names{$which} and (not defined $name or not length $name)); # die if we got an escape but can't use one die "HTML::Template->new() : ESCAPE option invalid in a $which tag at $fname : line $fcounter." if ($escape and ($which ne 'TMPL_VAR')); # die if we got a default but can't use one die "HTML::Template->new() : DEFAULT option invalid in a $which tag at $fname : line $fcounter." if (defined $default and ($which ne 'TMPL_VAR')); # take actions depending on which tag found if ($which eq 'TMPL_VAR') { print STDERR "### HTML::Template Debug ### $fname : line $fcounter : parsed VAR $name\n" if $options->{debug}; # if we already have this var, then simply link to the existing # HTML::Template::VAR, else create a new one. my $var; if (exists $pmap{$name}) { $var = $pmap{$name}; if( $options->{die_on_bad_params} && ref($var) ne 'HTML::Template::VAR') { die "HTML::Template->new() : Already used param name $name as a TMPL_LOOP, found in a TMPL_VAR at $fname : line $fcounter."; } } else { $var = HTML::Template::VAR->new(); $pmap{$name} = $var; $top_pmap{$name} = HTML::Template::VAR->new() if $options->{global_vars} and not exists $top_pmap{$name}; } # if a DEFAULT was provided, push a DEFAULT object on the # stack before the variable. if (defined $default) { push(@pstack, HTML::Template::DEF->new($default)); } # if ESCAPE was set, push an ESCAPE op on the stack before # the variable. output will handle the actual work. # unless of course, they have set escape=0 or escape=none if ($escape) { if ($escape =~ /^["']?url["']?$/i) { push(@pstack, $URLESCAPE); } elsif ($escape =~ /^["']?js["']?$/i) { push(@pstack, $JSESCAPE); } elsif ($escape =~ /^["']?0["']?$/) { # do nothing if escape=0 } elsif ($escape =~ /^["']?none["']?$/i) { # do nothing if escape=none } else { push(@pstack, $ESCAPE); } } push(@pstack, $var); } elsif ($which eq 'TMPL_LOOP') { # we've got a loop start print STDERR "### HTML::Template Debug ### $fname : line $fcounter : LOOP $name start\n" if $options->{debug}; # if we already have this loop, then simply link to the existing # HTML::Template::LOOP, else create a new one. my $loop; if (exists $pmap{$name}) { $loop = $pmap{$name}; if( $options->{die_on_bad_params} && ref($loop) ne 'HTML::Template::LOOP') { die "HTML::Template->new() : Already used param name $name as a TMPL_VAR, TMPL_IF or TMPL_UNLESS, found in a TMPL_LOOP at $fname : line $fcounter!"; } } else { # store the results in a LOOP object - actually just a # thin wrapper around another HTML::Template object. $loop = HTML::Template::LOOP->new(); $pmap{$name} = $loop; } # get it on the loopstack, pstack of the enclosing block push(@pstack, $loop); push(@loopstack, [$loop, $#pstack]); # magic time - push on a fresh pmap and pstack, adjust the typeglobs. # this gives the loop a separate namespace (i.e. pmap and pstack). push(@pstacks, []); *pstack = $pstacks[$#pstacks]; push(@pmaps, {}); *pmap = $pmaps[$#pmaps]; push(@ifstacks, []); *ifstack = $ifstacks[$#ifstacks]; push(@ucstacks, []); *ucstack = $ucstacks[$#ucstacks]; # auto-vivify __FIRST__, __LAST__ and __INNER__ if # loop_context_vars is set. Otherwise, with # die_on_bad_params set output() will might cause errors # when it tries to set them. if ($options->{loop_context_vars}) { $pmap{__first__} = HTML::Template::VAR->new(); $pmap{__inner__} = HTML::Template::VAR->new(); $pmap{__outer__} = HTML::Template::VAR->new(); $pmap{__last__} = HTML::Template::VAR->new(); $pmap{__odd__} = HTML::Template::VAR->new(); $pmap{__even__} = HTML::Template::VAR->new(); $pmap{__counter__} = HTML::Template::VAR->new(); $pmap{__index__} = HTML::Template::VAR->new(); } } elsif ($which eq '/TMPL_LOOP') { $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : LOOP end\n"; my $loopdata = pop(@loopstack); die "HTML::Template->new() : found </TMPL_LOOP> with no matching <TMPL_LOOP> at $fname : line $fcounter!" unless defined $loopdata; my ($loop, $starts_at) = @$loopdata; # resolve pending conditionals foreach my $uc (@ucstack) { my $var = $uc->[HTML::Template::COND::VARIABLE]; if (exists($pmap{$var})) { $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var}; } else { $pmap{$var} = HTML::Template::VAR->new(); $top_pmap{$var} = HTML::Template::VAR->new() if $options->{global_vars} and not exists $top_pmap{$var}; $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var}; } if (ref($pmap{$var}) eq 'HTML::Template::VAR') { $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_VAR; } else { $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_LOOP; } } # get pmap and pstack for the loop, adjust the typeglobs to # the enclosing block. my $param_map = pop(@pmaps); *pmap = $pmaps[$#pmaps]; my $parse_stack = pop(@pstacks); *pstack = $pstacks[$#pstacks]; scalar(@ifstack) and die "HTML::Template->new() : Dangling <TMPL_IF> or <TMPL_UNLESS> in loop ending at $fname : line $fcounter."; pop(@ifstacks); *ifstack = $ifstacks[$#ifstacks]; pop(@ucstacks); *ucstack = $ucstacks[$#ucstacks]; # instantiate the sub-Template, feeding it parse_stack and # param_map. This means that only the enclosing template # does _parse() - sub-templates get their parse_stack and # param_map fed to them already filled in. $loop->[HTML::Template::LOOP::TEMPLATE_HASH]{$starts_at} = ref($self)->_new_from_loop( parse_stack => $parse_stack, param_map => $param_map, debug => $options->{debug}, die_on_bad_params => $options->{die_on_bad_params}, loop_context_vars => $options->{loop_context_vars}, case_sensitive => $options->{case_sensitive}, force_untaint => $options->{force_untaint}, parent_global_vars => ($options->{global_vars} || $options->{parent_global_vars} || 0) ); # if this loop has been used multiple times we need to merge the "param_map" between them # all so that die_on_bad_params doesn't complain if we try to use different vars in # each instance of the same loop if ($options->{die_on_bad_params}) { my $loops = $loop->[HTML::Template::LOOP::TEMPLATE_HASH]; my @loop_keys = sort { $a <=> $b } keys %$loops; if (@loop_keys > 1) { my $last_loop = pop(@loop_keys); foreach my $loop (@loop_keys) { # make sure all the params in the last loop are also in this loop foreach my $param (keys %{$loops->{$last_loop}->{param_map}}) { next if $loops->{$loop}->{param_map}->{$param}; $loops->{$loop}->{param_map}->{$param} = $loops->{$last_loop}->{param_map}->{$param}; } # make sure all the params in this loop are also in the last loop foreach my $param (keys %{$loops->{$loop}->{param_map}}) { next if $loops->{$last_loop}->{param_map}->{$param}; $loops->{$last_loop}->{param_map}->{$param} = $loops->{$loop}->{param_map}->{$param}; } } } } } elsif ($which eq 'TMPL_IF' or $which eq 'TMPL_UNLESS') { $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : $which $name start\n"; # if we already have this var, then simply link to the existing # HTML::Template::VAR/LOOP, else defer the mapping my $var; if (exists $pmap{$name}) { $var = $pmap{$name}; } else { $var = $name; } # connect the var to a conditional my $cond = HTML::Template::COND->new($var); if ($which eq 'TMPL_IF') { $cond->[HTML::Template::COND::WHICH] = HTML::Template::COND::WHICH_IF; $cond->[HTML::Template::COND::JUMP_IF_TRUE] = 0; } else { $cond->[HTML::Template::COND::WHICH] = HTML::Template::COND::WHICH_UNLESS; $cond->[HTML::Template::COND::JUMP_IF_TRUE] = 1; } # push unconnected conditionals onto the ucstack for # resolution later. Otherwise, save type information now. if ($var eq $name) { push(@ucstack, $cond); } else { if (ref($var) eq 'HTML::Template::VAR') { $cond->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_VAR; } else { $cond->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_LOOP; } } # push what we've got onto the stacks push(@pstack, $cond); push(@ifstack, $cond); } elsif ($which eq '/TMPL_IF' or $which eq '/TMPL_UNLESS') { $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : $which end\n"; my $cond = pop(@ifstack); die "HTML::Template->new() : found </${which}> with no matching <TMPL_IF> at $fname : line $fcounter." unless defined $cond; if ($which eq '/TMPL_IF') { die "HTML::Template->new() : found </TMPL_IF> incorrectly terminating a <TMPL_UNLESS> (use </TMPL_UNLESS>) at $fname : line $fcounter.\n" if ($cond->[HTML::Template::COND::WHICH] == HTML::Template::COND::WHICH_UNLESS); } else { die "HTML::Template->new() : found </TMPL_UNLESS> incorrectly terminating a <TMPL_IF> (use </TMPL_IF>) at $fname : line $fcounter.\n" if ($cond->[HTML::Template::COND::WHICH] == HTML::Template::COND::WHICH_IF); } # connect the matching to this "address" - place a NOOP to # hold the spot. This allows output() to treat an IF in the # assembler-esque "Conditional Jump" mode. push(@pstack, $NOOP); $cond->[HTML::Template::COND::JUMP_ADDRESS] = $#pstack; } elsif ($which eq 'TMPL_ELSE') { $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : ELSE\n"; my $cond = pop(@ifstack); die "HTML::Template->new() : found <TMPL_ELSE> with no matching <TMPL_IF> or <TMPL_UNLESS> at $fname : line $fcounter." unless defined $cond; die "HTML::Template->new() : found second <TMPL_ELSE> tag for <TMPL_IF> or <TMPL_UNLESS> at $fname : line $fcounter." if $cond->[HTML::Template::COND::IS_ELSE]; my $else = HTML::Template::COND->new($cond->[HTML::Template::COND::VARIABLE]); $else->[HTML::Template::COND::WHICH] = $cond->[HTML::Template::COND::WHICH]; $else->[HTML::Template::COND::UNCONDITIONAL_JUMP] = 1; $else->[HTML::Template::COND::IS_ELSE] = 1; # need end-block resolution? if (defined($cond->[HTML::Template::COND::VARIABLE_TYPE])) { $else->[HTML::Template::COND::VARIABLE_TYPE] = $cond->[HTML::Template::COND::VARIABLE_TYPE]; } else { push(@ucstack, $else); } push(@pstack, $else); push(@ifstack, $else); # connect the matching to this "address" - thus the if, # failing jumps to the ELSE address. The else then gets # elaborated, and of course succeeds. On the other hand, if # the IF fails and falls though, output will reach the else # and jump to the /if address. $cond->[HTML::Template::COND::JUMP_ADDRESS] = $#pstack; } elsif ($which eq 'TMPL_INCLUDE') { # handle TMPL_INCLUDEs $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : INCLUDE $name \n"; # no includes here, bub $options->{no_includes} and croak("HTML::Template : Illegal attempt to use TMPL_INCLUDE in template file : (no_includes => 1)"); my $filename = $name; # look for the included file... my $filepath; if ($options->{search_path_on_include}) { $filepath = $self->_find_file($filename); } else { $filepath = $self->_find_file($filename, [File::Spec->splitdir($fstack[-1][0])]); } die "HTML::Template->new() : Cannot open included file $filename : file not found." if !defined $filepath && $options->{die_on_missing_include}; my $included_template = ""; if( $filepath ) { # use the open_mode if we have one if (my $mode = $options->{open_mode}) { open(TEMPLATE, $mode, $filepath) || confess("HTML::Template->new() : Cannot open included file $filepath with mode $mode: $!"); } else { open(TEMPLATE, $filepath) or confess("HTML::Template->new() : Cannot open included file $filepath : $!"); } # read into the array while (read(TEMPLATE, $included_template, 10240, length($included_template))) { } close(TEMPLATE); } # call filters if necessary $self->_call_filters(\$included_template) if @{$options->{filter}}; if ($included_template) { # not empty # handle the old vanguard format - this needs to happen here # since we're not about to do a next CHUNKS. $options->{vanguard_compatibility_mode} and $included_template =~ s/%([-\w\/\.+]+)%/<TMPL_VAR NAME=$1>/g; # collect mtimes for included files if ($options->{cache} and !$options->{blind_cache}) { $self->{included_mtimes}{$filepath} = (stat($filepath))[9]; } # adjust the fstack to point to the included file info push(@fstack, [$filepath, 1, scalar @{[$included_template =~ m/(\n)/g]} + 1]); (*fname, *fcounter, *fmax) = \(@{$fstack[$#fstack]}); # make sure we aren't infinitely recursing die "HTML::Template->new() : likely recursive includes - parsed $options->{max_includes} files deep and giving up (set max_includes higher to allow deeper recursion)." if ($options->{max_includes} and (scalar(@fstack) > $options->{max_includes})); # stick the remains of this chunk onto the bottom of the # included text. $included_template .= $post; $post = undef; # move the new chunks into place. splice(@chunks, $chunk_number, 1, split(m/(?=<)/, $included_template)); # recalculate stopping point $last_chunk = $#chunks; # start in on the first line of the included text - nothing # else to do on this line. $chunk = $chunks[$chunk_number]; redo CHUNK; } } else { # zuh!? die "HTML::Template->new() : Unknown or unmatched TMPL construct at $fname : line $fcounter."; } # push the rest after the tag if (defined($post)) { if (ref($pstack[$#pstack]) eq 'SCALAR') { ${$pstack[$#pstack]} .= $post; } else { push(@pstack, \$post); } } } else { # just your ordinary markup # make sure we didn't reject something TMPL_* but badly formed if ($options->{strict}) { die "HTML::Template->new() : Syntax error in <TMPL_*> tag at $fname : $fcounter." if ($chunk =~ /<(?:!--\s*)?\/?tmpl_/i); } # push the rest and get next chunk if (defined($chunk)) { if (ref($pstack[$#pstack]) eq 'SCALAR') { ${$pstack[$#pstack]} .= $chunk; } else { push(@pstack, \$chunk); } } } # count newlines in chunk and advance line count $fcounter += scalar(@{[$chunk =~ m/(\n)/g]}); # if we just crossed the end of an included file # pop off the record and re-alias to the enclosing file's info pop(@fstack), (*fname, *fcounter, *fmax) = \(@{$fstack[$#fstack]}) if ($fcounter > $fmax); } # next CHUNK # make sure we don't have dangling IF or LOOP blocks scalar(@ifstack) and die "HTML::Template->new() : At least one <TMPL_IF> or <TMPL_UNLESS> not terminated at end of file!"; scalar(@loopstack) and die "HTML::Template->new() : At least one <TMPL_LOOP> not terminated at end of file!"; # resolve pending conditionals foreach my $uc (@ucstack) { my $var = $uc->[HTML::Template::COND::VARIABLE]; if (exists($pmap{$var})) { $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var}; } else { $pmap{$var} = HTML::Template::VAR->new(); $top_pmap{$var} = HTML::Template::VAR->new() if $options->{global_vars} and not exists $top_pmap{$var}; $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var}; } if (ref($pmap{$var}) eq 'HTML::Template::VAR') { $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_VAR; } else { $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_LOOP; } } # want a stack dump? if ($options->{stack_debug}) { require 'Data/Dumper.pm'; print STDERR "### HTML::Template _param Stack Dump ###\n\n", Data::Dumper::Dumper($self->{parse_stack}), "\n"; } # get rid of filters - they cause runtime errors if Storable tries # to store them. This can happen under global_vars. delete $options->{filter}; } # a recursive sub that associates each loop with the loops above # (treating the top-level as a loop) sub _globalize_vars { my $self = shift; # associate with the loop (and top-level templates) above in the tree. push(@{$self->{options}{associate}}, @_); # recurse down into the template tree, adding ourself to the end of # list. push(@_, $self); map { $_->_globalize_vars(@_) } map { values %{$_->[HTML::Template::LOOP::TEMPLATE_HASH]} } grep { ref($_) eq 'HTML::Template::LOOP' } @{$self->{parse_stack}}; } # method used to recursively un-hook associate sub _unglobalize_vars { my $self = shift; # disassociate $self->{options}{associate} = undef; # recurse down into the template tree disassociating map { $_->_unglobalize_vars() } map { values %{$_->[HTML::Template::LOOP::TEMPLATE_HASH]} } grep { ref($_) eq 'HTML::Template::LOOP' } @{$self->{parse_stack}}; } =head2 config A package method that is used to set/get the global default configuration options. For instance, if you want to set the C<utf8> flag to always be on for every template loaded by this process you would do: HTML::Template->config(utf8 => 1); Or if you wanted to check if the C<utf8> flag was on or not, you could do: my %config = HTML::Template->config; if( $config{utf8} ) { ... } Any configuration options that are valid for C<new()> are acceptable to be passed to this method. =cut sub config { my ($pkg, %options) = @_; foreach my $opt (keys %options) { if( $opt eq 'associate' || $opt eq 'filter' || $opt eq 'path' ) { push(@{$OPTIONS{$opt}}, $options{$opt}); } else { $OPTIONS{$opt} = $options{$opt}; } } return %OPTIONS; } =head2 param C<param()> can be called in a number of ways =over =item 1 - To return a list of parameters in the template : my @parameter_names = $self->param(); =item 2 - To return the value set to a param : my $value = $self->param('PARAM'); =item 3 - To set the value of a parameter : # For simple TMPL_VARs: $self->param(PARAM => 'value'); # with a subroutine reference that gets called to get the value # of the scalar. The sub will receive the template object as a # parameter. $self->param(PARAM => sub { return 'value' }); # And TMPL_LOOPs: $self->param(LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}]); =item 4 - To set the value of a number of parameters : # For simple TMPL_VARs: $self->param( PARAM => 'value', PARAM2 => 'value' ); # And with some TMPL_LOOPs: $self->param( PARAM => 'value', PARAM2 => 'value', LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}], ANOTHER_LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}], ); =item 5 - To set the value of a number of parameters using a hash-ref : $self->param( { PARAM => 'value', PARAM2 => 'value', LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}], ANOTHER_LOOP_PARAM => [{PARAM => VALUE_FOR_FIRST_PASS}, {PARAM => VALUE_FOR_SECOND_PASS}], } ); An error occurs if you try to set a value that is tainted if the C<force_untaint> option is set. =back =cut sub param { my $self = shift; my $options = $self->{options}; my $param_map = $self->{param_map}; # the no-parameter case - return list of parameters in the template. return keys(%$param_map) unless scalar(@_); my $first = shift; my $type = ref $first; # the one-parameter case - could be a parameter value request or a # hash-ref. if (!scalar(@_) and !length($type)) { my $param = $options->{case_sensitive} ? $first : lc $first; # check for parameter existence $options->{die_on_bad_params} and !exists($param_map->{$param}) and croak( "HTML::Template : Attempt to get nonexistent parameter '$param' - this parameter name doesn't match any declarations in the template file : (die_on_bad_params set => 1)" ); return undef unless (exists($param_map->{$param}) and defined($param_map->{$param})); return ${$param_map->{$param}} if (ref($param_map->{$param}) eq 'HTML::Template::VAR'); return $param_map->{$param}[HTML::Template::LOOP::PARAM_SET]; } if (!scalar(@_)) { croak("HTML::Template->param() : Single reference arg to param() must be a hash-ref! You gave me a $type.") unless $type eq 'HASH' or UNIVERSAL::isa($first, 'HASH'); push(@_, %$first); } else { unshift(@_, $first); } croak("HTML::Template->param() : You gave me an odd number of parameters to param()!") unless ((@_ % 2) == 0); # strangely, changing this to a "while(@_) { shift, shift }" type # loop causes perl 5.004_04 to die with some nonsense about a # read-only value. for (my $x = 0 ; $x <= $#_ ; $x += 2) { my $param = $options->{case_sensitive} ? $_[$x] : lc $_[$x]; my $value = $_[($x + 1)]; # check that this param exists in the template $options->{die_on_bad_params} and !exists($param_map->{$param}) and croak( "HTML::Template : Attempt to set nonexistent parameter '$param' - this parameter name doesn't match any declarations in the template file : (die_on_bad_params => 1)" ); # if we're not going to die from bad param names, we need to ignore # them... unless (exists($param_map->{$param})) { next if not $options->{parent_global_vars}; # ... unless global vars is on - in which case we can't be # sure we won't need it in a lower loop. if (ref($value) eq 'ARRAY') { $param_map->{$param} = HTML::Template::LOOP->new(); } else { $param_map->{$param} = HTML::Template::VAR->new(); } } # figure out what we've got, taking special care to allow for # objects that are compatible underneath. my $type = ref $value || ''; if ($type eq 'REF') { croak("HTML::Template::param() : attempt to set parameter '$param' with a reference to a reference!"); } elsif ($type && ($type eq 'ARRAY' || ($type !~ /^(CODE)|(HASH)|(SCALAR)$/ && $value->isa('ARRAY')))) { ref($param_map->{$param}) eq 'HTML::Template::LOOP' || croak( "HTML::Template::param() : attempt to set parameter '$param' with an array ref - parameter is not a TMPL_LOOP!"); $param_map->{$param}[HTML::Template::LOOP::PARAM_SET] = [@{$value}]; } elsif( $type eq 'CODE' ) { # code can be used for a var or a loop if( ref($param_map->{$param}) eq 'HTML::Template::LOOP' ) { $param_map->{$param}[HTML::Template::LOOP::PARAM_SET] = $value; } else { ${$param_map->{$param}} = $value; } } else { ref($param_map->{$param}) eq 'HTML::Template::VAR' || croak( "HTML::Template::param() : attempt to set parameter '$param' with a scalar - parameter is not a TMPL_VAR!"); ${$param_map->{$param}} = $value; } } } =head2 clear_params Sets all the parameters to undef. Useful internally, if nowhere else! =cut sub clear_params { my $self = shift; my $type; foreach my $name (keys %{$self->{param_map}}) { $type = ref($self->{param_map}{$name}); undef(${$self->{param_map}{$name}}) if ($type eq 'HTML::Template::VAR'); undef($self->{param_map}{$name}[HTML::Template::LOOP::PARAM_SET]) if ($type eq 'HTML::Template::LOOP'); } } # obsolete implementation of associate sub associateCGI { my $self = shift; my $cgi = shift; (ref($cgi) eq 'CGI') or croak("Warning! non-CGI object was passed to HTML::Template::associateCGI()!\n"); push(@{$self->{options}{associate}}, $cgi); return 1; } =head2 output C<output()> returns the final result of the template. In most situations you'll want to print this, like: print $template->output(); When output is called each occurrence of C<< <TMPL_VAR NAME=name> >> is replaced with the value assigned to "name" via C<param()>. If a named parameter is unset it is simply replaced with ''. C<< <TMPL_LOOP> >>s are evaluated once per parameter set, accumulating output on each pass. Calling C<output()> is guaranteed not to change the state of the HTML::Template object, in case you were wondering. This property is mostly important for the internal implementation of loops. You may optionally supply a filehandle to print to automatically as the template is generated. This may improve performance and lower memory consumption. Example: $template->output(print_to => *STDOUT); The return value is undefined when using the C<print_to> option. =cut use vars qw(%URLESCAPE_MAP); sub output { my $self = shift; my $options = $self->{options}; local $_; croak("HTML::Template->output() : You gave me an odd number of parameters to output()!") unless ((@_ % 2) == 0); my %args = @_; print STDERR "### HTML::Template Memory Debug ### START OUTPUT ", $self->{proc_mem}->size(), "\n" if $options->{memory_debug}; $options->{debug} and print STDERR "### HTML::Template Debug ### In output\n"; # want a stack dump? if ($options->{stack_debug}) { require 'Data/Dumper.pm'; print STDERR "### HTML::Template output Stack Dump ###\n\n", Data::Dumper::Dumper($self->{parse_stack}), "\n"; } # globalize vars - this happens here to localize the circular # references created by global_vars. $self->_globalize_vars() if ($options->{global_vars}); # support the associate magic, searching for undefined params and # attempting to fill them from the associated objects. if (scalar(@{$options->{associate}})) { # prepare case-mapping hashes to do case-insensitive matching # against associated objects. This allows CGI.pm to be # case-sensitive and still work with associate. my (%case_map, $lparam); foreach my $associated_object (@{$options->{associate}}) { # what a hack! This should really be optimized out for case_sensitive. if ($options->{case_sensitive}) { map { $case_map{$associated_object}{$_} = $_ } $associated_object->param(); } else { map { $case_map{$associated_object}{lc($_)} = $_ } $associated_object->param(); } } foreach my $param (keys %{$self->{param_map}}) { unless (defined($self->param($param))) { OBJ: foreach my $associated_object (reverse @{$options->{associate}}) { $self->param($param, scalar $associated_object->param($case_map{$associated_object}{$param})), last OBJ if (exists($case_map{$associated_object}{$param})); } } } } use vars qw($line @parse_stack); local (*line, *parse_stack); # walk the parse stack, accumulating output in $result *parse_stack = $self->{parse_stack}; my $result = ''; tie $result, 'HTML::Template::PRINTSCALAR', $args{print_to} if defined $args{print_to} && !eval { tied *{$args{print_to}} }; my $type; my $parse_stack_length = $#parse_stack; for (my $x = 0 ; $x <= $parse_stack_length ; $x++) { *line = \$parse_stack[$x]; $type = ref($line); if ($type eq 'SCALAR') { $result .= $$line; } elsif ($type eq 'HTML::Template::VAR' and ref($$line) eq 'CODE') { if (defined($$line)) { my $tmp_val = $$line->($self); croak("HTML::Template->output() : 'force_untaint' option but coderef returns tainted value") if $options->{force_untaint} && tainted($tmp_val); $result .= $tmp_val; # change the reference to point to the value now not the code reference $$line = $tmp_val if $options->{cache_lazy_vars} } } elsif ($type eq 'HTML::Template::VAR') { if (defined $$line) { if ($options->{force_untaint} && tainted($$line)) { croak("HTML::Template->output() : tainted value with 'force_untaint' option"); } $result .= $$line; } } elsif ($type eq 'HTML::Template::LOOP') { if (defined($line->[HTML::Template::LOOP::PARAM_SET])) { eval { $result .= $line->output($x, $options->{loop_context_vars}); }; croak("HTML::Template->output() : fatal error in loop output : $@") if $@; } } elsif ($type eq 'HTML::Template::COND') { if ($line->[HTML::Template::COND::UNCONDITIONAL_JUMP]) { $x = $line->[HTML::Template::COND::JUMP_ADDRESS]; } else { if ($line->[HTML::Template::COND::JUMP_IF_TRUE]) { if ($line->[HTML::Template::COND::VARIABLE_TYPE] == HTML::Template::COND::VARIABLE_TYPE_VAR) { if (defined ${$line->[HTML::Template::COND::VARIABLE]}) { if (ref(${$line->[HTML::Template::COND::VARIABLE]}) eq 'CODE') { my $tmp_val = ${$line->[HTML::Template::COND::VARIABLE]}->($self); $x = $line->[HTML::Template::COND::JUMP_ADDRESS] if $tmp_val; ${$line->[HTML::Template::COND::VARIABLE]} = $tmp_val if $options->{cache_lazy_vars}; } else { $x = $line->[HTML::Template::COND::JUMP_ADDRESS] if ${$line->[HTML::Template::COND::VARIABLE]}; } } } else { # if it's a code reference, execute it to get the values my $loop_values = $line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET]; if (defined $loop_values && ref $loop_values eq 'CODE') { $loop_values = $loop_values->($self); $line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET] = $loop_values if $options->{cache_lazy_loops}; } # if we have anything for the loop, jump to the next part if (defined $loop_values && @$loop_values) { $x = $line->[HTML::Template::COND::JUMP_ADDRESS]; } } } else { if ($line->[HTML::Template::COND::VARIABLE_TYPE] == HTML::Template::COND::VARIABLE_TYPE_VAR) { if (defined ${$line->[HTML::Template::COND::VARIABLE]}) { if (ref(${$line->[HTML::Template::COND::VARIABLE]}) eq 'CODE') { my $tmp_val = ${$line->[HTML::Template::COND::VARIABLE]}->($self); $x = $line->[HTML::Template::COND::JUMP_ADDRESS] unless $tmp_val; ${$line->[HTML::Template::COND::VARIABLE]} = $tmp_val if $options->{cache_lazy_vars}; } else { $x = $line->[HTML::Template::COND::JUMP_ADDRESS] unless ${$line->[HTML::Template::COND::VARIABLE]}; } } else { $x = $line->[HTML::Template::COND::JUMP_ADDRESS]; } } else { # if we don't have anything for the loop, jump to the next part my $loop_values = $line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET]; if(!defined $loop_values) { $x = $line->[HTML::Template::COND::JUMP_ADDRESS]; } else { # check to see if the loop is a code ref and if it is execute it to get the values if( ref $loop_values eq 'CODE' ) { $loop_values = $line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET]->($self); $line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET] = $loop_values if $options->{cache_lazy_loops}; } # if we don't have anything in the loop, jump to the next part if(!@$loop_values) { $x = $line->[HTML::Template::COND::JUMP_ADDRESS]; } } } } } } elsif ($type eq 'HTML::Template::NOOP') { next; } elsif ($type eq 'HTML::Template::DEF') { $_ = $x; # remember default place in stack # find next VAR, there might be an ESCAPE in the way *line = \$parse_stack[++$x]; *line = \$parse_stack[++$x] if ref $line eq 'HTML::Template::ESCAPE' or ref $line eq 'HTML::Template::JSESCAPE' or ref $line eq 'HTML::Template::URLESCAPE'; # either output the default or go back if (defined $$line) { $x = $_; } else { $result .= ${$parse_stack[$_]}; } next; } elsif ($type eq 'HTML::Template::ESCAPE') { *line = \$parse_stack[++$x]; if (defined($$line)) { my $tmp_val; if (ref($$line) eq 'CODE') { $tmp_val = $$line->($self); if ($options->{force_untaint} > 1 && tainted($_)) { croak("HTML::Template->output() : 'force_untaint' option but coderef returns tainted value"); } $$line = $tmp_val if $options->{cache_lazy_vars}; } else { $tmp_val = $$line; if ($options->{force_untaint} > 1 && tainted($_)) { croak("HTML::Template->output() : tainted value with 'force_untaint' option"); } } # straight from the CGI.pm bible. $tmp_val =~ s/&/&/g; $tmp_val =~ s/\"/"/g; $tmp_val =~ s/>/>/g; $tmp_val =~ s/</</g; $tmp_val =~ s/'/'/g; $result .= $tmp_val; } next; } elsif ($type eq 'HTML::Template::JSESCAPE') { $x++; *line = \$parse_stack[$x]; if (defined($$line)) { my $tmp_val; if (ref($$line) eq 'CODE') { $tmp_val = $$line->($self); if ($options->{force_untaint} > 1 && tainted($_)) { croak("HTML::Template->output() : 'force_untaint' option but coderef returns tainted value"); } $$line = $tmp_val if $options->{cache_lazy_vars}; } else { $tmp_val = $$line; if ($options->{force_untaint} > 1 && tainted($_)) { croak("HTML::Template->output() : tainted value with 'force_untaint' option"); } } $tmp_val =~ s/\\/\\\\/g; $tmp_val =~ s/'/\\'/g; $tmp_val =~ s/"/\\"/g; $tmp_val =~ s/[\n\x{2028}]/\\n/g; $tmp_val =~ s/\x{2029}/\\n\\n/g; $tmp_val =~ s/\r/\\r/g; $result .= $tmp_val; } } elsif ($type eq 'HTML::Template::URLESCAPE') { $x++; *line = \$parse_stack[$x]; if (defined($$line)) { my $tmp_val; if (ref($$line) eq 'CODE') { $tmp_val = $$line->($self); if ($options->{force_untaint} > 1 && tainted($_)) { croak("HTML::Template->output() : 'force_untaint' option but coderef returns tainted value"); } $$line = $tmp_val if $options->{cache_lazy_vars}; } else { $tmp_val = $$line; if ($options->{force_untaint} > 1 && tainted($_)) { croak("HTML::Template->output() : tainted value with 'force_untaint' option"); } } # Build a char->hex map if one isn't already available unless (exists($URLESCAPE_MAP{chr(1)})) { for (0 .. 255) { $URLESCAPE_MAP{chr($_)} = sprintf('%%%02X', $_); } } # do the translation (RFC 2396 ^uric) $tmp_val =~ s!([^a-zA-Z0-9_.\-])!$URLESCAPE_MAP{$1}!g; $result .= $tmp_val; } } else { confess("HTML::Template::output() : Unknown item in parse_stack : " . $type); } } # undo the globalization circular refs $self->_unglobalize_vars() if ($options->{global_vars}); print STDERR "### HTML::Template Memory Debug ### END OUTPUT ", $self->{proc_mem}->size(), "\n" if $options->{memory_debug}; return undef if defined $args{print_to}; return $result; } =head2 query This method allow you to get information about the template structure. It can be called in a number of ways. The simplest usage of query is simply to check whether a parameter name exists in the template, using the C<name> option: if ($template->query(name => 'foo')) { # do something if a variable of any type named FOO is in the template } This same usage returns the type of the parameter. The type is the same as the tag minus the leading 'TMPL_'. So, for example, a C<TMPL_VAR> parameter returns 'VAR' from C<query()>. if ($template->query(name => 'foo') eq 'VAR') { # do something if FOO exists and is a TMPL_VAR } Note that the variables associated with C<TMPL_IF>s and C<TMPL_UNLESS>s will be identified as 'VAR' unless they are also used in a C<TMPL_LOOP>, in which case they will return 'LOOP'. C<query()> also allows you to get a list of parameters inside a loop (and inside loops inside loops). Example loop: <TMPL_LOOP NAME="EXAMPLE_LOOP"> <TMPL_VAR NAME="BEE"> <TMPL_VAR NAME="BOP"> <TMPL_LOOP NAME="EXAMPLE_INNER_LOOP"> <TMPL_VAR NAME="INNER_BEE"> <TMPL_VAR NAME="INNER_BOP"> </TMPL_LOOP> </TMPL_LOOP> And some query calls: # returns 'LOOP' $type = $template->query(name => 'EXAMPLE_LOOP'); # returns ('bop', 'bee', 'example_inner_loop') @param_names = $template->query(loop => 'EXAMPLE_LOOP'); # both return 'VAR' $type = $template->query(name => ['EXAMPLE_LOOP', 'BEE']); $type = $template->query(name => ['EXAMPLE_LOOP', 'BOP']); # and this one returns 'LOOP' $type = $template->query(name => ['EXAMPLE_LOOP', 'EXAMPLE_INNER_LOOP']); # and finally, this returns ('inner_bee', 'inner_bop') @inner_param_names = $template->query(loop => ['EXAMPLE_LOOP', 'EXAMPLE_INNER_LOOP']); # for non existent parameter names you get undef this returns undef. $type = $template->query(name => 'DWEAZLE_ZAPPA'); # calling loop on a non-loop parameter name will cause an error. This dies: $type = $template->query(loop => 'DWEAZLE_ZAPPA'); As you can see above the C<loop> option returns a list of parameter names and both C<name> and C<loop> take array refs in order to refer to parameters inside loops. It is an error to use C<loop> with a parameter that is not a loop. Note that all the names are returned in lowercase and the types are uppercase. Just like C<param()>, C<query()> with no arguments returns all the parameter names in the template at the top level. =cut sub query { my $self = shift; $self->{options}{debug} and print STDERR "### HTML::Template Debug ### query(", join(', ', @_), ")\n"; # the no-parameter case - return $self->param() return $self->param() unless scalar(@_); croak("HTML::Template::query() : Odd number of parameters passed to query!") if (scalar(@_) % 2); croak("HTML::Template::query() : Wrong number of parameters passed to query - should be 2.") if (scalar(@_) != 2); my ($opt, $path) = (lc shift, shift); croak("HTML::Template::query() : invalid parameter ($opt)") unless ($opt eq 'name' or $opt eq 'loop'); # make path an array unless it already is $path = [$path] unless (ref $path); # find the param in question. my @objs = $self->_find_param(@$path); return undef unless scalar(@objs); my ($obj, $type); # do what the user asked with the object if ($opt eq 'name') { # we only look at the first one. new() should make sure they're # all the same. ($obj, $type) = (shift(@objs), shift(@objs)); return undef unless defined $obj; return 'VAR' if $type eq 'HTML::Template::VAR'; return 'LOOP' if $type eq 'HTML::Template::LOOP'; croak("HTML::Template::query() : unknown object ($type) in param_map!"); } elsif ($opt eq 'loop') { my %results; while (@objs) { ($obj, $type) = (shift(@objs), shift(@objs)); croak( "HTML::Template::query() : Search path [", join(', ', @$path), "] doesn't end in a TMPL_LOOP - it is an error to use the 'loop' option on a non-loop parameter. To avoid this problem you can use the 'name' option to query() to check the type first." ) unless ((defined $obj) and ($type eq 'HTML::Template::LOOP')); # SHAZAM! This bit extracts all the parameter names from all the # loop objects for this name. map { $results{$_} = 1 } map { keys(%{$_->{'param_map'}}) } values(%{$obj->[HTML::Template::LOOP::TEMPLATE_HASH]}); } # this is our loop list, return it. return keys(%results); } } # a function that returns the object(s) corresponding to a given path and # its (their) ref()(s). Used by query() in the obvious way. sub _find_param { my $self = shift; my $spot = $self->{options}{case_sensitive} ? shift : lc shift; # get the obj and type for this spot my $obj = $self->{'param_map'}{$spot}; return unless defined $obj; my $type = ref $obj; # return if we're here or if we're not but this isn't a loop return ($obj, $type) unless @_; return unless ($type eq 'HTML::Template::LOOP'); # recurse. this is a depth first search on the template tree, for # the algorithm geeks in the audience. return map { $_->_find_param(@_) } values(%{$obj->[HTML::Template::LOOP::TEMPLATE_HASH]}); } # HTML::Template::VAR, LOOP, etc are *light* objects - their internal # spec is used above. No encapsulation or information hiding is to be # assumed. package HTML::Template::VAR; sub new { my $value; return bless(\$value, $_[0]); } package HTML::Template::DEF; sub new { my $value = $_[1]; return bless(\$value, $_[0]); } package HTML::Template::LOOP; sub new { return bless([], $_[0]); } sub output { my $self = shift; my $index = shift; my $loop_context_vars = shift; my $template = $self->[TEMPLATE_HASH]{$index}; my $value_sets_array = $self->[PARAM_SET]; return unless defined($value_sets_array); my $result = ''; my $count = 0; my $odd = 0; # execute the code to get the values if it's a code reference if( ref $value_sets_array eq 'CODE' ) { $value_sets_array = $value_sets_array->($template); croak("HTML::Template->output: TMPL_LOOP code reference did not return an ARRAY reference!") unless ref $value_sets_array && ref $value_sets_array eq 'ARRAY'; $self->[PARAM_SET] = $value_sets_array if $template->{options}->{cache_lazy_loops}; } foreach my $value_set (@$value_sets_array) { if ($loop_context_vars) { if ($count == 0) { @{$value_set}{qw(__first__ __inner__ __outer__ __last__)} = (1, 0, 1, $#{$value_sets_array} == 0); } elsif ($count == $#{$value_sets_array}) { @{$value_set}{qw(__first__ __inner__ __outer__ __last__)} = (0, 0, 1, 1); } else { @{$value_set}{qw(__first__ __inner__ __outer__ __last__)} = (0, 1, 0, 0); } $odd = $value_set->{__odd__} = !$odd; $value_set->{__even__} = !$odd; $value_set->{__counter__} = $count + 1; $value_set->{__index__} = $count; } $template->param($value_set); $result .= $template->output; $template->clear_params; @{$value_set}{qw(__first__ __last__ __inner__ __outer__ __odd__ __even__ __counter__ __index__)} = (0, 0, 0, 0, 0, 0, 0) if ($loop_context_vars); $count++; } return $result; } package HTML::Template::COND; sub new { my $pkg = shift; my $var = shift; my $self = []; $self->[VARIABLE] = $var; bless($self, $pkg); return $self; } package HTML::Template::NOOP; sub new { my $unused; my $self = \$unused; bless($self, $_[0]); return $self; } package HTML::Template::ESCAPE; sub new { my $unused; my $self = \$unused; bless($self, $_[0]); return $self; } package HTML::Template::JSESCAPE; sub new { my $unused; my $self = \$unused; bless($self, $_[0]); return $self; } package HTML::Template::URLESCAPE; sub new { my $unused; my $self = \$unused; bless($self, $_[0]); return $self; } # scalar-tying package for output(print_to => *HANDLE) implementation package HTML::Template::PRINTSCALAR; use strict; sub TIESCALAR { bless \$_[1], $_[0]; } sub FETCH { } sub STORE { my $self = shift; local *FH = $$self; print FH @_; } 1; __END__ =head1 LAZY VALUES As mentioned above, both C<TMPL_VAR> and C<TMPL_LOOP> values can be code references. These code references are only executed if the variable or loop is used in the template. This is extremely useful if you want to make a variable available to template designers but it can be expensive to calculate, so you only want to do so if you have to. Maybe an example will help to illustrate. Let's say you have a template like this: <tmpl_if we_care> <tmpl_if life_universe_and_everything> </tmpl_if> If C<life_universe_and_everything> is expensive to calculate we can wrap it's calculation in a code reference and HTML::Template will only execute that code if C<we_care> is also true. $tmpl->param(life_universe_and_everything => sub { calculate_42() }); Your code reference will be given a single argument, the HTML::Template object in use. In the above example, if we wanted C<calculate_42()> to have this object we'd do something like this: $tmpl->param(life_universe_and_everything => sub { calculate_42(shift) }); This same approach can be used for C<TMPL_LOOP>s too: <tmpl_if we_care> <tmpl_loop needles_in_haystack> Found <tmpl_var __counter>! </tmpl_loop> </tmpl_if> And in your Perl code: $tmpl->param(needles_in_haystack => sub { find_needles() }); The only difference in the C<TMPL_LOOP> case is that the subroutine needs to return a reference to an ARRAY, not just a scalar value. =head2 Multiple Calls It's important to recognize that while this feature is designed to save processing time when things aren't needed, if you're not careful it can actually increase the number of times you perform your calculation. HTML::Template calls your code reference each time it seems your loop in the template, this includes the times that you might use the loop in a conditional (C<TMPL_IF> or C<TMPL_UNLESS>). For instance: <tmpl_if we care> <tmpl_if needles_in_haystack> <tmpl_loop needles_in_haystack> Found <tmpl_var __counter>! </tmpl_loop> <tmpl_else> No needles found! </tmpl_if> </tmpl_if> This will actually call C<find_needles()> twice which will be even worse than you had before. One way to work around this is to cache the return value yourself: my $needles; $tmpl->param(needles_in_haystack => sub { defined $needles ? $needles : $needles = find_needles() }); =head1 BUGS I am aware of no bugs - if you find one, join the mailing list and tell us about it. You can join the HTML::Template mailing-list by visiting: http://lists.sourceforge.net/lists/listinfo/html-template-users Of course, you can still email me directly (C<sam@tregar.com>) with bugs, but I reserve the right to forward bug reports to the mailing list. When submitting bug reports, be sure to include full details, including the VERSION of the module, a test script and a test template demonstrating the problem! If you're feeling really adventurous, HTML::Template has a publically available Git repository. See below for more information in the PUBLIC GIT REPOSITORY section. =head1 CREDITS This module was the brain child of my boss, Jesse Erlbaum (C<jesse@vm.com>) at Vanguard Media (http://vm.com) . The most original idea in this module - the C<< <TMPL_LOOP> >> - was entirely his. Fixes, Bug Reports, Optimizations and Ideas have been generously provided by: =over =item * Richard Chen =item * Mike Blazer =item * Adriano Nagelschmidt Rodrigues =item * Andrej Mikus =item * Ilya Obshadko =item * Kevin Puetz =item * Steve Reppucci =item * Richard Dice =item * Tom Hukins =item * Eric Zylberstejn =item * David Glasser =item * Peter Marelas =item * James William Carlson =item * Frank D. Cringle =item * Winfried Koenig =item * Matthew Wickline =item * Doug Steinwand =item * Drew Taylor =item * Tobias Brox =item * Michael Lloyd =item * Simran Gambhir =item * Chris Houser <chouser@bluweb.com> =item * Larry Moore =item * Todd Larason =item * Jody Biggs =item * T.J. Mather =item * Martin Schroth =item * Dave Wolfe =item * uchum =item * Kawai Takanori =item * Peter Guelich =item * Chris Nokleberg =item * Ralph Corderoy =item * William Ward =item * Ade Olonoh =item * Mark Stosberg =item * Lance Thomas =item * Roland Giersig =item * Jere Julian =item * Peter Leonard =item * Kenny Smith =item * Sean P. Scanlon =item * Martin Pfeffer =item * David Ferrance =item * Gyepi Sam =item * Darren Chamberlain =item * Paul Baker =item * Gabor Szabo =item * Craig Manley =item * Richard Fein =item * The Phalanx Project =item * Sven Neuhaus =item * Michael Peters =item * Jan Dubois =item * Moritz Lenz =back Thanks! =head1 WEBSITE You can find information about HTML::Template and other related modules at: http://html-template.sourceforge.net =head1 PUBLIC GIT REPOSITORY HTML::Template now has a publicly accessible Git repository provided by GitHub (github.com). You can access it by going to https://github.com/mpeters/html-template. Give it a try! =head1 AUTHOR Sam Tregar, C<sam@tregar.com> =head1 CO-MAINTAINER Michael Peters, C<mpeters@plusthree.com> =head1 LICENSE HTML::Template : A module for using HTML Templates with Perl Copyright (C) 2000-2011 Sam Tregar (sam@tregar.com) This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, which means using either: a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" which comes with this module. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the Artistic License for more details. You should have received a copy of the Artistic License with this module. If not, I'll be glad to provide one. You should have received a copy of the GNU General Public License along with this program. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA =cut PK #L�[�D=� � Template/FAQ.pmnu �[��� use strict; use warnings; package HTML::Template::FAQ; # ABSTRACT: Frequently Asked Questions about HTML::Template use Carp (); Carp::confess "you're not meant to use the FAQ, just read it!"; 1; __END__ =pod =head1 NAME HTML::Template::FAQ - Frequently Asked Questions about HTML::Template =head1 SYNOPSIS In the interest of greater understanding I've started a FAQ section of the perldocs. Please look in here before you send me email. =head1 FREQUENTLY ASKED QUESTIONS =head2 Is there a place to go to discuss HTML::Template and/or get help? There's a mailing-list for discussing L<HTML::Template> at html-template-users@lists.sourceforge.net. Join at: http://lists.sourceforge.net/lists/listinfo/html-template-users If you just want to get email when new releases are available you can join the announcements mailing-list here: http://lists.sourceforge.net/lists/listinfo/html-template-announce =head2 Is there a searchable archive for the mailing-list? Yes, you can find an archive of the SourceForge list here: http://dir.gmane.org/gmane.comp.lang.perl.modules.html-template =head2 I want support for <TMPL_XXX>! How about it? Maybe. I definitely encourage people to discuss their ideas for L<HTML::Template> on the mailing list. Please be ready to explain to me how the new tag fits in with HTML::Template's mission to provide a fast, lightweight system for using HTML templates. NOTE: Offering to program said addition and provide it in the form of a patch to the most recent version of L<HTML::Template> will definitely have a softening effect on potential opponents! =head2 I found a bug, can you fix it? That depends. Did you send me the VERSION of L<HTML::Template>, a test script and a test template? If so, then almost certainly. If you're feeling really adventurous, L<HTML::Template> is publicly available on GitHub (https://github.com/mpeters/html-template). Please feel free to fork it and send me a pull request with any changes you have. =head2 <TMPL_VAR>s from the main template aren't working inside a <TMPL_LOOP>! Why? This is the intended behavior. C<< <TMPL_LOOP> >> introduces a separate scope for C<< <TMPL_VAR>s >> much like a subroutine call in Perl introduces a separate scope for C<my> variables. If you want your C<< <TMPL_VAR> >>s to be global you can set the C<global_vars> option when you call C<new()>. See above for documentation of the C<global_vars> C<new()> option. =head2 How can I pre-load my templates using cache-mode and mod_perl? Add something like this to your startup.pl: use HTML::Template; use File::Find; print STDERR "Pre-loading HTML Templates...\n"; find( sub { return unless /\.tmpl$/; HTML::Template->new( filename => "$File::Find::dir/$_", cache => 1, ); }, '/path/to/templates', '/another/path/to/templates/' ); Note that you'll need to modify the C<return unless> line to specify the extension you use for your template files - I use F<.tmpl>, as you can see. You'll also need to specify the path to your template files. One potential problem: the F</path/to/templates/> must be B<EXACTLY> the same path you use when you call C<< HTML::Template->new() >>. Otherwise the cache won't know they're the same file and will load a new copy - instead getting a speed increase, you'll double your memory usage. To find out if this is happening set C<cache_debug => 1> in your application code and look for "CACHE MISS" messages in the logs. =head2 What characters are allowed in TMPL_* names? Numbers, letters, '.', '/', '+', '-' and '_'. =head2 How can I execute a program from inside my template? Short answer: you can't. Longer answer: you shouldn't since this violates the fundamental concept behind L<HTML::Template> - that design and code should be separate. But, inevitably some people still want to do it. If that describes you then you should take a look at L<HTML::Template::Expr>. Using L<HTML::Template::Expr> it should be easy to write a C<run_program()> function. Then you can do awful stuff like: <tmpl_var expr="run_program('foo.pl')"> Just, please, don't tell me about it. I'm feeling guilty enough just for writing L<HTML::Template::Expr> in the first place. =head2 What's the best way to create a <select> form element using HTML::Template? There is much disagreement on this issue. My personal preference is to use L<CGI.pm>'s excellent C<popup_menu()> and C<scrolling_list()> functions to fill in a single C<< <tmpl_var select_foo> >> variable. To some people this smacks of mixing HTML and code in a way that they hoped L<HTML::Template> would help them avoid. To them I'd say that HTML is a violation of the principle of separating design from programming. There's no clear separation between the programmatic elements of the C<< <form> >> tags and the layout of the C<< <form> >> tags. You'll have to draw the line somewhere - clearly the designer can't be entirely in charge of form creation. It's a balancing act and you have to weigh the pros and cons on each side. It is certainly possible to produce a C<< <select> >> element entirely inside the template. What you end up with is a rat's nest of loops and conditionals. Alternately you can give up a certain amount of flexibility in return for vastly simplifying your templates. I generally choose the latter. Another option is to investigate L<HTML::FillInForm> which some have reported success using to solve this problem. PK #L�[T�00�2 �2 Tagset.pmnu �[��� package HTML::Tagset; use strict; =head1 NAME HTML::Tagset - data tables useful in parsing HTML =head1 VERSION Version 3.20 =cut use vars qw( $VERSION ); $VERSION = '3.20'; =head1 SYNOPSIS use HTML::Tagset; # Then use any of the items in the HTML::Tagset package # as need arises =head1 DESCRIPTION This module contains several data tables useful in various kinds of HTML parsing operations. Note that all tag names used are lowercase. In the following documentation, a "hashset" is a hash being used as a set -- the hash conveys that its keys are there, and the actual values associated with the keys are not significant. (But what values are there, are always true.) =cut use vars qw( $VERSION %emptyElement %optionalEndTag %linkElements %boolean_attr %isHeadElement %isBodyElement %isPhraseMarkup %is_Possible_Strict_P_Content %isHeadOrBodyElement %isList %isTableElement %isFormElement %isKnown %canTighten @p_closure_barriers %isCDATA_Parent ); =head1 VARIABLES Note that none of these variables are exported. =head2 hashset %HTML::Tagset::emptyElement This hashset has as values the tag-names (GIs) of elements that cannot have content. (For example, "base", "br", "hr".) So C<$HTML::Tagset::emptyElement{'hr'}> exists and is true. C<$HTML::Tagset::emptyElement{'dl'}> does not exist, and so is not true. =cut %emptyElement = map {; $_ => 1 } qw(base link meta isindex img br hr wbr input area param embed bgsound spacer basefont col frame ~comment ~literal ~declaration ~pi ); # The "~"-initial names are for pseudo-elements used by HTML::Entities # and TreeBuilder =head2 hashset %HTML::Tagset::optionalEndTag This hashset lists tag-names for elements that can have content, but whose end-tags are generally, "safely", omissible. Example: C<$HTML::Tagset::emptyElement{'li'}> exists and is true. =cut %optionalEndTag = map {; $_ => 1 } qw(p li dt dd); # option th tr td); =head2 hash %HTML::Tagset::linkElements Values in this hash are tagnames for elements that might contain links, and the value for each is a reference to an array of the names of attributes whose values can be links. =cut %linkElements = ( 'a' => ['href'], 'applet' => ['archive', 'codebase', 'code'], 'area' => ['href'], 'base' => ['href'], 'bgsound' => ['src'], 'blockquote' => ['cite'], 'body' => ['background'], 'del' => ['cite'], 'embed' => ['pluginspage', 'src'], 'form' => ['action'], 'frame' => ['src', 'longdesc'], 'iframe' => ['src', 'longdesc'], 'ilayer' => ['background'], 'img' => ['src', 'lowsrc', 'longdesc', 'usemap'], 'input' => ['src', 'usemap'], 'ins' => ['cite'], 'isindex' => ['action'], 'head' => ['profile'], 'layer' => ['background', 'src'], 'link' => ['href'], 'object' => ['classid', 'codebase', 'data', 'archive', 'usemap'], 'q' => ['cite'], 'script' => ['src', 'for'], 'table' => ['background'], 'td' => ['background'], 'th' => ['background'], 'tr' => ['background'], 'xmp' => ['href'], ); =head2 hash %HTML::Tagset::boolean_attr This hash (not hashset) lists what attributes of what elements can be printed without showing the value (for example, the "noshade" attribute of "hr" elements). For elements with only one such attribute, its value is simply that attribute name. For elements with many such attributes, the value is a reference to a hashset containing all such attributes. =cut %boolean_attr = ( # TODO: make these all hashes 'area' => 'nohref', 'dir' => 'compact', 'dl' => 'compact', 'hr' => 'noshade', 'img' => 'ismap', 'input' => { 'checked' => 1, 'readonly' => 1, 'disabled' => 1 }, 'menu' => 'compact', 'ol' => 'compact', 'option' => 'selected', 'select' => 'multiple', 'td' => 'nowrap', 'th' => 'nowrap', 'ul' => 'compact', ); #========================================================================== # List of all elements from Extensible HTML version 1.0 Transitional DTD: # # a abbr acronym address applet area b base basefont bdo big # blockquote body br button caption center cite code col colgroup # dd del dfn dir div dl dt em fieldset font form h1 h2 h3 h4 h5 h6 # head hr html i iframe img input ins isindex kbd label legend li # link map menu meta noframes noscript object ol optgroup option p # param pre q s samp script select small span strike strong style # sub sup table tbody td textarea tfoot th thead title tr tt u ul # var # # Varia from Mozilla source internal table of tags: # Implemented: # xmp listing wbr nobr frame frameset noframes ilayer # layer nolayer spacer embed multicol # But these are unimplemented: # sound?? keygen?? server?? # Also seen here and there: # marquee?? app?? (both unimplemented) #========================================================================== =head2 hashset %HTML::Tagset::isPhraseMarkup This hashset contains all phrasal-level elements. =cut %isPhraseMarkup = map {; $_ => 1 } qw( span abbr acronym q sub sup cite code em kbd samp strong var dfn strike b i u s tt small big a img br wbr nobr blink font basefont bdo spacer embed noembed ); # had: center, hr, table =head2 hashset %HTML::Tagset::is_Possible_Strict_P_Content This hashset contains all phrasal-level elements that be content of a P element, for a strict model of HTML. =cut %is_Possible_Strict_P_Content = ( %isPhraseMarkup, %isFormElement, map {; $_ => 1} qw( object script map ) # I've no idea why there's these latter exceptions. # I'm just following the HTML4.01 DTD. ); #from html4 strict: #<!ENTITY % fontstyle "TT | I | B | BIG | SMALL"> # #<!ENTITY % phrase "EM | STRONG | DFN | CODE | # SAMP | KBD | VAR | CITE | ABBR | ACRONYM" > # #<!ENTITY % special # "A | IMG | OBJECT | BR | SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO"> # #<!ENTITY % formctrl "INPUT | SELECT | TEXTAREA | LABEL | BUTTON"> # #<!-- %inline; covers inline or "text-level" elements --> #<!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;"> =head2 hashset %HTML::Tagset::isHeadElement This hashset contains all elements that elements that should be present only in the 'head' element of an HTML document. =cut %isHeadElement = map {; $_ => 1 } qw(title base link meta isindex script style object bgsound); =head2 hashset %HTML::Tagset::isList This hashset contains all elements that can contain "li" elements. =cut %isList = map {; $_ => 1 } qw(ul ol dir menu); =head2 hashset %HTML::Tagset::isTableElement This hashset contains all elements that are to be found only in/under a "table" element. =cut %isTableElement = map {; $_ => 1 } qw(tr td th thead tbody tfoot caption col colgroup); =head2 hashset %HTML::Tagset::isFormElement This hashset contains all elements that are to be found only in/under a "form" element. =cut %isFormElement = map {; $_ => 1 } qw(input select option optgroup textarea button label); =head2 hashset %HTML::Tagset::isBodyMarkup This hashset contains all elements that are to be found only in/under the "body" element of an HTML document. =cut %isBodyElement = map {; $_ => 1 } qw( h1 h2 h3 h4 h5 h6 p div pre plaintext address blockquote xmp listing center multicol iframe ilayer nolayer bgsound hr ol ul dir menu li dl dt dd ins del fieldset legend map area applet param object isindex script noscript table center form ), keys %isFormElement, keys %isPhraseMarkup, # And everything phrasal keys %isTableElement, ; =head2 hashset %HTML::Tagset::isHeadOrBodyElement This hashset includes all elements that I notice can fall either in the head or in the body. =cut %isHeadOrBodyElement = map {; $_ => 1 } qw(script isindex style object map area param noscript bgsound); # i.e., if we find 'script' in the 'body' or the 'head', don't freak out. =head2 hashset %HTML::Tagset::isKnown This hashset lists all known HTML elements. =cut %isKnown = (%isHeadElement, %isBodyElement, map{; $_=>1 } qw( head body html frame frameset noframes ~comment ~pi ~directive ~literal )); # that should be all known tags ever ever =head2 hashset %HTML::Tagset::canTighten This hashset lists elements that might have ignorable whitespace as children or siblings. =cut %canTighten = %isKnown; delete @canTighten{ keys(%isPhraseMarkup), 'input', 'select', 'xmp', 'listing', 'plaintext', 'pre', }; # xmp, listing, plaintext, and pre are untightenable, and # in a really special way. @canTighten{'hr','br'} = (1,1); # exceptional 'phrasal' things that ARE subject to tightening. # The one case where I can think of my tightening rules failing is: # <p>foo bar<center> <em>baz quux</em> ... # ^-- that would get deleted. # But that's pretty gruesome code anyhow. You gets what you pays for. #========================================================================== =head2 array @HTML::Tagset::p_closure_barriers This array has a meaning that I have only seen a need for in C<HTML::TreeBuilder>, but I include it here on the off chance that someone might find it of use: When we see a "E<lt>pE<gt>" token, we go lookup up the lineage for a p element we might have to minimize. At first sight, we might say that if there's a p anywhere in the lineage of this new p, it should be closed. But that's wrong. Consider this document: <html> <head> <title>foo</title> </head> <body> <p>foo <table> <tr> <td> foo <p>bar </td> </tr> </table> </p> </body> </html> The second p is quite legally inside a much higher p. My formalization of the reason why this is legal, but this: <p>foo<p>bar</p></p> isn't, is that something about the table constitutes a "barrier" to the application of the rule about what p must minimize. So C<@HTML::Tagset::p_closure_barriers> is the list of all such barrier-tags. =cut @p_closure_barriers = qw( li blockquote ul ol menu dir dl dt dd td th tr table caption div ); # In an ideal world (i.e., XHTML) we wouldn't have to bother with any of this # monkey business of barriers to minimization! =head2 hashset %isCDATA_Parent This hashset includes all elements whose content is CDATA. =cut %isCDATA_Parent = map {; $_ => 1 } qw(script style xmp listing plaintext); # TODO: there's nothing else that takes CDATA children, right? # As the HTML3 DTD (Raggett 1995-04-24) noted: # The XMP, LISTING and PLAINTEXT tags are incompatible with SGML # and derive from very early versions of HTML. They require non- # standard parsers and will cause problems for processing # documents with standard SGML tools. =head1 CAVEATS You may find it useful to alter the behavior of modules (like C<HTML::Element> or C<HTML::TreeBuilder>) that use C<HTML::Tagset>'s data tables by altering the data tables themselves. You are welcome to try, but be careful; and be aware that different modules may or may react differently to the data tables being changed. Note that it may be inappropriate to use these tables for I<producing> HTML -- for example, C<%isHeadOrBodyElement> lists the tagnames for all elements that can appear either in the head or in the body, such as "script". That doesn't mean that I am saying your code that produces HTML should feel free to put script elements in either place! If you are producing programs that spit out HTML, you should be I<intimately> familiar with the DTDs for HTML or XHTML (available at C<http://www.w3.org/>), and you should slavishly obey them, not the data tables in this document. =head1 SEE ALSO L<HTML::Element>, L<HTML::TreeBuilder>, L<HTML::LinkExtor> =head1 COPYRIGHT & LICENSE Copyright 1995-2000 Gisle Aas. Copyright 2000-2005 Sean M. Burke. Copyright 2005-2008 Andy Lester. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 ACKNOWLEDGEMENTS Most of the code/data in this module was adapted from code written by Gisle Aas for C<HTML::Element>, C<HTML::TreeBuilder>, and C<HTML::LinkExtor>. Then it was maintained by Sean M. Burke. =head1 AUTHOR Current maintainer: Andy Lester, C<< <andy at petdance.com> >> =head1 BUGS Please report any bugs or feature requests to C<bug-html-tagset at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=HTML-Tagset>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =cut 1; PK �X�[��=� � LinkExtor.pmnu �[��� package HTML::LinkExtor; require HTML::Parser; our @ISA = qw(HTML::Parser); our $VERSION = '3.76'; =head1 NAME HTML::LinkExtor - Extract links from an HTML document =head1 SYNOPSIS require HTML::LinkExtor; $p = HTML::LinkExtor->new(\&cb, "http://www.perl.org/"); sub cb { my($tag, %links) = @_; print "$tag @{[%links]}\n"; } $p->parse_file("index.html"); =head1 DESCRIPTION I<HTML::LinkExtor> is an HTML parser that extracts links from an HTML document. The I<HTML::LinkExtor> is a subclass of I<HTML::Parser>. This means that the document should be given to the parser by calling the $p->parse() or $p->parse_file() methods. =cut use strict; use HTML::Tagset (); # legacy (some applications grabs this hash directly) our %LINK_ELEMENT; *LINK_ELEMENT = \%HTML::Tagset::linkElements; =over 4 =item $p = HTML::LinkExtor->new =item $p = HTML::LinkExtor->new( $callback ) =item $p = HTML::LinkExtor->new( $callback, $base ) The constructor takes two optional arguments. The first is a reference to a callback routine. It will be called as links are found. If a callback is not provided, then links are just accumulated internally and can be retrieved by calling the $p->links() method. The $base argument is an optional base URL used to absolutize all URLs found. You need to have the I<URI> module installed if you provide $base. The callback is called with the lowercase tag name as first argument, and then all link attributes as separate key/value pairs. All non-link attributes are removed. =cut sub new { my($class, $cb, $base) = @_; my $self = $class->SUPER::new( start_h => ["_start_tag", "self,tagname,attr"], report_tags => [keys %HTML::Tagset::linkElements], ); $self->{extractlink_cb} = $cb; if ($base) { require URI; $self->{extractlink_base} = URI->new($base); } $self; } sub _start_tag { my($self, $tag, $attr) = @_; my $base = $self->{extractlink_base}; my $links = $HTML::Tagset::linkElements{$tag}; $links = [$links] unless ref $links; my @links; my $a; for $a (@$links) { next unless exists $attr->{$a}; (my $link = $attr->{$a}) =~ s/^\s+//; $link =~ s/\s+$//; # HTML5 push(@links, $a, $base ? URI->new($link, $base)->abs($base) : $link); } return unless @links; $self->_found_link($tag, @links); } sub _found_link { my $self = shift; my $cb = $self->{extractlink_cb}; if ($cb) { &$cb(@_); } else { push(@{$self->{'links'}}, [@_]); } } =item $p->links Returns a list of all links found in the document. The returned values will be anonymous arrays with the following elements: [$tag, $attr => $url1, $attr2 => $url2,...] The $p->links method will also truncate the internal link list. This means that if the method is called twice without any parsing between them the second call will return an empty list. Also note that $p->links will always be empty if a callback routine was provided when the I<HTML::LinkExtor> was created. =cut sub links { my $self = shift; exists($self->{'links'}) ? @{delete $self->{'links'}} : (); } # We override the parse_file() method so that we can clear the links # before we start a new file. sub parse_file { my $self = shift; delete $self->{'links'}; $self->SUPER::parse_file(@_); } =back =head1 EXAMPLE This is an example showing how you can extract links from a document received using LWP: use LWP::UserAgent; use HTML::LinkExtor; use URI::URL; $url = "http://www.perl.org/"; # for instance $ua = LWP::UserAgent->new; # Set up a callback that collect image links my @imgs = (); sub callback { my($tag, %attr) = @_; return if $tag ne 'img'; # we only look closer at <img ...> push(@imgs, values %attr); } # Make the parser. Unfortunately, we don't know the base yet # (it might be different from $url) $p = HTML::LinkExtor->new(\&callback); # Request document and parse it as it arrives $res = $ua->request(HTTP::Request->new(GET => $url), sub {$p->parse($_[0])}); # Expand all image URLs to absolute ones my $base = $res->base; @imgs = map { $_ = url($_, $base)->abs; } @imgs; # Print them out print join("\n", @imgs), "\n"; =head1 SEE ALSO L<HTML::Parser>, L<HTML::Tagset>, L<LWP>, L<URI::URL> =head1 COPYRIGHT Copyright 1996-2001 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; PK �X�[ �R< < PullParser.pmnu �[��� package HTML::PullParser; use strict; require HTML::Parser; our @ISA = qw(HTML::Parser); our $VERSION = '3.76'; use Carp (); sub new { my($class, %cnf) = @_; # Construct argspecs for the various events my %argspec; for (qw(start end text declaration comment process default)) { my $tmp = delete $cnf{$_}; next unless defined $tmp; $argspec{$_} = $tmp; } Carp::croak("Info not collected for any events") unless %argspec; my $file = delete $cnf{file}; my $doc = delete $cnf{doc}; Carp::croak("Can't parse from both 'doc' and 'file' at the same time") if defined($file) && defined($doc); Carp::croak("No 'doc' or 'file' given to parse from") unless defined($file) || defined($doc); # Create object $cnf{api_version} = 3; my $self = $class->SUPER::new(%cnf); my $accum = $self->{pullparser_accum} = []; while (my($event, $argspec) = each %argspec) { $self->SUPER::handler($event => $accum, $argspec); } if (defined $doc) { $self->{pullparser_str_ref} = ref($doc) ? $doc : \$doc; $self->{pullparser_str_pos} = 0; } else { if (!ref($file) && ref(\$file) ne "GLOB") { require IO::File; $file = IO::File->new($file, "r") || return; } $self->{pullparser_file} = $file; } $self; } sub handler { Carp::croak("Can't set handlers for HTML::PullParser"); } sub get_token { my $self = shift; while (!@{$self->{pullparser_accum}} && !$self->{pullparser_eof}) { if (my $f = $self->{pullparser_file}) { # must try to parse more from the file my $buf; if (read($f, $buf, 512)) { $self->parse($buf); } else { $self->eof; $self->{pullparser_eof}++; delete $self->{pullparser_file}; } } elsif (my $sref = $self->{pullparser_str_ref}) { # must try to parse more from the scalar my $pos = $self->{pullparser_str_pos}; my $chunk = substr($$sref, $pos, 512); $self->parse($chunk); $pos += length($chunk); if ($pos < length($$sref)) { $self->{pullparser_str_pos} = $pos; } else { $self->eof; $self->{pullparser_eof}++; delete $self->{pullparser_str_ref}; delete $self->{pullparser_str_pos}; } } else { die; } } shift @{$self->{pullparser_accum}}; } sub unget_token { my $self = shift; unshift @{$self->{pullparser_accum}}, @_; $self; } 1; __END__ =head1 NAME HTML::PullParser - Alternative HTML::Parser interface =head1 SYNOPSIS use HTML::PullParser; $p = HTML::PullParser->new(file => "index.html", start => 'event, tagname, @attr', end => 'event, tagname', ignore_elements => [qw(script style)], ) || die "Can't open: $!"; while (my $token = $p->get_token) { #...do something with $token } =head1 DESCRIPTION The HTML::PullParser is an alternative interface to the HTML::Parser class. It basically turns the HTML::Parser inside out. You associate a file (or any IO::Handle object or string) with the parser at construction time and then repeatedly call $parser->get_token to obtain the tags and text found in the parsed document. The following methods are provided: =over 4 =item $p = HTML::PullParser->new( file => $file, %options ) =item $p = HTML::PullParser->new( doc => \$doc, %options ) A C<HTML::PullParser> can be made to parse from either a file or a literal document based on whether the C<file> or C<doc> option is passed to the parser's constructor. The C<file> passed in can either be a file name or a file handle object. If a file name is passed, and it can't be opened for reading, then the constructor will return an undefined value and $! will tell you why it failed. Otherwise the argument is taken to be some object that the C<HTML::PullParser> can read() from when it needs more data. The stream will be read() until EOF, but not closed. A C<doc> can be passed plain or as a reference to a scalar. If a reference is passed then the value of this scalar should not be changed before all tokens have been extracted. Next the information to be returned for the different token types must be set up. This is done by simply associating an argspec (as defined in L<HTML::Parser>) with the events you have an interest in. For instance, if you want C<start> tokens to be reported as the string C<'S'> followed by the tagname and the attributes you might pass an C<start>-option like this: $p = HTML::PullParser->new( doc => $document_to_parse, start => '"S", tagname, @attr', end => '"E", tagname', ); At last other C<HTML::Parser> options, like C<ignore_tags>, and C<unbroken_text>, can be passed in. Note that you should not use the I<event>_h options to set up parser handlers. That would confuse the inner logic of C<HTML::PullParser>. =item $token = $p->get_token This method will return the next I<token> found in the HTML document, or C<undef> at the end of the document. The token is returned as an array reference. The content of this array match the argspec set up during C<HTML::PullParser> construction. =item $p->unget_token( @tokens ) If you find out you have read too many tokens you can push them back, so that they are returned again the next time $p->get_token is called. =back =head1 EXAMPLES The 'eg/hform' script shows how we might parse the form section of HTML::Documents using HTML::PullParser. =head1 SEE ALSO L<HTML::Parser>, L<HTML::TokeParser> =head1 COPYRIGHT Copyright 1998-2001 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK �X�[(w��f f Filter.pmnu �[��� package HTML::Filter; use strict; require HTML::Parser; our @ISA = qw(HTML::Parser); our $VERSION = '3.76'; sub declaration { $_[0]->output("<!$_[1]>") } sub process { $_[0]->output($_[2]) } sub comment { $_[0]->output("<!--$_[1]-->") } sub start { $_[0]->output($_[4]) } sub end { $_[0]->output($_[2]) } sub text { $_[0]->output($_[1]) } sub output { print $_[1] } 1; __END__ =head1 NAME HTML::Filter - Filter HTML text through the parser =head1 NOTE B<This module is deprecated.> The C<HTML::Parser> now provides the functionally of C<HTML::Filter> much more efficiently with the C<default> handler. =head1 SYNOPSIS require HTML::Filter; $p = HTML::Filter->new->parse_file("index.html"); =head1 DESCRIPTION C<HTML::Filter> is an HTML parser that by default prints the original text of each HTML element (a slow version of cat(1) basically). The callback methods may be overridden to modify the filtering for some HTML elements and you can override output() method which is called to print the HTML text. C<HTML::Filter> is a subclass of C<HTML::Parser>. This means that the document should be given to the parser by calling the $p->parse() or $p->parse_file() methods. =head1 EXAMPLES The first example is a filter that will remove all comments from an HTML file. This is achieved by simply overriding the comment method to do nothing. package CommentStripper; require HTML::Filter; @ISA=qw(HTML::Filter); sub comment { } # ignore comments The second example shows a filter that will remove any E<lt>TABLE>s found in the HTML file. We specialize the start() and end() methods to count table tags and then make output not happen when inside a table. package TableStripper; require HTML::Filter; @ISA=qw(HTML::Filter); sub start { my $self = shift; $self->{table_seen}++ if $_[0] eq "table"; $self->SUPER::start(@_); } sub end { my $self = shift; $self->SUPER::end(@_); $self->{table_seen}-- if $_[0] eq "table"; } sub output { my $self = shift; unless ($self->{table_seen}) { $self->SUPER::output(@_); } } If you want to collect the parsed text internally you might want to do something like this: package FilterIntoString; require HTML::Filter; @ISA=qw(HTML::Filter); sub output { push(@{$_[0]->{fhtml}}, $_[1]) } sub filtered_html { join("", @{$_[0]->{fhtml}}) } =head1 SEE ALSO L<HTML::Parser> =head1 COPYRIGHT Copyright 1997-1999 Gisle Aas. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK �X�[VZ�1m: m: Entities.pmnu �[��� package HTML::Entities; =encoding utf8 =head1 NAME HTML::Entities - Encode or decode strings with HTML entities =head1 SYNOPSIS use HTML::Entities; $a = "Våre norske tegn bør æres"; decode_entities($a); encode_entities($a, "\200-\377"); For example, this: $input = "vis-à-vis Beyoncé's naïve\npapier-mâché résumé"; print encode_entities($input), "\n" Prints this out: vis-à-vis Beyoncé's naïve papier-mâché résumé =head1 DESCRIPTION This module deals with encoding and decoding of strings with HTML character entities. The module provides the following functions: =over 4 =item decode_entities( $string, ... ) This routine replaces HTML entities found in the $string with the corresponding Unicode character. Unrecognized entities are left alone. If multiple strings are provided as argument they are each decoded separately and the same number of strings are returned. If called in void context the arguments are decoded in-place. This routine is exported by default. =item _decode_entities( $string, \%entity2char ) =item _decode_entities( $string, \%entity2char, $expand_prefix ) This will in-place replace HTML entities in $string. The %entity2char hash must be provided. Named entities not found in the %entity2char hash are left alone. Numeric entities are expanded unless their value overflow. The keys in %entity2char are the entity names to be expanded and their values are what they should expand into. The values do not have to be single character strings. If a key has ";" as suffix, then occurrences in $string are only expanded if properly terminated with ";". Entities without ";" will be expanded regardless of how they are terminated for compatibility with how common browsers treat entities in the Latin-1 range. If $expand_prefix is TRUE then entities without trailing ";" in %entity2char will even be expanded as a prefix of a longer unrecognized name. The longest matching name in %entity2char will be used. This is mainly present for compatibility with an MSIE misfeature. $string = "foo bar"; _decode_entities($string, { nb => "@", nbsp => "\xA0" }, 1); print $string; # will print "foo bar" This routine is exported by default. =item encode_entities( $string ) =item encode_entities( $string, $unsafe_chars ) This routine replaces unsafe characters in $string with their entity representation. A second argument can be given to specify which characters to consider unsafe. The unsafe characters is specified using the regular expression character class syntax (what you find within brackets in regular expressions). The default set of characters to encode are control chars, high-bit chars, and the C<< < >>, C<< & >>, C<< > >>, C<< ' >> and C<< " >> characters. But this, for example, would encode I<just> the C<< < >>, C<< & >>, C<< > >>, and C<< " >> characters: $encoded = encode_entities($input, '<>&"'); and this would only encode non-plain ASCII: $encoded = encode_entities($input, '^\n\x20-\x25\x27-\x7e'); This routine is exported by default. =item encode_entities_numeric( $string ) =item encode_entities_numeric( $string, $unsafe_chars ) This routine works just like encode_entities, except that the replacement entities are always C<&#xI<hexnum>;> and never C<&I<entname>;>. For example, C<encode_entities("r\xF4le")> returns "rôle", but C<encode_entities_numeric("r\xF4le")> returns "rôle". This routine is I<not> exported by default. But you can always export it with C<use HTML::Entities qw(encode_entities_numeric);> or even C<use HTML::Entities qw(:DEFAULT encode_entities_numeric);> =back All these routines modify the string passed as the first argument, if called in a void context. In scalar and array contexts, the encoded or decoded string is returned (without changing the input string). If you prefer not to import these routines into your namespace, you can call them as: use HTML::Entities (); $decoded = HTML::Entities::decode($a); $encoded = HTML::Entities::encode($a); $encoded = HTML::Entities::encode_numeric($a); The module can also export the %char2entity and the %entity2char hashes, which contain the mapping from all characters to the corresponding entities (and vice versa, respectively). =head1 COPYRIGHT Copyright 1995-2006 Gisle Aas. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut use strict; our $VERSION = '3.76'; our (%entity2char, %char2entity); require 5.004; require Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(encode_entities decode_entities _decode_entities); our @EXPORT_OK = qw(%entity2char %char2entity encode_entities_numeric); sub Version { $VERSION; } require HTML::Parser; # for fast XS implemented decode_entities %entity2char = ( # Some normal chars that have special meaning in SGML context amp => '&', # ampersand 'gt' => '>', # greater than 'lt' => '<', # less than quot => '"', # double quote apos => "'", # single quote # PUBLIC ISO 8879-1986//ENTITIES Added Latin 1//EN//HTML AElig => chr(198), # capital AE diphthong (ligature) Aacute => chr(193), # capital A, acute accent Acirc => chr(194), # capital A, circumflex accent Agrave => chr(192), # capital A, grave accent Aring => chr(197), # capital A, ring Atilde => chr(195), # capital A, tilde Auml => chr(196), # capital A, dieresis or umlaut mark Ccedil => chr(199), # capital C, cedilla ETH => chr(208), # capital Eth, Icelandic Eacute => chr(201), # capital E, acute accent Ecirc => chr(202), # capital E, circumflex accent Egrave => chr(200), # capital E, grave accent Euml => chr(203), # capital E, dieresis or umlaut mark Iacute => chr(205), # capital I, acute accent Icirc => chr(206), # capital I, circumflex accent Igrave => chr(204), # capital I, grave accent Iuml => chr(207), # capital I, dieresis or umlaut mark Ntilde => chr(209), # capital N, tilde Oacute => chr(211), # capital O, acute accent Ocirc => chr(212), # capital O, circumflex accent Ograve => chr(210), # capital O, grave accent Oslash => chr(216), # capital O, slash Otilde => chr(213), # capital O, tilde Ouml => chr(214), # capital O, dieresis or umlaut mark THORN => chr(222), # capital THORN, Icelandic Uacute => chr(218), # capital U, acute accent Ucirc => chr(219), # capital U, circumflex accent Ugrave => chr(217), # capital U, grave accent Uuml => chr(220), # capital U, dieresis or umlaut mark Yacute => chr(221), # capital Y, acute accent aacute => chr(225), # small a, acute accent acirc => chr(226), # small a, circumflex accent aelig => chr(230), # small ae diphthong (ligature) agrave => chr(224), # small a, grave accent aring => chr(229), # small a, ring atilde => chr(227), # small a, tilde auml => chr(228), # small a, dieresis or umlaut mark ccedil => chr(231), # small c, cedilla eacute => chr(233), # small e, acute accent ecirc => chr(234), # small e, circumflex accent egrave => chr(232), # small e, grave accent eth => chr(240), # small eth, Icelandic euml => chr(235), # small e, dieresis or umlaut mark iacute => chr(237), # small i, acute accent icirc => chr(238), # small i, circumflex accent igrave => chr(236), # small i, grave accent iuml => chr(239), # small i, dieresis or umlaut mark ntilde => chr(241), # small n, tilde oacute => chr(243), # small o, acute accent ocirc => chr(244), # small o, circumflex accent ograve => chr(242), # small o, grave accent oslash => chr(248), # small o, slash otilde => chr(245), # small o, tilde ouml => chr(246), # small o, dieresis or umlaut mark szlig => chr(223), # small sharp s, German (sz ligature) thorn => chr(254), # small thorn, Icelandic uacute => chr(250), # small u, acute accent ucirc => chr(251), # small u, circumflex accent ugrave => chr(249), # small u, grave accent uuml => chr(252), # small u, dieresis or umlaut mark yacute => chr(253), # small y, acute accent yuml => chr(255), # small y, dieresis or umlaut mark # Some extra Latin 1 chars that are listed in the HTML3.2 draft (21-May-96) copy => chr(169), # copyright sign reg => chr(174), # registered sign nbsp => chr(160), # non breaking space # Additional ISO-8859/1 entities listed in rfc1866 (section 14) iexcl => chr(161), cent => chr(162), pound => chr(163), curren => chr(164), yen => chr(165), brvbar => chr(166), sect => chr(167), uml => chr(168), ordf => chr(170), laquo => chr(171), 'not' => chr(172), # not is a keyword in perl shy => chr(173), macr => chr(175), deg => chr(176), plusmn => chr(177), sup1 => chr(185), sup2 => chr(178), sup3 => chr(179), acute => chr(180), micro => chr(181), para => chr(182), middot => chr(183), cedil => chr(184), ordm => chr(186), raquo => chr(187), frac14 => chr(188), frac12 => chr(189), frac34 => chr(190), iquest => chr(191), 'times' => chr(215), # times is a keyword in perl divide => chr(247), ( $] > 5.007 ? ( 'OElig;' => chr(338), 'oelig;' => chr(339), 'Scaron;' => chr(352), 'scaron;' => chr(353), 'Yuml;' => chr(376), 'fnof;' => chr(402), 'circ;' => chr(710), 'tilde;' => chr(732), 'Alpha;' => chr(913), 'Beta;' => chr(914), 'Gamma;' => chr(915), 'Delta;' => chr(916), 'Epsilon;' => chr(917), 'Zeta;' => chr(918), 'Eta;' => chr(919), 'Theta;' => chr(920), 'Iota;' => chr(921), 'Kappa;' => chr(922), 'Lambda;' => chr(923), 'Mu;' => chr(924), 'Nu;' => chr(925), 'Xi;' => chr(926), 'Omicron;' => chr(927), 'Pi;' => chr(928), 'Rho;' => chr(929), 'Sigma;' => chr(931), 'Tau;' => chr(932), 'Upsilon;' => chr(933), 'Phi;' => chr(934), 'Chi;' => chr(935), 'Psi;' => chr(936), 'Omega;' => chr(937), 'alpha;' => chr(945), 'beta;' => chr(946), 'gamma;' => chr(947), 'delta;' => chr(948), 'epsilon;' => chr(949), 'zeta;' => chr(950), 'eta;' => chr(951), 'theta;' => chr(952), 'iota;' => chr(953), 'kappa;' => chr(954), 'lambda;' => chr(955), 'mu;' => chr(956), 'nu;' => chr(957), 'xi;' => chr(958), 'omicron;' => chr(959), 'pi;' => chr(960), 'rho;' => chr(961), 'sigmaf;' => chr(962), 'sigma;' => chr(963), 'tau;' => chr(964), 'upsilon;' => chr(965), 'phi;' => chr(966), 'chi;' => chr(967), 'psi;' => chr(968), 'omega;' => chr(969), 'thetasym;' => chr(977), 'upsih;' => chr(978), 'piv;' => chr(982), 'ensp;' => chr(8194), 'emsp;' => chr(8195), 'thinsp;' => chr(8201), 'zwnj;' => chr(8204), 'zwj;' => chr(8205), 'lrm;' => chr(8206), 'rlm;' => chr(8207), 'ndash;' => chr(8211), 'mdash;' => chr(8212), 'lsquo;' => chr(8216), 'rsquo;' => chr(8217), 'sbquo;' => chr(8218), 'ldquo;' => chr(8220), 'rdquo;' => chr(8221), 'bdquo;' => chr(8222), 'dagger;' => chr(8224), 'Dagger;' => chr(8225), 'bull;' => chr(8226), 'hellip;' => chr(8230), 'permil;' => chr(8240), 'prime;' => chr(8242), 'Prime;' => chr(8243), 'lsaquo;' => chr(8249), 'rsaquo;' => chr(8250), 'oline;' => chr(8254), 'frasl;' => chr(8260), 'euro;' => chr(8364), 'image;' => chr(8465), 'weierp;' => chr(8472), 'real;' => chr(8476), 'trade;' => chr(8482), 'alefsym;' => chr(8501), 'larr;' => chr(8592), 'uarr;' => chr(8593), 'rarr;' => chr(8594), 'darr;' => chr(8595), 'harr;' => chr(8596), 'crarr;' => chr(8629), 'lArr;' => chr(8656), 'uArr;' => chr(8657), 'rArr;' => chr(8658), 'dArr;' => chr(8659), 'hArr;' => chr(8660), 'forall;' => chr(8704), 'part;' => chr(8706), 'exist;' => chr(8707), 'empty;' => chr(8709), 'nabla;' => chr(8711), 'isin;' => chr(8712), 'notin;' => chr(8713), 'ni;' => chr(8715), 'prod;' => chr(8719), 'sum;' => chr(8721), 'minus;' => chr(8722), 'lowast;' => chr(8727), 'radic;' => chr(8730), 'prop;' => chr(8733), 'infin;' => chr(8734), 'ang;' => chr(8736), 'and;' => chr(8743), 'or;' => chr(8744), 'cap;' => chr(8745), 'cup;' => chr(8746), 'int;' => chr(8747), 'there4;' => chr(8756), 'sim;' => chr(8764), 'cong;' => chr(8773), 'asymp;' => chr(8776), 'ne;' => chr(8800), 'equiv;' => chr(8801), 'le;' => chr(8804), 'ge;' => chr(8805), 'sub;' => chr(8834), 'sup;' => chr(8835), 'nsub;' => chr(8836), 'sube;' => chr(8838), 'supe;' => chr(8839), 'oplus;' => chr(8853), 'otimes;' => chr(8855), 'perp;' => chr(8869), 'sdot;' => chr(8901), 'lceil;' => chr(8968), 'rceil;' => chr(8969), 'lfloor;' => chr(8970), 'rfloor;' => chr(8971), 'lang;' => chr(9001), 'rang;' => chr(9002), 'loz;' => chr(9674), 'spades;' => chr(9824), 'clubs;' => chr(9827), 'hearts;' => chr(9829), 'diams;' => chr(9830), ) : ()) ); # Make the opposite mapping while (my($entity, $char) = each(%entity2char)) { $entity =~ s/;\z//; $char2entity{$char} = "&$entity;"; } delete $char2entity{"'"}; # only one-way decoding # Fill in missing entities for (0 .. 255) { next if exists $char2entity{chr($_)}; $char2entity{chr($_)} = "&#$_;"; } my %subst; # compiled encoding regexps sub encode_entities { return undef unless defined $_[0]; my $ref; if (defined wantarray) { my $x = $_[0]; $ref = \$x; # copy } else { $ref = \$_[0]; # modify in-place } if (defined $_[1] and length $_[1]) { unless (exists $subst{$_[1]}) { # Because we can't compile regex we fake it with a cached sub my $chars = $_[1]; $chars =~ s,(?<!\\)([]/]),\\$1,g; $chars =~ s,(?<!\\)\\\z,\\\\,; my $code = "sub {\$_[0] =~ s/([$chars])/\$char2entity{\$1} || num_entity(\$1)/ge; }"; $subst{$_[1]} = eval $code; die( $@ . " while trying to turn range: \"$_[1]\"\n " . "into code: $code\n " ) if $@; } &{$subst{$_[1]}}($$ref); } else { # Encode control chars, high bit chars and '<', '&', '>', ''' and '"' $$ref =~ s/([^\n\r\t !\#\$%\(-;=?-~])/$char2entity{$1} || num_entity($1)/ge; } $$ref; } sub encode_entities_numeric { local %char2entity; return &encode_entities; # a goto &encode_entities wouldn't work } sub num_entity { sprintf "&#x%X;", ord($_[0]); } # Set up aliases *encode = \&encode_entities; *encode_numeric = \&encode_entities_numeric; *encode_numerically = \&encode_entities_numeric; *decode = \&decode_entities; 1; PK �X�[пg9�� �� Parser.pmnu �[��� package HTML::Parser; use strict; our $VERSION = '3.76'; require HTML::Entities; require XSLoader; XSLoader::load('HTML::Parser', $VERSION); sub new { my $class = shift; my $self = bless {}, $class; return $self->init(@_); } sub init { my $self = shift; $self->_alloc_pstate; my %arg = @_; my $api_version = delete $arg{api_version} || (@_ ? 3 : 2); if ($api_version >= 4) { require Carp; Carp::croak("API version $api_version not supported " . "by HTML::Parser $VERSION"); } if ($api_version < 3) { # Set up method callbacks compatible with HTML-Parser-2.xx $self->handler(text => "text", "self,text,is_cdata"); $self->handler(end => "end", "self,tagname,text"); $self->handler(process => "process", "self,token0,text"); $self->handler(start => "start", "self,tagname,attr,attrseq,text"); $self->handler(comment => sub { my($self, $tokens) = @_; for (@$tokens) { $self->comment($_); } }, "self,tokens"); $self->handler(declaration => sub { my $self = shift; $self->declaration(substr($_[0], 2, -1)); }, "self,text"); } if (my $h = delete $arg{handlers}) { $h = {@$h} if ref($h) eq "ARRAY"; while (my($event, $cb) = each %$h) { $self->handler($event => @$cb); } } # In the end we try to assume plain attribute or handler while (my($option, $val) = each %arg) { if ($option =~ /^(\w+)_h$/) { $self->handler($1 => @$val); } elsif ($option =~ /^(text|start|end|process|declaration|comment)$/) { require Carp; Carp::croak("Bad constructor option '$option'"); } else { $self->$option($val); } } return $self; } sub parse_file { my($self, $file) = @_; my $opened; if (!ref($file) && ref(\$file) ne "GLOB") { # Assume $file is a filename local(*F); open(F, "<", $file) || return undef; binmode(F); # should we? good for byte counts $opened++; $file = *F; } my $chunk = ''; while (read($file, $chunk, 512)) { $self->parse($chunk) || last; } close($file) if $opened; $self->eof; } sub netscape_buggy_comment # legacy { my $self = shift; require Carp; Carp::carp("netscape_buggy_comment() is deprecated. " . "Please use the strict_comment() method instead"); my $old = !$self->strict_comment; $self->strict_comment(!shift) if @_; return $old; } # set up method stubs sub text { } *start = \&text; *end = \&text; *comment = \&text; *declaration = \&text; *process = \&text; 1; __END__ =head1 NAME HTML::Parser - HTML parser class =head1 SYNOPSIS use strict; use warnings; use HTML::Parser (); # Create parser object my $p = HTML::Parser->new( api_version => 3, start_h => [\&start, "tagname, attr"], end_h => [\&end, "tagname"], marked_sections => 1, ); # Parse document text chunk by chunk $p->parse($chunk1); $p->parse($chunk2); # ... # signal end of document $p->eof; # Parse directly from file $p->parse_file("foo.html"); # or open(my $fh, "<:utf8", "foo.html") || die; $p->parse_file($fh); =head1 DESCRIPTION Objects of the C<HTML::Parser> class will recognize markup and separate it from plain text (alias data content) in HTML documents. As different kinds of markup and text are recognized, the corresponding event handlers are invoked. C<HTML::Parser> is not a generic SGML parser. We have tried to make it able to deal with the HTML that is actually "out there", and it normally parses as closely as possible to the way the popular web browsers do it instead of strictly following one of the many HTML specifications from W3C. Where there is disagreement, there is often an option that you can enable to get the official behaviour. The document to be parsed may be supplied in arbitrary chunks. This makes on-the-fly parsing as documents are received from the network possible. If event driven parsing does not feel right for your application, you might want to use C<HTML::PullParser>. This is an C<HTML::Parser> subclass that allows a more conventional program structure. =head1 METHODS The following method is used to construct a new C<HTML::Parser> object: =over =item $p = HTML::Parser->new( %options_and_handlers ) This class method creates a new C<HTML::Parser> object and returns it. Key/value argument pairs may be provided to assign event handlers or initialize parser options. The handlers and parser options can also be set or modified later by the method calls described below. If a top level key is in the form "<event>_h" (e.g., "text_h") then it assigns a handler to that event, otherwise it initializes a parser option. The event handler specification value must be an array reference. Multiple handlers may also be assigned with the 'handlers => [%handlers]' option. See examples below. If new() is called without any arguments, it will create a parser that uses callback methods compatible with version 2 of C<HTML::Parser>. See the section on "version 2 compatibility" below for details. The special constructor option 'api_version => 2' can be used to initialize version 2 callbacks while still setting other options and handlers. The 'api_version => 3' option can be used if you don't want to set any options and don't want to fall back to v2 compatible mode. Examples: $p = HTML::Parser->new( api_version => 3, text_h => [ sub {...}, "dtext" ] ); This creates a new parser object with a text event handler subroutine that receives the original text with general entities decoded. $p = HTML::Parser->new( api_version => 3, start_h => [ 'my_start', "self,tokens" ] ); This creates a new parser object with a start event handler method that receives the $p and the tokens array. $p = HTML::Parser->new( api_version => 3, handlers => { text => [\@array, "event,text"], comment => [\@array, "event,text"], } ); This creates a new parser object that stores the event type and the original text in @array for text and comment events. =back The following methods feed the HTML document to the C<HTML::Parser> object: =over =item $p->parse( $string ) Parse $string as the next chunk of the HTML document. Handlers invoked should not attempt to modify the $string in-place until $p->parse returns. If an invoked event handler aborts parsing by calling $p->eof, then $p->parse() will return a FALSE value. Otherwise the return value is a reference to the parser object ($p). =item $p->parse( $code_ref ) If a code reference is passed as the argument to be parsed, then the chunks to be parsed are obtained by invoking this function repeatedly. Parsing continues until the function returns an empty (or undefined) result. When this happens $p->eof is automatically signaled. Parsing will also abort if one of the event handlers calls $p->eof. The effect of this is the same as: while (1) { my $chunk = &$code_ref(); if (!defined($chunk) || !length($chunk)) { $p->eof; return $p; } $p->parse($chunk) || return undef; } But it is more efficient as this loop runs internally in XS code. =item $p->parse_file( $file ) Parse text directly from a file. The $file argument can be a filename, an open file handle, or a reference to an open file handle. If $file contains a filename and the file can't be opened, then the method returns an undefined value and $! tells why it failed. Otherwise the return value is a reference to the parser object. If a file handle is passed as the $file argument, then the file will normally be read until EOF, but not closed. If an invoked event handler aborts parsing by calling $p->eof, then $p->parse_file() may not have read the entire file. On systems with multi-byte line terminators, the values passed for the offset and length argspecs may be too low if parse_file() is called on a file handle that is not in binary mode. If a filename is passed in, then parse_file() will open the file in binary mode. =item $p->eof Signals the end of the HTML document. Calling the $p->eof method outside a handler callback will flush any remaining buffered text (which triggers the C<text> event if there is any remaining text). Calling $p->eof inside a handler will terminate parsing at that point and cause $p->parse to return a FALSE value. This also terminates parsing by $p->parse_file(). After $p->eof has been called, the parse() and parse_file() methods can be invoked to feed new documents with the parser object. The return value from eof() is a reference to the parser object. =back Most parser options are controlled by boolean attributes. Each boolean attribute is enabled by calling the corresponding method with a TRUE argument and disabled with a FALSE argument. The attribute value is left unchanged if no argument is given. The return value from each method is the old attribute value. Methods that can be used to get and/or set parser options are: =over =item $p->attr_encoded =item $p->attr_encoded( $bool ) By default, the C<attr> and C<@attr> argspecs will have general entities for attribute values decoded. Enabling this attribute leaves entities alone. =item $p->backquote =item $p->backquote( $bool ) By default, only ' and " are recognized as quote characters around attribute values. MSIE also recognizes backquotes for some reason. Enabling this attribute provides compatibility with this behaviour. =item $p->boolean_attribute_value( $val ) This method sets the value reported for boolean attributes inside HTML start tags. By default, the name of the attribute is also used as its value. This affects the values reported for C<tokens> and C<attr> argspecs. =item $p->case_sensitive =item $p->case_sensitive( $bool ) By default, tag names and attribute names are down-cased. Enabling this attribute leaves them as found in the HTML source document. =item $p->closing_plaintext =item $p->closing_plaintext( $bool ) By default, C<plaintext> element can never be closed. Everything up to the end of the document is parsed in CDATA mode. This historical behaviour is what at least MSIE does. Enabling this attribute makes closing C< </plaintext> > tag effective and the parsing process will resume after seeing this tag. This emulates early gecko-based browsers. =item $p->empty_element_tags =item $p->empty_element_tags( $bool ) By default, empty element tags are not recognized as such and the "/" before ">" is just treated like a normal name character (unless C<strict_names> is enabled). Enabling this attribute make C<HTML::Parser> recognize these tags. Empty element tags look like start tags, but end with the character sequence "/>" instead of ">". When recognized by C<HTML::Parser> they cause an artificial end event in addition to the start event. The C<text> for the artificial end event will be empty and the C<tokenpos> array will be undefined even though the token array will have one element containing the tag name. =item $p->marked_sections =item $p->marked_sections( $bool ) By default, section markings like <![CDATA[...]]> are treated like ordinary text. When this attribute is enabled section markings are honoured. There are currently no events associated with the marked section markup, but the text can be returned as C<skipped_text>. =item $p->strict_comment =item $p->strict_comment( $bool ) By default, comments are terminated by the first occurrence of "-->". This is the behaviour of most popular browsers (like Mozilla, Opera and MSIE), but it is not correct according to the official HTML standard. Officially, you need an even number of "--" tokens before the closing ">" is recognized and there may not be anything but whitespace between an even and an odd "--". The official behaviour is enabled by enabling this attribute. Enabling of 'strict_comment' also disables recognizing these forms as comments: </ comment> <! comment> =item $p->strict_end =item $p->strict_end( $bool ) By default, attributes and other junk are allowed to be present on end tags in a manner that emulates MSIE's behaviour. The official behaviour is enabled with this attribute. If enabled, only whitespace is allowed between the tagname and the final ">". =item $p->strict_names =item $p->strict_names( $bool ) By default, almost anything is allowed in tag and attribute names. This is the behaviour of most popular browsers and allows us to parse some broken tags with invalid attribute values like: <IMG SRC=newprevlstGr.gif ALT=[PREV LIST] BORDER=0> By default, "LIST]" is parsed as a boolean attribute, not as part of the ALT value as was clearly intended. This is also what Mozilla sees. The official behaviour is enabled by enabling this attribute. If enabled, it will cause the tag above to be reported as text since "LIST]" is not a legal attribute name. =item $p->unbroken_text =item $p->unbroken_text( $bool ) By default, blocks of text are given to the text handler as soon as possible (but the parser takes care always to break text at a boundary between whitespace and non-whitespace so single words and entities can always be decoded safely). This might create breaks that make it hard to do transformations on the text. When this attribute is enabled, blocks of text are always reported in one piece. This will delay the text event until the following (non-text) event has been recognized by the parser. Note that the C<offset> argspec will give you the offset of the first segment of text and C<length> is the combined length of the segments. Since there might be ignored tags in between, these numbers can't be used to directly index in the original document file. =item $p->utf8_mode =item $p->utf8_mode( $bool ) Enable this option when parsing raw undecoded UTF-8. This tells the parser that the entities expanded for strings reported by C<attr>, C<@attr> and C<dtext> should be expanded as decoded UTF-8 so they end up compatible with the surrounding text. If C<utf8_mode> is enabled then it is an error to pass strings containing characters with code above 255 to the parse() method, and the parse() method will croak if you try. Example: The Unicode character "\x{2665}" is "\xE2\x99\xA5" when UTF-8 encoded. The character can also be represented by the entity "♥" or "♥". If we feed the parser: $p->parse("\xE2\x99\xA5♥"); then C<dtext> will be reported as "\xE2\x99\xA5\x{2665}" without C<utf8_mode> enabled, but as "\xE2\x99\xA5\xE2\x99\xA5" when enabled. The later string is what you want. This option is only available with perl-5.8 or better. =item $p->xml_mode =item $p->xml_mode( $bool ) Enabling this attribute changes the parser to allow some XML constructs. This enables the behaviour controlled by individually by the C<case_sensitive>, C<empty_element_tags>, C<strict_names> and C<xml_pic> attributes and also suppresses special treatment of elements that are parsed as CDATA for HTML. =item $p->xml_pic =item $p->xml_pic( $bool ) By default, I<processing instructions> are terminated by ">". When this attribute is enabled, processing instructions are terminated by "?>" instead. =back As markup and text is recognized, handlers are invoked. The following method is used to set up handlers for different events: =over =item $p->handler( event => \&subroutine, $argspec ) =item $p->handler( event => $method_name, $argspec ) =item $p->handler( event => \@accum, $argspec ) =item $p->handler( event => "" ); =item $p->handler( event => undef ); =item $p->handler( event ); This method assigns a subroutine, method, or array to handle an event. Event is one of C<text>, C<start>, C<end>, C<declaration>, C<comment>, C<process>, C<start_document>, C<end_document> or C<default>. The C<\&subroutine> is a reference to a subroutine which is called to handle the event. The C<$method_name> is the name of a method of $p which is called to handle the event. The C<@accum> is an array that will hold the event information as sub-arrays. If the second argument is "", the event is ignored. If it is undef, the default handler is invoked for the event. The C<$argspec> is a string that describes the information to be reported for the event. Any requested information that does not apply to a specific event is passed as C<undef>. If argspec is omitted, then it is left unchanged. The return value from $p->handler is the old callback routine or a reference to the accumulator array. Any return values from handler callback routines/methods are always ignored. A handler callback can request parsing to be aborted by invoking the $p->eof method. A handler callback is not allowed to invoke the $p->parse() or $p->parse_file() method. An exception will be raised if it tries. Examples: $p->handler(start => "start", 'self, attr, attrseq, text' ); This causes the "start" method of object C<$p> to be called for 'start' events. The callback signature is C<< $p->start(\%attr, \@attr_seq, $text) >>. $p->handler(start => \&start, 'attr, attrseq, text' ); This causes subroutine start() to be called for 'start' events. The callback signature is start(\%attr, \@attr_seq, $text). $p->handler(start => \@accum, '"S", attr, attrseq, text' ); This causes 'start' event information to be saved in @accum. The array elements will be ['S', \%attr, \@attr_seq, $text]. $p->handler(start => ""); This causes 'start' events to be ignored. It also suppresses invocations of any default handler for start events. It is in most cases equivalent to $p->handler(start => sub {}), but is more efficient. It is different from the empty-sub-handler in that C<skipped_text> is not reset by it. $p->handler(start => undef); This causes no handler to be associated with start events. If there is a default handler it will be invoked. =back Filters based on tags can be set up to limit the number of events reported. The main bottleneck during parsing is often the huge number of callbacks made from the parser. Applying filters can improve performance significantly. The following methods control filters: =over =item $p->ignore_elements( @tags ) Both the C<start> event and the C<end> event as well as any events that would be reported in between are suppressed. The ignored elements can contain nested occurrences of itself. Example: $p->ignore_elements(qw(script style)); The C<script> and C<style> tags will always nest properly since their content is parsed in CDATA mode. For most other tags C<ignore_elements> must be used with caution since HTML is often not I<well formed>. =item $p->ignore_tags( @tags ) Any C<start> and C<end> events involving any of the tags given are suppressed. To reset the filter (i.e. don't suppress any C<start> and C<end> events), call C<ignore_tags> without an argument. =item $p->report_tags( @tags ) Any C<start> and C<end> events involving any of the tags I<not> given are suppressed. To reset the filter (i.e. report all C<start> and C<end> events), call C<report_tags> without an argument. =back Internally, the system has two filter lists, one for C<report_tags> and one for C<ignore_tags>, and both filters are applied. This effectively gives C<ignore_tags> precedence over C<report_tags>. Examples: $p->ignore_tags(qw(style)); $p->report_tags(qw(script style)); results in only C<script> events being reported. =head2 Argspec Argspec is a string containing a comma-separated list that describes the information reported by the event. The following argspec identifier names can be used: =over =item C<attr> Attr causes a reference to a hash of attribute name/value pairs to be passed. Boolean attributes' values are either the value set by $p->boolean_attribute_value, or the attribute name if no value has been set by $p->boolean_attribute_value. This passes undef except for C<start> events. Unless C<xml_mode> or C<case_sensitive> is enabled, the attribute names are forced to lower case. General entities are decoded in the attribute values and one layer of matching quotes enclosing the attribute values is removed. The Unicode character set is assumed for entity decoding. =item C<@attr> Basically the same as C<attr>, but keys and values are passed as individual arguments and the original sequence of the attributes is kept. The parameters passed will be the same as the @attr calculated here: @attr = map { $_ => $attr->{$_} } @$attrseq; assuming $attr and $attrseq here are the hash and array passed as the result of C<attr> and C<attrseq> argspecs. This passes no values for events besides C<start>. =item C<attrseq> Attrseq causes a reference to an array of attribute names to be passed. This can be useful if you want to walk the C<attr> hash in the original sequence. This passes undef except for C<start> events. Unless C<xml_mode> or C<case_sensitive> is enabled, the attribute names are forced to lower case. =item C<column> Column causes the column number of the start of the event to be passed. The first column on a line is 0. =item C<dtext> Dtext causes the decoded text to be passed. General entities are automatically decoded unless the event was inside a CDATA section or was between literal start and end tags (C<script>, C<style>, C<xmp>, C<iframe>, C<title>, C<textarea> and C<plaintext>). The Unicode character set is assumed for entity decoding. With Perl version 5.6 or earlier only the Latin-1 range is supported, and entities for characters outside the range 0..255 are left unchanged. This passes undef except for C<text> events. =item C<event> Event causes the event name to be passed. The event name is one of C<text>, C<start>, C<end>, C<declaration>, C<comment>, C<process>, C<start_document> or C<end_document>. =item C<is_cdata> Is_cdata causes a TRUE value to be passed if the event is inside a CDATA section or between literal start and end tags (C<script>, C<style>, C<xmp>, C<iframe>, C<title>, C<textarea> and C<plaintext>). if the flag is FALSE for a text event, then you should normally either use C<dtext> or decode the entities yourself before the text is processed further. =item C<length> Length causes the number of bytes of the source text of the event to be passed. =item C<line> Line causes the line number of the start of the event to be passed. The first line in the document is 1. Line counting doesn't start until at least one handler requests this value to be reported. =item C<offset> Offset causes the byte position in the HTML document of the start of the event to be passed. The first byte in the document has offset 0. =item C<offset_end> Offset_end causes the byte position in the HTML document of the end of the event to be passed. This is the same as C<offset> + C<length>. =item C<self> Self causes the current object to be passed to the handler. If the handler is a method, this must be the first element in the argspec. An alternative to passing self as an argspec is to register closures that capture $self by themselves as handlers. Unfortunately this creates circular references which prevent the HTML::Parser object from being garbage collected. Using the C<self> argspec avoids this problem. =item C<skipped_text> Skipped_text returns the concatenated text of all the events that have been skipped since the last time an event was reported. Events might be skipped because no handler is registered for them or because some filter applies. Skipped text also includes marked section markup, since there are no events that can catch it. If an C<"">-handler is registered for an event, then the text for this event is not included in C<skipped_text>. Skipped text both before and after the C<"">-event is included in the next reported C<skipped_text>. =item C<tag> Same as C<tagname>, but prefixed with "/" if it belongs to an C<end> event and "!" for a declaration. The C<tag> does not have any prefix for C<start> events, and is in this case identical to C<tagname>. =item C<tagname> This is the element name (or I<generic identifier> in SGML jargon) for start and end tags. Since HTML is case insensitive, this name is forced to lower case to ease string matching. Since XML is case sensitive, the tagname case is not changed when C<xml_mode> is enabled. The same happens if the C<case_sensitive> attribute is set. The declaration type of declaration elements is also passed as a tagname, even if that is a bit strange. In fact, in the current implementation tagname is identical to C<token0> except that the name may be forced to lower case. =item C<token0> Token0 causes the original text of the first token string to be passed. This should always be the same as $tokens->[0]. For C<declaration> events, this is the declaration type. For C<start> and C<end> events, this is the tag name. For C<process> and non-strict C<comment> events, this is everything inside the tag. This passes undef if there are no tokens in the event. =item C<tokenpos> Tokenpos causes a reference to an array of token positions to be passed. For each string that appears in C<tokens>, this array contains two numbers. The first number is the offset of the start of the token in the original C<text> and the second number is the length of the token. Boolean attributes in a C<start> event will have (0,0) for the attribute value offset and length. This passes undef if there are no tokens in the event (e.g., C<text>) and for artificial C<end> events triggered by empty element tags. If you are using these offsets and lengths to modify C<text>, you should either work from right to left, or be very careful to calculate the changes to the offsets. =item C<tokens> Tokens causes a reference to an array of token strings to be passed. The strings are exactly as they were found in the original text, no decoding or case changes are applied. For C<declaration> events, the array contains each word, comment, and delimited string starting with the declaration type. For C<comment> events, this contains each sub-comment. If $p->strict_comments is disabled, there will be only one sub-comment. For C<start> events, this contains the original tag name followed by the attribute name/value pairs. The values of boolean attributes will be either the value set by $p->boolean_attribute_value, or the attribute name if no value has been set by $p->boolean_attribute_value. For C<end> events, this contains the original tag name (always one token). For C<process> events, this contains the process instructions (always one token). This passes C<undef> for C<text> events. =item C<text> Text causes the source text (including markup element delimiters) to be passed. =item C<undef> Pass an undefined value. Useful as padding where the same handler routine is registered for multiple events. =item C<'...'> A literal string of 0 to 255 characters enclosed in single (') or double (") quotes is passed as entered. =back The whole argspec string can be wrapped up in C<'@{...}'> to signal that the resulting event array should be flattened. This only makes a difference if an array reference is used as the handler target. Consider this example: $p->handler(text => [], 'text'); $p->handler(text => [], '@{text}']); With two text events; C<"foo">, C<"bar">; then the first example will end up with [["foo"], ["bar"]] and the second with ["foo", "bar"] in the handler target array. =head2 Events Handlers for the following events can be registered: =over =item C<comment> This event is triggered when a markup comment is recognized. Example: <!-- This is a comment -- -- So is this --> =item C<declaration> This event is triggered when a I<markup declaration> is recognized. For typical HTML documents, the only declaration you are likely to find is <!DOCTYPE ...>. Example: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> DTDs inside <!DOCTYPE ...> will confuse HTML::Parser. =item C<default> This event is triggered for events that do not have a specific handler. You can set up a handler for this event to catch stuff you did not want to catch explicitly. =item C<end> This event is triggered when an end tag is recognized. Example: </A> =item C<end_document> This event is triggered when $p->eof is called and after any remaining text is flushed. There is no document text associated with this event. =item C<process> This event is triggered when a processing instructions markup is recognized. The format and content of processing instructions are system and application dependent. Examples: <? HTML processing instructions > <? XML processing instructions ?> =item C<start> This event is triggered when a start tag is recognized. Example: <A HREF="http://www.perl.com/"> =item C<start_document> This event is triggered before any other events for a new document. A handler for it can be used to initialize stuff. There is no document text associated with this event. =item C<text> This event is triggered when plain text (characters) is recognized. The text may contain multiple lines. A sequence of text may be broken between several text events unless $p->unbroken_text is enabled. The parser will make sure that it does not break a word or a sequence of whitespace between two text events. =back =head2 Unicode C<HTML::Parser> can parse Unicode strings when running under perl-5.8 or better. If Unicode is passed to $p->parse() then chunks of Unicode will be reported to the handlers. The offset and length argspecs will also report their position in terms of characters. It is safe to parse raw undecoded UTF-8 if you either avoid decoding entities and make sure to not use I<argspecs> that do, or enable the C<utf8_mode> for the parser. Parsing of undecoded UTF-8 might be useful when parsing from a file where you need the reported offsets and lengths to match the byte offsets in the file. If a filename is passed to $p->parse_file() then the file will be read in binary mode. This will be fine if the file contains only ASCII or Latin-1 characters. If the file contains UTF-8 encoded text then care must be taken when decoding entities as described in the previous paragraph, but better is to open the file with the UTF-8 layer so that it is decoded properly: open(my $fh, "<:utf8", "index.html") || die "...: $!"; $p->parse_file($fh); If the file contains text encoded in a charset besides ASCII, Latin-1 or UTF-8 then decoding will always be needed. =head1 VERSION 2 COMPATIBILITY When an C<HTML::Parser> object is constructed with no arguments, a set of handlers is automatically provided that is compatible with the old HTML::Parser version 2 callback methods. This is equivalent to the following method calls: $p->handler(start => "start", "self, tagname, attr, attrseq, text"); $p->handler(end => "end", "self, tagname, text"); $p->handler(text => "text", "self, text, is_cdata"); $p->handler(process => "process", "self, token0, text"); $p->handler( comment => sub { my($self, $tokens) = @_; for (@$tokens) {$self->comment($_);} }, "self, tokens" ); $p->handler( declaration => sub { my $self = shift; $self->declaration(substr($_[0], 2, -1)); }, "self, text" ); Setting up these handlers can also be requested with the "api_version => 2" constructor option. =head1 SUBCLASSING The C<HTML::Parser> class is able to be subclassed. Parser objects are plain hashes and C<HTML::Parser> reserves only hash keys that start with "_hparser". The parser state can be set up by invoking the init() method, which takes the same arguments as new(). =head1 EXAMPLES The first simple example shows how you might strip out comments from an HTML document. We achieve this by setting up a comment handler that does nothing and a default handler that will print out anything else: use HTML::Parser; HTML::Parser->new( default_h => [sub { print shift }, 'text'], comment_h => [""], )->parse_file(shift || die) || die $!; An alternative implementation is: use HTML::Parser; HTML::Parser->new( end_document_h => [sub { print shift }, 'skipped_text'], comment_h => [""], )->parse_file(shift || die) || die $!; This will in most cases be much more efficient since only a single callback will be made. The next example prints out the text that is inside the <title> element of an HTML document. Here we start by setting up a start handler. When it sees the title start tag it enables a text handler that prints any text found and an end handler that will terminate parsing as soon as the title end tag is seen: use HTML::Parser (); sub start_handler { return if shift ne "title"; my $self = shift; $self->handler(text => sub { print shift }, "dtext"); $self->handler( end => sub { shift->eof if shift eq "title"; }, "tagname,self" ); } my $p = HTML::Parser->new(api_version => 3); $p->handler(start => \&start_handler, "tagname,self"); $p->parse_file(shift || die) || die $!; print "\n"; More examples are found in the F<eg/> directory of the C<HTML-Parser> distribution: the program C<hrefsub> shows how you can edit all links found in a document; the program C<htextsub> shows how to edit the text only; the program C<hstrip> shows how you can strip out certain tags/elements and/or attributes; and the program C<htext> show how to obtain the plain text, but not any script/style content. You can browse the F<eg/> directory online from the I<[Browse]> link on the http://search.cpan.org/~gaas/HTML-Parser/ page. =head1 BUGS The <style> and <script> sections do not end with the first "</", but need the complete corresponding end tag. The standard behaviour is not really practical. When the I<strict_comment> option is enabled, we still recognize comments where there is something other than whitespace between even and odd "--" markers. Once $p->boolean_attribute_value has been set, there is no way to restore the default behaviour. There is currently no way to get both quote characters into the same literal argspec. Empty tags, e.g. "<>" and "</>", are not recognized. SGML allows them to repeat the previous start tag or close the previous start tag respectively. NET tags, e.g. "code/.../" are not recognized. This is SGML shorthand for "<code>...</code>". Incomplete start or end tags, e.g. "<tt<b>...</b</tt>" are not recognized. =head1 DIAGNOSTICS The following messages may be produced by HTML::Parser. The notation in this listing is the same as used in L<perldiag>: =over =item Not a reference to a hash (F) The object blessed into or subclassed from HTML::Parser is not a hash as required by the HTML::Parser methods. =item Bad signature in parser state object at %p (F) The _hparser_xs_state element does not refer to a valid state structure. Something must have changed the internal value stored in this hash element, or the memory has been overwritten. =item _hparser_xs_state element is not a reference (F) The _hparser_xs_state element has been destroyed. =item Can't find '_hparser_xs_state' element in HTML::Parser hash (F) The _hparser_xs_state element is missing from the parser hash. It was either deleted, or not created when the object was created. =item API version %s not supported by HTML::Parser %s (F) The constructor option 'api_version' with an argument greater than or equal to 4 is reserved for future extensions. =item Bad constructor option '%s' (F) An unknown constructor option key was passed to the new() or init() methods. =item Parse loop not allowed (F) A handler invoked the parse() or parse_file() method. This is not permitted. =item marked sections not supported (F) The $p->marked_sections() method was invoked in a HTML::Parser module that was compiled without support for marked sections. =item Unknown boolean attribute (%d) (F) Something is wrong with the internal logic that set up aliases for boolean attributes. =item Only code or array references allowed as handler (F) The second argument for $p->handler must be either a subroutine reference, then name of a subroutine or method, or a reference to an array. =item No handler for %s events (F) The first argument to $p->handler must be a valid event name; i.e. one of "start", "end", "text", "process", "declaration" or "comment". =item Unrecognized identifier %s in argspec (F) The identifier is not a known argspec name. Use one of the names mentioned in the argspec section above. =item Literal string is longer than 255 chars in argspec (F) The current implementation limits the length of literals in an argspec to 255 characters. Make the literal shorter. =item Backslash reserved for literal string in argspec (F) The backslash character "\" is not allowed in argspec literals. It is reserved to permit quoting inside a literal in a later version. =item Unterminated literal string in argspec (F) The terminating quote character for a literal was not found. =item Bad argspec (%s) (F) Only identifier names, literals, spaces and commas are allowed in argspecs. =item Missing comma separator in argspec (F) Identifiers in an argspec must be separated with ",". =item Parsing of undecoded UTF-8 will give garbage when decoding entities (W) The first chunk parsed appears to contain undecoded UTF-8 and one or more argspecs that decode entities are used for the callback handlers. The result of decoding will be a mix of encoded and decoded characters for any entities that expand to characters with code above 127. This is not a good thing. The recommended solution is to apply Encode::decode_utf8() on the data before feeding it to the $p->parse(). For $p->parse_file() pass a file that has been opened in ":utf8" mode. The alternative solution is to enable the C<utf8_mode> and not decode before passing strings to $p->parse(). The parser can process raw undecoded UTF-8 sanely if the C<utf8_mode> is enabled, or if the C<attr>, C<@attr> or C<dtext> argspecs are avoided. =item Parsing string decoded with wrong endian selection (W) The first character in the document is U+FFFE. This is not a legal Unicode character but a byte swapped C<BOM>. The result of parsing will likely be garbage. =item Parsing of undecoded UTF-32 (W) The parser found the Unicode UTF-32 C<BOM> signature at the start of the document. The result of parsing will likely be garbage. =item Parsing of undecoded UTF-16 (W) The parser found the Unicode UTF-16 C<BOM> signature at the start of the document. The result of parsing will likely be garbage. =back =head1 SEE ALSO L<HTML::Entities>, L<HTML::PullParser>, L<HTML::TokeParser>, L<HTML::HeadParser>, L<HTML::LinkExtor>, L<HTML::Form> L<HTML::TreeBuilder> (part of the I<HTML-Tree> distribution) L<http://www.w3.org/TR/html4/> More information about marked sections and processing instructions may be found at L<http://www.is-thought.co.uk/book/sgml-8.htm>. =head1 COPYRIGHT Copyright 1996-2016 Gisle Aas. All rights reserved. Copyright 1999-2000 Michael A. Chase. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK �X�[{�JC! C! HeadParser.pmnu �[��� package HTML::HeadParser; =head1 NAME HTML::HeadParser - Parse <HEAD> section of a HTML document =head1 SYNOPSIS require HTML::HeadParser; $p = HTML::HeadParser->new; $p->parse($text) and print "not finished"; $p->header('Title') # to access <title>....</title> $p->header('Content-Base') # to access <base href="http://..."> $p->header('Foo') # to access <meta http-equiv="Foo" content="..."> $p->header('X-Meta-Author') # to access <meta name="author" content="..."> $p->header('X-Meta-Charset') # to access <meta charset="..."> =head1 DESCRIPTION The C<HTML::HeadParser> is a specialized (and lightweight) C<HTML::Parser> that will only parse the E<lt>HEAD>...E<lt>/HEAD> section of an HTML document. The parse() method will return a FALSE value as soon as some E<lt>BODY> element or body text are found, and should not be called again after this. Note that the C<HTML::HeadParser> might get confused if raw undecoded UTF-8 is passed to the parse() method. Make sure the strings are properly decoded before passing them on. The C<HTML::HeadParser> keeps a reference to a header object, and the parser will update this header object as the various elements of the E<lt>HEAD> section of the HTML document are recognized. The following header fields are affected: =over 4 =item Content-Base: The I<Content-Base> header is initialized from the E<lt>base href="..."> element. =item Title: The I<Title> header is initialized from the E<lt>title>...E<lt>/title> element. =item Isindex: The I<Isindex> header will be added if there is a E<lt>isindex> element in the E<lt>head>. The header value is initialized from the I<prompt> attribute if it is present. If no I<prompt> attribute is given it will have '?' as the value. =item X-Meta-Foo: All E<lt>meta> elements containing a C<name> attribute will result in headers using the prefix C<X-Meta-> appended with the value of the C<name> attribute as the name of the header, and the value of the C<content> attribute as the pushed header value. E<lt>meta> elements containing a C<http-equiv> attribute will result in headers as in above, but without the C<X-Meta-> prefix in the header name. E<lt>meta> elements containing a C<charset> attribute will result in an C<X-Meta-Charset> header, using the value of the C<charset> attribute as the pushed header value. The ':' character can't be represented in header field names, so if the meta element contains this char it's substituted with '-' before forming the field name. =back =head1 METHODS The following methods (in addition to those provided by the superclass) are available: =over 4 =cut require HTML::Parser; our @ISA = qw(HTML::Parser); use HTML::Entities (); use strict; our $DEBUG; #$DEBUG = 1; our $VERSION = '3.76'; =item $hp = HTML::HeadParser->new =item $hp = HTML::HeadParser->new( $header ) The object constructor. The optional $header argument should be a reference to an object that implement the header() and push_header() methods as defined by the C<HTTP::Headers> class. Normally it will be of some class that is a or delegates to the C<HTTP::Headers> class. If no $header is given C<HTML::HeadParser> will create an C<HTTP::Headers> object by itself (initially empty). =cut sub new { my($class, $header) = @_; unless ($header) { require HTTP::Headers; $header = HTTP::Headers->new; } my $self = $class->SUPER::new(api_version => 3, start_h => ["start", "self,tagname,attr"], end_h => ["end", "self,tagname"], text_h => ["text", "self,text"], ignore_elements => [qw(script style)], ); $self->{'header'} = $header; $self->{'tag'} = ''; # name of active element that takes textual content $self->{'text'} = ''; # the accumulated text associated with the element $self; } =item $hp->header; Returns a reference to the header object. =item $hp->header( $key ) Returns a header value. It is just a shorter way to write C<$hp-E<gt>header-E<gt>header($key)>. =cut sub header { my $self = shift; return $self->{'header'} unless @_; $self->{'header'}->header(@_); } sub as_string # legacy { my $self = shift; $self->{'header'}->as_string; } sub flush_text # internal { my $self = shift; my $tag = $self->{'tag'}; my $text = $self->{'text'}; $text =~ s/^\s+//; $text =~ s/\s+$//; $text =~ s/\s+/ /g; print "FLUSH $tag => '$text'\n" if $DEBUG; if ($tag eq 'title') { my $decoded; $decoded = utf8::decode($text) if $self->utf8_mode && defined &utf8::decode; HTML::Entities::decode($text); utf8::encode($text) if $decoded; $self->{'header'}->push_header(Title => $text); } $self->{'tag'} = $self->{'text'} = ''; } # This is an quote from the HTML3.2 DTD which shows which elements # that might be present in a <HEAD>...</HEAD>. Also note that the # <HEAD> tags themselves might be missing: # # <!ENTITY % head.content "TITLE & ISINDEX? & BASE? & STYLE? & # SCRIPT* & META* & LINK*"> # # <!ELEMENT HEAD O O (%head.content)> # # From HTML 4.01: # # <!ENTITY % head.misc "SCRIPT|STYLE|META|LINK|OBJECT"> # <!ENTITY % head.content "TITLE & BASE?"> # <!ELEMENT HEAD O O (%head.content;) +(%head.misc;)> # # From HTML 5 as of WD-html5-20090825: # # One or more elements of metadata content, [...] # => base, command, link, meta, noscript, script, style, title sub start { my($self, $tag, $attr) = @_; # $attr is reference to a HASH print "START[$tag]\n" if $DEBUG; $self->flush_text if $self->{'tag'}; if ($tag eq 'meta') { my $key = $attr->{'http-equiv'}; if (!defined($key) || !length($key)) { if ($attr->{name}) { $key = "X-Meta-\u$attr->{name}"; } elsif ($attr->{charset}) { # HTML 5 <meta charset="..."> $key = "X-Meta-Charset"; $self->{header}->push_header($key => $attr->{charset}); return; } else { return; } } $key =~ s/:/-/g; $self->{'header'}->push_header($key => $attr->{content}); } elsif ($tag eq 'base') { return unless exists $attr->{href}; (my $base = $attr->{href}) =~ s/^\s+//; $base =~ s/\s+$//; # HTML5 $self->{'header'}->push_header('Content-Base' => $base); } elsif ($tag eq 'isindex') { # This is a non-standard header. Perhaps we should just ignore # this element $self->{'header'}->push_header(Isindex => $attr->{prompt} || '?'); } elsif ($tag =~ /^(?:title|noscript|object|command)$/) { # Just remember tag. Initialize header when we see the end tag. $self->{'tag'} = $tag; } elsif ($tag eq 'link') { return unless exists $attr->{href}; # <link href="http:..." rel="xxx" rev="xxx" title="xxx"> my $href = delete($attr->{href}); $href =~ s/^\s+//; $href =~ s/\s+$//; # HTML5 my $h_val = "<$href>"; for (sort keys %{$attr}) { next if $_ eq "/"; # XHTML junk $h_val .= qq(; $_="$attr->{$_}"); } $self->{'header'}->push_header(Link => $h_val); } elsif ($tag eq 'head' || $tag eq 'html') { # ignore } else { # stop parsing $self->eof; } } sub end { my($self, $tag) = @_; print "END[$tag]\n" if $DEBUG; $self->flush_text if $self->{'tag'}; $self->eof if $tag eq 'head'; } sub text { my($self, $text) = @_; print "TEXT[$text]\n" if $DEBUG; unless ($self->{first_chunk}) { # drop Unicode BOM if found if ($self->utf8_mode) { $text =~ s/^\xEF\xBB\xBF//; } else { $text =~ s/^\x{FEFF}//; } $self->{first_chunk}++; } my $tag = $self->{tag}; if (!$tag && $text =~ /\S/) { # Normal text means start of body $self->eof; return; } return if $tag ne 'title'; $self->{'text'} .= $text; } BEGIN { *utf8_mode = sub { 1 } unless HTML::Entities::UNICODE_SUPPORT; } 1; __END__ =back =head1 EXAMPLE $h = HTTP::Headers->new; $p = HTML::HeadParser->new($h); $p->parse(<<EOT); <title>Stupid example</title> <base href="http://www.linpro.no/lwp/"> Normal text starts here. EOT undef $p; print $h->title; # should print "Stupid example" =head1 SEE ALSO L<HTML::Parser>, L<HTTP::Headers> The C<HTTP::Headers> class is distributed as part of the I<libwww-perl> package. If you don't have that distribution installed you need to provide the $header argument to the C<HTML::HeadParser> constructor with your own object that implements the documented protocol. =head1 COPYRIGHT Copyright 1996-2001 Gisle Aas. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK �X�[�v��'