A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

301 lines
9.8 KiB

  1. /*
  2. * Copyright © 2018-2020 A Bunch Tell LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. package writefreely
  11. import (
  12. "encoding/json"
  13. "fmt"
  14. "html"
  15. "html/template"
  16. "net/http"
  17. "net/url"
  18. "regexp"
  19. "strings"
  20. "unicode"
  21. "unicode/utf8"
  22. "github.com/microcosm-cc/bluemonday"
  23. stripmd "github.com/writeas/go-strip-markdown"
  24. "github.com/writeas/impart"
  25. blackfriday "github.com/writeas/saturday"
  26. "github.com/writeas/web-core/log"
  27. "github.com/writeas/web-core/stringmanip"
  28. "github.com/writeas/writefreely/config"
  29. "github.com/writeas/writefreely/parse"
  30. )
  31. var (
  32. blockReg = regexp.MustCompile("<(ul|ol|blockquote)>\n")
  33. endBlockReg = regexp.MustCompile("</([a-z]+)>\n</(ul|ol|blockquote)>")
  34. youtubeReg = regexp.MustCompile("(https?://www.youtube.com/embed/[a-zA-Z0-9\\-_]+)(\\?[^\t\n\f\r \"']+)?")
  35. titleElementReg = regexp.MustCompile("</?h[1-6]>")
  36. hashtagReg = regexp.MustCompile(`{{\[\[\|\|([^|]+)\|\|\]\]}}`)
  37. markeddownReg = regexp.MustCompile("<p>(.+)</p>")
  38. mentionReg = regexp.MustCompile(`@([A-Za-z0-9._%+-]+)(@[A-Za-z0-9.-]+\.[A-Za-z]+)\b`)
  39. )
  40. func (p *Post) formatContent(cfg *config.Config, c *Collection, isOwner bool) {
  41. baseURL := c.CanonicalURL()
  42. // TODO: redundant
  43. if !isSingleUser {
  44. baseURL = "/" + c.Alias + "/"
  45. }
  46. p.HTMLTitle = template.HTML(applyBasicMarkdown([]byte(p.Title.String)))
  47. p.HTMLContent = template.HTML(applyMarkdown([]byte(p.Content), baseURL, cfg))
  48. if exc := strings.Index(string(p.Content), "<!--more-->"); exc > -1 {
  49. p.HTMLExcerpt = template.HTML(applyMarkdown([]byte(p.Content[:exc]), baseURL, cfg))
  50. }
  51. }
  52. func (p *PublicPost) formatContent(cfg *config.Config, isOwner bool) {
  53. p.Post.formatContent(cfg, &p.Collection.Collection, isOwner)
  54. }
  55. func (p *Post) augmentContent(c *Collection) {
  56. // Add post signatures
  57. if c.Signature != "" {
  58. p.Content += "\n\n" + c.Signature
  59. }
  60. }
  61. func (p *PublicPost) augmentContent() {
  62. p.Post.augmentContent(&p.Collection.Collection)
  63. }
  64. func applyMarkdown(data []byte, baseURL string, cfg *config.Config) string {
  65. return applyMarkdownSpecial(data, false, baseURL, cfg)
  66. }
  67. func disableYoutubeAutoplay(outHTML string) string {
  68. for _, match := range youtubeReg.FindAllString(outHTML, -1) {
  69. u, err := url.Parse(match)
  70. if err != nil {
  71. continue
  72. }
  73. u.RawQuery = html.UnescapeString(u.RawQuery)
  74. q := u.Query()
  75. // Set Youtube autoplay url parameter, if any, to 0
  76. if len(q["autoplay"]) == 1 {
  77. q.Set("autoplay", "0")
  78. }
  79. u.RawQuery = q.Encode()
  80. cleanURL := u.String()
  81. outHTML = strings.Replace(outHTML, match, cleanURL, 1)
  82. }
  83. return outHTML
  84. }
  85. func applyMarkdownSpecial(data []byte, skipNoFollow bool, baseURL string, cfg *config.Config) string {
  86. mdExtensions := 0 |
  87. blackfriday.EXTENSION_TABLES |
  88. blackfriday.EXTENSION_FENCED_CODE |
  89. blackfriday.EXTENSION_AUTOLINK |
  90. blackfriday.EXTENSION_STRIKETHROUGH |
  91. blackfriday.EXTENSION_SPACE_HEADERS |
  92. blackfriday.EXTENSION_AUTO_HEADER_IDS
  93. htmlFlags := 0 |
  94. blackfriday.HTML_USE_SMARTYPANTS |
  95. blackfriday.HTML_SMARTYPANTS_DASHES
  96. if baseURL != "" {
  97. htmlFlags |= blackfriday.HTML_HASHTAGS
  98. }
  99. // Generate Markdown
  100. md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions)
  101. if baseURL != "" {
  102. // Replace special text generated by Markdown parser
  103. tagPrefix := baseURL + "tag:"
  104. if cfg.App.Chorus {
  105. tagPrefix = "/read/t/"
  106. }
  107. md = []byte(hashtagReg.ReplaceAll(md, []byte("<a href=\""+tagPrefix+"$1\" class=\"hashtag\"><span>#</span><span class=\"p-category\">$1</span></a>")))
  108. handlePrefix := cfg.App.Host + "/@/"
  109. md = []byte(mentionReg.ReplaceAll(md, []byte("<a href=\""+handlePrefix+"$1$2\" class=\"u-url mention\">@<span>$1$2</span></a>")))
  110. }
  111. // Strip out bad HTML
  112. policy := getSanitizationPolicy()
  113. policy.RequireNoFollowOnLinks(!skipNoFollow)
  114. outHTML := string(policy.SanitizeBytes(md))
  115. // Strip newlines on certain block elements that render with them
  116. outHTML = blockReg.ReplaceAllString(outHTML, "<$1>")
  117. outHTML = endBlockReg.ReplaceAllString(outHTML, "</$1></$2>")
  118. outHTML = disableYoutubeAutoplay(outHTML)
  119. return outHTML
  120. }
  121. func applyBasicMarkdown(data []byte) string {
  122. mdExtensions := 0 |
  123. blackfriday.EXTENSION_STRIKETHROUGH |
  124. blackfriday.EXTENSION_SPACE_HEADERS |
  125. blackfriday.EXTENSION_HEADER_IDS
  126. htmlFlags := 0 |
  127. blackfriday.HTML_SKIP_HTML |
  128. blackfriday.HTML_USE_SMARTYPANTS |
  129. blackfriday.HTML_SMARTYPANTS_DASHES
  130. // Generate Markdown
  131. md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions)
  132. // Strip out bad HTML
  133. policy := bluemonday.UGCPolicy()
  134. policy.AllowAttrs("class", "id").Globally()
  135. outHTML := string(policy.SanitizeBytes(md))
  136. outHTML = markeddownReg.ReplaceAllString(outHTML, "$1")
  137. outHTML = strings.TrimRightFunc(outHTML, unicode.IsSpace)
  138. return outHTML
  139. }
  140. func postTitle(content, friendlyId string) string {
  141. const maxTitleLen = 80
  142. content = stripHTMLWithoutEscaping(content)
  143. content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace)
  144. eol := strings.IndexRune(content, '\n')
  145. blankLine := strings.Index(content, "\n\n")
  146. if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen {
  147. return strings.TrimSpace(content[:blankLine])
  148. } else if utf8.RuneCountInString(content) <= maxTitleLen {
  149. return content
  150. }
  151. return friendlyId
  152. }
  153. // TODO: fix duplicated code from postTitle. postTitle is a widely used func we
  154. // don't have time to investigate right now.
  155. func friendlyPostTitle(content, friendlyId string) string {
  156. const maxTitleLen = 80
  157. content = stripHTMLWithoutEscaping(content)
  158. content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace)
  159. eol := strings.IndexRune(content, '\n')
  160. blankLine := strings.Index(content, "\n\n")
  161. if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen {
  162. return strings.TrimSpace(content[:blankLine])
  163. } else if eol == -1 && utf8.RuneCountInString(content) <= maxTitleLen {
  164. return content
  165. }
  166. title, truncd := parse.TruncToWord(parse.PostLede(content, true), maxTitleLen)
  167. if truncd {
  168. title += "..."
  169. }
  170. return title
  171. }
  172. // Strip HTML tags with bluemonday's StrictPolicy, then unescape the HTML
  173. // entities added in by sanitizing the content.
  174. func stripHTMLWithoutEscaping(content string) string {
  175. return html.UnescapeString(bluemonday.StrictPolicy().Sanitize(content))
  176. }
  177. func getSanitizationPolicy() *bluemonday.Policy {
  178. policy := bluemonday.UGCPolicy()
  179. policy.AllowAttrs("src", "style").OnElements("iframe", "video", "audio")
  180. policy.AllowAttrs("src", "type").OnElements("source")
  181. policy.AllowAttrs("frameborder", "width", "height").Matching(bluemonday.Integer).OnElements("iframe")
  182. policy.AllowAttrs("allowfullscreen").OnElements("iframe")
  183. policy.AllowAttrs("controls", "loop", "muted", "autoplay").OnElements("video")
  184. policy.AllowAttrs("controls", "loop", "muted", "autoplay", "preload").OnElements("audio")
  185. policy.AllowAttrs("target").OnElements("a")
  186. policy.AllowAttrs("title").OnElements("abbr")
  187. policy.AllowAttrs("style", "class", "id").Globally()
  188. policy.AllowElements("header", "footer")
  189. policy.AllowURLSchemes("http", "https", "mailto", "xmpp")
  190. return policy
  191. }
  192. func sanitizePost(content string) string {
  193. return strings.Replace(content, "<", "&lt;", -1)
  194. }
  195. // postDescription generates a description based on the given post content,
  196. // title, and post ID. This doesn't consider a V2 post field, `title` when
  197. // choosing what to generate. In case a post has a title, this function will
  198. // fail, and logic should instead be implemented to skip this when there's no
  199. // title, like so:
  200. // var desc string
  201. // if title == "" {
  202. // desc = postDescription(content, title, friendlyId)
  203. // } else {
  204. // desc = shortPostDescription(content)
  205. // }
  206. func postDescription(content, title, friendlyId string) string {
  207. maxLen := 140
  208. if content == "" {
  209. content = "WriteFreely is a painless, simple, federated blogging platform."
  210. } else {
  211. fmtStr := "%s"
  212. truncation := 0
  213. if utf8.RuneCountInString(content) > maxLen {
  214. // Post is longer than the max description, so let's show a better description
  215. fmtStr = "%s..."
  216. truncation = 3
  217. }
  218. if title == friendlyId {
  219. // No specific title was found; simply truncate the post, starting at the beginning
  220. content = fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1))
  221. } else {
  222. // There was a title, so return a real description
  223. blankLine := strings.Index(content, "\n\n")
  224. if blankLine < 0 {
  225. blankLine = 0
  226. }
  227. truncd := stringmanip.Substring(content, blankLine, blankLine+maxLen-truncation)
  228. contentNoNL := strings.Replace(truncd, "\n", " ", -1)
  229. content = strings.TrimSpace(fmt.Sprintf(fmtStr, contentNoNL))
  230. }
  231. }
  232. return content
  233. }
  234. func shortPostDescription(content string) string {
  235. maxLen := 140
  236. fmtStr := "%s"
  237. truncation := 0
  238. if utf8.RuneCountInString(content) > maxLen {
  239. // Post is longer than the max description, so let's show a better description
  240. fmtStr = "%s..."
  241. truncation = 3
  242. }
  243. return strings.TrimSpace(fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1)))
  244. }
  245. func handleRenderMarkdown(app *App, w http.ResponseWriter, r *http.Request) error {
  246. if !IsJSON(r) {
  247. return impart.HTTPError{Status: http.StatusUnsupportedMediaType, Message: "Markdown API only supports JSON requests"}
  248. }
  249. in := struct {
  250. CollectionURL string `json:"collection_url"`
  251. RawBody string `json:"raw_body"`
  252. }{}
  253. decoder := json.NewDecoder(r.Body)
  254. err := decoder.Decode(&in)
  255. if err != nil {
  256. log.Error("Couldn't parse markdown JSON request: %v", err)
  257. return ErrBadJSON
  258. }
  259. out := struct {
  260. Body string `json:"body"`
  261. }{
  262. Body: applyMarkdown([]byte(in.RawBody), in.CollectionURL, app.cfg),
  263. }
  264. return impart.WriteSuccess(w, out, http.StatusOK)
  265. }