WeBWorK::ContentGenerator - base class for modules that generate page content.
# start with a WeBWorK::Request object: $r use WeBWorK::ContentGenerator::SomeSubclass; my $cg = WeBWorK::ContentGenerator::SomeSubclass->new($r); my $result = $cg->go();
WeBWorK::ContentGenerator provides the framework for generating page content. ``Content generators'' are subclasses of this class which provide content for particular parts of the system.
Default versions of methods used by the templating system are provided. Several useful methods are provided for rendering common output idioms and some miscellaneous utilities are provided.
new($r)
Creates a new instance of a content generator. Supply a WeBWorK::Request object $r.
go()
Generates a page, using methods from the particular subclass of ContentGenerator that is instantiated. Generatoion is broken up into several steps, to give subclasses ample control over the process.
go() will attempt to call the method pre_header_initialize(). This method may be
implemented in subclasses which must do processing before the HTTP header is
emitted.
go() will attempt to call the method header(). This method emits the HTTP
header. It is defined in this class (see below), but may be overridden in
subclasses which need to send different header information. For some reason, the
return value of header() will be used as the result of this function, if it is
defined.
FIXME: figure out what the deal is with the return value of header(). If we sent
a header, it's too late to set the status by returning. If we didn't, header()
didn't perform its function!
At this point, go() will terminate if the request is a HEAD request or if the
field $self->{noContent} contains a true value.
FIXME: I don't think we'll need noContent after reply_with_redirect() is
adopted by all modules.
go() then attempts to call the method initialize(). This method may be
implemented in subclasses which must do processing after the HTTP header is sent
but before any content is sent.
The method content() is called to send the page content to client.
r()
Returns a reference to the WeBWorK::Request object associated with this instance.
do_reply_with_file($fileHash)
Handler for reply_with_file(), used by go(). DO NOT CALL THIS METHOD DIRECTLY.
do_reply_with_redirect($url)
Handler for reply_with_redirect(), used by go(). DO NOT CALL THIS METHOD DIRECTLY.
Modifiers allow the caller to register a piece of data for later retrieval in a standard way.
Enables file sending mode, causing go() to send the file specified by $source to
the client after calling pre_header_initialize(). The content type sent is
$type, and the suggested client-side file name is $name. If $delete_after is
true, $source is deleted after it is sent.
Must be called before the HTTP header is sent. Usually called from pre_header_initialize().
reply_with_redirect($url)
Enables redirect mode, causing go() to redirect to the given URL after calling
pre_header_initialize().
Must be called before the HTTP header is sent. Usually called from pre_header_initialize().
addmessage($message)
Adds a message to the list of messages to be printed by the message() template
escape handler.
Must be called before the message() template escape is invoked.
addgoodmessage($message)
Adds a success message to the list of messages to be printed by the
message() template escape handler.
addbadmessage($message)
Adds a failure message to the list of messages to be printed by the
message() template escape handler.
The following are the standard content generator methods. Some are defined here, but may be overridden in a subclass. Others are not defined unless they are defined in a subclass.
pre_header_initialize()
Not defined in this package.
May be defined by a subclass to perform any processing that must occur before the HTTP header is sent.
header()
Defined in this package.
Generates and sends a default HTTP header, specifying the ``text/html'' content type.
initialize()
Not defined in this package.
May be defined by a subclass to perform any processing that must occur after the HTTP header is sent but before any content is sent.
content()
Defined in this package.
Print the content of the generated page.
The implementation in this package uses WeBWorK::Template to define the content of the page. See WeBWorK::Template for details.
If a method named templateName() exists, it it called to determine the name of
the template to use. If not, the default template, ``system'', is used. The
location of the template is looked up in the course environment.
Template escape handlers are invoked when the template processor encounters a matching escape sequence in the template. The escapse sequence's arguments are passed to the methods as a reference to a hash.
For more information, refer to WeBWorK::Template.
The following template escapes handlers are defined here or may be defined in subclasses. For methods that are not defined in this package, the documentation defines the interface and behavior that any subclass implementation must follow.
head()
Not defined in this package.
Any tags that should appear in the HEAD of the document.
info()
Not defined in this package.
Auxiliary information related to the content displayed in the body.
links()
Defined in this package.
Links that should appear on every page.
loginstatus()
Defined in this package.
Print a notification message announcing the current real user and effective user, a link to stop acting as the effective user, and a link to logout.
nav($args)
Not defined in this package.
Links to the previous, next, and parent objects.
$args is a reference to a hash containing the following fields:
style => text|image imageprefix => prefix to prepend to base image URL imagesuffix => suffix to append to base image URL separator => HTML to place in between links
If style is ``image'', image URLs are constructed by prepending imageprefix
and postpending imagesuffix to the image base names defined by the
implementor. (Examples of base names include ``Prev'', ``Next'', ``ProbSet'', and
``Up''). Each concatenated string should form an absolute URL to an image file.
For example:
<!--#nav style="images" imageprefix="/webwork2_files/images/nav"
imagesuffix=".gif" separator=" "-->
options()
Not defined in this package.
Print an auxiliary options form, related to the content displayed in the
body.
path($args)
Defined in this package.
Print ``breadcrubs'' from the root of the virtual hierarchy to the current page. $args is a reference to a hash containing the following fields:
style => type of separator: text|image
image => if style=image, URL of image to use as path separator
text => if style=text, text to use as path separator
if style=image, the ALT text of each separator image
textonly => suppress all HTML, return only plain text
The implementation in this package takes information from the WeBWorK::URLPath associated with the current request.
siblings()
Not defined in this package.
Print links to siblings of the current object.
timestamp()
Defined in this package.
Display the current time and date using default format ``3:37pm on Jan 7, 2004''. The display format can be adjusted by giving a style in the template. For example,
<!--#timestamp style="%m/%d/%y at %I:%M%P"-->
will give standard WeBWorK time format. Wording and other formatting can be done in the template itself. =cut
sub timestamp { my ($self, $args) = @_; my $formatstring = ``%l:%M%P on %b %e, %Y''; $formatstring = $args->{style} if(defined($args->{style})); return(Date::Format::time2str($formatstring, time())); }
=item submiterror()
Defined in this package.
Print any error messages resulting from the last form submission.
This method is deprecated -- use message() instead
The implementation in this package prints the value of the field $self->{submitError}, if it is present.
message()
Defined in this package.
Print any messages (error or non-error) resulting from the last form submission. This could be used to give Sucess and Failure messages after an action is performed by a module.
The implementation in this package prints the value of the field $self->{status_message}, if it is present.
title()
Defined in this package.
Print the title of the current page.
The implementation in this package takes information from the WeBWorK::URLPath associated with the current request.
warnings()
Defined in this package.
Print accumulated warnings.
The implementation in this package checks for a note in the request named ``warnings''. If present, its contents are formatted and returned.
help()
Display a link to context-sensitive help. If the argument name is defined,
the link will be to the help document for that name. Otherwise the name of the
WeBWorK::URLPath node for the current system location will be used.
Conditional predicate methods are invoked when the #if escape sequence is
encountered in the template. If a method named if_predicate is defined in
here or in the instantiated subclass, it is invoked.
The following predicates are currently defined:
if_can($function)
If a function named $function is present in the current content generator (or any superclass), a true value is returned. Otherwise, a false value is returned.
The implementation in this package uses the method UNIVERSAL->can(function) to
arrive at the result.
A subclass could redefine this method to, for example, ``hide'' a method from the template:
sub if_can {
my ($self, $arg) = @_;
if ($arg eq "floobar") {
return 0;
} else {
return $self->SUPER::if_can($arg);
}
}
if_loggedin($arg)
If the user is currently logged in, $arg is returned. Otherwise, the inverse of $arg is returned.
The implementation in this package always returns $arg, since most content generators are only reachable when the user is authenticated. It is up to classes that can be reached without logging in to override this method and provide the correct behavior.
This is suboptimal, and may change in the future.
if_submiterror($arg)
If the last form submission generated an error, $arg is returned. Otherwise, the inverse of $arg is returned.
The implementation in this package checks for the field $self->{submitError} to determine if an error condition is present.
If a subclass uses some other method to classify submission results, this method could be redefined to handle that variance:
sub if_submiterror {
my ($self, $arg) = @_;
my $status = $self->{processReturnValue};
if ($status != 0) {
return $arg;
} else {
return !$arg;
}
}
if_message($arg)
If the last form submission generated a message, $arg is returned. Otherwise, the inverse of $arg is returned.
The implementation in this package checks for the field $self->{status_message} to determine if a message is present.
If a subclass uses some other method to classify submission results, this method could be redefined to handle that variance:
sub if_message {
my ($self, $arg) = @_;
my $status = $self->{processReturnValue};
if ($status != 0) {
return $arg;
} else {
return !$arg;
}
}
If warnings have been emitted while handling this request, $arg is returned. Otherwise, the inverse of $arg is returned.
The implementation in this package checks for a note in the request named ``warnings''. This is set by the WARN handler in Apache::WeBWorK when a warning is handled.
Various routines are defined in this package for rendering common WeBWorK idioms.
FIXME: some of these should be moved to WeBWorK::HTML:: modules!
# ------------------------------------------------------------------------------
These methods are used by implementations of the escape sequence handlers to maintain a consistent style.
Helper macro for the #path escape sequence: $args is a hash reference
containing the ``style'', ``image'', ``text'', and ``textonly'' arguments to the escape.
@path consists of ordered key-value pairs of the form:
"Page Name" => URL
If the page should not have a link associated with it, the URL should be left
empty. Authentication data is added to each URL so you don't have to. A fully-
formed path line is returned, suitable for returning by a function implementing
the #path escape.
FIXME: authentication data probably shouldn't be added here any more, now that we have systemLink().
siblingsMacro(@siblings)
Helper macro for the #siblings escape sequence. @siblings consists of ordered
key-value pairs of the form:
"Sibling Name" => URL
If the sibling should not have a link associated with it, the URL should be left
empty. Authentication data is added to each URL so you don't have to. A fully-
formed siblings block is returned, suitable for returning by a function
implementing the #siblings escape.
FIXME: authentication data probably shouldn't be added here any more, now that we have systemLink().
Helper macro for the #nav escape sequence: $args is a hash reference
containing the ``style'', ``imageprefix'', ``imagesuffix'', and ``separator'' arguments
to the escape. @siblings consists of ordered tuples of the form:
"Link Name", URL, ImageBaseName
If the sibling should not have a link associated with it, the URL should be left
empty. ImageBaseName is placed between the imageprefix and imagesuffix.
Authentication data is added to each URL so you don't have to. $tail is appended
to each URL, after the authentication information. A fully-formed nav line is
returned, suitable for returning by a function implementing the #nav escape.
helpMacro($name)
This escape is represented by a question mark which links to an html page in the helpFiles directory. Currently the link is made to the file $name.html
Methods for formatting request parameters as hidden form fields or query string fragments.
hidden_fields(@fields)
Return hidden <INPUT> tags for each field mentioned in @fields (or all fields if list is empty), taking data from the current request.
hidden_authen_fields()
Use hidden_fields to return hidden <INPUT> tags for request fields used in authentication.
url_args(@fields)
Return a URL query string (without the leading `?') containing values for each field mentioned in @fields, or all fields if list is empty. Data is taken from the current request.
url_authen_args()
Use url_args to return a URL query string for request fields used in authentication.
Return a string containing every request field not matched by the quoted reguar expression $omit, placing $begin before each field name, $middle between each field name and its value, and $end after each value. Values are taken from the current request.
Generate a link to another part of the system. $urlpath is WeBWorK::URLPath object from which the base path will be taken. %options can consist of:
Can be either a reference to an array or a reference to a hash.
If it is a reference to a hash, it maps parmaeter names to values. These parameters will be included in the generated link. If a value is an arrayref, the values of the array referenced will be used. If a value is undefined, the value from the current request will be used.
If params is an arrayref, it is interpreted as a list of parameter names.
These parameters will be included in the generated link, using the values from
the current request.
Unless authen is false (see below), the authentication parameters (user,
effectiveUser, and key) are included with their default values.
If set to a false value, the authentication parameters (user,
effectiveUser, and key) are included in the the generated link unless
explicitly listed in params.
nbsp($string)
If string consists of only whitespace, the HTML entity is returned.
Otherwise $string is returned.
sp2nbsp($string)
A copy of $string is returned with each space character replaced by the
entity.
space2nbsp($string)
Replace spaces in the string with html non-breaking spaces.
Used by Problem, ProblemSet, and Hardcopy to report errors encountered during problem rendering.
warningOutput($warnings)
Used by warnings() in this class to report warnings caught during dispatching
and content generation.
Parses $string as a datetime. If $display_tz is given, $string is assumed to be in that timezone. Otherwise, the timezone defined in the course environment variable $siteDefaults{timezone} is used. The result, $dateTime, is an integer UNIX datetime (epoch) in the server's timezone.
Formats the UNIX datetime $dateTime in the standard WeBWorK datetime format. $dateTime is assumed to be in the server's time zone. If $display_tz is given, the datetime is converted from the server's timezone to the timezone specified. Otherwise, the timezone defined in the course environment variable $siteDefaults{timezone} is used.
Written by Dennis Lambe Jr., malsyned (at) math.rochester.edu and Sam Hathaway, sh002i (at) math.rochester.edu.