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.
 
 
 
 
 

234 lines
8.2 KiB

  1. /*
  2. * Copyright © 2018 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. "fmt"
  13. "github.com/microcosm-cc/bluemonday"
  14. stripmd "github.com/writeas/go-strip-markdown"
  15. "github.com/writeas/saturday"
  16. "github.com/writeas/web-core/stringmanip"
  17. "github.com/writeas/writefreely/config"
  18. "github.com/writeas/writefreely/parse"
  19. "html"
  20. "html/template"
  21. "regexp"
  22. "strings"
  23. "unicode"
  24. "unicode/utf8"
  25. )
  26. var (
  27. blockReg = regexp.MustCompile("<(ul|ol|blockquote)>\n")
  28. endBlockReg = regexp.MustCompile("</([a-z]+)>\n</(ul|ol|blockquote)>")
  29. youtubeReg = regexp.MustCompile("(https?://www.youtube.com/embed/[a-zA-Z0-9\\-_]+)(\\?[^\t\n\f\r \"']+)?")
  30. titleElementReg = regexp.MustCompile("</?h[1-6]>")
  31. hashtagReg = regexp.MustCompile(`{{\[\[\|\|([^|]+)\|\|\]\]}}`)
  32. markeddownReg = regexp.MustCompile("<p>(.+)</p>")
  33. )
  34. func (p *Post) formatContent(cfg *config.Config, c *Collection, isOwner bool) {
  35. baseURL := c.CanonicalURL()
  36. if !isSingleUser {
  37. baseURL = "/" + c.Alias + "/"
  38. }
  39. p.HTMLTitle = template.HTML(applyBasicMarkdown([]byte(p.Title.String)))
  40. p.HTMLContent = template.HTML(applyMarkdown([]byte(p.Content), baseURL, cfg))
  41. if exc := strings.Index(string(p.Content), "<!--more-->"); exc > -1 {
  42. p.HTMLExcerpt = template.HTML(applyMarkdown([]byte(p.Content[:exc]), baseURL, cfg))
  43. }
  44. }
  45. func (p *PublicPost) formatContent(cfg *config.Config, isOwner bool) {
  46. p.Post.formatContent(cfg, &p.Collection.Collection, isOwner)
  47. }
  48. func applyMarkdown(data []byte, baseURL string, cfg *config.Config) string {
  49. return applyMarkdownSpecial(data, false, baseURL, cfg)
  50. }
  51. func applyMarkdownSpecial(data []byte, skipNoFollow bool, baseURL string, cfg *config.Config) string {
  52. mdExtensions := 0 |
  53. blackfriday.EXTENSION_TABLES |
  54. blackfriday.EXTENSION_FENCED_CODE |
  55. blackfriday.EXTENSION_AUTOLINK |
  56. blackfriday.EXTENSION_STRIKETHROUGH |
  57. blackfriday.EXTENSION_SPACE_HEADERS |
  58. blackfriday.EXTENSION_AUTO_HEADER_IDS
  59. htmlFlags := 0 |
  60. blackfriday.HTML_USE_SMARTYPANTS |
  61. blackfriday.HTML_SMARTYPANTS_DASHES
  62. if baseURL != "" {
  63. htmlFlags |= blackfriday.HTML_HASHTAGS
  64. }
  65. // Generate Markdown
  66. md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions)
  67. if baseURL != "" {
  68. // Replace special text generated by Markdown parser
  69. tagPrefix := baseURL + "tag:"
  70. if cfg.App.Chorus {
  71. tagPrefix = "/read/t/"
  72. }
  73. md = []byte(hashtagReg.ReplaceAll(md, []byte("<a href=\""+tagPrefix+"$1\" class=\"hashtag\"><span>#</span><span class=\"p-category\">$1</span></a>")))
  74. }
  75. // Strip out bad HTML
  76. policy := getSanitizationPolicy()
  77. policy.RequireNoFollowOnLinks(!skipNoFollow)
  78. outHTML := string(policy.SanitizeBytes(md))
  79. // Strip newlines on certain block elements that render with them
  80. outHTML = blockReg.ReplaceAllString(outHTML, "<$1>")
  81. outHTML = endBlockReg.ReplaceAllString(outHTML, "</$1></$2>")
  82. // Remove all query parameters on YouTube embed links
  83. // TODO: make this more specific. Taking the nuclear approach here to strip ?autoplay=1
  84. outHTML = youtubeReg.ReplaceAllString(outHTML, "$1")
  85. return outHTML
  86. }
  87. func applyBasicMarkdown(data []byte) string {
  88. mdExtensions := 0 |
  89. blackfriday.EXTENSION_STRIKETHROUGH |
  90. blackfriday.EXTENSION_SPACE_HEADERS |
  91. blackfriday.EXTENSION_HEADER_IDS
  92. htmlFlags := 0 |
  93. blackfriday.HTML_SKIP_HTML |
  94. blackfriday.HTML_USE_SMARTYPANTS |
  95. blackfriday.HTML_SMARTYPANTS_DASHES
  96. // Generate Markdown
  97. md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions)
  98. // Strip out bad HTML
  99. policy := bluemonday.UGCPolicy()
  100. policy.AllowAttrs("class", "id").Globally()
  101. outHTML := string(policy.SanitizeBytes(md))
  102. outHTML = markeddownReg.ReplaceAllString(outHTML, "$1")
  103. outHTML = strings.TrimRightFunc(outHTML, unicode.IsSpace)
  104. return outHTML
  105. }
  106. func postTitle(content, friendlyId string) string {
  107. const maxTitleLen = 80
  108. // Strip HTML tags with bluemonday's StrictPolicy, then unescape the HTML
  109. // entities added in by sanitizing the content.
  110. content = html.UnescapeString(bluemonday.StrictPolicy().Sanitize(content))
  111. content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace)
  112. eol := strings.IndexRune(content, '\n')
  113. blankLine := strings.Index(content, "\n\n")
  114. if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen {
  115. return strings.TrimSpace(content[:blankLine])
  116. } else if utf8.RuneCountInString(content) <= maxTitleLen {
  117. return content
  118. }
  119. return friendlyId
  120. }
  121. // TODO: fix duplicated code from postTitle. postTitle is a widely used func we
  122. // don't have time to investigate right now.
  123. func friendlyPostTitle(content, friendlyId string) string {
  124. const maxTitleLen = 80
  125. // Strip HTML tags with bluemonday's StrictPolicy, then unescape the HTML
  126. // entities added in by sanitizing the content.
  127. content = html.UnescapeString(bluemonday.StrictPolicy().Sanitize(content))
  128. content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace)
  129. eol := strings.IndexRune(content, '\n')
  130. blankLine := strings.Index(content, "\n\n")
  131. if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen {
  132. return strings.TrimSpace(content[:blankLine])
  133. } else if eol == -1 && utf8.RuneCountInString(content) <= maxTitleLen {
  134. return content
  135. }
  136. title, truncd := parse.TruncToWord(parse.PostLede(content, true), maxTitleLen)
  137. if truncd {
  138. title += "..."
  139. }
  140. return title
  141. }
  142. func getSanitizationPolicy() *bluemonday.Policy {
  143. policy := bluemonday.UGCPolicy()
  144. policy.AllowAttrs("src", "style").OnElements("iframe", "video", "audio")
  145. policy.AllowAttrs("src", "type").OnElements("source")
  146. policy.AllowAttrs("frameborder", "width", "height").Matching(bluemonday.Integer).OnElements("iframe")
  147. policy.AllowAttrs("allowfullscreen").OnElements("iframe")
  148. policy.AllowAttrs("controls", "loop", "muted", "autoplay").OnElements("video")
  149. policy.AllowAttrs("controls", "loop", "muted", "autoplay", "preload").OnElements("audio")
  150. policy.AllowAttrs("target").OnElements("a")
  151. policy.AllowAttrs("style", "class", "id").Globally()
  152. policy.AllowURLSchemes("http", "https", "mailto", "xmpp")
  153. return policy
  154. }
  155. func sanitizePost(content string) string {
  156. return strings.Replace(content, "<", "&lt;", -1)
  157. }
  158. // postDescription generates a description based on the given post content,
  159. // title, and post ID. This doesn't consider a V2 post field, `title` when
  160. // choosing what to generate. In case a post has a title, this function will
  161. // fail, and logic should instead be implemented to skip this when there's no
  162. // title, like so:
  163. // var desc string
  164. // if title == "" {
  165. // desc = postDescription(content, title, friendlyId)
  166. // } else {
  167. // desc = shortPostDescription(content)
  168. // }
  169. func postDescription(content, title, friendlyId string) string {
  170. maxLen := 140
  171. if content == "" {
  172. content = "WriteFreely is a painless, simple, federated blogging platform."
  173. } else {
  174. fmtStr := "%s"
  175. truncation := 0
  176. if utf8.RuneCountInString(content) > maxLen {
  177. // Post is longer than the max description, so let's show a better description
  178. fmtStr = "%s..."
  179. truncation = 3
  180. }
  181. if title == friendlyId {
  182. // No specific title was found; simply truncate the post, starting at the beginning
  183. content = fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1))
  184. } else {
  185. // There was a title, so return a real description
  186. blankLine := strings.Index(content, "\n\n")
  187. if blankLine < 0 {
  188. blankLine = 0
  189. }
  190. truncd := stringmanip.Substring(content, blankLine, blankLine+maxLen-truncation)
  191. contentNoNL := strings.Replace(truncd, "\n", " ", -1)
  192. content = strings.TrimSpace(fmt.Sprintf(fmtStr, contentNoNL))
  193. }
  194. }
  195. return content
  196. }
  197. func shortPostDescription(content string) string {
  198. maxLen := 140
  199. fmtStr := "%s"
  200. truncation := 0
  201. if utf8.RuneCountInString(content) > maxLen {
  202. // Post is longer than the max description, so let's show a better description
  203. fmtStr = "%s..."
  204. truncation = 3
  205. }
  206. return strings.TrimSpace(fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1)))
  207. }