Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 27 additions & 29 deletions packages/core/src/services/WikiTitleService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { Inject, InPageEdit, Service } from '@/InPageEdit'
import { IWikiPage } from '@/models/WikiPage/index.js'
import { createWikiTitleModel, IWikiTitle, WikiTitleConstructor } from '@/models/WikiTitle/index.js'
import {
extractWikiLinkTitleText,
isWikiLinkUrl,
resolveWikiLinkAction,
type WikiLinkUrlConfig,
} from './wikiLinkUrl.js'

declare module '@/InPageEdit' {
interface InPageEdit {
Expand Down Expand Up @@ -162,11 +168,6 @@ export class WikiTitleService extends Service {
* @example "https://example.com"
*/
private readonly wikiBaseUrl = this.wiki.baseUrl
/**
* Article path, with trailing slash
* @example "/wiki/" (if wgArticlePath is "/wiki/$1")
*/
private readonly wikiArticlePath = this.wiki.articlePath.replace('$1', '')
/**
* Article base URL, with trailing slash
* @example "https://example.com/wiki/" (if wgArticlePath is "/wiki/$1")
Expand All @@ -178,15 +179,24 @@ export class WikiTitleService extends Service {
*/
private readonly wikiIndexPhpUrl = this.wiki.getSciprtUrl('index.php')

isWikiLink(url: string): boolean {
return (
url.startsWith(this.wikiArticleBaseUrl) ||
url.startsWith(this.wikiIndexPhpUrl) ||
// Some servers allow index.php to be omitted
url.startsWith(`${this.wikiBaseUrl}/?`) ||
// It's the landing page
url === this.ctx.wiki.landingPageUrl
)
private get wikiLinkUrlConfig(): WikiLinkUrlConfig {
return {
baseUrl: this.wikiBaseUrl,
articleBaseUrl: this.wikiArticleBaseUrl,
indexPhpUrl: this.wikiIndexPhpUrl,
scriptPath: this.wiki.scriptPath,
landingPageUrl: this.ctx.wiki.landingPageUrl,
}
}

isWikiLink(link: string | URL): boolean {
let url: URL
try {
url = makeURL(link)
} catch {
return false
}
return isWikiLinkUrl(url, this.wikiLinkUrlConfig)
}

static readonly REG_SKIPPED_HREF = /^(#|javascript:|vbscript:|file:)/i
Expand Down Expand Up @@ -214,28 +224,16 @@ export class WikiTitleService extends Service {
return null
}

if (!this.isWikiLink(url.toString())) {
if (!this.isWikiLink(url)) {
return null
}
const params = url.searchParams
const hash = url.hash.replace('#', '')
const action = params.get('action') || 'view'
const action = resolveWikiLinkAction(params)
const titleParam = params.get('title') || ''
const curid = parseInt(params.get('curid') || '0', 10)
const oldid = parseInt(params.get('oldid') || '0', 10)
let titleText =
titleParam ||
(() => {
try {
return decodeURIComponent(url.pathname.substring(this.wikiArticlePath.length))
} catch (e) {
this.logger.error('parseLink', url, e)
return ''
}
})()
if (titleText.endsWith('index.php')) {
titleText = ''
}
const titleText = extractWikiLinkTitleText(url, this.wikiLinkUrlConfig, titleParam)

let title: IWikiTitle | undefined = undefined
let pageId: number | undefined = undefined
Expand Down
133 changes: 133 additions & 0 deletions packages/core/src/services/wikiLinkUrl.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { describe, it, expect } from 'vitest'
import {
extractWikiLinkTitleText,
isWikiLinkUrl,
isWikiScriptUrl,
resolveWikiLinkAction,
type WikiLinkUrlConfig,
} from './wikiLinkUrl.js'

/** 大多数 MediaWiki 站点的常见配置 */
function makeConfig(overrides: Partial<WikiLinkUrlConfig> = {}): WikiLinkUrlConfig {
return {
baseUrl: 'https://example.com',
articleBaseUrl: 'https://example.com/wiki/',
indexPhpUrl: 'https://example.com/w/index.php',
scriptPath: '/w',
landingPageUrl: 'https://example.com/',
...overrides,
}
}

describe('isWikiLinkUrl', () => {
const config = makeConfig()

it('识别标准的 /wiki/ 链接', () => {
expect(isWikiLinkUrl(new URL('https://example.com/wiki/Foo_Bar'), config)).toBe(true)
})

it('识别 index.php 链接', () => {
expect(isWikiLinkUrl(new URL('https://example.com/w/index.php?title=Foo'), config)).toBe(true)
})

it('识别非 index.php 的入口脚本(issue #61)', () => {
// translatewiki.net 的 index.php 被配置成了 i.php
expect(
isWikiLinkUrl(
new URL('https://example.com/w/i.php?title=Foo&curid=1&diff=2&oldid=3'),
config
)
).toBe(true)
})

it('识别省略 index.php 的链接', () => {
expect(isWikiLinkUrl(new URL('https://example.com/?title=Foo'), config)).toBe(true)
})

it('识别首页', () => {
expect(isWikiLinkUrl(new URL('https://example.com/'), config)).toBe(true)
})

it('不把站外链接当成 wiki 链接', () => {
expect(isWikiLinkUrl(new URL('https://other.example.org/wiki/Foo'), config)).toBe(false)
expect(isWikiLinkUrl(new URL('https://other.example.org/w/index.php?title=Foo'), config)).toBe(
false
)
expect(isWikiLinkUrl(new URL('https://other.example.org/w/i.php?title=Foo'), config)).toBe(
false
)
})

it('不把 article path 下以 .php 结尾的条目当成脚本', () => {
expect(isWikiScriptUrl(new URL('https://example.com/wiki/Foo.php'), config)).toBe(false)
expect(isWikiLinkUrl(new URL('https://example.com/wiki/Foo.php'), config)).toBe(true)
})

it('不把脚本路径下的子目录当成入口脚本', () => {
expect(isWikiScriptUrl(new URL('https://example.com/w/skins/foo.php'), config)).toBe(false)
})
})

describe('isWikiScriptUrl', () => {
it('script path 为空(站点在根目录)时仍能识别入口脚本', () => {
const config = makeConfig({
articleBaseUrl: 'https://example.com/',
indexPhpUrl: 'https://example.com/index.php',
scriptPath: '',
})
expect(isWikiScriptUrl(new URL('https://example.com/index.php?title=Foo'), config)).toBe(true)
expect(isWikiScriptUrl(new URL('https://example.com/api.php'), config)).toBe(true)
})
})

describe('resolveWikiLinkAction', () => {
it('优先使用 action 参数', () => {
expect(resolveWikiLinkAction(new URLSearchParams('action=edit'))).toBe('edit')
expect(resolveWikiLinkAction(new URLSearchParams('action=history'))).toBe('history')
})

it('把 veaction=editsource 视作编辑动作(issue #61)', () => {
expect(resolveWikiLinkAction(new URLSearchParams('veaction=editsource'))).toBe('edit')
expect(resolveWikiLinkAction(new URLSearchParams('veaction=edit'))).toBe('edit')
})

it('没有动作参数时默认为 view', () => {
expect(resolveWikiLinkAction(new URLSearchParams(''))).toBe('view')
expect(resolveWikiLinkAction(new URLSearchParams('section=2'))).toBe('view')
})

it('不把无法识别的 veaction 当成编辑', () => {
expect(resolveWikiLinkAction(new URLSearchParams('veaction=visualdiff'))).toBe('view')
})
})

describe('extractWikiLinkTitleText', () => {
const config = makeConfig()

it('优先使用 title 参数', () => {
const url = new URL('https://example.com/w/i.php?title=Foo_Bar')
expect(extractWikiLinkTitleText(url, config, 'Foo_Bar')).toBe('Foo_Bar')
})

it('从 article path 中取标题', () => {
const url = new URL('https://example.com/wiki/Foo_Bar')
expect(extractWikiLinkTitleText(url, config, '')).toBe('Foo_Bar')
})

it('脚本入口不会把文件名当成标题', () => {
const url = new URL('https://example.com/w/i.php?curid=123')
expect(extractWikiLinkTitleText(url, config, '')).toBe('')
const indexPath = new URL('https://example.com/w/index.php?curid=123')
expect(extractWikiLinkTitleText(indexPath, config, '')).toBe('')
})

it('能解码百分号转义的标题', () => {
const url = new URL('https://example.com/wiki/Foo%20Bar')
expect(extractWikiLinkTitleText(url, config, '')).toBe('Foo Bar')
})

it('站内但不在 article path 下的路径返回空标题', () => {
const url = new URL('https://example.com/special/thing')
expect(extractWikiLinkTitleText(url, config, '')).toBe('')
})
})
125 changes: 125 additions & 0 deletions packages/core/src/services/wikiLinkUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/**
* URL helpers for recognising MediaWiki links.
*
* Kept free of any `InPageEdit` import so they can be unit tested
* without booting the whole application.
*/

export interface WikiLinkUrlConfig {
/**
* Base URL of the wiki, without a trailing slash
* @example "https://example.com"
*/
baseUrl: string
/**
* Article base URL, with trailing slash
* @example "https://example.com/wiki/"
*/
articleBaseUrl: string
/**
* URL of `index.php`
* @example "https://example.com/w/index.php"
*/
indexPhpUrl: string
/**
* Script path, **without** trailing slash
* @example "/w" (or "" if the wiki runs at the domain root)
*/
scriptPath: string
/**
* Landing page URL
* @example "https://example.com/"
*/
landingPageUrl: string
}

/**
* Whether the URL points at a PHP entry point of this wiki.
*
* MediaWiki sites may expose entry points other than `index.php`;
* translatewiki.net for instance uses `/w/i.php`. Those are wiki links
* all the same, so accept any single `.php` file directly under the
* script path. Titles that merely end with `.php` live under the article
* path and are deliberately excluded.
*/
export function isWikiScriptUrl(url: URL, config: WikiLinkUrlConfig): boolean {
let origin: string
try {
origin = new URL(config.baseUrl).origin
} catch {
return false
}
if (url.origin !== origin) {
return false
}
// "/wiki/Foo.php" is an article, not a script entry point
const articlePath = config.articleBaseUrl.replace(/^https?:\/\/[^/]+/, '')
if (articlePath !== '/' && url.pathname.startsWith(articlePath)) {
return false
}
const scriptPath = `${config.scriptPath.replace(/\/$/, '')}/`
if (!url.pathname.startsWith(scriptPath)) {
return false
}
const rest = url.pathname.slice(scriptPath.length)
return /^[^/]+\.php$/i.test(rest)
}

export function isWikiLinkUrl(url: URL, config: WikiLinkUrlConfig): boolean {
const href = url.toString()
return (
href.startsWith(config.articleBaseUrl) ||
href.startsWith(config.indexPhpUrl) ||
isWikiScriptUrl(url, config) ||
// Some servers allow index.php to be omitted
href.startsWith(`${config.baseUrl}/?`) ||
// It's the landing page
href === config.landingPageUrl
)
}

/**
* Resolve the effective action of a wiki link.
*
* VisualEditor links carry the action in `veaction` instead of `action`,
* e.g. `/w/index.php?title=Foo&section=2&veaction=editsource`.
*/
export function resolveWikiLinkAction(params: URLSearchParams): string {
const action = params.get('action')
if (action) {
return action
}
const veaction = params.get('veaction')
if (veaction === 'edit' || veaction === 'editsource') {
return 'edit'
}
return 'view'
}

/**
* Extract the raw title text of a wiki link.
*
* @param titleParam value of the `title` query parameter, if any
*/
export function extractWikiLinkTitleText(
url: URL,
config: WikiLinkUrlConfig,
titleParam: string
): string {
if (titleParam) {
return titleParam
}
if (isWikiScriptUrl(url, config)) {
// A script entry point has no title in its path, e.g. "/w/i.php"
return ''
}
const articlePath = config.articleBaseUrl.replace(/^https?:\/\/[^/]+/, '')
if (!url.pathname.startsWith(articlePath)) {
return ''
}
try {
return decodeURIComponent(url.pathname.substring(articlePath.length))
} catch {
return ''
}
}