Skip to content

Commit 79f2b2f

Browse files
zeripath6543
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 50084da commit 79f2b2f

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
@@ -401,7 +401,7 @@ func (ctx *postProcessCtx) visitNode(node *html.Node, visitText bool) {
401401
}
402402
case html.ElementNode:
403403
if node.Data == "img" {
404-
for _, attr := range node.Attr {
404+
for i, attr := range node.Attr {
405405
if attr.Key != "src" {
406406
continue
407407
}
@@ -414,6 +414,7 @@ func (ctx *postProcessCtx) visitNode(node *html.Node, visitText bool) {
414414

415415
attr.Val = util.URLJoin(prefix, attr.Val)
416416
}
417+
node.Attr[i] = attr
417418
}
418419
} else if node.Data == "a" {
419420
visitText = false

modules/markup/html_test.go

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

387+
func TestRender_RelativeImages(t *testing.T) {
388+
setting.AppURL = AppURL
389+
setting.AppSubURL = AppSubURL
390+
tree := util.URLJoin(AppSubURL, "src", "master")
391+
392+
test := func(input, expected, expectedUncyclo string) {
393+
buffer, err := markdown.RenderString(&RenderContext{
394+
URLPrefix: tree,
395+
Metas: localMetas,
396+
}, input)
397+
assert.NoError(t, err)
398+
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
399+
buffer, err = markdown.RenderString(&RenderContext{
400+
URLPrefix: setting.AppSubURL,
401+
Metas: localMetas,
402+
IsUncyclo: true,
403+
}, input)
404+
assert.NoError(t, err)
405+
assert.Equal(t, strings.TrimSpace(expectedUncyclo), strings.TrimSpace(buffer))
406+
}
407+
408+
rawwiki := util.URLJoin(AppSubURL, "wiki", "raw")
409+
mediatree := util.URLJoin(AppSubURL, "media", "master")
410+
411+
test(
412+
`<img src="Link">`,
413+
`<img src="`+util.URLJoin(mediatree, "Link")+`"/>`,
414+
`<img src="`+util.URLJoin(rawwiki, "Link")+`"/>`)
415+
416+
test(
417+
`<img src="./icon.png">`,
418+
`<img src="`+util.URLJoin(mediatree, "icon.png")+`"/>`,
419+
`<img src="`+util.URLJoin(rawwiki, "icon.png")+`"/>`)
420+
}
421+
387422
func Test_ParseClusterFuzz(t *testing.T) {
388423
setting.AppURL = AppURL
389424
setting.AppSubURL = AppSubURL

0 commit comments

Comments
 (0)