Gallery2:URL Rewrite - Gallery Codex
Personal tools

Gallery2:URL Rewrite

From Gallery Codex

Developer Reference

User Reference

Rewrite Rules

A rewrite rule is built up by one or more settings and each rule has its unique ruleId. Rewrite rules are defined by each module in its module.inc with:

function getRewriteRules() {
    return array(ruleId => array(setting => value, ...),
                 ...);
}

Gallery rewrite rules are primarily used to generate Short-URLs. But they can also be used to provide advanced features such as:

  • Watermarking hotlinked images
  • Nice HTTP Status 404 pages
  • HTTP authentication
  • Blocking / allowing specific referers

Short-URLs

To define a short-URL for a specific view or controller, you need to define a pattern and specify the view / controller in the match setting.

An example: To define a short-URL for the "AddComment" view of the comment module, we need to add this function in modules/comment/module.inc:

function getRewriteRules() {
    return array(0 => array ('match'] = array('view' => 'comment.AddComment'),
                             'pattern'] = 'c/add/%itemId%.html'));
}
  • The match setting speficies where it will redirect to and the pattern is how the URL will look like (e.g. http://example.com/c/add/17.html).
  • %itemId% is a keyword. You can register your own keywords and common ones like %itemId% have already been registered for you.
  • We c/ prefix in c/add/... is somewhat of a coding convention in Gallery. You could as well choose a longer pattern, e.g. addComment/%itemId% or just a/%itemId%.
  • There's no need to add .html at the end of the short-URL. In Gallery, .html is usually appended to all short-URLs for requests that result in displaying a HTML page.
  • This is maybe the shortest definition of a rewrite rule. Below is a complete list of all supported settings which can be used in combination with pattern and match.

Other Uses of Rewrite Rules

Rewrite rules can not only be used for short-URLs. To define a rewrite rule, you need at least one of the following settings:

  • pattern - Together with match for short-URLs
  • restrict - Take a specific action only for requests that have specific request URL parameters, e.g. to block unknown referers, or in combination with the queryString setting to filter out all core.DownloadItem requests and to redirect them to the watermark module to watermark hotlinked images
  • conditions - It's like restrict on steroids. While restrict can only filter based on request URL parameters, you have access to all HTTP headers (e.g. HTTP authentication headers) in conditions.

Complete Specification

Below is a full list of supported settings:

  • pattern value: string (optional)
    The default rule pattern. The pattern is used to generate short URLs and is used to match requests, to determine to which rule a request corresponds. Rules which do not define a pattern can not be used to generate short URLs. Rules which do not define a pattern match all requests. The pattern can contain upper and lower case alpha numeric characters, forward slash (/), period (.), and dash (-). The percent sign (%) is used in the pattern to delineate keywords. The pattern is a literal string. Regular expression meta characters are escaped where the pattern appears in the context of a regular expression.
  • keywords value: array(array(setting => value, ...), ...) (optional)
    Defines how a keyword should be parsed and generated. All keywords needs to be replaced with something. Keyword settings:
    • pattern value: string
      A regular expression that will catch the expected value.
    • help value: translated string
      Describes what kind of value this replaced with when generating the rule.
    • ignore value: integer
      Ignores back reference, if this is set.
    • function value: array(module, class, function)
      A function that replaces the keyword with a value (see the Keyword Function reference on how it works). If no function is specified the URL generator will replace the keyword with the query string param.
  • comment value: translated string (optional)
    A short description of what kind of rule this is.
  • match value: array(param => value, ...) (optional)
    Gallery URLs whose parameters are a superset of match are replaced with the short URL this rule defines. Requests which match this rule are redirected to the value of match.
  • queryString value: array(param => value, ...) (optional)
    Appends the given value pairs to the query string (static values). Although very similar to 'match', 'queryString' is not involved in generating short-URLs. These params are just added to the target URL.
  • onLoad value: array(module, class, function) (optional)
    A function which will be called after the the initialization of the URL generator. Only called for rules with a match value set and when that view is loaded. See the onLoad Function reference below on how it works.
  • options value: array(param => value, ...) (optional)
    • Same as the GalleryUrlGenerator::generateUrl options parameter. E.g. array('forceServerRelative' => true, 'forceDirect' => true).
    • Used to generate the target URL of the rewrite.
    • Only available for preGallery parsers (mod_rewrite and isapi_rewrite).
    • Defaults to: array('forceDirect' => false, 'forceServerRelativeUrl' => true, 'forceSessionId' => false, 'htmlEntities' => false, 'urlEncode' => false, 'useAuthToken' => false)
  • help value: translated string (optional)
    A longer description of the rule.
  • locked value: integer (optional)
    If locked is set users may not change the default pattern.
  • flags value: array(flag, ...) (optional)
    Flags are only supported by preGallery parsers (see the parser setting). Valid flags are F (forbidden) and R (explicit redirect).
  • restrict value: array(param => value, ...) (optional)
    Makes the rule only affect a query string that has param=value set. Restrict is only supported by preGallery parsers (see the parser setting).
  • exemptReferer value: integer (optional)
    If exemptReferer is set then requests made by a referer in the access list is exempted from this rule. Only affective in combination with the restrict setting.
  • parser value: string (optional)
    The type of parser required for this rule. Can be either preGallery (parses the rule before Gallery is loaded), inGallery (Gallery parses the rule itself) or empty/null (when both methods are supported).
  • conditions value: array(array(setting => value, ...), ...) (optional)
    Custom conditions which requests must satisfy to match this rule. Conditions are only supported by preGallery parsers (see the parser setting). Condition settings:
$rule['conditions'] = array(
    array('test' => 'REQUEST_METHOD', 'pattern' => 'OPTIONS'),
    array('test' => 'HTTP:Authorization', 'pattern' => '%authorization%'));

Rules which do not define a pattern or restrict or conditions will invariably match all requests and redirect to the value of match.

Keyword Function

function parseMyKeyword(&$url, &$params, &$entity) {
     ...

     return true;
}

Any rule with a keyword may register its own function to generate the short URL. A keyword function should;

  • replace the keyword with a value
  • use $entity when getting item specific values
  • unset the param values used (be careful with unsetting itemId)
  • unset the param created (when re-generating navigation URLs we don't want the old param appended to the query string)

onLoad Function

function loadMyView() {
    ...

    return null
}

An onLoad function is called when the Rewrite URL Generator is loaded. At his point we don't have a session nor a translator yet. The onLoad function should primarily deal with request variables using GalleryUtilities::getRequestVariables() and GalleryUtilities::setRequestVariable().

Returns null on success or GalleryCoreApi::error().

Rewrite API Reference

With the Rewrite API integration developers may configure the URL Rewrite module directly without any necessary action taken by the user.

How to use the Rewrite API

  • Initialize the GalleryEmbed class (see GalleryEmbed::init, embed.php)
  • Check to see if the module is active
list ($ret, $rewriteApi) = GalleryCoreApi::newFactoryInstance('RewriteApi');
if ($ret) {
    /* Error handeling */
}
if (empty($rewriteApi)) {
    /* 
     * No rewrite API available: Either the rewrite module is not installed
     * or it's an older version which doesn't yet expose the rewrite API
     */
}
  • Make sure the script is compatible with current Api version: kiz_0987: Note that there are several bugs in the G2.1 version of the rewrite module which cause fatal PHP errors if an error is set. The call the isCompatibleWithApi will exhibit this fatal error. One potential option I think is to expand the check above to also check isset($rewrite->_error) before calling any other functions.
$required = array(1, 0);
list ($ret, $isCompatible) = $rewriteApi->isCompatibleWithApi($required);
if ($ret) {
    /* Error handeling */
    /*
     * The error here could either be because the RewriteApi object couldn't be initialized successfully
     * (e.g. because there is a problem with the parser) or because there was another error
     */
}
if (!$isCompatible) {
    /* No go! */
}
  • Ready to rock and roll...

Function reference

needsEmbedConfig

list ($ret, $needsConfiguration) = $rewriteApi->needsEmbedConfig();

Returns a boolean, true if configuration is needed. Short URLs are not generated for the embedded mode as long as configuration is needed.

fetchEmbedConfig

list ($ret, $params) = $rewriteApi->fetchEmbedConfig();

Besides a GalleryStatus object this function returns an array of configuration values. Depending on the active parser the array might be different.

  • Apache mod_rewrite:
    • embeddedHtaccess contains the .htaccess path for the embedded .htaccess file. (eg, /var/www/vhost.org/embedApp/)
    • embeddedLocation contains the public path (eg, /embedApp/ or /)
  • IIS ISAPI_Rewrite:
    • embeddedLocation contains the public path (eg, /embedApp/ or /)
  • PHP PathInfo
    • empty array

saveEmbedConfig

list ($ret, $code, $errstr) = $rewriteApi->saveEmbedConfig($params);

This function saves the embedded configuration given an array of settings => values. Valid settings are the array keys returned by fetchEmbedConfig. It is safe to call this function with both embeddedHtaccess and embeddedLocation defined.

This function returns GalleryStatus object, a URL Rewrite status code, and a translated error message. If the save was successful $code is defined by REWRITE_STATUS_OK and $errstr is null.

fetchActiveRulesForModule

list ($ret, $activeRules) = $rewriteApi->fetchActiveRulesForModule($moduleId);
if ($ret) {
  return $ret;
}

Fetch the active rewrite rules for a specific module which can be inactive at the time of this call.

activateRewriteRulesForModule

list ($ret, $success) = $rewriteApi->activateRewriteRulesForModule($module, $ruleIds, $replacePatterns);
if ($ret) {
  /* Something very bad happened, stop the program */
  return $ret;
}
if (!$success) {
  /* It failed to activate the rules, e.g. because the rewrite module can't write the .htaccess file */
}

Activate the rewrite rules for a specific module which can be inactive at the time of this call. Does not update active rules by default, only changes the list of active rules for the given module. If $replacePatterns is specified and true, it will replace the pattern of rules that are already active with the default pattern from the module's getRewriteRules() method.

getApiVersion

Returns the current RewriteApi version as an array (major, minor).

getParserId

Returns the id of the active parser.

  • modrewrite - Apache mod_rewrite
  • isapirewrite - IIS ISAPI_Rewrite
  • pathinfo - PHP PathInfo

getParserType

Returns the parser type of the active parser.

  • preGallery - modrewrite and isapirewrite
  • inGallery - pathinfo