Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Perl Web Development - From Novice To Professional (2006)

.pdf
Скачиваний:
56
Добавлен:
17.08.2013
Размер:
2.9 Mб
Скачать

260C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

[% USE date(format = '%Y') -%]

<p>Copyright (c) [% date.format %] Steve Suehring</p> </body></html>

Within the footer, the date plug-in is used. For copyright notices, only the year is necessary, so the date format is set appropriately.

Finally, the actual page is created. This page is stored in the source directory and is called index.html in this example. The source/index.html file contains the following:

[% META title = "Home Page" -%] <p> Welcome to the home page </p>

Obviously, the page is quite simple in this example. Notice, however, that the title for the page is defined and is done so with the META directive, so that the title will be available to the preprocessed header.tt file.

With the three files created, it’s time to run ttree. You should have the following directory and file layout:

Directory: /home/youruser/webproject

File: /home/youruser/webproject/project.cfg

Directory: /home/youruser/webproject/output

Directory: /home/youruser/webproject/source

File: /home/youruser/webproject/source/index.html

Directory: /home/youruser/webproject/lib

File: /home/youruser/webproject/lib/header.tt

File: /home/youruser/webproject/lib/footer.tt

From within the webproject directory, run ttree and point it toward your configuration

file:

ttree -f project.cfg

Here’s the output:

ttree 2.78 (Template Toolkit version 2.14)

Source: /home/suehring/webproject/source

Destination: /home/suehring/webproject/output

Include Path: [ /home/suehring/webproject/lib ]

