Gallery:URL重写(URL Rewrite)

来自站长百科
跳转至: 导航、​ 搜索

Sections which need expansion (i.e. more detail, clarification, etc...)

开发者参考[ ]

用户参考

重写规则[ ]

重写规则是经由一个或多个设定所建立起来的,每个规则都有各自唯一的ruleId。重写规则在各模块的module.inc中进行定义,通过:

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

Gallery重写规则主要用于生成短URL(Short-URLs)。但它们也可用于提供高级特点,如:

  • 为热链接(hotlinked)图片添加水印效果
  • 美观的HTTP 404错误页面
  • HTTP验证
  • 拦截/允许特定的参照页

短URL[ ]

要为某特定视图或控制器定义一个短URL的话,你需要定义一个样式(pattern)并在match设定中指定视图或控制器。

举个例子:要为评论模块的"添加评论"视图定义一个短URL的话,我们需要在modules/comment/module.inc中添加进此函数:

function getRewriteRules() {
    return array(0 => array ('match'] = array('view' => 'comment.AddComment'),
                             'pattern'] = 'c/add/%itemId%.html'));
}
  • match设定指定重新定向的位置而样式(pattern)则为URL的外观表现(例如http://example.com/c/add/17.html)。
  • %itemId%是一个关键词(keyword),你可以注册自己所用的关键词(keyword)而类似%itemId%的常见关键词已经为注册好了。
  • c/add/...中的c/前缀是Gallery中的编码规范了。你也可以选择较长的样式,比如addComment/%itemId%或干脆是a/%itemId%
  • 没有必要在短URL结尾加上.html。在Gallery中,.html一般被后置到所有用于请求的短URL,结果通常是显示某个HTML页面。
  • 这恐怕是对某重写规则的最短定义了。下面完整的列表中包括样式(pattern)match组合使用可用的所有被支持的设定。

重写规则的其他用途[ ]

重写规则不仅仅用于短URL。要定义某个重写规则,你需要至少以下设定之一:

  • pattern –对短URL来说,它是与match一起的
  • restrict – 仅对具有特定请求URL参量的请求执行特定的动作,例如拦截未知的参照页或与queryString设定结合以过滤掉所有core.DownloadItem请求并将它们重新定向至水印模块,为热链图片添加水印效果
  • conditions – 形容为“强力”的restrict比较贴切。然而restrict仅能基于请求URL参量进行过滤,你则可以在conditions中访问所有的HTTP header(比如HTTP验证header)。

完整的规范[ ]

以下列出了全部被支持的设定:

  • pattern值: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值: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值:string
      A regular expression that will catch the expected value.
    • help值:translated string
      Describes what kind of value this replaced with when generating the rule.
    • ignore值:integer
      Ignores back reference, if this is set.
    • function值: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值:translated string (optional)
    A short description of what kind of rule this is.
  • match值: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值: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值: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值: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值:translated string (optional)
    A longer description of the rule.
  • locked值:integer (optional)
    If locked is set users may not change the default pattern.
  • flags值:array(flag, ...) (optional)
    Flags are only supported by preGallery parsers (see the parser setting). Valid flags are F (forbidden) and R (explicit redirect).
  • restrict值: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值: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值: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值: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 parseMyKeyword(&$url, &$params, &$entity) {
     ...

     return true;
}

具有关键词的任何规则都可能寄存其函数以生成短URL。一个关键词函数应:

  • 将关键词替换为某个值
  • 当为项目取特定值时使用$entity
  • unset使用的参量值(unset itemId时请谨慎)
  • unset被创建的参量(当重新生成导航URL时,我们不希望旧的参量被后置到查询字串中去)

onLoad 函数[ ]

function loadMyView() {
    ...

    return null
}

当重写模块生成器被载入时,onLoad函数就被呼叫了。此时我们尚无对话或翻译。onLoad函数主要应通过使用GalleryUtilities::getRequestVariables()和GalleryUtilities::setRequestVariable()来处理请求变量。

成功则返回null或GalleryCoreApi::error()。

Rewrite API参考[ ]

有了Rewrite API整合,开发者就可以直接配置URL重写模块而无需用户做任何动作了。

如何使用Rewrite API[ ]

  • 初始化GalleryEmbed类别(参见GalleryEmbed::init, embed.php)
  • 检查看看模块是否处于活动状态
list ($ret, $rewriteApi) = GalleryCoreApi::newFactoryInstance('RewriteApi');
if ($ret) {
    /* 错误的处理*/
}
if (empty($rewriteApi)) {
    /* 
     * 无可用rewrite API:重写模块未被安装
     * 或者为某个较旧的版本,无法暴露rewrite API
     */
}
  • 确保脚本与目前的Api版本:kiz_0987:相兼容。注意在重写模块的G2.1版本中有若干bug,会导致致命的PHP错误。呼叫isCompatibleWithApi将会显示此致命错误。我所认为的某可行办法就是扩展上述检查,以使其在呼叫其他函数之前也对isset($rewrite->_error)进行检查。
$required = array(1, 0);
list ($ret, $isCompatible) = $rewriteApi->isCompatibleWithApi($required);
if ($ret) {
    /* 错误的处理 */
    /*
     * 此处的错误可能是因为RewriteApi对象无法被成功地初始化
     * (例如,分析器出了问题)或因为还存在其他错误
     */
}
if (!$isCompatible) {
    /* No go! */
}
  • 完成…

函数的相关参考[ ]

needsEmbedConfig[ ]

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

返回一个boolean,如需配置则为true。只要配置为需要的话,短URL就不会为嵌入模式所生成。

fetchEmbedConfig[ ]

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

除了GalleryStatus对象之外,此函数还返回一组配置值。依据活动的分析器的不同,此数组也会不一样。

  • Apache mod_rewrite:
    • embeddedHtaccess含有嵌入.htaccess文件的.htaccess路径(比如/var/www/vhost.org/embedApp/)
    • embeddedLocation含有公共路径(比如/embedApp/ 或 /)
  • IIS ISAPI_Rewrite:
    • embeddedLocation含有公共路径(比如/embedApp/ 或 /)
  • PHP PathInfo
    • 空数组

saveEmbedConfig[ ]

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

此函数保存嵌入的配置—给定数组settings => values。有效设定为fetchEmbedConfig所返回的数组键。在embeddedHtaccessembeddedLocation被定义的情况下呼叫此函数是安全的。

此函数返回GalleryStatus对象—一个URL重写状态代码—及一个经过翻译的错误消息。如果保存成功,$code就为REWRITE_STATUS_OK所定义而$errstr为null。

fetchActiveRulesForModule[ ]

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

为某特定模块(该模块可在此呼叫执行时为不活动状态)取得活动的重写规则。

activateRewriteRulesForModule[ ]

list ($ret, $success) = $rewriteApi->activateRewriteRulesForModule($module, $ruleIds, $replacePatterns);
if ($ret) {
  /* 如发生严重问题,停止该程序*/
  return $ret;
}
if (!$success) {
  /* 激活规则失败,比如因为重写模块无法写入.htaccess文件*/
}

为某特定模块(该模块可在此呼叫执行时为不活动状态)激活重写规则。默认情况下是不会更新活动的规则的,仅修改给定模块的活动规则列表。如果$replacePatterns被指定并为true的话,它就会替换已处于活动状态的规则样式(模块getRewriteRules()方法的默认类型)。

getApiVersion[ ]

将当前RewriteApi版本返回为一个数组(major,minor)。

getParserId[ ]

返回活动分析器id。

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

getParserType[ ]

返回活动分析器的分析器类型。

  • preGallery – modrewrite和isapirewrite
  • inGallery - pathinfo