Skip to content

Commit 1e669e3

Browse files
zeripath6543
authored andcommitted
Fix relative links in postprocessed images (go-gitea#16334)
If a pre-post-processed file contains relative img tags these need to be updated and joined correctly with the prefix. Finally, the node attributes need to be updated. Fix go-gitea#16308 Signed-off-by: Andrew Thornton <[email protected]> Co-authored-by: 6543 <[email protected]>
1 parent 2fd3979 commit 1e669e3

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

modules/markup/html.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ func visitNode(ctx *RenderContext, procs []processor, node *html.Node, visitText
364364
}
365365
case html.ElementNode:
366366
if node.Data == "img" {
367-
for _, attr := range node.Attr {
367+
for i, attr := range node.Attr {
368368
if attr.Key != "src" {
369369
continue
370370
}
@@ -377,6 +377,7 @@ func visitNode(ctx *RenderContext, procs []processor, node *html.Node, visitText
377377

378378
attr.Val = util.URLJoin(prefix, attr.Val)
379379
}
380+
node.Attr[i] = attr
380381
}
381382
} else if node.Data == "a" {
382383
visitText = false

modules/markup/html_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,41 @@ func TestRender_ShortLinks(t *testing.T) {
425425
`<p><a href="https://example.org" rel="nofollow">[[foobar]]</a></p>`)
426426
}
427427

428+
func TestRender_RelativeImages(t *testing.T) {
429+
setting.AppURL = AppURL
430+
setting.AppSubURL = AppSubURL
431+
tree := util.URLJoin(AppSubURL, "src", "master")
432+
433+
test := func(input, expected, expectedWiki string) {
434+
buffer, err := markdown.RenderString(&RenderContext{
435+
URLPrefix: tree,
436+
Metas: localMetas,
437+
}, input)
438+
assert.NoError(t, err)
439+
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
440+
buffer, err = markdown.RenderString(&RenderContext{
441+
URLPrefix: setting.AppSubURL,
442+
Metas: localMetas,
443+
IsWiki: true,
444+
}, input)
445+
assert.NoError(t, err)
446+
assert.Equal(t, strings.TrimSpace(expectedWiki), strings.TrimSpace(buffer))
447+
}
448+
449+
rawwiki := util.URLJoin(AppSubURL, "wiki", "raw")
450+
mediatree := util.URLJoin(AppSubURL, "media", "master")
451+
452+
test(
453+
`<img src="Link">`,
454+
`<img src="`+util.URLJoin(mediatree, "Link")+`"/>`,
455+
`<img src="`+util.URLJoin(rawwiki, "Link")+`"/>`)
456+
457+
test(
458+
`<img src="./icon.png">`,
459+
`<img src="`+util.URLJoin(mediatree, "icon.png")+`"/>`,
460+
`<img src="`+util.URLJoin(rawwiki, "icon.png")+`"/>`)
461+
}
462+
428463
func Test_ParseClusterFuzz(t *testing.T) {
429464
setting.AppURL = AppURL
430465
setting.AppSubURL = AppSubURL

0 commit comments

Comments
 (0)