package server import ( "context" "html" "html/template" "net/http" "net/url" "path" "sort" "strconv" "strings" "pageswiki/internal/store" ) type publicNavigationKey struct{} type publicNavigationSnapshot struct { pages map[string]store.Revision paths []string branches map[string]bool } func publicNavigationFor(r *http.Request) *publicNavigationSnapshot { v, _ := r.Context().Value(publicNavigationKey{}).(*publicNavigationSnapshot) return v } func (p *publicNavigationSnapshot) allows(target string) bool { _, ok := p.pages[target]; return ok } func (p *publicNavigationSnapshot) href(target string) string { if p.allows(target) { return cityPageHref(target) } return cityPageHref("/v/tree" + strings.TrimRight(target, "/")) } func (s *Server) withPublicNavigation(r *http.Request) (*http.Request, error) { pages, err := s.publicNavigation(r.Context(), s.domainUUIDForRequest(r)) if err != nil { return r, err } return s.withPublishedNavigation(r, pages) } func (s *Server) withPublishedNavigation(r *http.Request, pages []store.PublishedNavigationPage) (*http.Request, error) { p := &publicNavigationSnapshot{pages: map[string]store.Revision{}, branches: map[string]bool{}} priority := map[string]int{} for i, lang := range s.revisionLanguageCandidates(r) { priority[lang] = i + 1 } for _, e := range pages { if strings.Count(e.Path, "/") > 128 { return r, store.ErrNavigationBudget } old, ok := p.pages[e.Path] rank := priority[e.Revision.Language] if rank == 0 { rank = 10000 } oldRank := priority[old.Language] if oldRank == 0 { oldRank = 10000 } if !ok || rank < oldRank { p.pages[e.Path] = e.Revision } if !ok { p.paths = append(p.paths, e.Path) for at := e.Path; ; at = path.Dir(at) { p.branches[at] = true if len(p.branches) > store.MaxNavigationEntries { return r, store.ErrNavigationBudget } if at == "/" { break } } } } r = r.WithContext(context.WithValue(r.Context(), anonymousProjectionKey{}, true)) return r.WithContext(context.WithValue(r.Context(), publicNavigationKey{}, p)), nil } func publicNavigationRoute(target string) bool { return target == "/v/children" || target == "/v/tree" || strings.HasPrefix(target, "/v/tree/") || target == "/v/browser" || strings.HasPrefix(target, "/v/browser/") || target == "/v/city" || target == "/_/api/v1/city/map" } func (s *Server) servePublicNavigation(w http.ResponseWriter, r *http.Request) bool { if !publicNavigationRoute(r.URL.Path) { return false } r, err := s.withPublicNavigation(r) if err != nil { http.Error(w, "navigation unavailable", 503) return true } s.renderPublicNavigationRoute(w, r) return true } func (s *Server) renderPublicNavigationRoute(w http.ResponseWriter, r *http.Request) { p := publicNavigationFor(r) privateCityResponse(w) w.Header().Add("Vary", "Accept-Language") switch { case r.URL.Path == "/v/children": args := parseChildrenMacroArgs("", r.URL.Query().Get("path")) args.Excludes = splitExcludePatterns(r.URL.Query().Get("exclude")) args.View = r.URL.Query().Get("view") args.Offset, _ = strconv.Atoi(r.URL.Query().Get("offset")) args.Limit, _ = strconv.Atoi(r.URL.Query().Get("limit")) if args.Limit <= 0 || args.Limit > 400 { args.Limit = 120 } w.Header().Set("Content-Type", "text/html; charset=utf-8") if r.Method != "HEAD" { _, _ = w.Write([]byte(s.renderPublicChildren(r, args))) } case r.URL.Path == "/_/api/v1/city/map": city, err := s.publicCityProjection(r) if err != nil { http.Error(w, "navigation unavailable", 503) return } writeEventJSON(w, 200, city) case r.URL.Path == "/v/city": s.render(w, "city_map.gohtml", map[string]any{"Context": s.BuildRequestContext(r), "Locale": s.getLocale(s.domainUUIDForRequest(r)), "PublicNavigation": true, "CanPlan": false}) default: prefix := "/v/tree" directory := strings.HasPrefix(r.URL.Path, "/v/browser") if directory { prefix = "/v/browser" } scope := path.Clean("/" + strings.TrimPrefix(r.URL.Path, prefix)) if scope != "/" && !p.branches[scope] { http.NotFound(w, r) return } s.renderPublicDirectory(w, r, scope, directory) } } func publicFolderHref(scope string) string { return cityPageHref("/v/browser" + strings.TrimRight(scope, "/")) } func (s *Server) publicNavigationData(r *http.Request, scope string) map[string]any { p := publicNavigationFor(r) data := map[string]any{"Context": s.BuildRequestContext(r), "Locale": s.getLocale(s.domainUUIDForRequest(r)), "Path": scope, "PublicBreadcrumbs": publicBreadcrumbs(p, scope), "PublicFolderHref": publicFolderHref(scope), "PublicTreeHref": cityPageHref("/v/tree" + strings.TrimRight(scope, "/")), "PublicHasChildren": p.hasChildren(scope)} if p.allows(scope) { data["PublicPageHref"] = p.href(scope) } if scope != "/" { data["PublicParentHref"] = publicFolderHref(path.Dir(scope)) } return data } func (s *Server) renderPublicDirectory(w http.ResponseWriter, r *http.Request, scope string, directory bool) { data := s.publicNavigationData(r, scope) data["Directory"] = directory if directory { args := childrenMacroArgs{TargetPath: scope, Limit: 120, View: "list"} args.Excludes = splitExcludePatterns(r.URL.Query().Get("exclude")) if limit, _ := strconv.Atoi(r.URL.Query().Get("limit")); limit > 0 && limit <= 400 { args.Limit = limit } args.Offset, _ = strconv.Atoi(r.URL.Query().Get("offset")) if args.Offset < 0 || args.Offset > store.MaxNavigationEntries { args.Offset = 0 } data["PublicChildren"] = template.HTML(s.renderPublicChildren(r, args)) query := url.Values{"path": {scope}, "offset": {strconv.Itoa(args.Offset)}, "limit": {strconv.Itoa(args.Limit)}} if len(args.Excludes) > 0 { query.Set("exclude", strings.Join(args.Excludes, ",")) } data["PublicChildrenSource"] = "/v/children?" + query.Encode() if args.Offset > 0 { query.Del("path") query.Set("offset", strconv.Itoa(max(0, args.Offset-args.Limit))) data["PublicPreviousBatch"] = publicFolderHref(scope) + "?" + query.Encode() } } else { data["Nodes"] = publicTreeNodes(publicNavigationFor(r), scope) } privateCityResponse(w) w.Header().Add("Vary", "Accept-Language") s.render(w, "public_tree.gohtml", data) } func (p *publicNavigationSnapshot) hasChildren(scope string) bool { prefix := strings.TrimRight(scope, "/") + "/" for _, item := range p.paths { if item != scope && strings.HasPrefix(item, prefix) { return true } } return false } type publicNavigationLink struct{ Name, Href string } func publicBreadcrumbs(p *publicNavigationSnapshot, target string) []publicNavigationLink { links := []publicNavigationLink{} for at := target; ; at = path.Dir(at) { if p.branches[at] { name := path.Base(at) if at == "/" { name = "/" } links = append(links, publicNavigationLink{name, p.href(at)}) } if at == "/" { break } } for i, j := 0, len(links)-1; i < j; i, j = i+1, j-1 { links[i], links[j] = links[j], links[i] } return links } type publicTreeNode struct { Name, Path, Href, FolderHref string Depth int IsDir bool HasChildren bool } func publicTreeNodes(p *publicNavigationSnapshot, scope string) []publicTreeNode { keys := []string{} for item := range p.branches { if item != scope && strings.HasPrefix(item, strings.TrimRight(scope, "/")+"/") { keys = append(keys, item) } } // Compare path components, not raw bytes: /a/x must precede /a-b. // Tree collapse/keyboard navigation requires contiguous descendants. order := make(map[string]string, len(keys)) for _, item := range keys { order[item] = strings.ReplaceAll(item, "/", "\x00") } sort.Slice(keys, func(i, j int) bool { return order[keys[i]] < order[keys[j]] }) nodes := []publicTreeNode{} parents := map[string]bool{} for _, item := range keys { parents[path.Dir(item)] = true } for _, item := range keys { nodes = append(nodes, publicTreeNode{Name: path.Base(item), Path: item, Href: p.href(item), FolderHref: publicFolderHref(item), Depth: strings.Count(strings.TrimPrefix(item, strings.TrimRight(scope, "/")+"/"), "/"), IsDir: !p.allows(item), HasChildren: parents[item]}) } return nodes } func (s *Server) renderPublicChildren(r *http.Request, args childrenMacroArgs) string { p := publicNavigationFor(r) if p == nil { return "" } scope := path.Clean(args.TargetPath) prefix := strings.TrimRight(scope, "/") + "/" children := map[string]bool{} hasChildren := map[string]bool{} for _, item := range p.paths { if !strings.HasPrefix(item, prefix) || item == scope || isExcludedPath(item, args.Excludes) { continue } child := prefix + strings.Split(strings.TrimPrefix(item, prefix), "/")[0] if !isExcludedPath(child, args.Excludes) { children[child] = true if item != child { hasChildren[child] = true } } } keys := []string{} for child := range children { keys = append(keys, child) } sort.Strings(keys) start := args.Offset if start < 0 { start = 0 } if start > len(keys) { start = len(keys) } limit := args.Limit if limit <= 0 || limit > 400 { limit = 120 } end := min(start+limit, len(keys)) var out strings.Builder browseLabel := translate(s.getLocale(s.domainUUIDForRequest(r)), "public.navigation.browse") class := "public-children-list" if args.View == "icon" { class = "public-children-icons" } else if args.View == "detail" { class = "public-children-details" } out.WriteString(``) if len(keys) == 0 { out.WriteString(`

` + html.EscapeString(translate(s.getLocale(s.domainUUIDForRequest(r)), "public.navigation.empty")) + `

`) } args.TargetPath = scope args.Limit = limit if end < len(keys) { query := url.Values{"path": {scope}, "view": {args.View}, "offset": {strconv.Itoa(end)}, "limit": {strconv.Itoa(limit)}} if len(args.Excludes) > 0 { query.Set("exclude", strings.Join(args.Excludes, ",")) } // The link works without JavaScript; enhanced views replace it with // automatic lazy continuation. The next URL never counts private rows. out.WriteString(`
`) query.Del("path") out.WriteString(`` + html.EscapeString(translate(s.getLocale(s.domainUUIDForRequest(r)), "public.navigation.next_batch")) + `
`) } return out.String() } func (s *Server) expandPublicMacro(r *http.Request, macro, currentPath string) string { p := publicNavigationFor(r) if p == nil { return macro } if strings.HasPrefix(macro, "{{children") { match := childrenMacroRe.FindStringSubmatch(macro) if len(match) < 2 { return macro } args := parseChildrenMacroArgs(match[1], currentPath) fallback := `` + html.EscapeString(translate(s.getLocale(s.domainUUIDForRequest(r)), "public.navigation.browse")) + `` return strings.Replace(s.expandChildrenMacros(macro, currentPath), `
Loading…
`, fallback, 1) } if macro == "{{city-breadcrumbs}}" { var out strings.Builder out.WriteString(``) return out.String() } if macro == "{{city}}" { return `` + html.EscapeString(translate(s.getLocale(s.domainUUIDForRequest(r)), "city.map")) + `` } match := cityMacroRe.FindStringSubmatch(macro) if len(match) > 1 && (match[1] == "quartier" || match[1] == "street" || match[1] == "spot" || match[1] == "spot-pages") { city, err := s.publicCityProjection(r) if err != nil { return macro } within := func(scope string) bool { return currentPath == scope || strings.HasPrefix(currentPath, strings.TrimRight(scope, "/")+"/") } link := func(href, label string) string { return `` + html.EscapeString(label) + `` } for _, q := range city.Quartiers { if !within(q.PathPrefix) { continue } if match[1] == "quartier" { return link(q.DetailHref, q.Title) } for _, st := range q.Streets { if !within(st.PathPrefix) { continue } if match[1] == "street" { return link(st.DetailHref, st.Title) } for _, sp := range st.Spots { has := within(sp.PathPrefix) for _, page := range sp.Pages { if page.Path == currentPath { has = true } } if !has { continue } if match[1] == "spot" { return link(sp.DetailHref, sp.Title) } var out strings.Builder out.WriteString(``) return out.String() } } } return `—` } return macro } func (s *Server) publicCityProjection(r *http.Request) (store.CityMap, error) { p := publicNavigationFor(r) city, err := s.navigationCity(r.Context(), s.domainUUIDForRequest(r)) if err != nil { return city, err } // The hierarchy comes from actual topology, but labels/links/counts only // disclose approved semantic Paths. A private parent's custom prose is not // published merely because it contains an approved descendant. visible := map[string]bool{} for item := range p.branches { visible[item] = true } for _, q := range city.Quartiers { for _, st := range q.Streets { for _, sp := range st.Spots { for _, page := range sp.Pages { if p.allows(page.Path) && strings.HasPrefix(page.Path, strings.TrimRight(st.PathPrefix, "/")+"/") && strings.HasSuffix(sp.PathPrefix, "/_undefined") { visible[sp.PathPrefix] = true } } } } } city = filterCityProjection(city, func(item string) bool { return visible[item] }) city.Relations = []store.CitySpotRelation{} for qi := range city.Quartiers { q := &city.Quartiers[qi] q.Name = path.Base(q.PathPrefix) q.Title = q.Name q.Description = "" q.State = "active" q.SortKey = 0 q.DetailHref = "/v/city?quartier=" + url.QueryEscape(q.UUID) for si := range q.Streets { st := &q.Streets[si] st.Name = path.Base(st.PathPrefix) st.Title = st.Name st.Description = "" st.State = "active" st.SortKey = 0 st.DetailHref = "/v/city?street=" + url.QueryEscape(st.UUID) for pi := range st.Spots { sp := &st.Spots[pi] sp.Name = path.Base(sp.PathPrefix) sp.Title = sp.Name sp.Summary = "" sp.State = "active" sp.SortKey = 0 sp.DetailHref = "/v/city?spot=" + url.QueryEscape(sp.UUID) sp.PortalPath = "" sp.PortalPageUUID = "" pages := []store.CityPagePlacement{} seen := map[string]bool{} for _, page := range sp.Pages { if !p.allows(page.Path) { continue } page = store.CityPagePlacement{Path: page.Path, PageUUID: p.pages[page.Path].ObjectUUID, Label: path.Base(page.Path), EdgeType: "primary"} pages = append(pages, page) seen[page.PageUUID] = true if sp.PortalPath == "" || page.Path == sp.PathPrefix { sp.PortalPath = page.Path sp.PortalPageUUID = page.PageUUID } } sp.Pages = pages sp.PageCount = len(seen) } } } return city, nil }