Skip to content

Commit

Permalink
Fix relative links in postprocessed images (go-gitea#16334)
Browse files Browse the repository at this point in the history
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]>
  • Loading branch information
zeripath and 6543 committed Jul 4, 2021
1 parent 50084da commit 79f2b2f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
3 changes: 2 additions & 1 deletion modules/markup/html.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ func (ctx *postProcessCtx) visitNode(node *html.Node, visitText bool) {
}
case html.ElementNode:
if node.Data == "img" {
for _, attr := range node.Attr {
for i, attr := range node.Attr {
if attr.Key != "src" {
continue
}
Expand All @@ -414,6 +414,7 @@ func (ctx *postProcessCtx) visitNode(node *html.Node, visitText bool) {

attr.Val = util.URLJoin(prefix, attr.Val)
}
node.Attr[i] = attr
}
} else if node.Data == "a" {
visitText = false
Expand Down
35 changes: 35 additions & 0 deletions modules/markup/html_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,41 @@ func TestRender_ShortLinks(t *testing.T) {
`<p><a href="https://example.org" rel="nofollow">[[foobar]]</a></p>`)
}

func TestRender_RelativeImages(t *testing.T) {
setting.AppURL = AppURL
setting.AppSubURL = AppSubURL
tree := util.URLJoin(AppSubURL, "src", "master")

test := func(input, expected, expectedWiki string) {
buffer, err := markdown.RenderString(&RenderContext{
URLPrefix: tree,
Metas: localMetas,
}, input)
assert.NoError(t, err)
assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer))
buffer, err = markdown.RenderString(&RenderContext{
URLPrefix: setting.AppSubURL,
Metas: localMetas,
IsWiki: true,
}, input)
assert.NoError(t, err)
assert.Equal(t, strings.TrimSpace(expectedWiki), strings.TrimSpace(buffer))
}

rawwiki := util.URLJoin(AppSubURL, "wiki", "raw")
mediatree := util.URLJoin(AppSubURL, "media", "master")

test(
`<img src="Link">`,
`<img src="`+util.URLJoin(mediatree, "Link")+`"/>`,
`<img src="`+util.URLJoin(rawwiki, "Link")+`"/>`)

test(
`<img src="./icon.png">`,
`<img src="`+util.URLJoin(mediatree, "icon.png")+`"/>`,
`<img src="`+util.URLJoin(rawwiki, "icon.png")+`"/>`)
}

func Test_ParseClusterFuzz(t *testing.T) {
setting.AppURL = AppURL
setting.AppSubURL = AppSubURL
Expand Down

0 comments on commit 79f2b2f

Please sign in to comment.