NAME

WeBWorK::ContentGenerator - base class for modules that generate page content.

SYNOPSIS

# start with a WeBWorK::Controller object: $c

use WeBWorK::ContentGenerator::SomeSubclass;

my $cg = WeBWorK::ContentGenerator::SomeSubclass->new($c);
my $result = $cg->go();

DESCRIPTION

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.

INVOCATION

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.

  1. 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.

  2. 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!

  3. At this point, go() will terminate if the request is a HEAD request.

  4. 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.

  5. The method content() is called to send the page content to client.

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.

DATA MODIFIERS

Modifiers allow the caller to register a piece of data for later retrieval in a standard way.

reply_with_file($type, $source, $name, $delete_after)

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 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 from pre_header_initialize().

addmessage($message)

Adds a message to the list of messages to be output 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 output by the message() template escape handler.

addbadmessage($message)

Adds a failure message to the list of messages to be output by the message() template escape handler.

prepare_activity_entry()

Prepare a string to be sent to the activity log, if it is turned on. This can be overridden by different modules.

STANDARD METHODS

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.

FIXME: The names of the first three methods don't really make sense anymore. There really is no need for both of the pre_header_initialize and initialize methods. The initialize method should be dropped and the pre_header_initialize method renamed.

pre_header_initialize()

Not defined in this package.

May be defined by a subclass to perform any early processing that is needed. This method must be used if responding with a file or redirect.

This method may be asynchronous.

header()

Defined in this package.

