diff --git a/services/wiki/wiki_path.go b/services/wiki/wiki_path.go index 91363322e1..4961cdb75c 100644 --- a/services/wiki/wiki_path.go +++ b/services/wiki/wiki_path.go @@ -6,6 +6,7 @@ package wiki import ( "net/url" "path" + "regexp" "strings" repo_model "git.mokoconsulting.tech/MokoConsulting/MokoGitea/models/repo" @@ -148,10 +149,24 @@ func WebPathFromRequest(s string) WebPath { return WebPath(s) } +var multiHyphenRe = regexp.MustCompile(`-{2,}`) +var nonAlphanumRe = regexp.MustCompile(`[^a-zA-Z0-9\-]`) + +// sanitizeWikiTitle converts a user-provided title into a clean, URL-friendly slug. +// Spaces and special characters become hyphens, consecutive hyphens collapse to one. +func sanitizeWikiTitle(title string) string { + title = strings.TrimSpace(title) + title = strings.ReplaceAll(title, " ", "-") + title = nonAlphanumRe.ReplaceAllString(title, "-") + title = multiHyphenRe.ReplaceAllString(title, "-") + title = strings.Trim(title, "-") + return title +} + func UserTitleToWebPath(base, title string) WebPath { // TODO: no support for subdirectory, because the old wiki code's behavior is always using %2F, instead of subdirectory. // So we do not add the support for writing slashes in title at the moment. - title = strings.TrimSpace(title) + title = sanitizeWikiTitle(title) title = util.PathJoinRelX(base, escapeSegToWeb(title, false)) if title == "" || title == "." { title = "unnamed"