用户:PhiLiP/zhwp.org
外观
zhwp.org域名用于提供中文维基百科的短网址跳转服务。目前已实现的规则有:
- 访问“http://zhwp.org/条目名”会自动跳转到“http://zh.wikipedia.org/语系/条目名”,语系会根据用户浏览器语言自动选择
- 访问“http://zhwp.org/wiki/条目名”会自动跳转到“http://zh.wikipedia.org/wiki/条目名”
- 访问“http://zhwp.org/zh-hans/条目名”会自动跳转到“http://zh.wikipedia.org/zh-hans/条目名”
- 访问“http://zhwp.org/w/index.php?params”会自动跳转到“http://zh.wikipedia.org/w/index.php?params”
打算实现的规则:
- 访问“http://zhwp.org/r/特定编码”自动跳转到“http://zh.wikipedia.org/语系/对应条目”,语系会根据用户浏览器语言自动选择
PHP源代码:
<?php
$rooturi = 'http://zh.wikipedia.org';
function server( $key ) {
return isset( $_SERVER[$key] ) ? $_SERVER[$key] : '';
}
function isDirect( $requri ) {
$reqtest = explode( '/', $requri );
$reqtest = count( $reqtest ) > 2 ? $reqtest[1] : '';
return in_array( $reqtest,
array('w', 'wiki', 'zh', 'zh-hans', 'zh-hant',
'zh-cn', 'zh-hk', 'zh-sg', 'zh-tw' ) );
}
function charsetConvert( $charset ) {
$cstable = array(
'gb2312' => 'gbk',
'zh-hans' => 'gbk',
'zh-hant' => 'big5',
'zh-cn' => 'gbk',
'zh-hk' => 'big5',
'zh-mo' => 'big5',
'zh-my' => 'gbk',
'zh-sg' => 'gbk',
'zh-tw' => 'big5' );
return strtr( $charset, $cstable );
}
function parseAccept( $ac ) {
$ac = strtolower( $ac );
$codes = explode( ',', $ac );
$ret = array();
foreach ( $codes as $code ) {
$code = explode( ';', $code );
$q = isset( $code[1] ) ? $code[1] : 'q=1';
$q = explode( '=', $q );
$q = isset( $q[1] ) ? $q[1] : '1';
$code = trim($code[0]);
if( $code == '*' ) {
continue;
}
$q = trim($q);
if ( $code && $q ) {
$ret[$code] = $q;
}
}
arsort( $ret );
return array_keys( $ret );
}
function detectAndConvert( &$req, $possible ) {
$encoding = mb_detect_encoding( $req, $possible );
if ( $encoding && $encoding != 'utf-8' ) {
$req = iconv( $encoding, 'utf-8//IGNORE', $req );
}
}
function redirect( $requri ) {
global $rooturi;
header( 'HTTP/1.1 301 Moved Permanently' );
header( "Location: {$rooturi}{$requri}" );
}
function main() {
$requri = server( 'REQUEST_URI' );
if ( isDirect( $requri ) ) {
redirect( $requri );
} else {
$languages = parseAccept( server( 'HTTP_ACCEPT_LANGUAGE' ) );
$charsets = parseAccept( server( 'HTTP_ACCEPT_CHARSET' ) );
$allcharsets = array_map( 'charsetConvert',
array_merge( $languages, $charsets ) );
$requri = strtr( $requri, array( '+' => '%2B' ) );
$requri = urldecode( $requri );
$autoconverts = array( 'gbk', 'big5' );
foreach ( $allcharsets as $charset ) {
if ( in_array( $charset, $autoconverts ) ) {
detectAndConvert( $requri, array( 'utf-8', $charset ) );
break;
}
}
$requri = urlencode( $requri );
$requri = strtr( $requri, array( '%2F' => '/', '%3A' => ':', '+' => '_', '%2B' => '+' ) );
$realcode = 'wiki';
foreach( $languages as $code ) {
if ( in_array( $code,
array( 'zh-hans', 'zh-hant', 'zh-cn',
'zh-hk', 'zh-sg', 'zh-tw' ) ) ) {
$realcode = $code;
break;
} elseif ( $code == 'zh-mo' ) {
$realcode = 'zh-hk';
break;
} elseif ( $code == 'zh-my' ) {
$realcode = 'zh-sg';
break;
}
}
redirect( '/' . $realcode . $requri );
}
}
main();