home *** CD-ROM | disk | FTP | other *** search
/ PC Open 107 / PC Open 107 CD 1.bin / CD1 / INTERNET / EMAIL / pop file / setup.exe / $_1_ / HTML / Template.pm < prev   
Encoding:
Perl POD Document  |  2004-06-26  |  115.9 KB  |  3,332 lines

  1. package HTML::Template;
  2.  
  3. $HTML::Template::VERSION = '2.7';
  4.  
  5. =head1 NAME
  6.  
  7. HTML::Template - Perl module to use HTML Templates from CGI scripts
  8.  
  9. =head1 SYNOPSIS
  10.  
  11. First you make a template - this is just a normal HTML file with a few
  12. extra tags, the simplest being <TMPL_VAR>
  13.  
  14. For example, test.tmpl:
  15.  
  16.   <html>
  17.   <head><title>Test Template</title>
  18.   <body>
  19.   My Home Directory is <TMPL_VAR NAME=HOME>
  20.   <p>
  21.   My Path is set to <TMPL_VAR NAME=PATH>
  22.   </body>
  23.   </html>
  24.  
  25. Now create a small CGI program:
  26.  
  27.   #!/usr/bin/perl -w
  28.   use HTML::Template;
  29.  
  30.   # open the html template
  31.   my $template = HTML::Template->new(filename => 'test.tmpl');
  32.  
  33.   # fill in some parameters
  34.   $template->param(HOME => $ENV{HOME});
  35.   $template->param(PATH => $ENV{PATH});
  36.  
  37.   # send the obligatory Content-Type and print the template output
  38.   print "Content-Type: text/html\n\n", $template->output;
  39.  
  40. If all is well in the universe this should show something like this in
  41. your browser when visiting the CGI:
  42.  
  43.   My Home Directory is /home/some/directory
  44.   My Path is set to /bin;/usr/bin
  45.  
  46. =head1 DESCRIPTION
  47.  
  48. This module attempts to make using HTML templates simple and natural.
  49. It extends standard HTML with a few new HTML-esque tags - <TMPL_VAR>,
  50. <TMPL_LOOP>, <TMPL_INCLUDE>, <TMPL_IF>, <TMPL_ELSE> and <TMPL_UNLESS>.
  51. The file written with HTML and these new tags is called a template.
  52. It is usually saved separate from your script - possibly even created
  53. by someone else!  Using this module you fill in the values for the
  54. variables, loops and branches declared in the template.  This allows
  55. you to separate design - the HTML - from the data, which you generate
  56. in the Perl script.
  57.  
  58. This module is licensed under the GPL.  See the LICENSE section
  59. below for more details.
  60.  
  61. =head1 TUTORIAL
  62.  
  63. If you're new to HTML::Template, I suggest you start with the
  64. introductory article available on the HTML::Template website:
  65.  
  66.    http://html-template.sourceforge.net
  67.  
  68. =head1 MOTIVATION
  69.  
  70. It is true that there are a number of packages out there to do HTML
  71. templates.  On the one hand you have things like HTML::Embperl which
  72. allows you freely mix Perl with HTML.  On the other hand lie
  73. home-grown variable substitution solutions.  Hopefully the module can
  74. find a place between the two.
  75.  
  76. One advantage of this module over a full HTML::Embperl-esque solution
  77. is that it enforces an important divide - design and programming.  By
  78. limiting the programmer to just using simple variables and loops in
  79. the HTML, the template remains accessible to designers and other
  80. non-perl people.  The use of HTML-esque syntax goes further to make
  81. the format understandable to others.  In the future this similarity
  82. could be used to extend existing HTML editors/analyzers to support
  83. HTML::Template.
  84.  
  85. An advantage of this module over home-grown tag-replacement schemes is
  86. the support for loops.  In my work I am often called on to produce
  87. tables of data in html.  Producing them using simplistic HTML
  88. templates results in CGIs containing lots of HTML since the HTML
  89. itself cannot represent loops.  The introduction of loop statements in
  90. the HTML simplifies this situation considerably.  The designer can
  91. layout a single row and the programmer can fill it in as many times as
  92. necessary - all they must agree on is the parameter names.
  93.  
  94. For all that, I think the best thing about this module is that it does
  95. just one thing and it does it quickly and carefully.  It doesn't try
  96. to replace Perl and HTML, it just augments them to interact a little
  97. better.  And it's pretty fast.
  98.  
  99. =head1 THE TAGS
  100.  
  101. =head2 TMPL_VAR
  102.  
  103.   <TMPL_VAR NAME="PARAMETER_NAME">
  104.  
  105. The <TMPL_VAR> tag is very simple.  For each <TMPL_VAR> tag in the
  106. template you call $template->param(PARAMETER_NAME => "VALUE").  When
  107. the template is output the <TMPL_VAR> is replaced with the VALUE text
  108. you specified.  If you don't set a parameter it just gets skipped in
  109. the output.
  110.  
  111. Optionally you can use the "ESCAPE=HTML" option in the tag to indicate
  112. that you want the value to be HTML-escaped before being returned from
  113. output (the old ESCAPE=1 syntax is still supported).  This means that
  114. the ", <, >, and & characters get translated into ", <, >
  115. and & respectively.  This is useful when you want to use a
  116. TMPL_VAR in a context where those characters would cause trouble.
  117. Example:
  118.  
  119.    <input name=param type=text value="<TMPL_VAR NAME="PARAM">">
  120.  
  121. If you called param() with a value like sam"my you'll get in trouble
  122. with HTML's idea of a double-quote.  On the other hand, if you use
  123. ESCAPE=HTML, like this:
  124.  
  125.    <input name=param type=text value="<TMPL_VAR ESCAPE=HTML NAME="PARAM">">
  126.  
  127. You'll get what you wanted no matter what value happens to be passed in for
  128. param.  You can also write ESCAPE="HTML", ESCAPE='HTML' and ESCAPE='1'.
  129. Substitute a 0 for the HTML and you turn off escaping, which is the default
  130. anyway.
  131.  
  132. There is also the "ESCAPE=URL" option which may be used for VARs that
  133. populate a URL.  It will do URL escaping, like replacing ' ' with '+'
  134. and '/' with '%2F'.
  135.  
  136. There is also the "ESCAPE=JS" option which may be used for VARs that
  137. need to be placed within a Javascript string. All \n, \r, ' and " characters
  138. are escaped.
  139.  
  140. You can assign a default value to a variable with the DEFAULT
  141. attribute.  For example, this will output "the devil gave me a taco"
  142. if the "who" variable is not set.
  143.  
  144.   The <TMPL_VAR NAME=WHO DEFAULT=devil> gave me a taco.
  145.  
  146. =head2 TMPL_LOOP
  147.  
  148.   <TMPL_LOOP NAME="LOOP_NAME"> ... </TMPL_LOOP>
  149.  
  150. The <TMPL_LOOP> tag is a bit more complicated than <TMPL_VAR>.  The
  151. <TMPL_LOOP> tag allows you to delimit a section of text and give it a
  152. name.  Inside this named loop you place <TMPL_VAR>s.  Now you pass to
  153. param() a list (an array ref) of parameter assignments (hash refs) for
  154. this loop.  The loop iterates over the list and produces output from
  155. the text block for each pass.  Unset parameters are skipped.  Here's
  156. an example:
  157.  
  158.  In the template:
  159.  
  160.    <TMPL_LOOP NAME=EMPLOYEE_INFO>
  161.       Name: <TMPL_VAR NAME=NAME> <br>
  162.       Job:  <TMPL_VAR NAME=JOB>  <p>
  163.    </TMPL_LOOP>
  164.  
  165.  
  166.  In the script:
  167.  
  168.    $template->param(EMPLOYEE_INFO => [
  169.                                        { name => 'Sam', job => 'programmer' },
  170.                                        { name => 'Steve', job => 'soda jerk' },
  171.                                      ]
  172.                    );
  173.    print $template->output();
  174.  
  175.  
  176.  The output in a browser:
  177.  
  178.    Name: Sam
  179.    Job: programmer
  180.  
  181.    Name: Steve
  182.    Job: soda jerk
  183.  
  184. As you can see above the <TMPL_LOOP> takes a list of variable
  185. assignments and then iterates over the loop body producing output.
  186.  
  187. Often you'll want to generate a <TMPL_LOOP>'s contents
  188. programmatically.  Here's an example of how this can be done (many
  189. other ways are possible!):
  190.  
  191.    # a couple of arrays of data to put in a loop:
  192.    my @words = qw(I Am Cool);
  193.    my @numbers = qw(1 2 3);
  194.  
  195.    my @loop_data = ();  # initialize an array to hold your loop
  196.  
  197.    while (@words and @numbers) {
  198.      my %row_data;  # get a fresh hash for the row data
  199.  
  200.      # fill in this row
  201.      $row_data{WORD} = shift @words;
  202.      $row_data{NUMBER} = shift @numbers;
  203.  
  204.      # the crucial step - push a reference to this row into the loop!
  205.      push(@loop_data, \%row_data);
  206.    }
  207.  
  208.    # finally, assign the loop data to the loop param, again with a
  209.    # reference:
  210.    $template->param(THIS_LOOP => \@loop_data);
  211.  
  212. The above example would work with a template like:
  213.  
  214.    <TMPL_LOOP NAME="THIS_LOOP">
  215.       Word: <TMPL_VAR NAME="WORD">     <br>
  216.       Number: <TMPL_VAR NAME="NUMBER"> <p>
  217.    </TMPL_LOOP>
  218.  
  219. It would produce output like:
  220.  
  221.    Word: I
  222.    Number: 1
  223.  
  224.    Word: Am
  225.    Number: 2
  226.  
  227.    Word: Cool
  228.    Number: 3
  229.  
  230. <TMPL_LOOP>s within <TMPL_LOOP>s are fine and work as you would
  231. expect.  If the syntax for the param() call has you stumped, here's an
  232. example of a param call with one nested loop:
  233.  
  234.   $template->param(LOOP => [
  235.                             { name => 'Bobby',
  236.                               nicknames => [
  237.                                             { name => 'the big bad wolf' },
  238.                                             { name => 'He-Man' },
  239.                                            ],
  240.                             },
  241.                            ],
  242.                   );
  243.  
  244. Basically, each <TMPL_LOOP> gets an array reference.  Inside the array
  245. are any number of hash references.  These hashes contain the
  246. name=>value pairs for a single pass over the loop template.
  247.  
  248. Inside a <TMPL_LOOP>, the only variables that are usable are the ones
  249. from the <TMPL_LOOP>.  The variables in the outer blocks are not
  250. visible within a template loop.  For the computer-science geeks among
  251. you, a <TMPL_LOOP> introduces a new scope much like a perl subroutine
  252. call.  If you want your variables to be global you can use
  253. 'global_vars' option to new() described below.
  254.  
  255. =head2 TMPL_INCLUDE
  256.  
  257.   <TMPL_INCLUDE NAME="filename.tmpl">
  258.  
  259. This tag includes a template directly into the current template at the
  260. point where the tag is found.  The included template contents are used
  261. exactly as if its contents were physically included in the master
  262. template.
  263.  
  264. The file specified can be an absolute path (beginning with a '/' under
  265. Unix, for example).  If it isn't absolute, the path to the enclosing
  266. file is tried first.  After that the path in the environment variable
  267. HTML_TEMPLATE_ROOT is tried, if it exists.  Next, the "path" option is
  268. consulted, first as-is and then with HTML_TEMPLATE_ROOT prepended if
  269. available.  As a final attempt, the filename is passed to open()
  270. directly.  See below for more information on HTML_TEMPLATE_ROOT and
  271. the "path" option to new().
  272.  
  273. As a protection against infinitly recursive includes, an arbitary
  274. limit of 10 levels deep is imposed.  You can alter this limit with the
  275. "max_includes" option.  See the entry for the "max_includes" option
  276. below for more details.
  277.  
  278. =head2 TMPL_IF
  279.  
  280.   <TMPL_IF NAME="PARAMETER_NAME"> ... </TMPL_IF>
  281.  
  282. The <TMPL_IF> tag allows you to include or not include a block of the
  283. template based on the value of a given parameter name.  If the
  284. parameter is given a value that is true for Perl - like '1' - then the
  285. block is included in the output.  If it is not defined, or given a
  286. false value - like '0' - then it is skipped.  The parameters are
  287. specified the same way as with TMPL_VAR.
  288.  
  289. Example Template:
  290.  
  291.    <TMPL_IF NAME="BOOL">
  292.      Some text that only gets displayed if BOOL is true!
  293.    </TMPL_IF>
  294.  
  295. Now if you call $template->param(BOOL => 1) then the above block will
  296. be included by output.
  297.  
  298. <TMPL_IF> </TMPL_IF> blocks can include any valid HTML::Template
  299. construct - VARs and LOOPs and other IF/ELSE blocks.  Note, however,
  300. that intersecting a <TMPL_IF> and a <TMPL_LOOP> is invalid.
  301.  
  302.    Not going to work:
  303.    <TMPL_IF BOOL>
  304.       <TMPL_LOOP SOME_LOOP>
  305.    </TMPL_IF>
  306.       </TMPL_LOOP>
  307.  
  308. If the name of a TMPL_LOOP is used in a TMPL_IF, the IF block will
  309. output if the loop has at least one row.  Example:
  310.  
  311.   <TMPL_IF LOOP_ONE>
  312.     This will output if the loop is not empty.
  313.   </TMPL_IF>
  314.  
  315.   <TMPL_LOOP LOOP_ONE>
  316.     ....
  317.   </TMPL_LOOP>
  318.  
  319. WARNING: Much of the benefit of HTML::Template is in decoupling your
  320. Perl and HTML.  If you introduce numerous cases where you have
  321. TMPL_IFs and matching Perl if()s, you will create a maintenance
  322. problem in keeping the two synchronized.  I suggest you adopt the
  323. practice of only using TMPL_IF if you can do so without requiring a
  324. matching if() in your Perl code.
  325.  
  326. =head2 TMPL_ELSE
  327.  
  328.   <TMPL_IF NAME="PARAMETER_NAME"> ... <TMPL_ELSE> ... </TMPL_IF>
  329.  
  330. You can include an alternate block in your TMPL_IF block by using
  331. TMPL_ELSE.  NOTE: You still end the block with </TMPL_IF>, not
  332. </TMPL_ELSE>!
  333.  
  334.    Example:
  335.  
  336.    <TMPL_IF BOOL>
  337.      Some text that is included only if BOOL is true
  338.    <TMPL_ELSE>
  339.      Some text that is included only if BOOL is false
  340.    </TMPL_IF>
  341.  
  342. =head2 TMPL_UNLESS
  343.  
  344.   <TMPL_UNLESS NAME="PARAMETER_NAME"> ... </TMPL_UNLESS>
  345.  
  346. This tag is the opposite of <TMPL_IF>.  The block is output if the
  347. CONTROL_PARAMETER is set false or not defined.  You can use
  348. <TMPL_ELSE> with <TMPL_UNLESS> just as you can with <TMPL_IF>.
  349.  
  350.   Example:
  351.  
  352.   <TMPL_UNLESS BOOL>
  353.     Some text that is output only if BOOL is FALSE.
  354.   <TMPL_ELSE>
  355.     Some text that is output only if BOOL is TRUE.
  356.   </TMPL_UNLESS>
  357.  
  358. If the name of a TMPL_LOOP is used in a TMPL_UNLESS, the UNLESS block
  359. output if the loop has zero rows.
  360.  
  361.   <TMPL_UNLESS LOOP_ONE>
  362.     This will output if the loop is empty.
  363.   </TMPL_UNLESS>
  364.  
  365.   <TMPL_LOOP LOOP_ONE>
  366.     ....
  367.   </TMPL_LOOP>
  368.  
  369. =cut
  370.  
  371. =head2 NOTES
  372.  
  373. HTML::Template's tags are meant to mimic normal HTML tags.  However,
  374. they are allowed to "break the rules".  Something like:
  375.  
  376.    <img src="<TMPL_VAR IMAGE_SRC>">
  377.  
  378. is not really valid HTML, but it is a perfectly valid use and will
  379. work as planned.
  380.  
  381. The "NAME=" in the tag is optional, although for extensibility's sake I
  382. recommend using it.  Example - "<TMPL_LOOP LOOP_NAME>" is acceptable.
  383.  
  384. If you're a fanatic about valid HTML and would like your templates
  385. to conform to valid HTML syntax, you may optionally type template tags
  386. in the form of HTML comments. This may be of use to HTML authors who
  387. would like to validate their templates' HTML syntax prior to
  388. HTML::Template processing, or who use DTD-savvy editing tools.
  389.  
  390.   <!-- TMPL_VAR NAME=PARAM1 -->
  391.  
  392. In order to realize a dramatic savings in bandwidth, the standard
  393. (non-comment) tags will be used throughout this documentation.
  394.  
  395. =head1 METHODS
  396.  
  397. =head2 new()
  398.  
  399. Call new() to create a new Template object:
  400.  
  401.   my $template = HTML::Template->new( filename => 'file.tmpl',
  402.                                       option => 'value'
  403.                                     );
  404.  
  405. You must call new() with at least one name => value pair specifying how
  406. to access the template text.  You can use "filename => 'file.tmpl'" to
  407. specify a filename to be opened as the template.  Alternately you can
  408. use:
  409.  
  410.   my $t = HTML::Template->new( scalarref => $ref_to_template_text,
  411.                                option => 'value'
  412.                              );
  413.  
  414. and
  415.  
  416.   my $t = HTML::Template->new( arrayref => $ref_to_array_of_lines ,
  417.                                option => 'value'
  418.                              );
  419.  
  420.  
  421. These initialize the template from in-memory resources.  In almost
  422. every case you'll want to use the filename parameter.  If you're
  423. worried about all the disk access from reading a template file just
  424. use mod_perl and the cache option detailed below.
  425.  
  426. You can also read the template from an already opened filehandle,
  427. either traditionally as a glob or as a FileHandle:
  428.  
  429.   my $t = HTML::Template->new( filehandle => *FH, option => 'value');
  430.  
  431. The four new() calling methods can also be accessed as below, if you
  432. prefer.
  433.  
  434.   my $t = HTML::Template->new_file('file.tmpl', option => 'value');
  435.  
  436.   my $t = HTML::Template->new_scalar_ref($ref_to_template_text,
  437.                                         option => 'value');
  438.  
  439.   my $t = HTML::Template->new_array_ref($ref_to_array_of_lines,
  440.                                        option => 'value');
  441.  
  442.   my $t = HTML::Template->new_filehandle($fh,
  443.                                        option => 'value');
  444.  
  445. And as a final option, for those that might prefer it, you can call new as:
  446.  
  447.   my $t = HTML::Template->new(type => 'filename',
  448.                               source => 'file.tmpl');
  449.  
  450. Which works for all three of the source types.
  451.  
  452. If the environment variable HTML_TEMPLATE_ROOT is set and your
  453. filename doesn't begin with /, then the path will be relative to the
  454. value of $HTML_TEMPLATE_ROOT.  Example - if the environment variable
  455. HTML_TEMPLATE_ROOT is set to "/home/sam" and I call
  456. HTML::Template->new() with filename set to "sam.tmpl", the
  457. HTML::Template will try to open "/home/sam/sam.tmpl" to access the
  458. template file.  You can also affect the search path for files with the
  459. "path" option to new() - see below for more information.
  460.  
  461. You can modify the Template object's behavior with new().  The options
  462. are available:
  463.  
  464. =over 4
  465.  
  466. =item Error Detection Options
  467.  
  468. =over 4
  469.  
  470. =item *
  471.  
  472. die_on_bad_params - if set to 0 the module will let you call
  473. $template->param(param_name => 'value') even if 'param_name' doesn't
  474. exist in the template body.  Defaults to 1.
  475.  
  476. =item *
  477.  
  478. strict - if set to 0 the module will allow things that look like they
  479. might be TMPL_* tags to get by without dieing.  Example:
  480.  
  481.    <TMPL_HUH NAME=ZUH>
  482.  
  483. Would normally cause an error, but if you call new with strict => 0,
  484. HTML::Template will ignore it.  Defaults to 1.
  485.  
  486. =item *
  487.  
  488. vanguard_compatibility_mode - if set to 1 the module will expect to
  489. see <TMPL_VAR>s that look like %NAME% in addition to the standard
  490. syntax.  Also sets die_on_bad_params => 0.  If you're not at Vanguard
  491. Media trying to use an old format template don't worry about this one.
  492. Defaults to 0.
  493.  
  494. =back
  495.  
  496. =item Caching Options
  497.  
  498. =over 4
  499.  
  500. =item *
  501.  
  502. cache - if set to 1 the module will cache in memory the parsed
  503. templates based on the filename parameter and modification date of the
  504. file.  This only applies to templates opened with the filename
  505. parameter specified, not scalarref or arrayref templates.  Caching
  506. also looks at the modification times of any files included using
  507. <TMPL_INCLUDE> tags, but again, only if the template is opened with
  508. filename parameter.
  509.  
  510. This is mainly of use in a persistent environment like
  511. Apache/mod_perl.  It has absolutely no benefit in a normal CGI
  512. environment since the script is unloaded from memory after every
  513. request.  For a cache that does work for normal CGIs see the
  514. 'shared_cache' option below.
  515.  
  516. Note that different new() parameter settings do not cause a cache
  517. refresh, only a change in the modification time of the template will
  518. trigger a cache refresh.  For most usages this is fine.  My simplistic
  519. testing shows that using cache yields a 90% performance increase under
  520. mod_perl.  Cache defaults to 0.
  521.  
  522. =item *
  523.  
  524. shared_cache - if set to 1 the module will store its cache in shared
  525. memory using the IPC::SharedCache module (available from CPAN).  The
  526. effect of this will be to maintain a single shared copy of each parsed
  527. template for all instances of HTML::Template to use.  This can be a
  528. significant reduction in memory usage in a multiple server
  529. environment.  As an example, on one of our systems we use 4MB of
  530. template cache and maintain 25 httpd processes - shared_cache results
  531. in saving almost 100MB!  Of course, some reduction in speed versus
  532. normal caching is to be expected.  Another difference between normal
  533. caching and shared_cache is that shared_cache will work in a CGI
  534. environment - normal caching is only useful in a persistent
  535. environment like Apache/mod_perl.
  536.  
  537. By default HTML::Template uses the IPC key 'TMPL' as a shared root
  538. segment (0x4c504d54 in hex), but this can be changed by setting the
  539. 'ipc_key' new() parameter to another 4-character or integer key.
  540. Other options can be used to affect the shared memory cache correspond
  541. to IPC::SharedCache options - ipc_mode, ipc_segment_size and
  542. ipc_max_size.  See L<IPC::SharedCache> for a description of how these
  543. work - in most cases you shouldn't need to change them from the
  544. defaults.
  545.  
  546. For more information about the shared memory cache system used by
  547. HTML::Template see L<IPC::SharedCache>.
  548.  
  549. =item *
  550.  
  551. double_cache - if set to 1 the module will use a combination of
  552. shared_cache and normal cache mode for the best possible caching.  Of
  553. course, it also uses the most memory of all the cache modes.  All the
  554. same ipc_* options that work with shared_cache apply to double_cache
  555. as well.  By default double_cache is off.
  556.  
  557. =item *
  558.  
  559. blind_cache - if set to 1 the module behaves exactly as with normal
  560. caching but does not check to see if the file has changed on each
  561. request.  This option should be used with caution, but could be of use
  562. on high-load servers.  My tests show blind_cache performing only 1 to
  563. 2 percent faster than cache under mod_perl.
  564.  
  565. NOTE: Combining this option with shared_cache can result in stale
  566. templates stuck permanently in shared memory!
  567.  
  568. =item *
  569.  
  570. file_cache - if set to 1 the module will store its cache in a file
  571. using the Storable module.  It uses no additional memory, and my
  572. simplistic testing shows that it yields a 50% performance advantage.
  573. Like shared_cache, it will work in a CGI environment. Default is 0.
  574.  
  575. If you set this option you must set the "file_cache_dir" option.  See
  576. below for details.
  577.  
  578. NOTE: Storable using flock() to ensure safe access to cache files.
  579. Using file_cache on a system or filesystem (NFS) without flock()
  580. support is dangerous.
  581.  
  582.  
  583. =item *
  584.  
  585. file_cache_dir - sets the directory where the module will store the
  586. cache files if file_cache is enabled.  Your script will need write
  587. permissions to this directory.  You'll also need to make sure the
  588. sufficient space is available to store the cache files.
  589.  
  590. =item *
  591.  
  592. file_cache_dir_mode - sets the file mode for newly created file_cache
  593. directories and subdirectories.  Defaults to 0700 for security but
  594. this may be inconvenient if you do not have access to the account
  595. running the webserver.
  596.  
  597. =item *
  598.  
  599. double_file_cache - if set to 1 the module will use a combination of
  600. file_cache and normal cache mode for the best possible caching.  The
  601. file_cache_* options that work with file_cache apply to double_file_cache
  602. as well.  By default double_file_cache is 0.
  603.  
  604. =back
  605.  
  606. =item Filesystem Options
  607.  
  608. =over 4
  609.  
  610. =item *
  611.  
  612. path - you can set this variable with a list of paths to search for
  613. files specified with the "filename" option to new() and for files
  614. included with the <TMPL_INCLUDE> tag.  This list is only consulted
  615. when the filename is relative.  The HTML_TEMPLATE_ROOT environment
  616. variable is always tried first if it exists.  Also, if
  617. HTML_TEMPLATE_ROOT is set then an attempt will be made to prepend
  618. HTML_TEMPLATE_ROOT onto paths in the path array.  In the case of a
  619. <TMPL_INCLUDE> file, the path to the including file is also tried
  620. before path is consulted.
  621.  
  622. Example:
  623.  
  624.    my $template = HTML::Template->new( filename => 'file.tmpl',
  625.                                        path => [ '/path/to/templates',
  626.                                                  '/alternate/path'
  627.                                                ]
  628.                                       );
  629.  
  630. NOTE: the paths in the path list must be expressed as UNIX paths,
  631. separated by the forward-slash character ('/').
  632.  
  633. =item *
  634.  
  635. search_path_on_include - if set to a true value the module will search
  636. from the top of the array of paths specified by the path option on
  637. every <TMPL_INCLUDE> and use the first matching template found.  The
  638. normal behavior is to look only in the current directory for a
  639. template to include.  Defaults to 0.
  640.  
  641. =back
  642.  
  643. =item Debugging Options
  644.  
  645. =over 4
  646.  
  647. =item *
  648.  
  649. debug - if set to 1 the module will write random debugging information
  650. to STDERR.  Defaults to 0.
  651.  
  652. =item *
  653.  
  654. stack_debug - if set to 1 the module will use Data::Dumper to print
  655. out the contents of the parse_stack to STDERR.  Defaults to 0.
  656.  
  657. =item *
  658.  
  659. cache_debug - if set to 1 the module will send information on cache
  660. loads, hits and misses to STDERR.  Defaults to 0.
  661.  
  662. =item *
  663.  
  664. shared_cache_debug - if set to 1 the module will turn on the debug
  665. option in IPC::SharedCache - see L<IPC::SharedCache> for
  666. details. Defaults to 0.
  667.  
  668. =item *
  669.  
  670. memory_debug - if set to 1 the module will send information on cache
  671. memory usage to STDERR.  Requires the GTop module.  Defaults to 0.
  672.  
  673. =back
  674.  
  675. =item Miscellaneous Options
  676.  
  677. =over 4
  678.  
  679. =item *
  680.  
  681. associate - this option allows you to inherit the parameter values
  682. from other objects.  The only requirement for the other object is that
  683. it have a param() method that works like HTML::Template's param().  A
  684. good candidate would be a CGI.pm query object.  Example:
  685.  
  686.   my $query = new CGI;
  687.   my $template = HTML::Template->new(filename => 'template.tmpl',
  688.                                      associate => $query);
  689.  
  690. Now, $template->output() will act as though
  691.  
  692.   $template->param('FormField', $cgi->param('FormField'));
  693.  
  694. had been specified for each key/value pair that would be provided by
  695. the $cgi->param() method.  Parameters you set directly take precedence
  696. over associated parameters.
  697.  
  698. You can specify multiple objects to associate by passing an anonymous
  699. array to the associate option.  They are searched for parameters in
  700. the order they appear:
  701.  
  702.   my $template = HTML::Template->new(filename => 'template.tmpl',
  703.                                      associate => [$query, $other_obj]);
  704.  
  705. The old associateCGI() call is still supported, but should be
  706. considered obsolete.
  707.  
  708. NOTE: The parameter names are matched in a case-insensitve manner.  If
  709. you have two parameters in a CGI object like 'NAME' and 'Name' one
  710. will be chosen randomly by associate.  This behavior can be changed by
  711. the following option.
  712.  
  713. =item *
  714.  
  715. case_sensitive - setting this option to true causes HTML::Template to
  716. treat template variable names case-sensitively.  The following example
  717. would only set one parameter without the "case_sensitive" option:
  718.  
  719.   my $template = HTML::Template->new(filename => 'template.tmpl',
  720.                                      case_sensitive => 1);
  721.   $template->param(
  722.     FieldA => 'foo',
  723.     fIELDa => 'bar',
  724.   );
  725.  
  726. This option defaults to off.
  727.  
  728. NOTE: with case_sensitive and loop_context_vars the special loop
  729. variables are available in lower-case only.
  730.  
  731. =item *
  732.  
  733. loop_context_vars - when this parameter is set to true (it is false by
  734. default) four loop context variables are made available inside a loop:
  735. __first__, __last__, __inner__, __odd__.  They can be used with
  736. <TMPL_IF>, <TMPL_UNLESS> and <TMPL_ELSE> to control how a loop is
  737. output.  
  738.  
  739. In addition to the above, a __counter__ var is also made available
  740. when loop context variables are turned on.
  741.  
  742. Example:
  743.  
  744.    <TMPL_LOOP NAME="FOO">
  745.       <TMPL_IF NAME="__first__">
  746.         This only outputs on the first pass.
  747.       </TMPL_IF>
  748.  
  749.       <TMPL_IF NAME="__odd__">
  750.         This outputs every other pass, on the odd passes.
  751.       </TMPL_IF>
  752.  
  753.       <TMPL_UNLESS NAME="__odd__">
  754.         This outputs every other pass, on the even passes.
  755.       </TMPL_IF>
  756.  
  757.       <TMPL_IF NAME="__inner__">
  758.         This outputs on passes that are neither first nor last.
  759.       </TMPL_IF>
  760.  
  761.       This is pass number <TMPL_VAR NAME="__counter__">.
  762.  
  763.       <TMPL_IF NAME="__last__">
  764.         This only outputs on the last pass.
  765.       <TMPL_IF>
  766.    </TMPL_LOOP>
  767.  
  768. One use of this feature is to provide a "separator" similar in effect
  769. to the perl function join().  Example:
  770.  
  771.    <TMPL_LOOP FRUIT>
  772.       <TMPL_IF __last__> and </TMPL_IF>
  773.       <TMPL_VAR KIND><TMPL_UNLESS __last__>, <TMPL_ELSE>.</TMPL_UNLESS>
  774.    </TMPL_LOOP>
  775.  
  776. Would output (in a browser) something like:
  777.  
  778.   Apples, Oranges, Brains, Toes, and Kiwi.
  779.  
  780. Given an appropriate param() call, of course.  NOTE: A loop with only
  781. a single pass will get both __first__ and __last__ set to true, but
  782. not __inner__.
  783.  
  784. =item *
  785.  
  786. no_includes - set this option to 1 to disallow the <TMPL_INCLUDE> tag
  787. in the template file.  This can be used to make opening untrusted
  788. templates B<slightly> less dangerous.  Defaults to 0.
  789.  
  790. =item *
  791.  
  792. max_includes - set this variable to determine the maximum depth that
  793. includes can reach.  Set to 10 by default.  Including files to a depth
  794. greater than this value causes an error message to be displayed.  Set
  795. to 0 to disable this protection.
  796.  
  797. =item *
  798.  
  799. global_vars - normally variables declared outside a loop are not
  800. available inside a loop.  This option makes <TMPL_VAR>s like global
  801. variables in Perl - they have unlimited scope.  This option also
  802. affects <TMPL_IF> and <TMPL_UNLESS>.
  803.  
  804. Example:
  805.  
  806.   This is a normal variable: <TMPL_VAR NORMAL>.<P>
  807.  
  808.   <TMPL_LOOP NAME=FROOT_LOOP>
  809.      Here it is inside the loop: <TMPL_VAR NORMAL><P>
  810.   </TMPL_LOOP>
  811.  
  812. Normally this wouldn't work as expected, since <TMPL_VAR NORMAL>'s
  813. value outside the loop is not available inside the loop.
  814.  
  815. The global_vars option also allows you to access the values of an
  816. enclosing loop within an inner loop.  For example, in this loop the
  817. inner loop will have access to the value of OUTER_VAR in the correct
  818. iteration:
  819.  
  820.    <TMPL_LOOP OUTER_LOOP>
  821.       OUTER: <TMPL_VAR OUTER_VAR>
  822.         <TMPL_LOOP INNER_LOOP>
  823.            INNER: <TMPL_VAR INNER_VAR>
  824.            INSIDE OUT: <TMPL_VAR OUTER_VAR>
  825.         </TMPL_LOOP>
  826.    </TMPL_LOOP>
  827.  
  828. B<NOTE>: C<global_vars> is not C<global_loops> (which does not exist).
  829. That means that loops you declare at one scope are not available
  830. inside other loops even when C<global_vars> is on.
  831.  
  832. =item *
  833.  
  834. filter - this option allows you to specify a filter for your template
  835. files.  A filter is a subroutine that will be called after
  836. HTML::Template reads your template file but before it starts parsing
  837. template tags.
  838.  
  839. In the most simple usage, you simply assign a code reference to the
  840. filter parameter.  This subroutine will recieve a single arguement - a
  841. reference to a string containing the template file text.  Here is an
  842. example that accepts templates with tags that look like "!!!ZAP_VAR
  843. FOO!!!" and transforms them into HTML::Template tags:
  844.  
  845.    my $filter = sub {
  846.      my $text_ref = shift;
  847.      $$text_ref =~ s/!!!ZAP_(.*?)!!!/<TMPL_$1>/g;
  848.    };
  849.  
  850.    # open zap.tmpl using the above filter
  851.    my $template = HTML::Template->new(filename => 'zap.tmpl',
  852.                                       filter => $filter);
  853.  
  854. More complicated usages are possible.  You can request that your
  855. filter receieve the template text as an array of lines rather than as
  856. a single scalar.  To do that you need to specify your filter using a
  857. hash-ref.  In this form you specify the filter using the "sub" key and
  858. the desired argument format using the "format" key.  The available
  859. formats are "scalar" and "array".  Using the "array" format will incur
  860. a performance penalty but may be more convenient in some situations.
  861.  
  862.    my $template = HTML::Template->new(filename => 'zap.tmpl',
  863.                                       filter => { sub => $filter,
  864.                                                   format => 'array' });
  865.  
  866. You may also have multiple filters.  This allows simple filters to be
  867. combined for more elaborate functionality.  To do this you specify an
  868. array of filters.  The filters are applied in the order they are
  869. specified.
  870.  
  871.    my $template = HTML::Template->new(filename => 'zap.tmpl',
  872.                                       filter => [
  873.                                            { sub => \&decompress,
  874.                                              format => 'scalar' },
  875.                                            { sub => \&remove_spaces,
  876.                                              format => 'array' }
  877.                                         ]);
  878.  
  879. The specified filters will be called for any TMPL_INCLUDEed files just
  880. as they are for the main template file.
  881.  
  882. =back
  883.  
  884. =back 4
  885.  
  886. =cut
  887.  
  888.  
  889. use integer; # no floating point math so far!
  890. use strict; # and no funny business, either.
  891.  
  892. use Carp; # generate better errors with more context
  893. use File::Spec; # generate paths that work on all platforms
  894. use Digest::MD5 qw(md5_hex); # generate cache keys
  895.  
  896. # define accessor constants used to improve readability of array
  897. # accesses into "objects".  I used to use 'use constant' but that
  898. # seems to cause occasional irritating warnings in older Perls.
  899. package HTML::Template::LOOP;
  900. sub TEMPLATE_HASH () { 0; }
  901. sub PARAM_SET     () { 1 };
  902.  
  903. package HTML::Template::COND;
  904. sub VARIABLE           () { 0 };
  905. sub VARIABLE_TYPE      () { 1 };
  906. sub VARIABLE_TYPE_VAR  () { 0 };
  907. sub VARIABLE_TYPE_LOOP () { 1 };
  908. sub JUMP_IF_TRUE       () { 2 };
  909. sub JUMP_ADDRESS       () { 3 };
  910. sub WHICH              () { 4 };
  911. sub WHICH_IF           () { 0 };
  912. sub WHICH_UNLESS       () { 1 };
  913.  
  914. # back to the main package scope.
  915. package HTML::Template;
  916.  
  917. # open a new template and return an object handle
  918. sub new {
  919.   my $pkg = shift;
  920.   my $self; { my %hash; $self = bless(\%hash, $pkg); }
  921.  
  922.   # the options hash
  923.   my $options = {};
  924.   $self->{options} = $options;
  925.  
  926.   # set default parameters in options hash
  927.   %$options = (
  928.                debug => 0,
  929.                stack_debug => 0,
  930.                timing => 0,
  931.                search_path_on_include => 0,
  932.                cache => 0,               
  933.                blind_cache => 0,
  934.            file_cache => 0,
  935.            file_cache_dir => '',
  936.            file_cache_dir_mode => 0700,
  937.                cache_debug => 0,
  938.                shared_cache_debug => 0,
  939.                memory_debug => 0,
  940.                die_on_bad_params => 1,
  941.                vanguard_compatibility_mode => 0,
  942.                associate => [],
  943.                path => [],
  944.                strict => 1,
  945.                loop_context_vars => 0,
  946.                max_includes => 10,
  947.                shared_cache => 0,
  948.                double_cache => 0,
  949.                double_file_cache => 0,
  950.                ipc_key => 'TMPL',
  951.                ipc_mode => 0666,
  952.                ipc_segment_size => 65536,
  953.                ipc_max_size => 0,
  954.                global_vars => 0,
  955.                no_includes => 0,
  956.                case_sensitive => 0,
  957.                filter => [],
  958.               );
  959.   
  960.   # load in options supplied to new()
  961.   for (my $x = 0; $x <= $#_; $x += 2) {
  962.     defined($_[($x + 1)]) or croak("HTML::Template->new() called with odd number of option parameters - should be of the form option => value");
  963.     $options->{lc($_[$x])} = $_[($x + 1)]; 
  964.   }
  965.  
  966.   # blind_cache = 1 implies cache = 1
  967.   $options->{blind_cache} and $options->{cache} = 1;
  968.  
  969.   # shared_cache = 1 implies cache = 1
  970.   $options->{shared_cache} and $options->{cache} = 1;
  971.  
  972.   # file_cache = 1 implies cache = 1
  973.   $options->{file_cache} and $options->{cache} = 1;
  974.  
  975.   # double_cache is a combination of shared_cache and cache.
  976.   $options->{double_cache} and $options->{cache} = 1;
  977.   $options->{double_cache} and $options->{shared_cache} = 1;
  978.  
  979.   # double_file_cache is a combination of file_cache and cache.
  980.   $options->{double_file_cache} and $options->{cache} = 1;
  981.   $options->{double_file_cache} and $options->{file_cache} = 1;
  982.  
  983.   # vanguard_compatibility_mode implies die_on_bad_params = 0
  984.   $options->{vanguard_compatibility_mode} and 
  985.     $options->{die_on_bad_params} = 0;
  986.  
  987.   # handle the "type", "source" parameter format (does anyone use it?)
  988.   if (exists($options->{type})) {
  989.     exists($options->{source}) or croak("HTML::Template->new() called with 'type' parameter set, but no 'source'!");
  990.     ($options->{type} eq 'filename' or $options->{type} eq 'scalarref' or
  991.      $options->{type} eq 'arrayref' or $options->{type} eq 'filehandle') or
  992.        croak("HTML::Template->new() : type parameter must be set to 'filename', 'arrayref', 'scalarref' or 'filehandle'!");
  993.  
  994.     $options->{$options->{type}} = $options->{source};
  995.     delete $options->{type};
  996.     delete $options->{source};
  997.   }
  998.  
  999.   # associate should be an array of one element if it's not
  1000.   # already an array.
  1001.   if (ref($options->{associate}) ne 'ARRAY') {
  1002.     $options->{associate} = [ $options->{associate} ];
  1003.   }
  1004.  
  1005.   # path should be an array if it's not already
  1006.   if (ref($options->{path}) ne 'ARRAY') {
  1007.     $options->{path} = [ $options->{path} ];
  1008.   }
  1009.  
  1010.   # filter should be an array if it's not already
  1011.   if (ref($options->{filter}) ne 'ARRAY') {
  1012.     $options->{filter} = [ $options->{filter} ];
  1013.   }
  1014.   
  1015.   # make sure objects in associate area support param()
  1016.   foreach my $object (@{$options->{associate}}) {
  1017.     defined($object->can('param')) or
  1018.       croak("HTML::Template->new called with associate option, containing object of type " . ref($object) . " which lacks a param() method!");
  1019.   } 
  1020.  
  1021.   # check for syntax errors:
  1022.   my $source_count = 0;
  1023.   exists($options->{filename}) and $source_count++;
  1024.   exists($options->{filehandle}) and $source_count++;
  1025.   exists($options->{arrayref}) and $source_count++;
  1026.   exists($options->{scalarref}) and $source_count++;
  1027.   if ($source_count != 1) {
  1028.     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");
  1029.   }
  1030.  
  1031.   # check that filenames aren't empty
  1032.   if (exists($options->{filename})) {
  1033.       croak("HTML::Template->new called with empty filename parameter!")
  1034.         unless defined $options->{filename} and length $options->{filename};
  1035.   }
  1036.  
  1037.   # do some memory debugging - this is best started as early as possible
  1038.   if ($options->{memory_debug}) {
  1039.     # memory_debug needs GTop
  1040.     eval { require GTop; };
  1041.     croak("Could not load GTop.  You must have GTop installed to use HTML::Template in memory_debug mode.  The error was: $@")
  1042.       if ($@);
  1043.     $self->{gtop} = GTop->new();
  1044.     $self->{proc_mem} = $self->{gtop}->proc_mem($$);
  1045.     print STDERR "\n### HTML::Template Memory Debug ### START ", $self->{proc_mem}->size(), "\n";
  1046.   }
  1047.  
  1048.   if ($options->{file_cache}) {
  1049.     # make sure we have a file_cache_dir option
  1050.     croak("You must specify the file_cache_dir option if you want to use file_cache.") 
  1051.       unless defined $options->{file_cache_dir} and 
  1052.         length $options->{file_cache_dir};
  1053.  
  1054.     # file_cache needs some extra modules loaded
  1055.     eval { require Storable; };
  1056.     croak("Could not load Storable.  You must have Storable installed to use HTML::Template in file_cache mode.  The error was: $@")
  1057.       if ($@);
  1058.   }
  1059.  
  1060.   if ($options->{shared_cache}) {
  1061.     # shared_cache needs some extra modules loaded
  1062.     eval { require IPC::SharedCache; };
  1063.     croak("Could not load IPC::SharedCache.  You must have IPC::SharedCache installed to use HTML::Template in shared_cache mode.  The error was: $@")
  1064.       if ($@);
  1065.  
  1066.     # initialize the shared cache
  1067.     my %cache;
  1068.     tie %cache, 'IPC::SharedCache',
  1069.       ipc_key => $options->{ipc_key},
  1070.       load_callback => [\&_load_shared_cache, $self],
  1071.       validate_callback => [\&_validate_shared_cache, $self],
  1072.       debug => $options->{shared_cache_debug},
  1073.       ipc_mode => $options->{ipc_mode},
  1074.       max_size => $options->{ipc_max_size},
  1075.       ipc_segment_size => $options->{ipc_segment_size};
  1076.     $self->{cache} = \%cache;
  1077.   }
  1078.  
  1079.   print STDERR "### HTML::Template Memory Debug ### POST CACHE INIT ", $self->{proc_mem}->size(), "\n"
  1080.     if $options->{memory_debug};
  1081.  
  1082.   # initialize data structures
  1083.   $self->_init;
  1084.   
  1085.   print STDERR "### HTML::Template Memory Debug ### POST _INIT CALL ", $self->{proc_mem}->size(), "\n"
  1086.     if $options->{memory_debug};
  1087.   
  1088.   # drop the shared cache - leaving out this step results in the
  1089.   # template object evading garbage collection since the callbacks in
  1090.   # the shared cache tie hold references to $self!  This was not easy
  1091.   # to find, by the way.
  1092.   delete $self->{cache} if $options->{shared_cache};
  1093.  
  1094.   return $self;
  1095. }
  1096.  
  1097. # an internally used new that receives its parse_stack and param_map as input
  1098. sub _new_from_loop {
  1099.   my $pkg = shift;
  1100.   my $self; { my %hash; $self = bless(\%hash, $pkg); }
  1101.  
  1102.   # the options hash
  1103.   my $options = {};
  1104.   $self->{options} = $options;
  1105.  
  1106.   # set default parameters in options hash - a subset of the options
  1107.   # valid in a normal new().  Since _new_from_loop never calls _init,
  1108.   # many options have no relevance.
  1109.   %$options = (
  1110.                debug => 0,
  1111.                stack_debug => 0,
  1112.                die_on_bad_params => 1,
  1113.                associate => [],
  1114.                loop_context_vars => 0,
  1115.               );
  1116.   
  1117.   # load in options supplied to new()
  1118.   for (my $x = 0; $x <= $#_; $x += 2) { 
  1119.     defined($_[($x + 1)]) or croak("HTML::Template->new() called with odd number of option parameters - should be of the form option => value");
  1120.     $options->{lc($_[$x])} = $_[($x + 1)]; 
  1121.   }
  1122.  
  1123.   $self->{param_map} = $options->{param_map};
  1124.   $self->{parse_stack} = $options->{parse_stack};
  1125.   delete($options->{param_map});
  1126.   delete($options->{parse_stack});
  1127.  
  1128.   return $self;
  1129. }
  1130.  
  1131. # a few shortcuts to new(), of possible use...
  1132. sub new_file {
  1133.   my $pkg = shift; return $pkg->new('filename', @_);
  1134. }
  1135. sub new_filehandle {
  1136.   my $pkg = shift; return $pkg->new('filehandle', @_);
  1137. }
  1138. sub new_array_ref {
  1139.   my $pkg = shift; return $pkg->new('arrayref', @_);
  1140. }
  1141. sub new_scalar_ref {
  1142.   my $pkg = shift; return $pkg->new('scalarref', @_);
  1143. }
  1144.  
  1145. # initializes all the object data structures, either from cache or by
  1146. # calling the appropriate routines.
  1147. sub _init {
  1148.   my $self = shift;
  1149.   my $options = $self->{options};
  1150.  
  1151.   if ($options->{double_cache}) {
  1152.     # try the normal cache, return if we have it.
  1153.     $self->_fetch_from_cache();
  1154.     return if (defined $self->{param_map} and defined $self->{parse_stack});
  1155.  
  1156.     # try the shared cache
  1157.     $self->_fetch_from_shared_cache();
  1158.  
  1159.     # put it in the local cache if we got it.
  1160.     $self->_commit_to_cache()
  1161.       if (defined $self->{param_map} and defined $self->{parse_stack});
  1162.   } elsif ($options->{double_file_cache}) {
  1163.     # try the normal cache, return if we have it.
  1164.     $self->_fetch_from_cache();
  1165.     return if (defined $self->{param_map} and defined $self->{parse_stack});
  1166.  
  1167.     # try the file cache
  1168.     $self->_fetch_from_file_cache();
  1169.  
  1170.     # put it in the local cache if we got it.
  1171.     $self->_commit_to_cache()
  1172.       if (defined $self->{param_map} and defined $self->{parse_stack});
  1173.   } elsif ($options->{shared_cache}) {
  1174.     # try the shared cache
  1175.     $self->_fetch_from_shared_cache();
  1176.   } elsif ($options->{file_cache}) {
  1177.     # try the file cache
  1178.     $self->_fetch_from_file_cache();
  1179.   } elsif ($options->{cache}) {
  1180.     # try the normal cache
  1181.     $self->_fetch_from_cache();
  1182.   }
  1183.   
  1184.   # if we got a cache hit, return
  1185.   return if (defined $self->{param_map} and defined $self->{parse_stack});
  1186.  
  1187.   # if we're here, then we didn't get a cached copy, so do a full
  1188.   # init.
  1189.   $self->_init_template();
  1190.   $self->_parse();
  1191.  
  1192.   # now that we have a full init, cache the structures if cacheing is
  1193.   # on.  shared cache is already cool.
  1194.   if($options->{file_cache}){
  1195.     $self->_commit_to_file_cache();
  1196.   }
  1197.   $self->_commit_to_cache() if (($options->{cache}
  1198.                                 and not $options->{shared_cache}
  1199.                 and not $options->{file_cache}) or
  1200.                                 ($options->{double_cache}) or
  1201.                 ($options->{double_file_cache}));
  1202. }
  1203.  
  1204. # Caching subroutines - they handle getting and validating cache
  1205. # records from either the in-memory or shared caches.
  1206.  
  1207. # handles the normal in memory cache
  1208. use vars qw( %CACHE );
  1209. sub _fetch_from_cache {
  1210.   my $self = shift;
  1211.   my $options = $self->{options};
  1212.  
  1213.   # return if there's no file here
  1214.   return unless exists($options->{filename});
  1215.   my $filepath = $self->_find_file($options->{filename});
  1216.   return unless (defined($filepath));
  1217.   $options->{filepath} = $filepath;
  1218.  
  1219.   # return if there's no cache entry for this key
  1220.   my $key = $self->_cache_key();
  1221.   return unless exists($CACHE{$key});  
  1222.   
  1223.   # validate the cache
  1224.   my $mtime = $self->_mtime($filepath);  
  1225.   if (defined $mtime) {
  1226.     # return if the mtime doesn't match the cache
  1227.     if (defined($CACHE{$key}{mtime}) and 
  1228.         ($mtime != $CACHE{$key}{mtime})) {
  1229.       $options->{cache_debug} and 
  1230.         print STDERR "CACHE MISS : $filepath : $mtime\n";
  1231.       return;
  1232.     }
  1233.  
  1234.     # if the template has includes, check each included file's mtime
  1235.     # and return if different
  1236.     if (exists($CACHE{$key}{included_mtimes})) {
  1237.       foreach my $filename (keys %{$CACHE{$key}{included_mtimes}}) {
  1238.         next unless 
  1239.           defined($CACHE{$key}{included_mtimes}{$filename});
  1240.         
  1241.         my $included_mtime = (stat($filename))[9];
  1242.         if ($included_mtime != $CACHE{$key}{included_mtimes}{$filename}) {
  1243.           $options->{cache_debug} and 
  1244.             print STDERR "### HTML::Template Cache Debug ### CACHE MISS : $filepath : INCLUDE $filename : $included_mtime\n";
  1245.           
  1246.           return;
  1247.         }
  1248.       }
  1249.     }
  1250.   }
  1251.  
  1252.   # got a cache hit!
  1253.   
  1254.   $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### CACHE HIT : $filepath => $key\n";
  1255.       
  1256.   $self->{param_map} = $CACHE{$key}{param_map};
  1257.   $self->{parse_stack} = $CACHE{$key}{parse_stack};
  1258.   exists($CACHE{$key}{included_mtimes}) and
  1259.     $self->{included_mtimes} = $CACHE{$key}{included_mtimes};
  1260.  
  1261.   # clear out values from param_map from last run
  1262.   $self->_normalize_options();
  1263.   $self->clear_params();
  1264. }
  1265.  
  1266. sub _commit_to_cache {
  1267.   my $self     = shift;
  1268.   my $options  = $self->{options};
  1269.   my $key      = $self->_cache_key();
  1270.   my $filepath = $options->{filepath};
  1271.  
  1272.   $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### CACHE LOAD : $filepath => $key\n";
  1273.     
  1274.   $options->{blind_cache} or
  1275.     $CACHE{$key}{mtime} = $self->_mtime($filepath);
  1276.   $CACHE{$key}{param_map} = $self->{param_map};
  1277.   $CACHE{$key}{parse_stack} = $self->{parse_stack};
  1278.   exists($self->{included_mtimes}) and
  1279.     $CACHE{$key}{included_mtimes} = $self->{included_mtimes};
  1280. }
  1281.  
  1282. # create a cache key from a template object.  The cache key includes
  1283. # the full path to the template and options which affect template
  1284. # loading.  Has the side-effect of loading $self->{options}{filepath}
  1285. sub _cache_key {
  1286.     my $self = shift;
  1287.     my $options = $self->{options};
  1288.  
  1289.     # determine path to file unless already known
  1290.     my $filepath = $options->{filepath};
  1291.     if (not defined $filepath) {
  1292.         $filepath = $self->_find_file($options->{filename});
  1293.         confess("HTML::Template->new() : Cannot find file '$options->{filename}'.")
  1294.           unless defined($filepath);
  1295.         $options->{filepath} = $filepath;   
  1296.     }
  1297.  
  1298.     # assemble pieces of the key
  1299.     my @key = ($filepath);
  1300.     push(@key, @{$options->{path}}) if $options->{path};
  1301.     push(@key, $options->{search_path_on_include} || 0);
  1302.     push(@key, $options->{loop_context_vars} || 0);
  1303.     push(@key, $options->{global_vars} || 0);
  1304.  
  1305.     # compute the md5 and return it
  1306.     return md5_hex(@key);
  1307. }
  1308.  
  1309. # generates MD5 from filepath to determine filename for cache file
  1310. sub _get_cache_filename {
  1311.   my ($self, $filepath) = @_;
  1312.  
  1313.   # get a cache key
  1314.   $self->{options}{filepath} = $filepath;
  1315.   my $hash = $self->_cache_key();
  1316.   
  1317.   # ... and build a path out of it.  Using the first two charcters
  1318.   # gives us 255 buckets.  This means you can have 255,000 templates
  1319.   # in the cache before any one directory gets over a few thousand
  1320.   # files in it.  That's probably pretty good for this planet.  If not
  1321.   # then it should be configurable.
  1322.   if (wantarray) {
  1323.     return (substr($hash,0,2), substr($hash,2))
  1324.   } else {
  1325.     return File::Spec->join($self->{options}{file_cache_dir}, 
  1326.                             substr($hash,0,2), substr($hash,2));
  1327.   }
  1328. }
  1329.  
  1330. # handles the file cache
  1331. sub _fetch_from_file_cache {
  1332.   my $self = shift;
  1333.   my $options = $self->{options};
  1334.   return unless exists($options->{filename});
  1335.   
  1336.   # return if there's no cache entry for this filename
  1337.   my $filepath = $self->_find_file($options->{filename});
  1338.   return unless defined $filepath;
  1339.   my $cache_filename = $self->_get_cache_filename($filepath);
  1340.   return unless -e $cache_filename;
  1341.   
  1342.   eval {
  1343.     $self->{record} = Storable::lock_retrieve($cache_filename);
  1344.   };
  1345.   croak("HTML::Template::new() - Problem reading cache file $cache_filename (file_cache => 1) : $@")
  1346.     if $@;
  1347.   croak("HTML::Template::new() - Problem reading cache file $cache_filename (file_cache => 1) : $!") 
  1348.     unless defined $self->{record};
  1349.  
  1350.   ($self->{mtime}, 
  1351.    $self->{included_mtimes}, 
  1352.    $self->{param_map}, 
  1353.    $self->{parse_stack}) = @{$self->{record}};
  1354.   
  1355.   $options->{filepath} = $filepath;
  1356.  
  1357.   # validate the cache
  1358.   my $mtime = $self->_mtime($filepath);
  1359.   if (defined $mtime) {
  1360.     # return if the mtime doesn't match the cache
  1361.     if (defined($self->{mtime}) and 
  1362.         ($mtime != $self->{mtime})) {
  1363.       $options->{cache_debug} and 
  1364.         print STDERR "### HTML::Template Cache Debug ### FILE CACHE MISS : $filepath : $mtime\n";
  1365.       ($self->{mtime}, 
  1366.        $self->{included_mtimes}, 
  1367.        $self->{param_map}, 
  1368.        $self->{parse_stack}) = (undef, undef, undef, undef);
  1369.       return;
  1370.     }
  1371.  
  1372.     # if the template has includes, check each included file's mtime
  1373.     # and return if different
  1374.     if (exists($self->{included_mtimes})) {
  1375.       foreach my $filename (keys %{$self->{included_mtimes}}) {
  1376.         next unless 
  1377.           defined($self->{included_mtimes}{$filename});
  1378.         
  1379.         my $included_mtime = (stat($filename))[9];
  1380.         if ($included_mtime != $self->{included_mtimes}{$filename}) {
  1381.           $options->{cache_debug} and 
  1382.             print STDERR "### HTML::Template Cache Debug ### FILE CACHE MISS : $filepath : INCLUDE $filename : $included_mtime\n";
  1383.           ($self->{mtime}, 
  1384.            $self->{included_mtimes}, 
  1385.            $self->{param_map}, 
  1386.            $self->{parse_stack}) = (undef, undef, undef, undef);
  1387.           return;
  1388.         }
  1389.       }
  1390.     }
  1391.   }
  1392.  
  1393.   # got a cache hit!
  1394.   $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### FILE CACHE HIT : $filepath\n";
  1395.  
  1396.   # clear out values from param_map from last run
  1397.   $self->_normalize_options();
  1398.   $self->clear_params();
  1399. }
  1400.  
  1401. sub _commit_to_file_cache {
  1402.   my $self = shift;
  1403.   my $options = $self->{options};
  1404.  
  1405.   my $filepath = $options->{filepath};
  1406.   if (not defined $filepath) {
  1407.     $filepath = $self->_find_file($options->{filename});
  1408.     confess("HTML::Template->new() : Cannot open included file $options->{filename} : file not found.")
  1409.       unless defined($filepath);
  1410.     $options->{filepath} = $filepath;   
  1411.   }
  1412.  
  1413.   my ($cache_dir, $cache_file) = $self->_get_cache_filename($filepath);  
  1414.   $cache_dir = File::Spec->join($options->{file_cache_dir}, $cache_dir);
  1415.   if (not -d $cache_dir) {
  1416.     if (not -d $options->{file_cache_dir}) {
  1417.       mkdir($options->{file_cache_dir},$options->{file_cache_dir_mode})
  1418.     or croak("HTML::Template->new() : can't mkdir $options->{file_cache_dir} (file_cache => 1): $!");
  1419.     }
  1420.     mkdir($cache_dir,$options->{file_cache_dir_mode})
  1421.       or croak("HTML::Template->new() : can't mkdir $cache_dir (file_cache => 1): $!");
  1422.   }
  1423.  
  1424.   $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### FILE CACHE LOAD : $options->{filepath}\n";
  1425.  
  1426.   my $result;
  1427.   eval {
  1428.     $result = Storable::lock_store([ $self->{mtime},
  1429.                                      $self->{included_mtimes}, 
  1430.                                      $self->{param_map}, 
  1431.                                      $self->{parse_stack} ],
  1432.                                    scalar File::Spec->join($cache_dir, $cache_file)
  1433.                                   );
  1434.   };
  1435.   croak("HTML::Template::new() - Problem writing cache file $cache_dir/$cache_file (file_cache => 1) : $@")
  1436.     if $@;
  1437.   croak("HTML::Template::new() - Problem writing cache file $cache_dir/$cache_file (file_cache => 1) : $!")
  1438.     unless defined $result;
  1439. }
  1440.  
  1441. # Shared cache routines.
  1442. sub _fetch_from_shared_cache {
  1443.   my $self = shift;
  1444.   my $options = $self->{options};
  1445.  
  1446.   my $filepath = $self->_find_file($options->{filename});
  1447.   return unless defined $filepath;
  1448.  
  1449.   # fetch from the shared cache.
  1450.   $self->{record} = $self->{cache}{$filepath};
  1451.   
  1452.   ($self->{mtime}, 
  1453.    $self->{included_mtimes}, 
  1454.    $self->{param_map}, 
  1455.    $self->{parse_stack}) = @{$self->{record}}
  1456.      if defined($self->{record});
  1457.   
  1458.   $options->{cache_debug} and defined($self->{record}) and print STDERR "### HTML::Template Cache Debug ### CACHE HIT : $filepath\n";
  1459.   # clear out values from param_map from last run
  1460.   $self->_normalize_options(), $self->clear_params()
  1461.     if (defined($self->{record}));
  1462.   delete($self->{record});
  1463.  
  1464.   return $self;
  1465. }
  1466.  
  1467. sub _validate_shared_cache {
  1468.   my ($self, $filename, $record) = @_;
  1469.   my $options = $self->{options};
  1470.  
  1471.   $options->{shared_cache_debug} and print STDERR "### HTML::Template Cache Debug ### SHARED CACHE VALIDATE : $filename\n";
  1472.  
  1473.   return 1 if $options->{blind_cache};
  1474.  
  1475.   my ($c_mtime, $included_mtimes, $param_map, $parse_stack) = @$record;
  1476.  
  1477.   # if the modification time has changed return false
  1478.   my $mtime = $self->_mtime($filename);
  1479.   if (defined $mtime and defined $c_mtime
  1480.       and $mtime != $c_mtime) {
  1481.     $options->{cache_debug} and 
  1482.       print STDERR "### HTML::Template Cache Debug ### SHARED CACHE MISS : $filename : $mtime\n";
  1483.     return 0;
  1484.   }
  1485.  
  1486.   # if the template has includes, check each included file's mtime
  1487.   # and return false if different
  1488.   if (defined $mtime and defined $included_mtimes) {
  1489.     foreach my $fname (keys %$included_mtimes) {
  1490.       next unless defined($included_mtimes->{$fname});
  1491.       if ($included_mtimes->{$fname} != (stat($fname))[9]) {
  1492.         $options->{cache_debug} and 
  1493.           print STDERR "### HTML::Template Cache Debug ### SHARED CACHE MISS : $filename : INCLUDE $fname\n";
  1494.         return 0;
  1495.       }
  1496.     }
  1497.   }
  1498.  
  1499.   # all done - return true
  1500.   return 1;
  1501. }
  1502.  
  1503. sub _load_shared_cache {
  1504.   my ($self, $filename) = @_;
  1505.   my $options = $self->{options};
  1506.   my $cache = $self->{cache};
  1507.   
  1508.   $self->_init_template();
  1509.   $self->_parse();
  1510.  
  1511.   $options->{cache_debug} and print STDERR "### HTML::Template Cache Debug ### SHARED CACHE LOAD : $options->{filepath}\n";
  1512.   
  1513.   print STDERR "### HTML::Template Memory Debug ### END CACHE LOAD ", $self->{proc_mem}->size(), "\n"
  1514.     if $options->{memory_debug};
  1515.  
  1516.   return [ $self->{mtime},
  1517.            $self->{included_mtimes}, 
  1518.            $self->{param_map}, 
  1519.            $self->{parse_stack} ]; 
  1520. }
  1521.  
  1522. # utility function - given a filename performs documented search and
  1523. # returns a full path of undef if the file cannot be found.
  1524. sub _find_file {
  1525.   my ($self, $filename, $extra_path) = @_;
  1526.   my $options = $self->{options};
  1527.   my $filepath;
  1528.  
  1529.   # first check for a full path
  1530.   return File::Spec->canonpath($filename)
  1531.     if (File::Spec->file_name_is_absolute($filename) and (-e $filename));
  1532.  
  1533.   # try the extra_path if one was specified
  1534.   if (defined($extra_path)) {
  1535.     $extra_path->[$#{$extra_path}] = $filename;
  1536.     $filepath = File::Spec->canonpath(File::Spec->catfile(@$extra_path));
  1537.     return File::Spec->canonpath($filepath) if -e $filepath;
  1538.   }
  1539.  
  1540.   # try pre-prending HTML_Template_Root
  1541.   if (exists($ENV{HTML_TEMPLATE_ROOT}) and defined($ENV{HTML_TEMPLATE_ROOT})) {
  1542.     $filepath =  File::Spec->catfile($ENV{HTML_TEMPLATE_ROOT}, $filename);
  1543.     return File::Spec->canonpath($filepath) if -e $filepath;
  1544.   }
  1545.  
  1546.   # try "path" option list..
  1547.   foreach my $path (@{$options->{path}}) {
  1548.     $filepath = File::Spec->catfile($path, $filename);
  1549.     return File::Spec->canonpath($filepath) if -e $filepath;
  1550.   }
  1551.  
  1552.   # try even a relative path from the current directory...
  1553.   return File::Spec->canonpath($filename) if -e $filename;
  1554.  
  1555.   # try "path" option list with HTML_TEMPLATE_ROOT prepended...
  1556.   if (exists($ENV{HTML_TEMPLATE_ROOT})) {
  1557.     foreach my $path (@{$options->{path}}) {
  1558.       $filepath = File::Spec->catfile($ENV{HTML_TEMPLATE_ROOT}, $path, $filename);
  1559.       return File::Spec->canonpath($filepath) if -e $filepath;
  1560.     }
  1561.   }
  1562.   
  1563.   return undef;
  1564. }
  1565.  
  1566. # utility function - computes the mtime for $filename
  1567. sub _mtime {
  1568.   my ($self, $filepath) = @_;
  1569.   my $options = $self->{options};
  1570.   
  1571.   return(undef) if ($options->{blind_cache});
  1572.  
  1573.   # make sure it still exists in the filesystem 
  1574.   (-r $filepath) or Carp::confess("HTML::Template : template file $filepath does not exist or is unreadable.");
  1575.   
  1576.   # get the modification time
  1577.   return (stat(_))[9];
  1578. }
  1579.  
  1580. # utility function - enforces new() options across LOOPs that have
  1581. # come from a cache.  Otherwise they would have stale options hashes.
  1582. sub _normalize_options {
  1583.   my $self = shift;
  1584.   my $options = $self->{options};
  1585.  
  1586.   my @pstacks = ($self->{parse_stack});
  1587.   while(@pstacks) {
  1588.     my $pstack = pop(@pstacks);
  1589.     foreach my $item (@$pstack) {
  1590.       next unless (ref($item) eq 'HTML::Template::LOOP');
  1591.       foreach my $template (values %{$item->[HTML::Template::LOOP::TEMPLATE_HASH]}) {
  1592.         # must be the same list as the call to _new_from_loop...
  1593.         $template->{options}{debug} = $options->{debug};
  1594.         $template->{options}{stack_debug} = $options->{stack_debug};
  1595.         $template->{options}{die_on_bad_params} = $options->{die_on_bad_params};
  1596.         $template->{options}{case_sensitive} = $options->{case_sensitive};
  1597.  
  1598.         push(@pstacks, $template->{parse_stack});
  1599.       }
  1600.     }
  1601.   }
  1602. }      
  1603.  
  1604. # initialize the template buffer
  1605. sub _init_template {
  1606.   my $self = shift;
  1607.   my $options = $self->{options};
  1608.  
  1609.   print STDERR "### HTML::Template Memory Debug ### START INIT_TEMPLATE ", $self->{proc_mem}->size(), "\n"
  1610.     if $options->{memory_debug};
  1611.  
  1612.   if (exists($options->{filename})) {    
  1613.     my $filepath = $options->{filepath};
  1614.     if (not defined $filepath) {
  1615.       $filepath = $self->_find_file($options->{filename});
  1616.       confess("HTML::Template->new() : Cannot open included file $options->{filename} : file not found.")
  1617.         unless defined($filepath);
  1618.       # we'll need this for future reference - to call stat() for example.
  1619.       $options->{filepath} = $filepath;   
  1620.     }
  1621.  
  1622.     confess("HTML::Template->new() : Cannot open included file $options->{filename} : $!")
  1623.         unless defined(open(TEMPLATE, $filepath));
  1624.     $self->{mtime} = $self->_mtime($filepath);
  1625.  
  1626.     # read into scalar, note the mtime for the record
  1627.     $self->{template} = "";
  1628.     while (read(TEMPLATE, $self->{template}, 10240, length($self->{template}))) {}
  1629.     close(TEMPLATE);
  1630.  
  1631.   } elsif (exists($options->{scalarref})) {
  1632.     # copy in the template text
  1633.     $self->{template} = ${$options->{scalarref}};
  1634.  
  1635.     delete($options->{scalarref});
  1636.   } elsif (exists($options->{arrayref})) {
  1637.     # if we have an array ref, join and store the template text
  1638.     $self->{template} = join("", @{$options->{arrayref}});
  1639.  
  1640.     delete($options->{arrayref});
  1641.   } elsif (exists($options->{filehandle})) {
  1642.     # just read everything in in one go
  1643.     local $/ = undef;
  1644.     $self->{template} = readline($options->{filehandle});
  1645.  
  1646.     delete($options->{filehandle});
  1647.   } else {
  1648.     confess("HTML::Template : Need to call new with filename, filehandle, scalarref or arrayref parameter specified.");
  1649.   }
  1650.  
  1651.   print STDERR "### HTML::Template Memory Debug ### END INIT_TEMPLATE ", $self->{proc_mem}->size(), "\n"
  1652.     if $options->{memory_debug};
  1653.  
  1654.   # handle filters if necessary
  1655.   $self->_call_filters(\$self->{template}) if @{$options->{filter}};
  1656.  
  1657.   return $self;
  1658. }
  1659.  
  1660. # handle calling user defined filters
  1661. sub _call_filters {
  1662.   my $self = shift;
  1663.   my $template_ref = shift;
  1664.   my $options = $self->{options};
  1665.  
  1666.   my ($format, $sub);
  1667.   foreach my $filter (@{$options->{filter}}) {
  1668.     croak("HTML::Template->new() : bad value set for filter parameter - must be a code ref or a hash ref.")
  1669.       unless ref $filter;
  1670.  
  1671.     # translate into CODE->HASH
  1672.     $filter = { 'format' => 'scalar', 'sub' => $filter }
  1673.       if (ref $filter eq 'CODE');
  1674.  
  1675.     if (ref $filter eq 'HASH') {
  1676.       $format = $filter->{'format'};
  1677.       $sub = $filter->{'sub'};
  1678.  
  1679.       # check types and values
  1680.       croak("HTML::Template->new() : bad value set for filter parameter - hash must contain \"format\" key and \"sub\" key.")
  1681.         unless defined $format and defined $sub;
  1682.       croak("HTML::Template->new() : bad value set for filter parameter - \"format\" must be either 'array' or 'scalar'")
  1683.         unless $format eq 'array' or $format eq 'scalar';
  1684.       croak("HTML::Template->new() : bad value set for filter parameter - \"sub\" must be a code ref")
  1685.         unless ref $sub and ref $sub eq 'CODE';
  1686.  
  1687.       # catch errors
  1688.       eval {
  1689.         if ($format eq 'scalar') {
  1690.           # call
  1691.           $sub->($template_ref);
  1692.         } else {
  1693.       # modulate
  1694.       my @array = map { $_."\n" } split("\n", $$template_ref);
  1695.           # call
  1696.           $sub->(\@array);
  1697.       # demodulate
  1698.       $$template_ref = join("", @array);
  1699.         }
  1700.       };
  1701.       croak("HTML::Template->new() : fatal error occured during filter call: $@") if $@;
  1702.     } else {
  1703.       croak("HTML::Template->new() : bad value set for filter parameter - must be code ref or hash ref");
  1704.     }
  1705.   }
  1706.   # all done
  1707.   return $template_ref;
  1708. }
  1709.  
  1710. # _parse sifts through a template building up the param_map and
  1711. # parse_stack structures.
  1712. #
  1713. # The end result is a Template object that is fully ready for
  1714. # output().
  1715. sub _parse {
  1716.   my $self = shift;
  1717.   my $options = $self->{options};
  1718.   
  1719.   $options->{debug} and print STDERR "### HTML::Template Debug ### In _parse:\n";
  1720.   
  1721.   # setup the stacks and maps - they're accessed by typeglobs that
  1722.   # reference the top of the stack.  They are masked so that a loop
  1723.   # can transparently have its own versions.
  1724.   use vars qw(@pstack %pmap @ifstack @ucstack %top_pmap);
  1725.   local (*pstack, *ifstack, *pmap, *ucstack, *top_pmap);
  1726.   
  1727.   # the pstack is the array of scalar refs (plain text from the
  1728.   # template file), VARs, LOOPs, IFs and ELSEs that output() works on
  1729.   # to produce output.  Looking at output() should make it clear what
  1730.   # _parse is trying to accomplish.
  1731.   my @pstacks = ([]);
  1732.   *pstack = $pstacks[0];
  1733.   $self->{parse_stack} = $pstacks[0];
  1734.   
  1735.   # the pmap binds names to VARs, LOOPs and IFs.  It allows param() to
  1736.   # access the right variable.  NOTE: output() does not look at the
  1737.   # pmap at all!
  1738.   my @pmaps = ({});
  1739.   *pmap = $pmaps[0];
  1740.   *top_pmap = $pmaps[0];
  1741.   $self->{param_map} = $pmaps[0];
  1742.  
  1743.   # the ifstack is a temporary stack containing pending ifs and elses
  1744.   # waiting for a /if.
  1745.   my @ifstacks = ([]);
  1746.   *ifstack = $ifstacks[0];
  1747.  
  1748.   # the ucstack is a temporary stack containing conditions that need
  1749.   # to be bound to param_map entries when their block is finished.
  1750.   # This happens when a conditional is encountered before any other
  1751.   # reference to its NAME.  Since a conditional can reference VARs and
  1752.   # LOOPs it isn't possible to make the link right away.
  1753.   my @ucstacks = ([]);
  1754.   *ucstack = $ucstacks[0];
  1755.   
  1756.   # the loopstack is another temp stack for closing loops.  unlike
  1757.   # those above it doesn't get scoped inside loops, therefore it
  1758.   # doesn't need the typeglob magic.
  1759.   my @loopstack = ();
  1760.  
  1761.   # the fstack is a stack of filenames and counters that keeps track
  1762.   # of which file we're in and where we are in it.  This allows
  1763.   # accurate error messages even inside included files!
  1764.   # fcounter, fmax and fname are aliases for the current file's info
  1765.   use vars qw($fcounter $fname $fmax);
  1766.   local (*fcounter, *fname, *fmax);
  1767.  
  1768.   my @fstack = ([$options->{filepath} || "/fake/path/for/non/file/template",
  1769.                  1, 
  1770.                  scalar @{[$self->{template} =~ m/(\n)/g]} + 1
  1771.                 ]);
  1772.   (*fname, *fcounter, *fmax) = \ ( @{$fstack[0]} );
  1773.  
  1774.   my $NOOP = HTML::Template::NOOP->new();
  1775.   my $ESCAPE = HTML::Template::ESCAPE->new();
  1776.   my $JSESCAPE = HTML::Template::JSESCAPE->new();
  1777.   my $URLESCAPE = HTML::Template::URLESCAPE->new();
  1778.  
  1779.   # all the tags that need NAMEs:
  1780.   my %need_names = map { $_ => 1 } 
  1781.     qw(TMPL_VAR TMPL_LOOP TMPL_IF TMPL_UNLESS TMPL_INCLUDE);
  1782.     
  1783.   # variables used below that don't need to be my'd in the loop
  1784.   my ($name, $which, $escape, $default);
  1785.  
  1786.   # handle the old vanguard format
  1787.   $options->{vanguard_compatibility_mode} and 
  1788.     $self->{template} =~ s/%([-\w\/\.+]+)%/<TMPL_VAR NAME=$1>/g;
  1789.  
  1790.   # now split up template on '<', leaving them in
  1791.   my @chunks = split(m/(?=<)/, $self->{template});
  1792.  
  1793.   # all done with template
  1794.   delete $self->{template};
  1795.  
  1796.   # loop through chunks, filling up pstack
  1797.   my $last_chunk =  $#chunks;
  1798.  CHUNK: for (my $chunk_number = 0;
  1799.         $chunk_number <= $last_chunk;
  1800.         $chunk_number++) {
  1801.     next unless defined $chunks[$chunk_number]; 
  1802.     my $chunk = $chunks[$chunk_number];
  1803.     
  1804.     # a general regex to match any and all TMPL_* tags 
  1805.     if ($chunk =~ /^<
  1806.                     (?:!--\s*)?
  1807.                     (
  1808.                       \/?[Tt][Mm][Pp][Ll]_
  1809.                       (?:
  1810.                          (?:[Vv][Aa][Rr])
  1811.                          |
  1812.                          (?:[Ll][Oo][Oo][Pp])
  1813.                          |
  1814.                          (?:[Ii][Ff])
  1815.                          |
  1816.                          (?:[Ee][Ll][Ss][Ee])
  1817.                          |
  1818.                          (?:[Uu][Nn][Ll][Ee][Ss][Ss])
  1819.                          |
  1820.                          (?:[Ii][Nn][Cc][Ll][Uu][Dd][Ee])
  1821.                       )
  1822.                     ) # $1 => $which - start of the tag
  1823.  
  1824.                     \s* 
  1825.  
  1826.                     # DEFAULT attribute
  1827.                     (?:
  1828.                       [Dd][Ee][Ff][Aa][Uu][Ll][Tt]
  1829.                       \s*=\s*
  1830.                       (?:
  1831.                         "([^">]*)"  # $2 => double-quoted DEFAULT value "
  1832.                         |
  1833.                         '([^'>]*)'  # $3 => single-quoted DEFAULT value
  1834.                         |
  1835.                         ([^\s=>]*)  # $4 => unquoted DEFAULT value
  1836.                       )
  1837.                     )?
  1838.  
  1839.                     \s*
  1840.  
  1841.                     # ESCAPE attribute
  1842.                     (?:
  1843.                       [Ee][Ss][Cc][Aa][Pp][Ee]
  1844.                       \s*=\s*
  1845.                       (?:
  1846.                          (?: 0 | (?:"0") | (?:'0') )
  1847.                          |
  1848.                          ( 1 | (?:"1") | (?:'1') | 
  1849.                            (?:[Hh][Tt][Mm][Ll]) | 
  1850.                            (?:"[Hh][Tt][Mm][Ll]") |
  1851.                            (?:'[Hh][Tt][Mm][Ll]') |
  1852.                            (?:[Uu][Rr][Ll]) | 
  1853.                            (?:"[Uu][Rr][Ll]") |
  1854.                            (?:'[Uu][Rr][Ll]') |
  1855.                            (?:[Jj][Ss]) |
  1856.                            (?:"[Jj][Ss]") |
  1857.                            (?:'[Jj][Ss]') |
  1858.                          )                         # $5 => ESCAPE on
  1859.                        )
  1860.                     )* # allow multiple ESCAPEs
  1861.  
  1862.                     \s*
  1863.  
  1864.                     # DEFAULT attribute
  1865.                     (?:
  1866.                       [Dd][Ee][Ff][Aa][Uu][Ll][Tt]
  1867.                       \s*=\s*
  1868.                       (?:
  1869.                         "([^">]*)"  # $6 => double-quoted DEFAULT value "
  1870.                         |
  1871.                         '([^'>]*)'  # $7 => single-quoted DEFAULT value
  1872.                         |
  1873.                         ([^\s=>]*)  # $8 => unquoted DEFAULT value
  1874.                       )
  1875.                     )?
  1876.  
  1877.                     \s*                    
  1878.  
  1879.                     # NAME attribute
  1880.                     (?:
  1881.                       (?:
  1882.                         [Nn][Aa][Mm][Ee]
  1883.                         \s*=\s*
  1884.                       )?
  1885.                       (?:
  1886.                         "([^">]*)"  # $9 => double-quoted NAME value "
  1887.                         |
  1888.                         '([^'>]*)'  # $10 => single-quoted NAME value
  1889.                         |
  1890.                         ([^\s=>]*)  # $11 => unquoted NAME value
  1891.                       )
  1892.                     )? 
  1893.                     
  1894.                     \s*
  1895.  
  1896.                     # DEFAULT attribute
  1897.                     (?:
  1898.                       [Dd][Ee][Ff][Aa][Uu][Ll][Tt]
  1899.                       \s*=\s*
  1900.                       (?:
  1901.                         "([^">]*)"  # $12 => double-quoted DEFAULT value "
  1902.                         |
  1903.                         '([^'>]*)'  # $13 => single-quoted DEFAULT value
  1904.                         |
  1905.                         ([^\s=>]*)  # $14 => unquoted DEFAULT value
  1906.                       )
  1907.                     )?
  1908.  
  1909.                     \s*
  1910.  
  1911.                     # ESCAPE attribute
  1912.                     (?:
  1913.                       [Ee][Ss][Cc][Aa][Pp][Ee]
  1914.                       \s*=\s*
  1915.                       (?:
  1916.                          (?: 0 | (?:"0") | (?:'0') )
  1917.                          |
  1918.                          ( 1 | (?:"1") | (?:'1') | 
  1919.                            (?:[Hh][Tt][Mm][Ll]) | 
  1920.                            (?:"[Hh][Tt][Mm][Ll]") |
  1921.                            (?:'[Hh][Tt][Mm][Ll]') |
  1922.                            (?:[Uu][Rr][Ll]) | 
  1923.                            (?:"[Uu][Rr][Ll]") |
  1924.                            (?:'[Uu][Rr][Ll]') |
  1925.                            (?:[Jj][Ss]) |
  1926.                            (?:"[Jj][Ss]") |
  1927.                            (?:'[Jj][Ss]') |
  1928.                          )                         # $15 => ESCAPE on
  1929.                        )
  1930.                     )* # allow multiple ESCAPEs
  1931.  
  1932.                     \s*
  1933.  
  1934.                     # DEFAULT attribute
  1935.                     (?:
  1936.                       [Dd][Ee][Ff][Aa][Uu][Ll][Tt]
  1937.                       \s*=\s*
  1938.                       (?:
  1939.                         "([^">]*)"  # $16 => double-quoted DEFAULT value "
  1940.                         |
  1941.                         '([^'>]*)'  # $17 => single-quoted DEFAULT value
  1942.                         |
  1943.                         ([^\s=>]*)  # $18 => unquoted DEFAULT value
  1944.                       )
  1945.                     )?
  1946.  
  1947.                     \s*
  1948.  
  1949.                     (?:--)?>                    
  1950.                     (.*) # $19 => $post - text that comes after the tag
  1951.                    $/sx) {
  1952.  
  1953.       $which = uc($1); # which tag is it
  1954.  
  1955.       $escape = defined $5 ? $5 : defined $15 ? $15 : 0; # escape set?
  1956.       
  1957.       # what name for the tag?  undef for a /tag at most, one of the
  1958.       # following three will be defined
  1959.       $name = defined $9 ? $9 : defined $10 ? $10 : defined $11 ? $11 : undef;
  1960.  
  1961.       # is there a default?
  1962.       $default = defined $2  ? $2  : defined $3  ? $3  : defined $4  ? $4 : 
  1963.                  defined $6  ? $6  : defined $7  ? $7  : defined $8  ? $8 : 
  1964.                  defined $12 ? $12 : defined $13 ? $13 : defined $14 ? $14 : 
  1965.                  defined $16 ? $16 : defined $17 ? $17 : defined $18 ? $18 :
  1966.                  undef;
  1967.  
  1968.       my $post = $19; # what comes after on the line
  1969.  
  1970.       # allow mixed case in filenames, otherwise flatten
  1971.       $name = lc($name) unless (not defined $name or $which eq 'TMPL_INCLUDE' or $options->{case_sensitive});
  1972.  
  1973.       # die if we need a name and didn't get one
  1974.       die "HTML::Template->new() : No NAME given to a $which tag at $fname : line $fcounter." 
  1975.         if ($need_names{$which} and (not defined $name or not length $name));
  1976.  
  1977.       # die if we got an escape but can't use one
  1978.       die "HTML::Template->new() : ESCAPE option invalid in a $which tag at $fname : line $fcounter." if ( $escape and ($which ne 'TMPL_VAR'));
  1979.  
  1980.       # die if we got a default but can't use one
  1981.       die "HTML::Template->new() : DEFAULT option invalid in a $which tag at $fname : line $fcounter." if ( defined $default and ($which ne 'TMPL_VAR'));
  1982.         
  1983.       # take actions depending on which tag found
  1984.       if ($which eq 'TMPL_VAR') {
  1985.     $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : parsed VAR $name\n";
  1986.     
  1987.     # if we already have this var, then simply link to the existing
  1988.     # HTML::Template::VAR, else create a new one.        
  1989.     my $var;        
  1990.     if (exists $pmap{$name}) {
  1991.       $var = $pmap{$name};
  1992.       (ref($var) eq 'HTML::Template::VAR') or
  1993.         die "HTML::Template->new() : Already used param name $name as a TMPL_LOOP, found in a TMPL_VAR at $fname : line $fcounter.";
  1994.     } else {
  1995.       $var = HTML::Template::VAR->new();
  1996.       $pmap{$name} = $var;
  1997.       $top_pmap{$name} = HTML::Template::VAR->new()
  1998.         if $options->{global_vars} and not exists $top_pmap{$name};
  1999.     }
  2000.  
  2001.         # if a DEFAULT was provided, push a DEFAULT object on the
  2002.         # stack before the variable.
  2003.     if (defined $default) {
  2004.             push(@pstack, HTML::Template::DEFAULT->new($default));
  2005.         }
  2006.     
  2007.     # if ESCAPE was set, push an ESCAPE op on the stack before
  2008.     # the variable.  output will handle the actual work.
  2009.     if ($escape) {
  2010.           if ($escape =~ /^["']?[Uu][Rr][Ll]["']?$/) {
  2011.         push(@pstack, $URLESCAPE);
  2012.       } elsif ($escape =~ /^"?[Jj][Ss]"?$/) {
  2013.         push(@pstack, $JSESCAPE);
  2014.       } else {
  2015.         push(@pstack, $ESCAPE);
  2016.       }
  2017.     }
  2018.  
  2019.     push(@pstack, $var);
  2020.     
  2021.       } elsif ($which eq 'TMPL_LOOP') {
  2022.     # we've got a loop start
  2023.     $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : LOOP $name start\n";
  2024.     
  2025.     # if we already have this loop, then simply link to the existing
  2026.     # HTML::Template::LOOP, else create a new one.
  2027.     my $loop;
  2028.     if (exists $pmap{$name}) {
  2029.       $loop = $pmap{$name};
  2030.       (ref($loop) eq 'HTML::Template::LOOP') or
  2031.         die "HTML::Template->new() : Already used param name $name as a TMPL_VAR, TMPL_IF or TMPL_UNLESS, found in a TMP_LOOP at $fname : line $fcounter!";
  2032.       
  2033.     } else {
  2034.       # store the results in a LOOP object - actually just a
  2035.       # thin wrapper around another HTML::Template object.
  2036.       $loop = HTML::Template::LOOP->new();
  2037.       $pmap{$name} = $loop;
  2038.     }
  2039.     
  2040.     # get it on the loopstack, pstack of the enclosing block
  2041.     push(@pstack, $loop);
  2042.     push(@loopstack, [$loop, $#pstack]);
  2043.     
  2044.     # magic time - push on a fresh pmap and pstack, adjust the typeglobs.
  2045.     # this gives the loop a separate namespace (i.e. pmap and pstack).
  2046.     push(@pstacks, []);
  2047.     *pstack = $pstacks[$#pstacks];
  2048.     push(@pmaps, {});
  2049.     *pmap = $pmaps[$#pmaps];
  2050.     push(@ifstacks, []);
  2051.     *ifstack = $ifstacks[$#ifstacks];
  2052.     push(@ucstacks, []);
  2053.     *ucstack = $ucstacks[$#ucstacks];
  2054.     
  2055.     # auto-vivify __FIRST__, __LAST__ and __INNER__ if
  2056.     # loop_context_vars is set.  Otherwise, with
  2057.     # die_on_bad_params set output() will might cause errors
  2058.     # when it tries to set them.
  2059.     if ($options->{loop_context_vars}) {
  2060.       $pmap{__first__}   = HTML::Template::VAR->new();
  2061.       $pmap{__inner__}   = HTML::Template::VAR->new();
  2062.       $pmap{__last__}    = HTML::Template::VAR->new();
  2063.       $pmap{__odd__}     = HTML::Template::VAR->new();
  2064.       $pmap{__counter__} = HTML::Template::VAR->new();
  2065.     }
  2066.     
  2067.       } elsif ($which eq '/TMPL_LOOP') {
  2068.     $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : LOOP end\n";
  2069.     
  2070.     my $loopdata = pop(@loopstack);
  2071.     die "HTML::Template->new() : found </TMPL_LOOP> with no matching <TMPL_LOOP> at $fname : line $fcounter!" unless defined $loopdata;
  2072.     
  2073.     my ($loop, $starts_at) = @$loopdata;
  2074.     
  2075.     # resolve pending conditionals
  2076.     foreach my $uc (@ucstack) {
  2077.       my $var = $uc->[HTML::Template::COND::VARIABLE]; 
  2078.       if (exists($pmap{$var})) {
  2079.         $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var};
  2080.       } else {
  2081.         $pmap{$var} = HTML::Template::VAR->new();
  2082.         $top_pmap{$var} = HTML::Template::VAR->new()
  2083.           if $options->{global_vars} and not exists $top_pmap{$var};
  2084.         $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var};
  2085.       }
  2086.       if (ref($pmap{$var}) eq 'HTML::Template::VAR') {
  2087.         $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_VAR;
  2088.       } else {
  2089.         $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_LOOP;
  2090.       }
  2091.     }
  2092.     
  2093.     # get pmap and pstack for the loop, adjust the typeglobs to
  2094.     # the enclosing block.
  2095.     my $param_map = pop(@pmaps);
  2096.     *pmap = $pmaps[$#pmaps];
  2097.     my $parse_stack = pop(@pstacks);
  2098.     *pstack = $pstacks[$#pstacks];
  2099.     
  2100.     scalar(@ifstack) and die "HTML::Template->new() : Dangling <TMPL_IF> or <TMPL_UNLESS> in loop ending at $fname : line $fcounter.";
  2101.     pop(@ifstacks);
  2102.     *ifstack = $ifstacks[$#ifstacks];
  2103.     pop(@ucstacks);
  2104.     *ucstack = $ucstacks[$#ucstacks];
  2105.     
  2106.     # instantiate the sub-Template, feeding it parse_stack and
  2107.     # param_map.  This means that only the enclosing template
  2108.     # does _parse() - sub-templates get their parse_stack and
  2109.     # param_map fed to them already filled in.
  2110.     $loop->[HTML::Template::LOOP::TEMPLATE_HASH]{$starts_at}             
  2111.       = HTML::Template->_new_from_loop(
  2112.                        parse_stack => $parse_stack,
  2113.                        param_map => $param_map,
  2114.                        debug => $options->{debug}, 
  2115.                        die_on_bad_params => $options->{die_on_bad_params}, 
  2116.                        loop_context_vars => $options->{loop_context_vars},
  2117.                                            case_sensitive => $options->{case_sensitive},
  2118.                       );
  2119.     
  2120.       } elsif ($which eq 'TMPL_IF' or $which eq 'TMPL_UNLESS' ) {
  2121.     $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : $which $name start\n";
  2122.     
  2123.     # if we already have this var, then simply link to the existing
  2124.     # HTML::Template::VAR/LOOP, else defer the mapping
  2125.     my $var;        
  2126.     if (exists $pmap{$name}) {
  2127.       $var = $pmap{$name};
  2128.     } else {
  2129.       $var = $name;
  2130.     }
  2131.     
  2132.     # connect the var to a conditional
  2133.     my $cond = HTML::Template::COND->new($var);
  2134.     if ($which eq 'TMPL_IF') {
  2135.       $cond->[HTML::Template::COND::WHICH] = HTML::Template::COND::WHICH_IF;
  2136.       $cond->[HTML::Template::COND::JUMP_IF_TRUE] = 0;
  2137.     } else {
  2138.       $cond->[HTML::Template::COND::WHICH] = HTML::Template::COND::WHICH_UNLESS;
  2139.       $cond->[HTML::Template::COND::JUMP_IF_TRUE] = 1;
  2140.     }
  2141.     
  2142.     # push unconnected conditionals onto the ucstack for
  2143.     # resolution later.  Otherwise, save type information now.
  2144.     if ($var eq $name) {
  2145.       push(@ucstack, $cond);
  2146.     } else {
  2147.       if (ref($var) eq 'HTML::Template::VAR') {
  2148.         $cond->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_VAR;
  2149.       } else {
  2150.         $cond->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_LOOP;
  2151.       }
  2152.     }
  2153.     
  2154.     # push what we've got onto the stacks
  2155.     push(@pstack, $cond);
  2156.     push(@ifstack, $cond);
  2157.     
  2158.       } elsif ($which eq '/TMPL_IF' or $which eq '/TMPL_UNLESS') {
  2159.     $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : $which end\n";
  2160.     
  2161.     my $cond = pop(@ifstack);
  2162.     die "HTML::Template->new() : found </${which}> with no matching <TMPL_IF> at $fname : line $fcounter." unless defined $cond;
  2163.     if ($which eq '/TMPL_IF') {
  2164.       die "HTML::Template->new() : found </TMPL_IF> incorrectly terminating a <TMPL_UNLESS> (use </TMPL_UNLESS>) at $fname : line $fcounter.\n" 
  2165.         if ($cond->[HTML::Template::COND::WHICH] == HTML::Template::COND::WHICH_UNLESS);
  2166.     } else {
  2167.       die "HTML::Template->new() : found </TMPL_UNLESS> incorrectly terminating a <TMPL_IF> (use </TMPL_IF>) at $fname : line $fcounter.\n" 
  2168.         if ($cond->[HTML::Template::COND::WHICH] == HTML::Template::COND::WHICH_IF);
  2169.     }
  2170.     
  2171.     # connect the matching to this "address" - place a NOOP to
  2172.     # hold the spot.  This allows output() to treat an IF in the
  2173.     # assembler-esque "Conditional Jump" mode.
  2174.     push(@pstack, $NOOP);
  2175.     $cond->[HTML::Template::COND::JUMP_ADDRESS] = $#pstack;
  2176.     
  2177.       } elsif ($which eq 'TMPL_ELSE') {
  2178.     $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : ELSE\n";
  2179.     
  2180.     my $cond = pop(@ifstack);
  2181.     die "HTML::Template->new() : found <TMPL_ELSE> with no matching <TMPL_IF> or <TMPL_UNLESS> at $fname : line $fcounter." unless defined $cond;
  2182.     
  2183.     
  2184.     my $else = HTML::Template::COND->new($cond->[HTML::Template::COND::VARIABLE]);
  2185.     $else->[HTML::Template::COND::WHICH] = $cond->[HTML::Template::COND::WHICH];
  2186.     $else->[HTML::Template::COND::JUMP_IF_TRUE] = not $cond->[HTML::Template::COND::JUMP_IF_TRUE];
  2187.     
  2188.     # need end-block resolution?
  2189.     if (defined($cond->[HTML::Template::COND::VARIABLE_TYPE])) {
  2190.       $else->[HTML::Template::COND::VARIABLE_TYPE] = $cond->[HTML::Template::COND::VARIABLE_TYPE];
  2191.     } else {
  2192.       push(@ucstack, $else);
  2193.     }
  2194.     
  2195.     push(@pstack, $else);
  2196.     push(@ifstack, $else);
  2197.     
  2198.     # connect the matching to this "address" - thus the if,
  2199.     # failing jumps to the ELSE address.  The else then gets
  2200.     # elaborated, and of course succeeds.  On the other hand, if
  2201.     # the IF fails and falls though, output will reach the else
  2202.     # and jump to the /if address.
  2203.     $cond->[HTML::Template::COND::JUMP_ADDRESS] = $#pstack;
  2204.     
  2205.       } elsif ($which eq 'TMPL_INCLUDE') {
  2206.     # handle TMPL_INCLUDEs
  2207.     $options->{debug} and print STDERR "### HTML::Template Debug ### $fname : line $fcounter : INCLUDE $name \n";
  2208.     
  2209.     # no includes here, bub
  2210.     $options->{no_includes} and croak("HTML::Template : Illegal attempt to use TMPL_INCLUDE in template file : (no_includes => 1)");
  2211.     
  2212.     my $filename = $name;
  2213.     
  2214.     # look for the included file...
  2215.     my $filepath;
  2216.     if ($options->{search_path_on_include}) {
  2217.       $filepath = $self->_find_file($filename);
  2218.     } else {
  2219.       $filepath = $self->_find_file($filename, 
  2220.                     [File::Spec->splitdir($fstack[-1][0])]
  2221.                        );
  2222.     }
  2223.     die "HTML::Template->new() : Cannot open included file $filename : file not found."
  2224.       unless defined($filepath);
  2225.     die "HTML::Template->new() : Cannot open included file $filename : $!"
  2226.       unless defined(open(TEMPLATE, $filepath));              
  2227.     
  2228.     # read into the array
  2229.     my $included_template = "";
  2230.         while(read(TEMPLATE, $included_template, 10240, length($included_template))) {}
  2231.     close(TEMPLATE);
  2232.     
  2233.     # call filters if necessary
  2234.     $self->_call_filters(\$included_template) if @{$options->{filter}};
  2235.     
  2236.     if ($included_template) { # not empty
  2237.       # handle the old vanguard format - this needs to happen here
  2238.       # since we're not about to do a next CHUNKS.
  2239.       $options->{vanguard_compatibility_mode} and 
  2240.         $included_template =~ s/%([-\w\/\.+]+)%/<TMPL_VAR NAME=$1>/g;
  2241.       
  2242.       # collect mtimes for included files
  2243.       if ($options->{cache} and !$options->{blind_cache}) {
  2244.         $self->{included_mtimes}{$filepath} = (stat($filepath))[9];
  2245.       }
  2246.       
  2247.       # adjust the fstack to point to the included file info
  2248.       push(@fstack, [$filepath, 1,
  2249.              scalar @{[$included_template =~ m/(\n)/g]} + 1]);
  2250.       (*fname, *fcounter, *fmax) = \ ( @{$fstack[$#fstack]} );
  2251.       
  2252.           # make sure we aren't infinitely recursing
  2253.           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}));
  2254.           
  2255.       # stick the remains of this chunk onto the bottom of the
  2256.       # included text.
  2257.       $included_template .= $post;
  2258.       $post = undef;
  2259.       
  2260.       # move the new chunks into place.  
  2261.       splice(@chunks, $chunk_number, 1,
  2262.          split(m/(?=<)/, $included_template));
  2263.  
  2264.       # recalculate stopping point
  2265.       $last_chunk = $#chunks;
  2266.  
  2267.       # start in on the first line of the included text - nothing
  2268.       # else to do on this line.
  2269.       $chunk = $chunks[$chunk_number];
  2270.  
  2271.       redo CHUNK;
  2272.     }
  2273.       } else {
  2274.     # zuh!?
  2275.     die "HTML::Template->new() : Unknown or unmatched TMPL construct at $fname : line $fcounter.";
  2276.       }
  2277.       # push the rest after the tag
  2278.       if (defined($post)) {
  2279.     if (ref($pstack[$#pstack]) eq 'SCALAR') {
  2280.       ${$pstack[$#pstack]} .= $post;
  2281.     } else {
  2282.       push(@pstack, \$post);
  2283.     }
  2284.       }
  2285.     } else { # just your ordinary markup
  2286.       # make sure we didn't reject something TMPL_* but badly formed
  2287.       if ($options->{strict}) {
  2288.     die "HTML::Template->new() : Syntax error in <TMPL_*> tag at $fname : $fcounter." if ($chunk =~ /<(?:!--\s*)?\/?[Tt][Mm][Pp][Ll]_/);
  2289.       }
  2290.       
  2291.       # push the rest and get next chunk
  2292.       if (defined($chunk)) {
  2293.     if (ref($pstack[$#pstack]) eq 'SCALAR') {
  2294.       ${$pstack[$#pstack]} .= $chunk;
  2295.     } else {
  2296.       push(@pstack, \$chunk);
  2297.     }
  2298.       }
  2299.     }
  2300.     # count newlines in chunk and advance line count
  2301.     $fcounter += scalar(@{[$chunk =~ m/(\n)/g]});
  2302.     # if we just crossed the end of an included file
  2303.     # pop off the record and re-alias to the enclosing file's info
  2304.     pop(@fstack), (*fname, *fcounter, *fmax) = \ ( @{$fstack[$#fstack]} )
  2305.       if ($fcounter > $fmax);
  2306.     
  2307.   } # next CHUNK
  2308.  
  2309.   # make sure we don't have dangling IF or LOOP blocks
  2310.   scalar(@ifstack) and die "HTML::Template->new() : At least one <TMPL_IF> or <TMPL_UNLESS> not terminated at end of file!";
  2311.   scalar(@loopstack) and die "HTML::Template->new() : At least one <TMPL_LOOP> not terminated at end of file!";
  2312.  
  2313.   # resolve pending conditionals
  2314.   foreach my $uc (@ucstack) {
  2315.     my $var = $uc->[HTML::Template::COND::VARIABLE]; 
  2316.     if (exists($pmap{$var})) {
  2317.       $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var};
  2318.     } else {
  2319.       $pmap{$var} = HTML::Template::VAR->new();
  2320.       $top_pmap{$var} = HTML::Template::VAR->new()
  2321.         if $options->{global_vars} and not exists $top_pmap{$var};
  2322.       $uc->[HTML::Template::COND::VARIABLE] = $pmap{$var};
  2323.     }
  2324.     if (ref($pmap{$var}) eq 'HTML::Template::VAR') {
  2325.       $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_VAR;
  2326.     } else {
  2327.       $uc->[HTML::Template::COND::VARIABLE_TYPE] = HTML::Template::COND::VARIABLE_TYPE_LOOP;
  2328.     }
  2329.   }
  2330.  
  2331.   # want a stack dump?
  2332.   if ($options->{stack_debug}) {
  2333.     require 'Data/Dumper.pm';
  2334.     print STDERR "### HTML::Template _param Stack Dump ###\n\n", Data::Dumper::Dumper($self->{parse_stack}), "\n";
  2335.   }
  2336.  
  2337.   # get rid of filters - they cause runtime errors if Storable tries
  2338.   # to store them.  This can happen under global_vars.
  2339.   delete $options->{filter};
  2340. }
  2341.  
  2342. # a recursive sub that associates each loop with the loops above
  2343. # (treating the top-level as a loop)
  2344. sub _globalize_vars {
  2345.   my $self = shift;
  2346.   
  2347.   # associate with the loop (and top-level templates) above in the tree.
  2348.   push(@{$self->{options}{associate}}, @_);
  2349.   
  2350.   # recurse down into the template tree, adding ourself to the end of
  2351.   # list.
  2352.   push(@_, $self);
  2353.   map { $_->_globalize_vars(@_) } 
  2354.     map {values %{$_->[HTML::Template::LOOP::TEMPLATE_HASH]}}
  2355.       grep { ref($_) eq 'HTML::Template::LOOP'} @{$self->{parse_stack}};
  2356. }
  2357.  
  2358. # method used to recursively un-hook associate
  2359. sub _unglobalize_vars {
  2360.   my $self = shift;
  2361.   
  2362.   # disassociate
  2363.   $self->{options}{associate} = undef;
  2364.   
  2365.   # recurse down into the template tree disassociating
  2366.   map { $_->_unglobalize_vars() } 
  2367.     map {values %{$_->[HTML::Template::LOOP::TEMPLATE_HASH]}}
  2368.       grep { ref($_) eq 'HTML::Template::LOOP'} @{$self->{parse_stack}};
  2369. }
  2370.  
  2371. =head2 param()
  2372.  
  2373. param() can be called in a number of ways
  2374.  
  2375. 1) To return a list of parameters in the template :
  2376.  
  2377.    my @parameter_names = $self->param();
  2378.  
  2379.  
  2380. 2) To return the value set to a param :
  2381.  
  2382.    my $value = $self->param('PARAM');
  2383.  
  2384. 3) To set the value of a parameter :
  2385.  
  2386.       # For simple TMPL_VARs:
  2387.       $self->param(PARAM => 'value');
  2388.  
  2389.       # with a subroutine reference that gets called to get the value
  2390.       # of the scalar.  The sub will recieve the template object as a
  2391.       # parameter.
  2392.       $self->param(PARAM => sub { return 'value' });
  2393.  
  2394.       # And TMPL_LOOPs:
  2395.       $self->param(LOOP_PARAM =>
  2396.                    [
  2397.                     { PARAM => VALUE_FOR_FIRST_PASS, ... },
  2398.                     { PARAM => VALUE_FOR_SECOND_PASS, ... }
  2399.                     ...
  2400.                    ]
  2401.                   );
  2402.  
  2403. 4) To set the value of a a number of parameters :
  2404.  
  2405.      # For simple TMPL_VARs:
  2406.      $self->param(PARAM => 'value',
  2407.                   PARAM2 => 'value'
  2408.                  );
  2409.  
  2410.       # And with some TMPL_LOOPs:
  2411.       $self->param(PARAM => 'value',
  2412.                    PARAM2 => 'value',
  2413.                    LOOP_PARAM =>
  2414.                    [
  2415.                     { PARAM => VALUE_FOR_FIRST_PASS, ... },
  2416.                     { PARAM => VALUE_FOR_SECOND_PASS, ... }
  2417.                     ...
  2418.                    ],
  2419.                    ANOTHER_LOOP_PARAM =>
  2420.                    [
  2421.                     { PARAM => VALUE_FOR_FIRST_PASS, ... },
  2422.                     { PARAM => VALUE_FOR_SECOND_PASS, ... }
  2423.                     ...
  2424.                    ]
  2425.                   );
  2426.  
  2427. 5) To set the value of a a number of parameters using a hash-ref :
  2428.  
  2429.       $self->param(
  2430.                    {
  2431.                       PARAM => 'value',
  2432.                       PARAM2 => 'value',
  2433.                       LOOP_PARAM =>
  2434.                       [
  2435.                         { PARAM => VALUE_FOR_FIRST_PASS, ... },
  2436.                         { PARAM => VALUE_FOR_SECOND_PASS, ... }
  2437.                         ...
  2438.                       ],
  2439.                       ANOTHER_LOOP_PARAM =>
  2440.                       [
  2441.                         { PARAM => VALUE_FOR_FIRST_PASS, ... },
  2442.                         { PARAM => VALUE_FOR_SECOND_PASS, ... }
  2443.                         ...
  2444.                       ]
  2445.                     }
  2446.                    );
  2447.  
  2448. =cut
  2449.  
  2450.  
  2451. sub param {
  2452.   my $self = shift;
  2453.   my $options = $self->{options};
  2454.   my $param_map = $self->{param_map};
  2455.  
  2456.   # the no-parameter case - return list of parameters in the template.
  2457.   return keys(%$param_map) unless scalar(@_);
  2458.   
  2459.   my $first = shift;
  2460.   my $type = ref $first;
  2461.  
  2462.   # the one-parameter case - could be a parameter value request or a
  2463.   # hash-ref.
  2464.   if (!scalar(@_) and !length($type)) {
  2465.     my $param = $options->{case_sensitive} ? $first : lc $first;
  2466.     
  2467.     # check for parameter existence 
  2468.     $options->{die_on_bad_params} and !exists($param_map->{$param}) and
  2469.       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)");
  2470.     
  2471.     return undef unless (exists($param_map->{$param}) and
  2472.                          defined($param_map->{$param}));
  2473.  
  2474.     return ${$param_map->{$param}} if 
  2475.       (ref($param_map->{$param}) eq 'HTML::Template::VAR');
  2476.     return $param_map->{$param}[HTML::Template::LOOP::PARAM_SET];
  2477.   } 
  2478.  
  2479.   if (!scalar(@_)) {
  2480.     croak("HTML::Template->param() : Single reference arg to param() must be a hash-ref!  You gave me a $type.")
  2481.       unless $type eq 'HASH' or 
  2482.         (ref($first) and UNIVERSAL::isa($first, 'HASH'));  
  2483.     push(@_, %$first);
  2484.   } else {
  2485.     unshift(@_, $first);
  2486.   }
  2487.   
  2488.   croak("HTML::Template->param() : You gave me an odd number of parameters to param()!")
  2489.     unless ((@_ % 2) == 0);
  2490.  
  2491.   # strangely, changing this to a "while(@_) { shift, shift }" type
  2492.   # loop causes perl 5.004_04 to die with some nonsense about a
  2493.   # read-only value.
  2494.   for (my $x = 0; $x <= $#_; $x += 2) {
  2495.     my $param = $options->{case_sensitive} ? $_[$x] : lc $_[$x];
  2496.     my $value = $_[($x + 1)];
  2497.     
  2498.     # check that this param exists in the template
  2499.     $options->{die_on_bad_params} and !exists($param_map->{$param}) and
  2500.       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)");
  2501.     
  2502.     # if we're not going to die from bad param names, we need to ignore
  2503.     # them...
  2504.     next unless (exists($param_map->{$param}));
  2505.     
  2506.     # figure out what we've got, taking special care to allow for
  2507.     # objects that are compatible underneath.
  2508.     my $value_type = ref($value);
  2509.     if (defined($value_type) and length($value_type) and ($value_type eq 'ARRAY' or ((ref($value) !~ /^(CODE)|(HASH)|(SCALAR)$/) and $value->isa('ARRAY')))) {
  2510.       (ref($param_map->{$param}) eq 'HTML::Template::LOOP') or
  2511.         croak("HTML::Template::param() : attempt to set parameter '$param' with an array ref - parameter is not a TMPL_LOOP!");
  2512.       $param_map->{$param}[HTML::Template::LOOP::PARAM_SET] = [@{$value}];
  2513.     } else {
  2514.       (ref($param_map->{$param}) eq 'HTML::Template::VAR') or
  2515.         croak("HTML::Template::param() : attempt to set parameter '$param' with a scalar - parameter is not a TMPL_VAR!");
  2516.       ${$param_map->{$param}} = $value;
  2517.     }
  2518.   }
  2519. }
  2520.  
  2521.  
  2522. =head2 clear_params()
  2523.  
  2524. Sets all the parameters to undef.  Useful internally, if nowhere else!
  2525.  
  2526. =cut
  2527.  
  2528. sub clear_params {
  2529.   my $self = shift;
  2530.   my $type;
  2531.   foreach my $name (keys %{$self->{param_map}}) {
  2532.     $type = ref($self->{param_map}{$name});
  2533.     undef(${$self->{param_map}{$name}})
  2534.       if ($type eq 'HTML::Template::VAR');
  2535.     undef($self->{param_map}{$name}[HTML::Template::LOOP::PARAM_SET])
  2536.       if ($type eq 'HTML::Template::LOOP');    
  2537.   }
  2538. }
  2539.  
  2540.  
  2541. # obsolete implementation of associate
  2542. sub associateCGI { 
  2543.   my $self = shift;
  2544.   my $cgi  = shift;
  2545.   (ref($cgi) eq 'CGI') or
  2546.     croak("Warning! non-CGI object was passed to HTML::Template::associateCGI()!\n");
  2547.   push(@{$self->{options}{associate}}, $cgi);
  2548.   return 1;
  2549. }
  2550.  
  2551.  
  2552. =head2 output()
  2553.  
  2554. output() returns the final result of the template.  In most situations
  2555. you'll want to print this, like:
  2556.  
  2557.    print $template->output();
  2558.  
  2559. When output is called each occurrence of <TMPL_VAR NAME=name> is
  2560. replaced with the value assigned to "name" via param().  If a named
  2561. parameter is unset it is simply replaced with ''.  <TMPL_LOOPS> are
  2562. evaluated once per parameter set, accumlating output on each pass.
  2563.  
  2564. Calling output() is guaranteed not to change the state of the
  2565. Template object, in case you were wondering.  This property is mostly
  2566. important for the internal implementation of loops.
  2567.  
  2568. You may optionally supply a filehandle to print to automatically as
  2569. the template is generated.  This may improve performance and lower
  2570. memory consumption.  Example:
  2571.  
  2572.    $template->output(print_to => *STDOUT);
  2573.  
  2574. The return value is undefined when using the "print_to" option.
  2575.  
  2576. =cut
  2577.  
  2578. use vars qw(%URLESCAPE_MAP);
  2579. sub output {
  2580.   my $self = shift;
  2581.   my $options = $self->{options};
  2582.   local $_;
  2583.  
  2584.   croak("HTML::Template->output() : You gave me an odd number of parameters to output()!")
  2585.     unless ((@_ % 2) == 0);
  2586.   my %args = @_;
  2587.  
  2588.   print STDERR "### HTML::Template Memory Debug ### START OUTPUT ", $self->{proc_mem}->size(), "\n"
  2589.     if $options->{memory_debug};
  2590.  
  2591.   $options->{debug} and print STDERR "### HTML::Template Debug ### In output\n";
  2592.  
  2593.   # want a stack dump?
  2594.   if ($options->{stack_debug}) {
  2595.     require 'Data/Dumper.pm';
  2596.     print STDERR "### HTML::Template output Stack Dump ###\n\n", Data::Dumper::Dumper($self->{parse_stack}), "\n";
  2597.   }
  2598.  
  2599.   # globalize vars - this happens here to localize the circular
  2600.   # references created by global_vars.
  2601.   $self->_globalize_vars() if ($options->{global_vars});
  2602.  
  2603.   # support the associate magic, searching for undefined params and
  2604.   # attempting to fill them from the associated objects.
  2605.   if (scalar(@{$options->{associate}})) {
  2606.     # prepare case-mapping hashes to do case-insensitive matching
  2607.     # against associated objects.  This allows CGI.pm to be
  2608.     # case-sensitive and still work with asssociate.
  2609.     my (%case_map, $lparam);
  2610.     foreach my $associated_object (@{$options->{associate}}) {
  2611.       # what a hack!  This should really be optimized out for case_sensitive.
  2612.       if ($options->{case_sensitive}) {
  2613.         map {
  2614.           $case_map{$associated_object}{$_} = $_
  2615.         } $associated_object->param();
  2616.       } else {
  2617.         map {
  2618.           $case_map{$associated_object}{lc($_)} = $_
  2619.         } $associated_object->param();
  2620.       }
  2621.     }
  2622.  
  2623.     foreach my $param (keys %{$self->{param_map}}) {
  2624.       unless (defined($self->param($param))) {
  2625.       OBJ: foreach my $associated_object (reverse @{$options->{associate}}) {
  2626.           $self->param($param, scalar $associated_object->param($case_map{$associated_object}{$param})), last OBJ
  2627.             if (exists($case_map{$associated_object}{$param}));
  2628.         }
  2629.       }
  2630.     }
  2631.   }
  2632.  
  2633.   use vars qw($line @parse_stack); local(*line, *parse_stack);
  2634.  
  2635.   # walk the parse stack, accumulating output in $result
  2636.   *parse_stack = $self->{parse_stack};
  2637.   my $result = '';
  2638.  
  2639.   tie $result, 'HTML::Template::PRINTSCALAR', $args{print_to}
  2640.     if defined $args{print_to} and not tied $args{print_to};
  2641.     
  2642.   my $type;
  2643.   my $parse_stack_length = $#parse_stack;
  2644.   for (my $x = 0; $x <= $parse_stack_length; $x++) {
  2645.     *line = \$parse_stack[$x];
  2646.     $type = ref($line);
  2647.     
  2648.     if ($type eq 'SCALAR') {
  2649.       $result .= $$line;
  2650.     } elsif ($type eq 'HTML::Template::VAR' and ref($$line) eq 'CODE') {
  2651.       defined($$line) and $result .= $$line->($self);
  2652.     } elsif ($type eq 'HTML::Template::VAR') {
  2653.       defined($$line) and $result .= $$line;
  2654.     } elsif ($type eq 'HTML::Template::LOOP') {
  2655.       if (defined($line->[HTML::Template::LOOP::PARAM_SET])) {
  2656.         eval { $result .= $line->output($x, $options->{loop_context_vars}); };
  2657.         croak("HTML::Template->output() : fatal error in loop output : $@") 
  2658.           if $@;
  2659.       }
  2660.     } elsif ($type eq 'HTML::Template::COND') {
  2661.       if ($line->[HTML::Template::COND::JUMP_IF_TRUE]) {
  2662.         if ($line->[HTML::Template::COND::VARIABLE_TYPE] == HTML::Template::COND::VARIABLE_TYPE_VAR) {
  2663.           if (defined ${$line->[HTML::Template::COND::VARIABLE]}) {
  2664.             if (ref(${$line->[HTML::Template::COND::VARIABLE]}) eq 'CODE') {
  2665.               $x = $line->[HTML::Template::COND::JUMP_ADDRESS] if ${$line->[HTML::Template::COND::VARIABLE]}->($self);
  2666.             } else {
  2667.               $x = $line->[HTML::Template::COND::JUMP_ADDRESS] if ${$line->[HTML::Template::COND::VARIABLE]};
  2668.             }
  2669.           }
  2670.         } else {
  2671.           $x = $line->[HTML::Template::COND::JUMP_ADDRESS] if
  2672.             (defined $line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET] and
  2673.              scalar @{$line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET]});
  2674.         }
  2675.       } else {
  2676.         if ($line->[HTML::Template::COND::VARIABLE_TYPE] == HTML::Template::COND::VARIABLE_TYPE_VAR) {
  2677.           if (defined ${$line->[HTML::Template::COND::VARIABLE]}) {
  2678.             if (ref(${$line->[HTML::Template::COND::VARIABLE]}) eq 'CODE') {
  2679.               $x = $line->[HTML::Template::COND::JUMP_ADDRESS] unless ${$line->[HTML::Template::COND::VARIABLE]}->($self);
  2680.             } else {
  2681.               $x = $line->[HTML::Template::COND::JUMP_ADDRESS] unless ${$line->[HTML::Template::COND::VARIABLE]};
  2682.             }
  2683.           } else {
  2684.             $x = $line->[HTML::Template::COND::JUMP_ADDRESS];
  2685.           }
  2686.         } else {
  2687.           $x = $line->[HTML::Template::COND::JUMP_ADDRESS] if
  2688.             (not defined $line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET] or
  2689.              not scalar @{$line->[HTML::Template::COND::VARIABLE][HTML::Template::LOOP::PARAM_SET]});
  2690.         }
  2691.       }
  2692.     } elsif ($type eq 'HTML::Template::NOOP') {
  2693.       next;
  2694.     } elsif ($type eq 'HTML::Template::DEFAULT') {
  2695.       $_ = $x;  # remember default place in stack
  2696.  
  2697.       # find next VAR, there might be an ESCAPE in the way
  2698.       *line = \$parse_stack[++$x];
  2699.       *line = \$parse_stack[++$x] if ref $line eq 'HTML::Template::ESCAPE';
  2700.  
  2701.       # either output the default or go back
  2702.       if (defined $$line) {
  2703.         $x = $_;
  2704.       } else {
  2705.         $result .= ${$parse_stack[$_]};
  2706.       }
  2707.       next;      
  2708.     } elsif ($type eq 'HTML::Template::ESCAPE') {
  2709.       *line = \$parse_stack[++$x];
  2710.       if (defined($$line)) {
  2711.         $_ = $$line;
  2712.         
  2713.         # straight from the CGI.pm bible.
  2714.         s/&/&/g;
  2715.         s/\"/"/g; #"
  2716.         s/>/>/g;
  2717.         s/</</g;
  2718.         s/'/'/g; #'
  2719.         
  2720.         $result .= $_;
  2721.       }
  2722.       next;
  2723.     } elsif ($type eq 'HTML::Template::JSESCAPE') {
  2724.       $x++;
  2725.       *line = \$parse_stack[$x];
  2726.       if (defined($$line)) {
  2727.         $_ = $$line;
  2728.         s/\\/\\\\/g;
  2729.         s/'/\\'/g;
  2730.         s/"/\\"/g;
  2731.         s/\n/\\n/g;
  2732.         s/\r/\\r/g;
  2733.         $result .= $_;
  2734.       }
  2735.     } elsif ($type eq 'HTML::Template::URLESCAPE') {
  2736.       $x++;
  2737.       *line = \$parse_stack[$x];
  2738.       if (defined($$line)) {
  2739.         $_ = $$line;
  2740.         # Build a char->hex map if one isn't already available
  2741.         unless (exists($URLESCAPE_MAP{chr(1)})) {
  2742.           for (0..255) { $URLESCAPE_MAP{chr($_)} = sprintf('%%%02X', $_); }
  2743.         }
  2744.         # do the translation (RFC 2396 ^uric)
  2745.         s!([^a-zA-Z0-9_.\-])!$URLESCAPE_MAP{$1}!g;
  2746.         $result .= $_;
  2747.       }
  2748.     } else {
  2749.       confess("HTML::Template::output() : Unknown item in parse_stack : " . $type);
  2750.     }
  2751.   }
  2752.  
  2753.   # undo the globalization circular refs
  2754.   $self->_unglobalize_vars() if ($options->{global_vars});
  2755.  
  2756.   print STDERR "### HTML::Template Memory Debug ### END OUTPUT ", $self->{proc_mem}->size(), "\n"
  2757.     if $options->{memory_debug};
  2758.     
  2759.   return undef if defined $args{print_to};
  2760.   return $result;
  2761. }
  2762.  
  2763.  
  2764. =head2 query()
  2765.  
  2766. This method allow you to get information about the template structure.
  2767. It can be called in a number of ways.  The simplest usage of query is
  2768. simply to check whether a parameter name exists in the template, using
  2769. the C<name> option:
  2770.  
  2771.   if ($template->query(name => 'foo')) {
  2772.     # do something if a varaible of any type
  2773.     # named FOO is in the template
  2774.   }
  2775.  
  2776. This same usage returns the type of the parameter.  The type is the
  2777. same as the tag minus the leading 'TMPL_'.  So, for example, a
  2778. TMPL_VAR parameter returns 'VAR' from query().
  2779.  
  2780.   if ($template->query(name => 'foo') eq 'VAR') {
  2781.     # do something if FOO exists and is a TMPL_VAR
  2782.   }
  2783.  
  2784. Note that the variables associated with TMPL_IFs and TMPL_UNLESSs will
  2785. be identified as 'VAR' unless they are also used in a TMPL_LOOP, in
  2786. which case they will return 'LOOP'.
  2787.  
  2788. C<query()> also allows you to get a list of parameters inside a loop
  2789. (and inside loops inside loops).  Example loop:
  2790.  
  2791.    <TMPL_LOOP NAME="EXAMPLE_LOOP">
  2792.      <TMPL_VAR NAME="BEE">
  2793.      <TMPL_VAR NAME="BOP">
  2794.      <TMPL_LOOP NAME="EXAMPLE_INNER_LOOP">
  2795.        <TMPL_VAR NAME="INNER_BEE">
  2796.        <TMPL_VAR NAME="INNER_BOP">
  2797.      </TMPL_LOOP>
  2798.    </TMPL_LOOP>
  2799.  
  2800. And some query calls:
  2801.  
  2802.   # returns 'LOOP'
  2803.   $type = $template->query(name => 'EXAMPLE_LOOP');
  2804.  
  2805.   # returns ('bop', 'bee', 'example_inner_loop')
  2806.   @param_names = $template->query(loop => 'EXAMPLE_LOOP');
  2807.  
  2808.   # both return 'VAR'
  2809.   $type = $template->query(name => ['EXAMPLE_LOOP', 'BEE']);
  2810.   $type = $template->query(name => ['EXAMPLE_LOOP', 'BOP']);
  2811.  
  2812.   # and this one returns 'LOOP'
  2813.   $type = $template->query(name => ['EXAMPLE_LOOP',
  2814.                                     'EXAMPLE_INNER_LOOP']);
  2815.  
  2816.   # and finally, this returns ('inner_bee', 'inner_bop')
  2817.   @inner_param_names = $template->query(loop => ['EXAMPLE_LOOP',
  2818.                                                  'EXAMPLE_INNER_LOOP']);
  2819.  
  2820.   # for non existent parameter names you get undef
  2821.   # this returns undef.
  2822.   $type = $template->query(name => 'DWEAZLE_ZAPPA');
  2823.  
  2824.   # calling loop on a non-loop parameter name will cause an error.
  2825.   # this dies:
  2826.   $type = $template->query(loop => 'DWEAZLE_ZAPPA');
  2827.  
  2828. As you can see above the C<loop> option returns a list of parameter
  2829. names and both C<name> and C<loop> take array refs in order to refer
  2830. to parameters inside loops.  It is an error to use C<loop> with a
  2831. parameter that is not a loop.
  2832.  
  2833. Note that all the names are returned in lowercase and the types are
  2834. uppercase.
  2835.  
  2836. Just like C<param()>, C<query()> with no arguements returns all the
  2837. parameter names in the template at the top level.
  2838.  
  2839. =cut
  2840.  
  2841. sub query {
  2842.   my $self = shift;
  2843.   $self->{options}{debug} and print STDERR "### HTML::Template Debug ### query(", join(', ', @_), ")\n";
  2844.  
  2845.   # the no-parameter case - return $self->param()
  2846.   return $self->param() unless scalar(@_);
  2847.   
  2848.   croak("HTML::Template::query() : Odd number of parameters passed to query!")
  2849.     if (scalar(@_) % 2);
  2850.   croak("HTML::Template::query() : Wrong number of parameters passed to query - should be 2.")
  2851.     if (scalar(@_) != 2);
  2852.  
  2853.   my ($opt, $path) = (lc shift, shift);
  2854.   croak("HTML::Template::query() : invalid parameter ($opt)")
  2855.     unless ($opt eq 'name' or $opt eq 'loop');
  2856.  
  2857.   # make path an array unless it already is
  2858.   $path = [$path] unless (ref $path);
  2859.  
  2860.   # find the param in question.
  2861.   my @objs = $self->_find_param(@$path);
  2862.   return undef unless scalar(@objs);
  2863.   my ($obj, $type);
  2864.  
  2865.   # do what the user asked with the object
  2866.   if ($opt eq 'name') {
  2867.     # we only look at the first one.  new() should make sure they're
  2868.     # all the same.
  2869.     ($obj, $type) = (shift(@objs), shift(@objs));
  2870.     return undef unless defined $obj;
  2871.     return 'VAR' if $type eq 'HTML::Template::VAR';
  2872.     return 'LOOP' if $type eq 'HTML::Template::LOOP';
  2873.     croak("HTML::Template::query() : unknown object ($type) in param_map!");
  2874.  
  2875.   } elsif ($opt eq 'loop') {
  2876.     my %results;
  2877.     while(@objs) {
  2878.       ($obj, $type) = (shift(@objs), shift(@objs));
  2879.       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.") 
  2880.         unless ((defined $obj) and ($type eq 'HTML::Template::LOOP'));
  2881.       
  2882.       # SHAZAM!  This bit extracts all the parameter names from all the
  2883.       # loop objects for this name.
  2884.       map {$results{$_} = 1} map { keys(%{$_->{'param_map'}}) }
  2885.         values(%{$obj->[HTML::Template::LOOP::TEMPLATE_HASH]});
  2886.     }
  2887.     # this is our loop list, return it.
  2888.     return keys(%results);   
  2889.   }
  2890. }
  2891.  
  2892. # a function that returns the object(s) corresponding to a given path and
  2893. # its (their) ref()(s).  Used by query() in the obvious way.
  2894. sub _find_param {
  2895.   my $self = shift;
  2896.   my $spot = $self->{options}{case_sensitive} ? shift : lc shift;
  2897.  
  2898.   # get the obj and type for this spot
  2899.   my $obj = $self->{'param_map'}{$spot};
  2900.   return unless defined $obj;
  2901.   my $type = ref $obj;
  2902.  
  2903.   # return if we're here or if we're not but this isn't a loop
  2904.   return ($obj, $type) unless @_;
  2905.   return unless ($type eq 'HTML::Template::LOOP');
  2906.  
  2907.   # recurse.  this is a depth first seach on the template tree, for
  2908.   # the algorithm geeks in the audience.
  2909.   return map { $_->_find_param(@_) }
  2910.     values(%{$obj->[HTML::Template::LOOP::TEMPLATE_HASH]});
  2911. }
  2912.  
  2913. # HTML::Template::VAR, LOOP, etc are *light* objects - their internal
  2914. # spec is used above.  No encapsulation or information hiding is to be
  2915. # assumed.
  2916.  
  2917. package HTML::Template::VAR;
  2918.  
  2919. sub new {
  2920.     my $value;
  2921.     return bless(\$value, $_[0]);
  2922. }
  2923.  
  2924. package HTML::Template::DEFAULT;
  2925.  
  2926. sub new {
  2927.     my $value = $_[1];
  2928.     return bless(\$value, $_[0]);
  2929. }
  2930.  
  2931. package HTML::Template::LOOP;
  2932.  
  2933. sub new {
  2934.     return bless([], $_[0]);
  2935. }
  2936.  
  2937. sub output {
  2938.   my $self = shift;
  2939.   my $index = shift;
  2940.   my $loop_context_vars = shift;
  2941.   my $template = $self->[TEMPLATE_HASH]{$index};
  2942.   my $value_sets_array = $self->[PARAM_SET];
  2943.   return unless defined($value_sets_array);  
  2944.   
  2945.   my $result = '';
  2946.   my $count = 0;
  2947.   my $odd = 0;
  2948.   foreach my $value_set (@$value_sets_array) {
  2949.     if ($loop_context_vars) {
  2950.       if ($count == 0) {
  2951.         @{$value_set}{qw(__first__ __inner__ __last__)} = (1,0,$#{$value_sets_array} == 0);
  2952.       } elsif ($count == $#{$value_sets_array}) {
  2953.         @{$value_set}{qw(__first__ __inner__ __last__)} = (0,0,1);
  2954.       } else {
  2955.         @{$value_set}{qw(__first__ __inner__ __last__)} = (0,1,0);
  2956.       }
  2957.       $odd = $value_set->{__odd__} = not $odd;
  2958.       $value_set->{__counter__} = $count + 1;
  2959.     }
  2960.     $template->param($value_set);    
  2961.     $result .= $template->output;
  2962.     $template->clear_params;
  2963.     @{$value_set}{qw(__first__ __last__ __inner__ __odd__ __counter__)} = 
  2964.       (0,0,0,0)
  2965.         if ($loop_context_vars);
  2966.     $count++;
  2967.   }
  2968.  
  2969.   return $result;
  2970. }
  2971.  
  2972. package HTML::Template::COND;
  2973.  
  2974. sub new {
  2975.   my $pkg = shift;
  2976.   my $var = shift;
  2977.   my $self = [];
  2978.   $self->[VARIABLE] = $var;
  2979.  
  2980.   bless($self, $pkg);  
  2981.   return $self;
  2982. }
  2983.  
  2984. package HTML::Template::NOOP;
  2985. sub new {
  2986.   my $unused;
  2987.   my $self = \$unused;
  2988.   bless($self, $_[0]);
  2989.   return $self;
  2990. }
  2991.  
  2992. package HTML::Template::ESCAPE;
  2993. sub new {
  2994.   my $unused;
  2995.   my $self = \$unused;
  2996.   bless($self, $_[0]);
  2997.   return $self;
  2998. }
  2999.  
  3000. package HTML::Template::JSESCAPE;
  3001. sub new {
  3002.   my $unused;
  3003.   my $self = \$unused;
  3004.   bless($self, $_[0]);
  3005.   return $self;
  3006. }
  3007.  
  3008. package HTML::Template::URLESCAPE;
  3009. sub new {
  3010.   my $unused;
  3011.   my $self = \$unused;
  3012.   bless($self, $_[0]);
  3013.   return $self;
  3014. }
  3015.  
  3016. # scalar-tying package for output(print_to => *HANDLE) implementation
  3017. package HTML::Template::PRINTSCALAR;
  3018. use strict;
  3019.  
  3020. sub TIESCALAR { bless \$_[1], $_[0]; }
  3021. sub FETCH { }
  3022. sub STORE {
  3023.   my $self = shift;
  3024.   local *FH = $$self;
  3025.   print FH @_;
  3026. }
  3027. 1;
  3028. __END__
  3029.  
  3030. =head1 FREQUENTLY ASKED QUESTIONS
  3031.  
  3032. In the interest of greater understanding I've started a FAQ section of
  3033. the perldocs.  Please look in here before you send me email.
  3034.  
  3035. =over 4
  3036.  
  3037. =item 1
  3038.  
  3039. Q: Is there a place to go to discuss HTML::Template and/or get help?
  3040.  
  3041. A: There's a mailing-list for discussing HTML::Template at
  3042. html-template-users@lists.sourceforge.net.  To join:
  3043.  
  3044.    http://lists.sourceforge.net/lists/listinfo/html-template-users
  3045.  
  3046. If you just want to get email when new releases are available you can
  3047. join the announcements mailing-list here:
  3048.  
  3049.    http://lists.sourceforge.net/lists/listinfo/html-template-announce
  3050.     
  3051. =item 2
  3052.  
  3053. Q: Is there a searchable archive for the mailing-list?
  3054.  
  3055. A: Yes, you can find an archive of the SourceForge list here:
  3056.  
  3057.   http://www.geocrawler.com/lists/3/SourceForge/23294/0/
  3058.  
  3059. For an archive of the old vm.com list, setup by Sean P. Scanlon, see:
  3060.  
  3061.    http://bluedot.net/mail/archive/
  3062.  
  3063. =item 3
  3064.  
  3065. Q: I want support for <TMPL_XXX>!  How about it?
  3066.  
  3067. A: Maybe.  I definitely encourage people to discuss their ideas for
  3068. HTML::Template on the mailing list.  Please be ready to explain to me
  3069. how the new tag fits in with HTML::Template's mission to provide a
  3070. fast, lightweight system for using HTML templates.
  3071.  
  3072. NOTE: Offering to program said addition and provide it in the form of
  3073. a patch to the most recent version of HTML::Template will definitely
  3074. have a softening effect on potential opponents!
  3075.  
  3076. =item 4
  3077.  
  3078. Q: I found a bug, can you fix it?
  3079.  
  3080. A: That depends.  Did you send me the VERSION of HTML::Template, a test
  3081. script and a test template?  If so, then almost certainly.
  3082.  
  3083. If you're feeling really adventurous, HTML::Template has a publically
  3084. available CVS server.  See below for more information in the PUBLIC
  3085. CVS SERVER section.
  3086.  
  3087. =item 5
  3088.  
  3089. Q: <TMPL_VAR>s from the main template aren't working inside a
  3090. <TMPL_LOOP>!  Why?
  3091.  
  3092. A: This is the intended behavior.  <TMPL_LOOP> introduces a separate
  3093. scope for <TMPL_VAR>s much like a subroutine call in Perl introduces a
  3094. separate scope for "my" variables.
  3095.  
  3096. If you want your <TMPL_VAR>s to be global you can set the
  3097. 'global_vars' option when you call new().  See above for documentation
  3098. of the 'global_vars' new() option.
  3099.  
  3100. =item 6
  3101.  
  3102. Q: Why do you use /[Tt]/ instead of /t/i?  It's so ugly!
  3103.  
  3104. A: Simple - the case-insensitive match switch is very inefficient.
  3105. According to _Mastering_Regular_Expressions_ from O'Reilly Press,
  3106. /[Tt]/ is faster and more space efficient than /t/i - by as much as
  3107. double against long strings.  //i essentially does a lc() on the
  3108. string and keeps a temporary copy in memory.
  3109.  
  3110. When this changes, and it is in the 5.6 development series, I will
  3111. gladly use //i.  Believe me, I realize [Tt] is hideously ugly.
  3112.  
  3113. =item 7
  3114.  
  3115. Q: How can I pre-load my templates using cache-mode and mod_perl?
  3116.  
  3117. A: Add something like this to your startup.pl:
  3118.  
  3119.    use HTML::Template;
  3120.    use File::Find;
  3121.  
  3122.    print STDERR "Pre-loading HTML Templates...\n";
  3123.    find(
  3124.         sub {
  3125.           return unless /\.tmpl$/;
  3126.           HTML::Template->new(
  3127.                               filename => "$File::Find::dir/$_",
  3128.                               cache => 1,
  3129.                              );
  3130.         },
  3131.         '/path/to/templates',
  3132.         '/another/path/to/templates/'
  3133.       );
  3134.  
  3135. Note that you'll need to modify the "return unless" line to specify
  3136. the extension you use for your template files - I use .tmpl, as you
  3137. can see.  You'll also need to specify the path to your template files.
  3138.  
  3139. One potential problem: the "/path/to/templates/" must be EXACTLY the
  3140. same path you use when you call HTML::Template->new().  Otherwise the
  3141. cache won't know they're the same file and will load a new copy -
  3142. instead getting a speed increase, you'll double your memory usage.  To
  3143. find out if this is happening set cache_debug => 1 in your application
  3144. code and look for "CACHE MISS" messages in the logs.
  3145.  
  3146. =item 8
  3147.  
  3148. Q: What characters are allowed in TMPL_* NAMEs?
  3149.  
  3150. A: Numbers, letters, '.', '/', '+', '-' and '_'.
  3151.  
  3152. =item 9
  3153.  
  3154. Q: How can I execute a program from inside my template?
  3155.  
  3156. A: Short answer: you can't.  Longer answer: you shouldn't since this
  3157. violates the fundamental concept behind HTML::Template - that design
  3158. and code should be seperate.
  3159.  
  3160. But, inevitably some people still want to do it.  If that describes
  3161. you then you should take a look at
  3162. L<HTML::Template::Expr|HTML::Template::Expr>.  Using
  3163. HTML::Template::Expr it should be easy to write a run_program()
  3164. function.  Then you can do awful stuff like:
  3165.  
  3166.   <tmpl_var expr="run_program('foo.pl')">
  3167.  
  3168. Just, please, don't tell me about it.  I'm feeling guilty enough just
  3169. for writing HTML::Template::Expr in the first place.
  3170.  
  3171. =item 10
  3172.  
  3173. Q: Can I get a copy of these docs in Japanese?
  3174.  
  3175. A: Yes you can.  See Kawai Takanori's translation at:
  3176.  
  3177.    http://member.nifty.ne.jp/hippo2000/perltips/html/template.htm
  3178.  
  3179. =item 11
  3180.  
  3181. Q: What's the best way to create a <select> form element using
  3182. HTML::Template?
  3183.  
  3184. A: There is much disagreement on this issue.  My personal preference
  3185. is to use CGI.pm's excellent popup_menu() and scrolling_list()
  3186. functions to fill in a single <tmpl_var select_foo> variable.
  3187.  
  3188. To some people this smacks of mixing HTML and code in a way that they
  3189. hoped HTML::Template would help them avoid.  To them I'd say that HTML
  3190. is a violation of the principle of separating design from programming.
  3191. There's no clear separation between the programmatic elements of the
  3192. <form> tags and the layout of the <form> tags.  You'll have to draw
  3193. the line somewhere - clearly the designer can't be entirely in charge
  3194. of form creation.
  3195.  
  3196. It's a balancing act and you have to weigh the pros and cons on each side.
  3197. It is certainly possible to produce a <select> element entirely inside the
  3198. template.  What you end up with is a rat's nest of loops and conditionals.
  3199. Alternately you can give up a certain amount of flexibility in return for
  3200. vastly simplifying your templates.  I generally choose the latter.
  3201.  
  3202. Another option is to investigate HTML::FillInForm which some have
  3203. reported success using to solve this problem.
  3204.  
  3205. =back
  3206.  
  3207. =head1 BUGS
  3208.  
  3209. I am aware of no bugs - if you find one, join the mailing list and
  3210. tell us about it.  You can join the HTML::Template mailing-list by
  3211. visiting:
  3212.  
  3213.   http://lists.sourceforge.net/lists/listinfo/html-template-users
  3214.  
  3215. Of course, you can still email me directly (sam@tregar.com) with bugs,
  3216. but I reserve the right to forward bug reports to the mailing list.
  3217.  
  3218. When submitting bug reports, be sure to include full details,
  3219. including the VERSION of the module, a test script and a test template
  3220. demonstrating the problem!
  3221.  
  3222. If you're feeling really adventurous, HTML::Template has a publically
  3223. available CVS server.  See below for more information in the PUBLIC
  3224. CVS SERVER section.
  3225.  
  3226. =head1 CREDITS
  3227.  
  3228. This module was the brain child of my boss, Jesse Erlbaum
  3229. ( jesse@vm.com ) at Vanguard Media ( http://vm.com ) .  The most original
  3230. idea in this module - the <TMPL_LOOP> - was entirely his.
  3231.  
  3232. Fixes, Bug Reports, Optimizations and Ideas have been generously
  3233. provided by:
  3234.  
  3235.    Richard Chen
  3236.    Mike Blazer
  3237.    Adriano Nagelschmidt Rodrigues
  3238.    Andrej Mikus
  3239.    Ilya Obshadko
  3240.    Kevin Puetz
  3241.    Steve Reppucci
  3242.    Richard Dice
  3243.    Tom Hukins
  3244.    Eric Zylberstejn
  3245.    David Glasser
  3246.    Peter Marelas
  3247.    James William Carlson
  3248.    Frank D. Cringle
  3249.    Winfried Koenig
  3250.    Matthew Wickline
  3251.    Doug Steinwand
  3252.    Drew Taylor
  3253.    Tobias Brox
  3254.    Michael Lloyd
  3255.    Simran Gambhir
  3256.    Chris Houser <chouser@bluweb.com>
  3257.    Larry Moore
  3258.    Todd Larason
  3259.    Jody Biggs
  3260.    T.J. Mather
  3261.    Martin Schroth
  3262.    Dave Wolfe
  3263.    uchum
  3264.    Kawai Takanori
  3265.    Peter Guelich
  3266.    Chris Nokleberg
  3267.    Ralph Corderoy
  3268.    William Ward
  3269.    Ade Olonoh
  3270.    Mark Stosberg
  3271.    Lance Thomas
  3272.    Roland Giersig
  3273.    Jere Julian
  3274.    Peter Leonard
  3275.    Kenny Smith
  3276.    Sean P. Scanlon
  3277.    Martin Pfeffer
  3278.    David Ferrance
  3279.    Gyepi Sam
  3280.    Darren Chamberlain
  3281.    Paul Baker
  3282.    Gabor Szabo
  3283.    Craig Manley
  3284.  
  3285. Thanks!
  3286.  
  3287. =head1 WEBSITE
  3288.  
  3289. You can find information about HTML::Template and other related modules at:
  3290.  
  3291.    http://html-template.sourceforge.net
  3292.  
  3293. =head1 PUBLIC CVS SERVER
  3294.  
  3295. HTML::Template now has a publicly accessible CVS server provided by
  3296. SourceForge (www.sourceforge.net).  You can access it by going to
  3297. http://sourceforge.net/cvs/?group_id=1075.  Give it a try!
  3298.  
  3299. =head1 AUTHOR
  3300.  
  3301. Sam Tregar, sam@tregar.com
  3302.  
  3303. =head1 LICENSE
  3304.  
  3305.   HTML::Template : A module for using HTML Templates with Perl
  3306.   Copyright (C) 2000-2002 Sam Tregar (sam@tregar.com)
  3307.  
  3308.   This module is free software; you can redistribute it and/or modify it
  3309.   under the terms of either:
  3310.  
  3311.   a) the GNU General Public License as published by the Free Software
  3312.   Foundation; either version 1, or (at your option) any later version,
  3313.  
  3314.   or
  3315.  
  3316.   b) the "Artistic License" which comes with this module.
  3317.  
  3318.   This program is distributed in the hope that it will be useful,
  3319.   but WITHOUT ANY WARRANTY; without even the implied warranty of
  3320.   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either
  3321.   the GNU General Public License or the Artistic License for more details.
  3322.  
  3323.   You should have received a copy of the Artistic License with this
  3324.   module, in the file ARTISTIC.  If not, I'll be glad to provide one.
  3325.  
  3326.   You should have received a copy of the GNU General Public License
  3327.   along with this program; if not, write to the Free Software
  3328.   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  3329.   USA
  3330.  
  3331. =cut
  3332.