This method is not really useful anymore. For now it returns the response status code and this return value is ignored. Headers are now set when rendering a response (as it really should have been done before.

initialize()

Not defined in this package.

May be defined by a subclass to perform any early processing that is needed. This method can not be used if responding with a file or redirect.

This method may be asynchronous.

output_course_lang_and_dir()

Output the LANG and DIR tags in the main HTML tag of a generated web page when a template file calls this function.

This calls WeBWorK::Utils::LanguageAndDirection::get_lang_and_dir.

webwork_logo()

Create the link to the webwork installation landing page with a logo and alt text

institution_logo()

Create the link to the host institution with a logo and alt text

content()

Defined in this package.

Print the content of the generated page.

This renders the Mojo::Template corresponding to the called ContentGenerator sub-package.

Template escape handlers

Template escape handlers are invoked in the templates.

Some of the template escapes handlers are defined here but may be overridden in a subclass. Others, like head and info are not defined here, but may be defined in a subclass if needed.

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.

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|buttons
separator   => HTML to place in between links

For example:

<!--#nav style="buttons" separator=" "-->
options()

Not defined in this package.

View options related to the content displayed in the body or info areas.

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 gathers the route information from 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 in the 'datetime_format_long' format. For example, for the 'en' language this will give "January 4, 2023 at 8:54:33 PM EST". Note that the "at" is replaced with a comma for the latest version of DateTime::Locale::FromData.

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 outputs the value of the field $c->{status_message}, if it is present.

page_title()

Defined in this package.

Print the title of the current page.

The implementation in this package takes information from the current route.

webwork_url

Defined in this package.

Outputs the $webwork_url defined in site.conf, unless $webwork_url is equal to "/", in which case this outputs the empty string.

This is used to set a value in a global webworkConfig javascript variable, that can be accessed in javascript files.

warnings()

Defined in this package.

Print accumulated warnings.

The implementation in this package checks for a stash key named "warnings". If present, its contents are formatted and returned.

help()

Display a link to context-sensitive help for the current content generator module.

url($args)

Defined in this package.

Returns the specified URL from either %webworkURLs or %courseURLs in the course environment. $args is a reference to a hash containing the following fields:

type => type of URL: webwork|course (defaults to webwork)
name => name of URL type (must be 'theme' or undefined)
file => the local file name

Template conditions

Template condition methods are called in the template. If a method is defined here or overridden in the instantiated subclass, it is invoked.

The following conditions are currently defined:

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.

This package just uses the UNIVERSAL::can() function.

A subclass could redefine this method to, for example, "hide" a method from the template:

sub can ($c, $arg) {
    my ($c, $arg) = @_;

    if ($arg eq "floobar") {
            return 0;
    } else {
            return $c->SUPER::can($arg);
    }
}
have_warnings

If warnings have been emitted while handling this request return true, otherwise return false.

This implementation checks if a stash value named "warnings" has been set or if there are pg errors.

exists_theme_file

Returns true if the specified file exists in the current theme directory and false otherwise

HTML MACROS

Various routines are defined in this package for rendering common WeBWorK idioms.

FIXME: some of these should be moved to WeBWorK::HTML:: modules!

# ------------------------------------------------------------------------------

Template escape handler macros

These methods are used by implementations of the escape sequence handlers to maintain a consistent style.

pathMacro($args, @path)

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" => Mojo::URL

If the page should not have a link associated with it, the URL should be the empty string. 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.

navMacro($args, $tail, @links)

Helper macro for the #nav escape sequence: $args is a hash reference containing the "style" and "separator" arguments to the escape. @links consists of ordered tuples of the form:

"Link Name", Mojo::URL

If a nav element should not have a link associated with it, the URL should be the empty string. $tail should be a hash reference of URL query parameters to add 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 method outputs a link that opens a modal dialog containing the results of rendering a HelpFiles template. The template file that is rendered is $name.html. If that file does not exist, then nothing is output.

The optional argument $args is a hash that may contain the keys label, label_size, or class. $args->{label} is the displayed label, $args->{label_size} is a font awesome size class and is only used if $args->{label} is not set, and $args->{class} is added to the html class attribute if defined.

feedbackMacro(%params)

Helper macro for displaying the feedback form. Returns a button named "Email Instructor". %params contains the request parameters accepted by the Feedback module and their values.

Parameter management

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.

A hash of options may be passed for the first argument of this method. The only supported option is an "id_prefix" to prepend to the id's of all of the hidden inputs that are created.

hidden_authen_fields()

Use hidden_fields to return hidden <INPUT> tags for request fields used in authentication.

An optional $id_prefix may be passed as the first argument of this method.

If session_management_via is "session_cookie" then the hidden authentication fields that are return are for the "user" and the "effectiveUser". If session_management_via is "key" then the "key" is added.

url_args(@fields)

Return a hash containing values for each field mentioned in @fields, or all fields if list is empty. Data is taken from the current request. This return value is suitable for passing to the Mojo::URL query method.

url_authen_args()

Use url_args to return a hash of request fields used in authentication that is suitable for passing to the Mojo::URL query method.

Utilities

systemLink($urlpath, %options)

Generate a link to another part of the system. $urlpath is Mojo::URL object from which the base path will be taken. %options can consist of:

params

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.

authen

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.

use_abs_url

If set to a true value, the scheme, host, and port are prepended to the URL. This is useful for links which must be usable on their own, such as those sent via email.

nbsp($string)

If string consists of only whitespace, the HTML entity &nbsp; is returned. Otherwise $string is returned.

errorOutput($error, $details)

Used by Problem, ProblemSet, and Hardcopy to report errors encountered during problem rendering.

warningMessage

Used to display a generic warning message at the top of the page

$string = formatDateTime($date_time, $format_string, $timezone, $locale)

Formats a $date_time epoch into a string in the format defined by $format_string. If $format_string is not provided, the default WeBWorK date/time format is used. If $format_string is a method of the $dt->locale instance, then format_cldr is used, and otherwise strftime is used. The available patterns for $format_string can be found at "strftime Patterns" in DateTime. The available methods for the $dt->locale instance are documented at DateTime::Locale::FromData. If $timezone is given, then the formatted string that is returned is in the specified timezone. If $locale is provided, the string returned will be in the format of that locale. If $locale is not provided, Perl defaults to using en-US.

Note that the defaults for $timezone and $locale should almost never be overriden when this method is used.

read_scoring_file($fileName)

Wrapper for WeBWorK::File::Scoring that no-ops if $fileName is "None" and prepends the path to the scoring directory.