Ignore: [ \b(CVS|RCS)\b, ^#, \b(CVS|RCS)\b, ^# ]

Copy: [ \.png$, \.gif$, \.png$, \.gif$ ]

Accept: [ ]

Suffix: [ ]

+ index.html

If you run into problems, ensure your paths are correct and that you’ve placed the files in the correct locations.

C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

261

The contents of output/index.html will now be as follows:

<!DOCTYPE html

PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"><head>

<title>Home Page</title> </head><body>

<p> Welcome to the home page </p> <p>Copyright (c) 2005 Steve Suehring</p> </body></html>

Notice that the three files have been joined, the title called in the header but defined within the page has been properly filled in, and the date has been placed correctly in the footer.

Building a second page and subsequent pages gets easier, as you now have the infrastructure in place to process the templates for the project. For example, you can create a web form using the CGI plug-in as follows:

[% META title = "Order Form" -%] [% USE localcgi = CGI -%]

[% localcgi.start_form(action => 'order.cgi'); localcgi.textfield(name => 'username'

size => '25');

localcgi.p;

localcgi.submit(name => 'submit_user');

%]

The file is called order.html and is located in the source directory. Running ttree with both the index.html and order.html files in place yields this output:

ttree 2.78 (Template Toolkit version 2.14)

Source: /home/suehring/webproject/source

Destination: /home/suehring/webproject/output

Include Path: [ /home/suehring/webproject/lib ]

Ignore: [ \b(CVS|RCS)\b, ^#, \b(CVS|RCS)\b, ^# ]

Copy: [ \.png$, \.gif$, \.png$, \.gif$ ]

Accept: [ ]

Suffix: [ ]

+

order.html

 

-

index.html

(not modified)

Notice that the index.html file was not processed by ttree this time through because it had not been modified since the last run of ttree. You can change this by adding the -a option to the ttree command or by adding the all option to the configuration file for the project.

262 C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

Security Considerations

For the most part, if you merely use the Template Toolkit to manage a web site by keeping common text such as headers and footers, then there is very little to worry about security-wise. However, as mentioned throughout this chapter, the Template Toolkit is quite powerful. With that power comes the ability to do some things that can lead to security problems. One such problem is unauthorized information disclosure through the template. Storing items such as database names, usernames, and passwords within template files can lead to this information being discovered by a potential attacker. If you use advanced options, such as CGI processing, through the Template Toolkit, you must take care to ensure that input data is properly sanitized. Again, if the Template Toolkit is used to merely generate these pages rather than process the input, then the risk is essentially negated.

Summary

The Template Toolkit’s unrivaled power and flexibility make it an excellent choice for managing a web site of any size. In this chapter, you learned that through the definition of both static and dynamic variables, the use of looping and conditionals, and the large number of plug-ins, the Template Toolkit can also make the management of a complex site rather easy. This chapter covered several available plug-ins that really extend the usefulness of the toolkit. As you’ve seen, the Template Toolkit can be used for much more than simple web page generation.

If this chapter has piqued your interest in the Template Toolkit, I encourage you to read the excellent documentation available on this software. Begin with the perldoc for Template::Manual, which will point you toward even more specific documentation for the various aspects of the Template Toolkit.

C H A P T E R 1 3

■ ■ ■

Perl Web Sites with Mason

The Mason software program creates dynamic web sites by enabling Perl code to be inserted into HTML.1 Programming languages such as PHP or ASP.NET operate under a similar premise. While each of these languages has its own set of advantages, neither of them are Perl. And since this book is devoted to Perl, I’ll cover only dynamic web sites with Perl and Mason.

I use Mason for my own web site (http://www.braingia.org), and I’ve done consulting with clients where Mason has been the recommended approach for their sites. Not only is Mason easy to use, but it’s also powerful. Elements such as headers and footers (the text at the top and bottom of web site pages), site maps, copyright notices, terms and conditions, contact information, and so on—sometimes referred to collectively as the “look and feel” of a site—are all relatively common on each page within a given site. Using Mason, developers can quickly create, for example, a common header and footer to be used across all pages within a site. Even though the pages are similar, however, they are not exactly the same. For example, the titles of pages usually change from page to page. Mason enables arguments to be passed into its components to handle such differences. As you’ll learn in the chapter, components are central to working with Mason.

With that, it’s time to jump into a quick introduction to Mason. Then you’ll learn how to install Mason, followed by coverage of Mason’s syntax. Finally, you’ll walk through building a sample site using Mason.

Introducing Mason

As stated previously, Mason enables Perl code to be interspersed within HTML and other such web languages. Though it can operate in other modes, Mason requires mod_perl to run. The intention of the developer is to create dynamic web sites, rendered at runtime or the time of the request/response cycle. For example, here’s a fully functional web page that could be served with an Apache server running mod_perl and Mason:

1. Other tools to embed Perl are available as well, one of which is called Embperl.

 

(http://perl.apache.org/embperl).

263

264C H A P T E R 1 3 P E R L W E B S I T E S W I T H M A S O N

<html><head><title>Song List</title></head>

%my $song = "Driven";

%my $artist = "Rush"; <body>

<h1>Steve's Music Stream</h1>

<p>The current song playing on Steve's Apache music stream is <% $song %> by <% $artist %>.</p>

</body>

</html>

The output from this code when viewed in a web browser looks as shown in Figure 13-1.

Figure 13-1. A Mason example

As you’ll learn a little later, Mason is built around an object called a component, which is nothing more than a file that is processed by Mason. Within that file can be a line or two of code, HTML, or something else entirely. Alternatively, a component can be a complex Perl program. A component is essentially what you make it.

At the very top of the component hierarchy is something called the top-level component. The top-level component is the first component called when Mason processes a request for a page. It could be a simple HTML page; a page with some Perl code on it (like that shown in

the preceding example); or a component that calls other components, which in turn call other components, and so on.

Mason can do far more than was shown in the previous example. For example, you can load database queries, pass values between components, and handle pages completely dynamically with Mason—the pages don’t even need to exist on the filesystem!

The rest of this chapter is devoted to showing you the basic syntax for Mason, but please be aware that there is far more to Mason than I was able to cover in this chapter. I invite you to supplement the material in this chapter with information from the Mason perldocs and the

C H A P T E R 1 3 P E R L W E B S I T E S W I T H M A S O N

265

Installing Mason

Mason is already included with many Linux distributions, saving the need to install it from source. Debian, for example, includes Mason in the libhtml-mason-perl package along with other packages containing documentation and examples. Use the package search capabilities within your distribution to find out if Mason is available as a package with your distribution.

If Mason isn’t available with your distribution, or if you want to compile from source for some other reason, you can download Mason from http://www.masonhq.com. Although they’re not technically required to use Mason, you’ll need Apache and mod_perl. You could get by without them and still use Mason, but this chapter will not cover any of those other uses. You will also need Perl to install Mason (though I suspect that if you didn’t have Perl by now, you might have had trouble with the previous 12 chapters!). Some additional modules are required to install Mason, including the following:

Class::Container

Exception::Class

File::Spec (this may already be included in your version of Perl)

Params::Validate

Scalar::Util

Optionally, you can also install the following:

Test::More

Cache::Cache

You can obtain these modules from your favorite CPAN mirror.

Note Apache::Request and CGI.pm aren’t technically required to compile the Mason software, but they are required if you’d like to follow along with the examples in this chapter, and you’ll likely need them for programming Mason anyway. (You likely have them both already.)

Compiling Mason

Mason is downloaded as a gzipped tar archive and will have a filename like HTML-Mason-N.NN. tar.gz, where NNN is the version number, such as 1.28. Unzip and unarchive the file:

tar -zxvf HTML-Mason-1.28.tar.gz

and change into the HTML-Mason-N.NN directory:

cd HTML-Mason-1.28

Once you’re inside the directory, run the Perl-style Makefile.PL by typing

perl Makefile.PL

wing:

266 C H A P T E R 1 3 P E R L W E B S I T E S W I T H M A S O N

Checking for Scalar::Util...ok

Checking for File::Spec...ok

Checking for CGI...ok

Checking for Cache::Cache...ok

Checking for Exception::Class...ok

Checking for Test::More...ok

Checking for Params::Validate...ok

Checking for Class::Container...ok

Checking for Apache::Request...ok

Checking if your kit is complete...

Looks good

Writing Makefile for HTML::Mason

If you’re missing any of the prerequisites, you’ll be notified and likely required to install the missing prerequisites before continuing. If you receive a notice that the make file has been written, as shown in the example, then you can continue the installation by typing the following:

make

Though obviously dependent on the available resources, the make process will go quickly. At this point, you could simply install the software, but I recommend running the tests available prior to installing the software. Doing so can save headaches later if the software mysteriously doesn’t work. Run the tests by typing

make test

The tests will run, producing output similar to the following:

PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" " \$ENV{PORT}=8228; \$ENV{APACHE_DIR}=q^^; \$ENV{MASON_MAINTAINER}=0; test_harness(0, 'blib/lib', 'blib/arch')" t/*.t

t/01-syntax...........

ok

t/02-sections.........

ok

t/02a-filter..........

ok

t/04-misc.............

ok

t/05-request..........

ok

t/06-compiler.........

ok

t/06a-compiler_obj....

ok

t/07-interp...........

ok

t/08-ah...............

skipped

all skipped: no reason given

t/09-component........

ok

t/09a-comp_content....

ok

t/10-cache............

ok

t/10a-cache-1.0x......

ok

t/11-inherit..........

ok

t/12-taint............

ok

t/13-errors...........

ok

t/14-cgi..............

ok

t/14a-fake_apache.....

ok

 

C H A P T E R 1 3 P E R L W E B S I T E S W I T H M A S O N

267

t/15-subclass.........

ok

 

t/16-live_cgi.........

skipped

 

all skipped: no reason given

 

t/17-print............

ok

 

t/18-leak.............

ok

 

t/19-subrequest.......

ok

 

All tests successful,

2 tests skipped.

 

Files=23, Tests=393, 33 wallclock secs (15.66 cusr + 0.96 csys = 16.62

 

CPU)

 

 

If any of the tests fail, refer to the Mason documentation at http://www.masonhq.com. It’s actually rather uncommon for tests to fail at this point, but it can happen.

If the tests were successful, as they were in the output shown in the example, you can install the software. To install the software, you will likely need to be the root user. Run the installation by typing the following:

make install

The next section guides you through the steps required to configure Mason for use with your Apache installation.

Configuring Apache and Mason

With the help of the configuration in Apache, Mason can be automatically called to interpret or process files of various extensions or for an entire directory or site. Apache directives are used to load the Mason Apache module and then to configure a handler for certain files or directories. Within the Mason-related Apache configuration you can (and likely will) use Mason-specific configuration parameters to configure and change the behavior of Mason when it processes your templates. A configuration for Apache might look like this:

PerlModule HTML::Mason::ApacheHandler <FilesMatch "\.mhtml$">

SetHandler perl-script

PerlHandler HTML::Mason::ApacheHandler </FilesMatch>

This configuration would be placed within the httpd.conf file for Apache, and files with the extension .mhtml would be processed by Mason. You could also limit this processing to the files within a given directory, as shown here:

PerlModule HTML::Mason::ApacheHandler <Directory /path/to/mason/files> <FilesMatch "\.mhtml$">

SetHandler perl-script

PerlHandler HTML::Mason::ApacheHandler </FilesMatch>

</Directory>

In practice, you’ll find that it’s helpful to define certain types of files to be processed by Mason limited to a given directory or site. For example, the configurations shown might be

268C H A P T E R 1 3 P E R L W E B S I T E S W I T H M A S O N

placed in a <VirtualHost> directive within the Apache configuration file. Using this, you wouldn’t have to define a special file extension for your Mason files.

Within the Mason configuration area in the Apache configuration file, you may find it necessary to set one or more additional Mason-specific configuration parameters. These parameters can be set within the Apache configuration file, when making a subrequest, or within a Mason script. There are different names for the parameters based on where they are being set. For example, a parameter would be called args_method if set within a subrequest, but it would be called MasonArgsMethod if set within the Apache configuration file. For the purposes of this section, we’ll use the name of the parameter as it would appear in the Apache configuration file.

You can find a full list of configuration parameters on the Mason web site at http:// www.masonhq.com/docs/manual/Params.html. Some of the parameters you may find necessary to set within the Apache configuration file include those listed in Table 13-1.

Table 13-1. Select Configuration Parameters for Use with Mason

Parameter

Values

Description

MasonArgsMethod

mod_perl or CGI

Used to set the way in which arguments from GETs

 

 

and POSTs are unpacked. The default is mod_perl.

 

 

You may need to set the value to CGI while

 

 

converting the site to work with Mason.

MasonAutoSentHeaders

true or false

Used to determine whether or not Mason will

 

 

automatically send HTTP headers to the client.

 

 

The default is true.

MasonCompRoot

No default

Used to set the default path for the component

 

 

root. The component root will be explained later.

MasonDataDir

No default

Used to set the directory that Mason uses to write

 

 

temporary files for some features.

MasonUseStrict

true or false

Used to configure whether or not the Mason files

 

 

should take advantage of the use strict pragma.

 

 

The default is true.

 

 

 

When using parameters within the Apache configuration file, the PerlSetVar and PerlAddVar directives must be used. For example, to set the MasonCompRoot parameter, you would use the following line in the Apache configuration file:

PerlSetVar MasonCompRoot /path/to/comp_root

In my own configuration, I’m running Apache within a chroot and have various virtual hosts running on the server for which I have different configurations from the main Apache server process. I’ve therefore set both the MasonCompRoot and MasonDataDir parameters within the <VirtualHost> configuration on the server.

I’m now using Mason for serving every file that has an .html extension on the site, which I configured using the <FilesMatch> directive shown earlier. However, when I initially converted to Mason, I used a <FilesMatch> directive of .mhtml.

C H A P T E R 1 3 P E R L W E B S I T E S W I T H M A S O N

269

I’ve also had to bring some legacy CGI scripts over to the site. In doing so, I found that I needed to set the MasonArgsMethod to CGI, away from its default of mod_perl. I suspect (or

hope) that I’ll have time to port these scripts to mod_perl by the time you’re reading this book. In addition to that basic configuration, I’ve also tightened the security for the site by

sending a “404: Not Found” error whenever someone tries to access one of the Mason-specific components that I might or might not use. I accomplish this with the help of a <LocationMatch> directive and Apache::Constants::NOT_FOUND, as directed by the perldoc for HTML::Mason::Admin.

Here is the full configuration for Mason as it appears in my httpd.conf. Your configuration may vary from this, but my hope is to pass along some practical information about a real-world implementation of Mason.

PerlModule HTML::Mason::ApacheHandler <FilesMatch "\.html$">

SetHandler perl-script

PerlHandler HTML::Mason::ApacheHandler PerlSetVar MasonCompRoot /home/suehring/www PerlSetVar MasonDataDir /home/suehring/mason #sws 5/27/2005

PerlSetVar MasonArgsMethod CGI </FilesMatch>

<LocationMatch "(\.m(html|pl|ase)|dhandler|autohandler)$"> SetHandler perl-script

PerlInitHandler Apache::Constants::NOT_FOUND </LocationMatch>

With the appropriate configuration for your Apache installation in place, you can restart the Apache server.

Mason Syntax

It’s time to create a “Hello World” example, Mason-style. In general, I’m fed up with “Hello World” examples, though, so I’m going to create something even more annoying: a page that uses the <blink> HTML tag. I’ll do this by wrapping the output inside of a <%perl> block in the page. Listing 13-1 shows the simple text for this page.

Listing 13-1. A Mason-Style Page Using <%perl> to Print a Blinking Tag

<%perl> print "<blink>This is the blinkin' example.</blink><P>\n"; </%perl>

The page can be saved within the directory you configured as the MasonCompRoot and viewed in a web browser. When I viewed the page, I saw blinking text. It’s difficult to illustrate blinking text in a screenshot, however, so Figure 13-2 shows the text when it appears.