MT::App - Movable Type base web application class


    package MT::App::Foo;
    use MT::App;
    @MT::App::Foo::ISA = qw( MT::App );

    package main;
    my $app = MT::App::Foo->new;


MT::App is the base class for Movable Type web applications. It provides support for an application running using standard CGI, or under Apache::Registry, or as a mod_perl handler. MT::App is not meant to be used directly, but rather as a base class for other web applications using the Movable Type framework (for example, MT::App::CMS).


MT::App subclasses the MT class, which provides it access to the publishing methods in that class.


    callback($eh, $app, \$tmpl)

Executed after loading the MT::Template file. The <package> portion is the full package name of the application running. For example,


Is the full callback name for loading the menu.tmpl file under the MT::App::CMS application. The "MT::App::CMS::template_source" callback is also invoked for all templates loading by the CMS. Finally, you can also hook into:


as a wildcard callback name to capture any MT::Template files that are loaded regardless of application.

    callback($eh, $app, \%param, $tmpl)

This callback is invoked in conjunction with the MT::App->build_page method. The $param argument is a hashref of MT::Template parameter data that will eventually be passed to the template to produce the page.

    callback($eh, $app, \$tmpl_str, \%param, $tmpl)

This callback is invoked in conjunction with the MT::App->build_page method. The $tmpl_str parameter is a string reference for the page that was built by the MT::App->build_page method. Since it is a reference, it can be modified by the callback. The $param parameter is a hash reference to the parameter data that was given to build the page. The $tmpl parameter is the MT::Template object used to generate the page.


Following are the list of methods specific to MT::App:


Constructs and returns a new MT::App object.


Invoked at the start of each request. This method is a good place to initialize any settings that are request-specific. When overriding this method, always call the superclass init_request method.

