internal/httpd/wiki.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/httpd/wiki.go

248 lines · 7216 bytes

13 symbols in this file
  1package httpd
  2
  3import (
  4	"html/template"
  5	"net/http"
  6	"path"
  7	"sort"
  8	"strings"
  9
 10	"gitbay.org/gitbay/internal/control"
 11	"gitbay.org/gitbay/internal/gitutil"
 12	"gitbay.org/gitbay/internal/store"
 13)
 14
 15// wikiTreePath is where wiki pages live in a repository's tree.
 16const wikiTreePath = ".gitbay/wiki"
 17
 18// wikiExts are the page formats that count as wiki content.
 19var wikiExts = []string{".md", ".org", ".markdown"}
 20
 21// wikiDir returns repo's directory and default branch, where wiki pages
 22// are resolved from .gitbay/wiki.
 23func (s *Server) wikiDir(repo store.Repo) (dir, branch string) {
 24	return control.RepoDir(s.cfg.Server.Root, repo.OwnerName, repo.Name), repo.DefaultBranch
 25}
 26
 27// hasWiki reports whether repo's default branch holds a wiki page.
 28func (s *Server) hasWiki(repo store.Repo) bool {
 29	dir, branch := s.wikiDir(repo)
 30	entries, err := gitutil.ListTreeRecursive(dir, branch, wikiTreePath)
 31	if err != nil {
 32		return false
 33	}
 34	for _, e := range entries {
 35		if e.Type == "blob" && wikiExtMatch(e.Name) {
 36			return true
 37		}
 38	}
 39	return false
 40}
 41
 42// wikiExtMatch reports whether name has one of the wiki page extensions.
 43func wikiExtMatch(name string) bool {
 44	ext := strings.ToLower(path.Ext(name))
 45	for _, want := range wikiExts {
 46		if ext == want {
 47			return true
 48		}
 49	}
 50	return false
 51}
 52
 53// wiki renders a page from the repo's .gitbay/wiki tree. The home page is
 54// Home.<ext> (or README.<ext>); /wiki/<name> resolves <name> with .md and
 55// .org fallbacks, and a name may be a path into a subfolder. Rendering
 56// reuses the same sanitized pipeline as READMEs.
 57func (s *Server) wiki(w http.ResponseWriter, r *http.Request) {
 58	p, ok := s.repoFor(w, r, "")
 59	if !ok {
 60		return
 61	}
 62	p.Tab = "wiki"
 63	var listing struct {
 64		Home  string   `json:"home"`
 65		Pages []string `json:"pages"`
 66	}
 67	var viewer store.User
 68	if s.cfg.Web.Mode == "accounts" {
 69		viewer = s.viewer(r)
 70	}
 71	_, listed := s.runControlInto(viewer, []string{"wiki", "list", p.Repo.Path()}, &listing)
 72	if !listed || len(listing.Pages) == 0 { // no wiki, or no commits yet
 73		s.render(w, "wiki.html", struct {
 74			repoPage
 75			Page     string
 76			PageHTML template.HTML
 77			Nav      []wikiNavGroup
 78			Missing  bool
 79		}{repoPage: p, Missing: true})
 80		return
 81	}
 82	pages := listing.Pages
 83
 84	page := strings.Trim(r.PathValue("page"), "/")
 85	if page == "" {
 86		page = listing.Home
 87	}
 88	var pageHTML template.HTML
 89	if page != "" {
 90		var shown struct {
 91			File    string `json:"file"`
 92			Content string `json:"content"`
 93		}
 94		if _, ok := s.runControlInto(viewer,
 95			[]string{"wiki", "show", p.Repo.Path(), page}, &shown); !ok {
 96			s.notFound(w, r)
 97			return
 98		}
 99		isPage := map[string]bool{}
100		for _, pg := range pages {
101			isPage[pg] = true
102		}
103		isFile := map[string]bool{}
104		dir, branch := s.wikiDir(p.Repo)
105		if entries, err := gitutil.ListTreeRecursive(dir, branch, wikiTreePath); err == nil {
106			for _, e := range entries {
107				isFile[e.Name] = e.Type == "blob"
108			}
109		}
110		pageHTML = rewriteWikiLinks(renderReadme(shown.File, []byte(shown.Content)), p, page,
111			func(t string) bool { return isPage[t] }, func(t string) bool { return isFile[t] })
112	}
113	s.render(w, "wiki.html", struct {
114		repoPage
115		Page     string
116		PageHTML template.HTML
117		Nav      []wikiNavGroup
118		Missing  bool
119	}{p, page, pageHTML, wikiNav(pages), false})
120}
121
122// wikiNavGroup is one folder of the wiki sidebar; Dir is empty for the
123// top level, which comes first.
124type wikiNavGroup struct {
125	Dir   string
126	Pages []wikiNavPage
127}
128
129type wikiNavPage struct {
130	Name  string // the page's path, as routed
131	Label string // its last segment
132}
133
134// wikiNav groups page names by folder, keeping the listing's order within
135// each folder.
136func wikiNav(pages []string) []wikiNavGroup {
137	var groups []wikiNavGroup
138	at := map[string]int{}
139	for _, pg := range pages {
140		d := path.Dir(pg)
141		if d == "." {
142			d = ""
143		}
144		i, ok := at[d]
145		if !ok {
146			i = len(groups)
147			at[d] = i
148			groups = append(groups, wikiNavGroup{Dir: d})
149		}
150		groups[i].Pages = append(groups[i].Pages, wikiNavPage{Name: pg, Label: path.Base(pg)})
151	}
152	sort.SliceStable(groups, func(a, b int) bool {
153		if (groups[a].Dir == "") != (groups[b].Dir == "") {
154			return groups[a].Dir == ""
155		}
156		return groups[a].Dir < groups[b].Dir
157	})
158	return groups
159}
160
161// wikiRaw serves non-page files from the wiki (images referenced by pages).
162func (s *Server) wikiRaw(w http.ResponseWriter, r *http.Request) {
163	p, ok := s.repoFor(w, r, "")
164	if !ok {
165		return
166	}
167	dir, branch := s.wikiDir(p.Repo)
168	rel := path.Join(wikiTreePath, strings.Trim(r.PathValue("path"), "/"))
169	if !strings.HasPrefix(rel, wikiTreePath+"/") {
170		s.notFound(w, r)
171		return
172	}
173	oid, err := gitutil.BlobID(dir, branch, rel)
174	if err != nil {
175		s.notFound(w, r)
176		return
177	}
178	if blobNotModified(w, r, p.Repo, branch, oid) {
179		return
180	}
181	data, err := gitutil.ReadBlob(dir, branch, rel, s.cfg.Limits.MaxBlobBytes)
182	if err != nil {
183		s.notFound(w, r)
184		return
185	}
186	ct := "application/octet-stream"
187	if t, ok := imageTypes[strings.ToLower(path.Ext(rel))]; ok {
188		ct = t
189	}
190	w.Header().Set("Content-Type", ct)
191	w.Header().Set("X-Content-Type-Options", "nosniff")
192	w.Write(data)
193}
194
195// wikiResolve maps a relative link on page to a path inside the wiki. A
196// page in a subfolder looks in its own folder first and then at the wiki
197// root, so [[Admin]] still reaches a top-level page; when neither exists
198// the folder-relative path is kept, so a broken link points where its
199// author wrote it. A top-level page resolves exactly as before.
200func wikiResolve(page, v string, exists func(string) bool) (string, bool) {
201	dir := path.Dir(page)
202	local := path.Clean(path.Join(dir, v))
203	if local == ".." || strings.HasPrefix(local, "../") {
204		return "", false
205	}
206	if dir == "." || exists(local) {
207		return local, true
208	}
209	if root := path.Clean(v); root != ".." && !strings.HasPrefix(root, "../") && exists(root) {
210		return root, true
211	}
212	return local, true
213}
214
215// trimPageExt drops a page extension from a link target.
216func trimPageExt(target string) string {
217	switch strings.ToLower(path.Ext(target)) {
218	case ".md", ".org", ".markdown", ".html":
219		return strings.TrimSuffix(target, path.Ext(target))
220	}
221	return target
222}
223
224// rewriteWikiLinks makes relative links resolve inside the wiki: page
225// links (with or without .md/.org/.html extensions) go to /wiki/<page>,
226// other relative targets (images) to the wiki raw route. Targets resolve
227// from the current page's folder, as wikiResolve describes.
228func rewriteWikiLinks(rendered template.HTML, p repoPage, page string, isPage, isFile func(string) bool) template.HTML {
229	base := "/" + p.Repo.Path() + "/wiki"
230	return rewriteRelativeTargets(rendered, func(v string, src bool) (string, bool) {
231		if src {
232			target, ok := wikiResolve(page, v, isFile)
233			return base + "/_raw/" + target, ok
234		}
235		// A plain link is usually to another page, but a link to an
236		// existing non-page file (an .svg, .txt, .pdf) must go to _raw
237		// the same as an image src, or it 404s against the page route
238		// (#283).
239		target, ok := wikiResolve(page, trimPageExt(v), isPage)
240		if !ok {
241			return "", false
242		}
243		if raw, rok := wikiResolve(page, v, isFile); rok && isFile(raw) && !isPage(target) {
244			return base + "/_raw/" + raw, true
245		}
246		return base + "/" + target, true
247	})
248}