diff --git a/modules/html/html.go b/modules/html/html.go
index 6cb6b847ef19..b1ebd584c6b6 100644
--- a/modules/html/html.go
+++ b/modules/html/html.go
@@ -6,28 +6,20 @@ package html
// ParseSizeAndClass get size and class from string with default values
// If present, "others" expects the new size first and then the classes to use
func ParseSizeAndClass(defaultSize int, defaultClass string, others ...any) (int, string) {
- if len(others) == 0 {
- return defaultSize, defaultClass
- }
-
size := defaultSize
- _size, ok := others[0].(int)
- if ok && _size != 0 {
- size = _size
- }
-
- if len(others) == 1 {
- return size, defaultClass
- }
-
- class := defaultClass
- if _class, ok := others[1].(string); ok && _class != "" {
- if defaultClass == "" {
- class = _class
- } else {
- class = defaultClass + " " + _class
+ if len(others) >= 1 {
+ if v, ok := others[0].(int); ok && v != 0 {
+ size = v
+ }
+ }
+ class := defaultClass
+ if len(others) >= 2 {
+ if v, ok := others[1].(string); ok && v != "" {
+ if class != "" {
+ class += " "
+ }
+ class += v
}
}
-
return size, class
}
diff --git a/modules/svg/processor.go b/modules/svg/processor.go
new file mode 100644
index 000000000000..82248fb0c121
--- /dev/null
+++ b/modules/svg/processor.go
@@ -0,0 +1,59 @@
+// Copyright 2023 The Gitea Authors. All rights reserved.
+// SPDX-License-Identifier: MIT
+
+package svg
+
+import (
+ "bytes"
+ "fmt"
+ "regexp"
+ "sync"
+)
+
+type normalizeVarsStruct struct {
+ reXMLDoc,
+ reComment,
+ reAttrXMLNs,
+ reAttrSize,
+ reAttrClassPrefix *regexp.Regexp
+}
+
+var (
+ normalizeVars *normalizeVarsStruct
+ normalizeVarsOnce sync.Once
+)
+
+// Normalize normalizes the SVG content: set default width/height, remove unnecessary tags/attributes
+// It's designed to work with valid SVG content. For invalid SVG content, the returned content is not guaranteed.
+func Normalize(data []byte, size int) []byte {
+ normalizeVarsOnce.Do(func() {
+ normalizeVars = &normalizeVarsStruct{
+ reXMLDoc: regexp.MustCompile(`(?s)<\?xml.*?>`),
+ reComment: regexp.MustCompile(`(?s)`),
+
+ reAttrXMLNs: regexp.MustCompile(`(?s)\s+xmlns\s*=\s*"[^"]*"`),
+ reAttrSize: regexp.MustCompile(`(?s)\s+(width|height)\s*=\s*"[^"]+"`),
+ reAttrClassPrefix: regexp.MustCompile(`(?s)\s+class\s*=\s*"`),
+ }
+ })
+ data = normalizeVars.reXMLDoc.ReplaceAll(data, nil)
+ data = normalizeVars.reComment.ReplaceAll(data, nil)
+
+ data = bytes.TrimSpace(data)
+ svgTag, svgRemaining, ok := bytes.Cut(data, []byte(">"))
+ if !ok || !bytes.HasPrefix(svgTag, []byte(`