One such setting is the requires_login member element that controls whether the active application mode requires the user to login first.


    sub init_request {
        my $app = shift;
        $app->{requires_login} = 1 unless $app->mode eq 'unprotected';


Runs the application. This gathers the input, chooses the method to execute, executes it, and prints the output to the client.

If an error occurs during the execution of the application, run handles all of the errors thrown either through the MT::ErrorHandler or through die.


Checks the user's credentials, first by looking for a login cookie, then by looking for the username and password CGI parameters. In both cases, the username and password are verified for validity. This method does not set the user's login cookie, however--that should be done by the caller (in most cases, the caller is the run method).

On success, returns the MT::Author object representing the author who logged in, and a boolean flag; if the boolean flag is true, it indicates the the login credentials were obtained from the CGI parameters, and thus that a cookie should be set by the caller. If the flag is false, the credentials came from an existing cookie.

On an authentication error, login removes any authentication cookies that the user might have on his or her browser, then returns undef, and the error message can be obtained from $app->errstr.


A handler method for logging the user out of the application.

$app->send_http_header([ $content_type ])

Sends the HTTP header to the client; if $content_type is specified, the Content-Type header is set to $content_type. Otherwise, text/html is used as the default.

In a mod_perl context, this calls the Apache::send_http_header method; in a CGI context, the CGI::header method is called.


Sends data @data to the client.

In a mod_perl context, this calls the Apache::print method; in a CGI context, data is printed directly to STDOUT.


Bakes a cookie to be sent to the client.

%arg can contain any valid parameters to the new methods of CGI::Cookie (or Apache::Cookie--both take the same parameters). These include -name, -value, -path, -secure, and -expires.

If you do not include the -path parameter in %arg, it will be set automatically to $app->path (below).

In a mod_perl context, this method uses Apache::Cookie; in a CGI context, it uses CGI::Cookie.

This method will automatically assign a "secure" flag for the cookie if it the current HTTP request is using the https protocol. To forcibly disable the secure flag, provide a -secure argument with a value of 0.


Returns a reference to a hash containing cookie objects, where the objects are either of class Apache::Cookie (in a mod_perl context) or CGI::Cookie (in a CGI context).


Returns the string of the cookie name used for the user login cookie.


Returns the object of the logged in user. Typically a MT::Author object.


Sends a cookie back to the user's browser which clears their existing authenication cookie.


Returns the active user's "magic token" which is used to validate posted data with the validate_magic method.


Creates a new "magic token" string which is a random set of characters. The


Returns an array of directory paths where application templates exist.

$app->find_file(\@paths, $filename)

Returns the path and filename for a file found in any of the given paths. If the file cannot be found, it returns undef.

$app->load_tmpl($file[, @params])

Loads a MT::Template template using the filename specified. See the documentation for the build_page method to learn about how templates are located. The optional @params are passed to the MT::Template constructor.


Assigns standard parameters to the given MT::Template $tmpl object. Refer to the "STANDARD APPLICATION TEMPLATE PARAMETERS" section for a complete list of these parameters.


Gets or sets the application's character set based on the "PublishCharset" configuration setting or the encoding of the active language ($app->current_language).


Adds one or more arguments to the list of 'return' arguments that are use to construct a return URL.


    $app->add_return_arg(finished_task => 1)

This will redirect the user back to the URL they came from, adding a new 'finished_task' query parameter to the URL.


Invokes $app->redirect using the $app->return_uri method as the address.


Constructs the list of return arguments using the data available from $app->state_params and $app->mode>.


Gets or sets the active application run mode.


Returns a list of the parameter names that preserve the given state of the application. These are declared during the application's init method, using the state_params member element.


    $app->{state_params} = ['filter','page','blog_id'];


Gets or sets a string containing query parameters which is used by return_uri in constructing a 'return' address for the current request.


Returns a string composed of the $app->uri and the $app->return_args.


A utility method that assembles the query portion of a URI, taking a mode and set of parameters. The string returned does include the '?' character if query parameters exist.


    my $query_str = $app->uri_params(mode => 'go',
                                     args => { 'this' => 'that' });
    # $query_str == '?__mode=go&this=that'


Returns the active user's session object. This also acts as a get/set method for assigning arbitrary data into the user's session record. At the end of the active request, any unsaved session data is written to the MT::Session record.


    # saves the value of a 'color' parameter into the user's session
    # this value will persist from one request to the next, but will
    # be cleared when the user logs out or has to reauthenicate.
    $app->session('color', $app->param('color'))

$app->start_session([$author, $remember])

Initializes a new user session by both calling make_session and setting the user's login cookie.


Creates a new user session MT::Session record for the active user.

$app->session_user($user_obj, $session_id, %options)

Given an existing user object and a session ID ("token"), this returns the user object back if the session's user ID matches the requested $user_obj->id, undef if the session can't be found or if the session's user ID doesn't match the $user_obj->id.


Handles the display of an application error.


This method is deprecated.


Returns the application's static web path.


Called at the end of the web request for cleanup purposes.

$app->add_breadcrumb($name, $uri)

Adds to the navigation history path that is displayed to the end user when using the application. The last breadcrumb should always be a reference to the active mode of the application. Example:

    $app->add_breadcrumb('Edit Foo',
        $app->uri_params(mode => 'edit',
                         args => { '_type' => 'foo' }));


Used to supply the application class with a list of available run modes and the code references for each of them. %arg should be a hash list of methods and the code reference for it. Example:

        'one' => \&one,
        'two' => \&two,
        'three' => \&three,

$app->add_plugin_action($where, $action_link, $link_text)

  $app->add_plugin_action($where, $action_link, $link_text)

Adds a link to the given plugin action from the location specified by $where. This allows plugins to create actions that apply to, for example, the entry which the user is editing. The type of object the user was editing, and its ID, are passed as parameters.

Values that are used from the $where parameter are as follows:

  • list_entries
  • list_commenter
  • list_comments
  • <type> (Where <type> is any object that the user can already edit, such as 'entry,' 'comment,' 'commenter,' 'blog,' etc.)

The $where value will be passed to the given action_link as a CGI parameter called from. For example, on the list_entries page, a link will appear to:


If the $where is a single-item page, such as an entry-editing page, then the action_link will also receive a CGI parameter id whose value is the ID of the object under consideration:


Note that the link is always formed by appending an ampersand. Thus, if your $action_link is simply the name of a CGI script, such as my-plugin.cgi, you'll want to append a '?' to the argument you pass:

    MT->add_plugin_action('entry', 'my-plugin.cgi?', \
                          'Touch this entry with MyPlugin')

Finally, the $link_text parameter specifies the text of the link; this value will be wrapped in <a> tags that point to the $action_link.


Returns a list of plugin actions that are registered for the $type specified. The return value is an array of hashrefs with the following keys set for each: page (the registered 'action link'), link_text (the registered 'link text'), plugin (the plugin's envelope). See the documentation for "$app->add_plugin_action($where, $action_link, $link_text)" for more information.


Returns the path portion of the active URI.


Returns the current application's URI.


Returns the path portion of the URI that is used for accessing the MT CGI scripts.


Returns the full URI of the MT "admin" script (typically a reference to mt.cgi).


Returns the active weblog, if available. The blog_id query parameter identifies this weblog.


An internal routine that is used during the end of an application request to update each MT::Blog object's timestamp if any of it's child objects were changed during the application request.

$app->build_page($tmpl_name, \%param)

Builds an application page to be sent to the client; the page name is specified in $tmpl_name, which should be the name of a template containing valid MT::Template markup. \%param is a hash ref whose keys and values will be passed to MT::Template::param for use in the template.

On success, returns a scalar containing the page to be sent to the client. On failure, returns undef, and the error message can be obtained from $app->errstr.

How does build_page find a template?

The build_page function looks in several places for an app template. Two configuration directives can modify these search paths, and application and plugin code can also affect them.

The TemplatePath config directive is an absolute path to the directory where MT's core application templates live. It defaults to the mt_dir plus an additional path segment of 'tmpl'.

The optional AltTemplatePath config directive is a path (absolute or relative) to a directory where some 'override templates' may live. An override template takes the place of one of MT's core application templates, and is used interchangeably with the core template. This allows power users to customize the look and feel of the MT application. If AltTemplatePath is relative, its base path is the value of the Movable Type configuration file.

Next, any application built on the MT::App foundation can define its own template_dir parameter, which identifies a subdirectory of TemplatePath (or AltTemplatePath) where that application's templates can be found. template_dir defaults to cms. Most templates will be found in this directory, but sometimes the template search will fall through to the parent directory, where a default error template is found, for example. template_dir should rightly have been named application_template_dir, since it is application-specific.

Finally, a plugin can specify its plugin_template_path, which locates a directory where the templates for that plugin's own interface are found. If the plugin_template_path is relative, it may be relative to either the app_dir, or the mt_dir; the former takes precedence if it exists. (for a definition of app_dir and mt_dir, see MT)

Given these values, the order of search is as follows:

  • plugin_template_path
  • AltTemplatePath
  • AltTemplatePath/template_dir
  • TemplatePath/template_dir
  • TemplatePath

If a template with the given name is not found in any of these locations, an ugly error is thrown to the user.

$app->build_page_in_mem($tmpl, \%param)

Used internally by the build_page method to render the output of a MT::Template object (the first parameter) using the parameter data (the second parameter). It additionally calls the process_mt_template method (to process any <MT_ACTION> and <MT_X:Y> marker tags) and then translate_templatized (to process any <MT_TRANS> tags).


Processes the <MT_ACTION> tags that are present in $str. These tags are in the following format:

    <MT_ACTION mode="mode_name" parameter="value">

The mode parameter is required (and must be the first attribute). The following attributes are appended as regular query parameters.

The MT_ACTION tag is a preferred way to specify application links rather than using this syntax:

    <TMPL_VAR NAME=SCRIPT_URL>?__mode=mode_name&parameter=value

process_mt_templates also strips the $str variable of any tags in the format of <MT_\w+:\w+>. These are 'marker' tags that are used to identify specific portions of the template page and used in conjunction with the transformer callback helper methods tmpl_prepend, tmpl_append, tmpl_replace, tmpl_select.

$app->tmpl_prepend(\$str, $section, $id, $content)

Adds text at the top of a MT marker tag identified by $section and $id. If a template contains the following:

    <link ...>

A call to tmpl_prepend like this:

    $app->tmpl_prepend($tmpl_ref, 'HEAD', 'STYLE', "new link tag\n");

will result in this change in the template page:

    new link tag
    <link ...>

$app->tmpl_append(\$str, $section, $id, $content)

Adds text at the bottom of a MT marker tag identified by $section and $id. If a template contains the following:

    <link ...>

A call to tmpl_append like this:

    $app->tmpl_append($tmpl_ref, 'HEAD', 'STYLE', "new link tag\n");

will result in this change in the template page:

    <link ...>
    new link tag

$app->tmpl_replace(\$str, $section, $id, $content)

Replaces text within a MT marker tag identified by $section and $id. If a template contains the following:

    <link ...>

A call to tmpl_replace like this:

    $app->tmpl_prepend($tmpl_ref, 'HEAD', 'STYLE', "new style content\n");

will result in this change in the template page:

    new style content

$app->tmpl_select(\$str, $section, $id)

Returns the text found within a MT marker tag identified by $section and $id. If a template contains the following:

    <link ...>

A call to tmpl_select like this:

    my $str = $app->tmpl_select($tmpl_ref, 'HEAD', 'STYLE');

will select the following and return it:

    <link ...>


Returns the value of a given cookie.


Clears the value of a given CGI parameter.

$app->errtrans($msg[, @param])

Translates the $msg text, passing through @param for any parameters within the message. This also sets the error state of the application, assinging the translated text as the error message.


Returns the value of the specified HTTP header.


The mod_perl handler used when the application is run as a native mod_perl handler.


Initializes the application object, setting default values and establishing the parameters necessary to run. The @param values are passed through to the parent class, the MT package.

This method needs to be invoked by any subclass when the object is initialized.


Returns a true value if the active user is authorized to access the application. By default, this always returns true; subclasses may override it to check app-specific authorization. A login attempt will be rejected with a generic error message at the MT::App level, if is_authorized returns false, but MT::App subclasses may wish to perform additional checks which produce more specific error messages.

Subclass authors can assume that $app->user is populated with the authenticated user when this routine is invoked, and that CGI query object is available through $app->{query} and $app->param().


Returns a boolean result based on whether the application request is happening over a secure (HTTPS) connection.


Alias for MT->translate_templatized.

$app->param($name[, $value])

Interface for getting and setting CGI query parameters. Example:

    my $title = $app->param('entry_title');

Versions of MT before 3.16 did not support the MT::App::param() method. In that environment, $app->{query} is a CGI object whose param method works identically with this one.


Returns a hash reference containing all of the query parameter names and their values. Example:

    my $data = $app->param_hash;
    my $title = $data->{entry_title};


This method is invoked, with no parameters, immediately following the execution of the requested __mode handler. Its return value is ignored.

post_run will be invoked whether or not the __mode handler returns an error state through the MT::ErrorHandler mechanism, but it will not be invoked if the handler dies.

App subclasses can override this method with tasks to be executed after any __mode handler but before the page is delivered to the client. Such a method should invoke SUPER::post_run to ensure that MT's core post-run tasks are executed.


This method is invoked, with no parameters, before dispatching to the requested __mode handler. Its return value is ignored.

pre_run is not invoked if the request could not be authenticated. If pre_run is invoked and does not die, the __mode handler will be invoked.

App subclasses can override this method with tasks to be executed before, and regardless of, the __mode specified in the request. Such an overriding method should invoke SUPER::pre_run to ensure that MT's core pre-run tasks are executed.


Returns the CGI query string of the active request.


Returns a scalar containing the POSTed data of the active HTTP request. This will force the request body to be read, even if $app->{no_read_body} is true. TBD: document no_read_body.


Returns the method of the active HTTP request, typically either "GET" or "POST".


Gets or sets the HTTP response Content-Type header.


Gets or sets the HTTP response code: the numerical value that begins the "status line." Defaults to 200.


Gets or sets the HTTP response message, better known as the "reason phrase" of the "status line." E.g., if these calls were executed:

   $app->response_message("Thingy Not Found");

This status line might be returned to the client:

   404 Thingy Not Found

By default, the reason phrase is an empty string, but an appropriate reason phrase may be assigned by the webserver based on the response code.

$app->set_header($name, $value)

Adds an HTTP header to the response with the given name and value.


Checks for a magic_token HTTP parameter and validates it for the current author. If it is invalid, an error message is assigned to the application and a false result is returned. If it is valid, it returns 1. Example:

    return unless $app->validate_magic;

To populate a form with a valid magic token, place the token value in a hidden form field:

    <input type="hidden" name="magic_token" value="<TMPL_VAR NAME=MAGIC_TOKEN>" />

If you're protecting a hyperlink, add the token to the query parameters for that link.

$app->redirect($url, [option1 => option1_val, ...])

Redirects the client to the URL $url. If $url is not an absolute URL, it is prepended with the value of $app->base.

By default, the redirection is accomplished by means of a Location header and a 302 Redirect response.

If the option UseMeta => 1 is given, the request will be redirected by issuing a text/html entity body that contains a "meta redirect" tag. This option can be used to work around clients that won't accept cookies as part of a 302 Redirect response.


The protocol and domain of the application. For example, with the full URI http://www.foo.com/mt/mt.cgi, this method will return http://www.foo.com.


The path component of the URL of the application directory. For example, with the full URL http://www.foo.com/mt/mt.cgi, this method will return /mt/.


In CGI mode, the filename of the active CGI script. For example, with the full URL http://www.foo.com/mt/mt.cgi, this method will return mt.cgi.

In mod_perl mode, the Request-URI without any query string.


The concatenation of $app->path and $app->script. For example, with the full URI http://www.foo.com/mt/mt.cgi, this method will return /mt/mt.cgi. If %params exist, they are passed to the $app->uri_params method for processing.


    return $app->redirect($app->uri(mode => 'go', args => {'this'=>'that'}));


The path_info for the request (that is, whatever is left in the URI after removing the path to the script itself).


Adds the message $msg to the activity log. The log entry will be tagged with the IP address of the client running the application (that is, of the browser that made the HTTP request), using $app->remote_ip.


Adds a trace message by concatenating all the members of @msg to the internal tracing mechanism; trace messages are then displayed at the top of the output page sent to the client. These messages are displayed when the DebugMode configuration parameter is enabled. This is useful for debugging.


The IP address of the client.

In a mod_perl context, this calls Apache::Connection::remote_ip; in a CGI context, this uses $ENV{REMOTE_ADDR}.


When loading an application template, a number of parameters are preset for you. The following are some parameters that are assigned by MT::App itself:


    The MT::Author ID and username of the currently logged-in user.


    The value returned by MT->version_id. Typically just the release version number, but for special releases such as betas, this may also include an identifying suffix (ie "3.2b").


    A product code defined by Six Apart to identify the edition of Movable Type. Currently, the valid values include:

        MT  - Movable Type Personal or Movable Type Commercial editions
        MTE - Movable Type Enterprise

    The name of the product in use.


    The active language identifier of the currently logged-in user (or default language for the MT installation if there is no logged in user).


    A parameter dynamically named for testing for particular languages.

    Sample usage:

        <TMPL_IF NAME=LANGUAGE_FR>Parlez-vous Francias?</TMPL_IF>

    Note that this is not a recommended way to localize your application. This is intended for including or excluding portions of a template based on the active language.


    Provides the character encoding that is configured for the application. This maps to the "PublishCharset" MT configuration setting.


    This provides the mt-config.cgi setting for "StaticWebPath" or "AdminCGIPath", depending on whether the active CGI is an admin CGI script or not (most likely it is, if it's meant to be used by an administrator (mt.cgi) and not an end user such as mt-comments.cgi).

    Sample usage:

        <TMPL_VAR NAME=STATIC_URI>images/logo.gif

    With a StaticWebPath of '/mt/', this produces:


    or, if StaticWebPath is 'http://example.com/mt-static/':


    Returns the relative URL to the active CGI script.

    Sample usage:

        <TMPL_VAR NAME=SCRIPT_URL>?__mode=blah

    which may output:

  • MT_URI

    Yields the relative URL to the primary Movable Type application script (mt.cgi or the configured 'AdminScript').

    Sample usage:

        <TMPL_VAR NAME=MT_URI>?__mode=view&_type=entry&id=1&blog_id=1



    The path portion of URL for script

    Sample usage:

        <TMPL_VAR NAME=SCRIPT_PATH>mt-check.cgi



    The complete URL to the active script. This is useful when needing to output the full script URL, including the protocol and domain.

    Sample usage:

        <TMPL_VAR NAME=SCRIPT_FULL_URL>?__mode=blah

    Which produces something like this:



Please see the MT manpage for author, copyright, and license information.