package classes
import (
"regexp"
"strings"
)
// The PHP routes.php patterns of the frontend rewrite.
var (
locElement = regexp.MustCompile(`(.*?)`)
xhtmlLinkRef = regexp.MustCompile(`(]*href=")([^"]*)(")`)
)
// Rewrite is the frontend_url rewrite of PHP routes.php: with frontendURL
// set, backendURL is replaced literally (str_replace) inside every loc
// element, inside every xhtml:link href and in the exact stylesheet href.
// Both URLs are right-trimmed of slashes first. An empty frontendURL (or
// "0", which PHP reads as false) leaves xml unchanged.
func Rewrite(xml, backendURL, frontendURL string) string {
if frontendURL == "" || frontendURL == "0" {
return xml
}
frontend := strings.TrimRight(frontendURL, "/")
backend := strings.TrimRight(backendURL, "/")
replace := func(s string) string {
if backend == "" {
return s
}
return strings.ReplaceAll(s, backend, frontend)
}
xml = locElement.ReplaceAllStringFunc(xml, func(m string) string {
inner := m[len("") : len(m)-len("")]
return "" + replace(inner) + ""
})
xml = xhtmlLinkRef.ReplaceAllStringFunc(xml, func(m string) string {
sub := xhtmlLinkRef.FindStringSubmatch(m)
return sub[1] + replace(sub[2]) + sub[3]
})
if backend != "" {
xml = strings.ReplaceAll(xml, `href="`+backend+`/sitemap.xsl"`, `href="`+frontend+`/sitemap.xsl"`)
}
return xml
}
// BackendURL is PHP rtrim(url('/'), '/') for a request whose root URL is
// root: the URL the rewrite replaces.
func BackendURL(root string) string {
return strings.TrimRight(URLTo(root, "/"), "/")
}