A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 

349 行
12 KiB

  1. /*
  2. * Copyright © 2018-2021 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/writefreely/writefreely/config"
  29. "github.com/writefreely/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) handlePremiumContent(c *Collection, isOwner, postPage bool, cfg *config.Config) {
  41. if c.Monetization != "" {
  42. // User has Web Monetization enabled, so split content if it exists
  43. spl := strings.Index(p.Content, shortCodePaid)
  44. p.IsPaid = spl > -1
  45. if postPage {
  46. // We're viewing the individual post
  47. if isOwner {
  48. p.Content = strings.Replace(p.Content, shortCodePaid, "\n\n"+`<p class="split">Your subscriber content begins here.</p>`+"\n\n", 1)
  49. } else {
  50. if spl > -1 {
  51. p.Content = p.Content[:spl+len(shortCodePaid)]
  52. p.Content = strings.Replace(p.Content, shortCodePaid, "\n\n"+`<p class="split">Continue reading with a <strong>Coil</strong> membership.</p>`+"\n\n", 1)
  53. }
  54. }
  55. } else {
  56. // We've viewing the post on the collection landing
  57. if spl > -1 {
  58. baseURL := c.CanonicalURL()
  59. if isOwner {
  60. baseURL = "/" + c.Alias + "/"
  61. }
  62. p.Content = p.Content[:spl+len(shortCodePaid)]
  63. p.HTMLExcerpt = template.HTML(applyMarkdown([]byte(p.Content[:spl]), baseURL, cfg))
  64. }
  65. }
  66. }
  67. }
  68. func (p *Post) formatContent(cfg *config.Config, c *Collection, isOwner bool, isPostPage bool) {
  69. baseURL := c.CanonicalURL()
  70. // TODO: redundant
  71. if !isSingleUser {
  72. baseURL = "/" + c.Alias + "/"
  73. }
  74. p.handlePremiumContent(c, isOwner, isPostPage, cfg)
  75. p.Content = strings.Replace(p.Content, "&lt;!--paid-->", "<!--paid-->", 1)
  76. p.HTMLTitle = template.HTML(applyBasicMarkdown([]byte(p.Title.String)))
  77. p.HTMLContent = template.HTML(applyMarkdown([]byte(p.Content), baseURL, cfg))
  78. if exc := strings.Index(string(p.Content), "<!--more-->"); exc > -1 {
  79. p.HTMLExcerpt = template.HTML(applyMarkdown([]byte(p.Content[:exc]), baseURL, cfg))
  80. }
  81. }
  82. func (p *PublicPost) formatContent(cfg *config.Config, isOwner bool, isPostPage bool) {
  83. p.Post.formatContent(cfg, &p.Collection.Collection, isOwner, isPostPage)
  84. }
  85. func (p *Post) augmentContent(c *Collection) {
  86. if p.PinnedPosition.Valid {
  87. // Don't augment posts that are pinned
  88. return
  89. }
  90. if strings.Index(p.Content, "<!--nosig-->") > -1 {
  91. // Don't augment posts with the special "nosig" shortcode
  92. return
  93. }
  94. // Add post signatures
  95. if c.Signature != "" {
  96. p.Content += "\n\n" + c.Signature
  97. }
  98. }
  99. func (p *PublicPost) augmentContent() {
  100. p.Post.augmentContent(&p.Collection.Collection)
  101. }
  102. func (p *PublicPost) augmentReadingDestination() {
  103. if p.IsPaid {
  104. p.HTMLContent += template.HTML("\n\n" + `<p><a class="read-more" href="` + p.Collection.CanonicalURL() + p.Slug.String + `">` + localStr("Read more...", p.Language.String) + `</a> ($)</p>`)
  105. }
  106. }
  107. func applyMarkdown(data []byte, baseURL string, cfg *config.Config) string {
  108. return applyMarkdownSpecial(data, false, baseURL, cfg)
  109. }
  110. func disableYoutubeAutoplay(outHTML string) string {
  111. for _, match := range youtubeReg.FindAllString(outHTML, -1) {
  112. u, err := url.Parse(match)
  113. if err != nil {
  114. continue
  115. }
  116. u.RawQuery = html.UnescapeString(u.RawQuery)
  117. q := u.Query()
  118. // Set Youtube autoplay url parameter, if any, to 0
  119. if len(q["autoplay"]) == 1 {
  120. q.Set("autoplay", "0")
  121. }
  122. u.RawQuery = q.Encode()
  123. cleanURL := u.String()
  124. outHTML = strings.Replace(outHTML, match, cleanURL, 1)
  125. }
  126. return outHTML
  127. }
  128. func applyMarkdownSpecial(data []byte, skipNoFollow bool, baseURL string, cfg *config.Config) string {
  129. mdExtensions := 0 |
  130. blackfriday.EXTENSION_TABLES |
  131. blackfriday.EXTENSION_FENCED_CODE |
  132. blackfriday.EXTENSION_AUTOLINK |
  133. blackfriday.EXTENSION_STRIKETHROUGH |
  134. blackfriday.EXTENSION_SPACE_HEADERS |
  135. blackfriday.EXTENSION_AUTO_HEADER_IDS
  136. htmlFlags := 0 |
  137. blackfriday.HTML_USE_SMARTYPANTS |
  138. blackfriday.HTML_SMARTYPANTS_DASHES
  139. if baseURL != "" {
  140. htmlFlags |= blackfriday.HTML_HASHTAGS
  141. }
  142. // Generate Markdown
  143. md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions)
  144. if baseURL != "" {
  145. // Replace special text generated by Markdown parser
  146. tagPrefix := baseURL + "tag:"
  147. if cfg.App.Chorus {
  148. tagPrefix = "/read/t/"
  149. }
  150. md = []byte(hashtagReg.ReplaceAll(md, []byte("<a href=\""+tagPrefix+"$1\" class=\"hashtag\"><span>#</span><span class=\"p-category\">$1</span></a>")))
  151. handlePrefix := cfg.App.Host + "/@/"
  152. md = []byte(mentionReg.ReplaceAll(md, []byte("<a href=\""+handlePrefix+"$1$2\" class=\"u-url mention\">@<span>$1$2</span></a>")))
  153. }
  154. // Strip out bad HTML
  155. policy := getSanitizationPolicy()
  156. policy.RequireNoFollowOnLinks(!skipNoFollow)
  157. outHTML := string(policy.SanitizeBytes(md))
  158. // Strip newlines on certain block elements that render with them
  159. outHTML = blockReg.ReplaceAllString(outHTML, "<$1>")
  160. outHTML = endBlockReg.ReplaceAllString(outHTML, "</$1></$2>")
  161. outHTML = disableYoutubeAutoplay(outHTML)
  162. return outHTML
  163. }
  164. func applyBasicMarkdown(data []byte) string {
  165. mdExtensions := 0 |
  166. blackfriday.EXTENSION_STRIKETHROUGH |
  167. blackfriday.EXTENSION_SPACE_HEADERS |
  168. blackfriday.EXTENSION_HEADER_IDS
  169. htmlFlags := 0 |
  170. blackfriday.HTML_SKIP_HTML |
  171. blackfriday.HTML_USE_SMARTYPANTS |
  172. blackfriday.HTML_SMARTYPANTS_DASHES
  173. // Generate Markdown
  174. md := blackfriday.Markdown([]byte(data), blackfriday.HtmlRenderer(htmlFlags, "", ""), mdExtensions)
  175. // Strip out bad HTML
  176. policy := bluemonday.UGCPolicy()
  177. policy.AllowAttrs("class", "id").Globally()
  178. outHTML := string(policy.SanitizeBytes(md))
  179. outHTML = markeddownReg.ReplaceAllString(outHTML, "$1")
  180. outHTML = strings.TrimRightFunc(outHTML, unicode.IsSpace)
  181. return outHTML
  182. }
  183. func postTitle(content, friendlyId string) string {
  184. const maxTitleLen = 80
  185. content = stripHTMLWithoutEscaping(content)
  186. content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace)
  187. eol := strings.IndexRune(content, '\n')
  188. blankLine := strings.Index(content, "\n\n")
  189. if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen {
  190. return strings.TrimSpace(content[:blankLine])
  191. } else if utf8.RuneCountInString(content) <= maxTitleLen {
  192. return content
  193. }
  194. return friendlyId
  195. }
  196. // TODO: fix duplicated code from postTitle. postTitle is a widely used func we
  197. // don't have time to investigate right now.
  198. func friendlyPostTitle(content, friendlyId string) string {
  199. const maxTitleLen = 80
  200. content = stripHTMLWithoutEscaping(content)
  201. content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace)
  202. eol := strings.IndexRune(content, '\n')
  203. blankLine := strings.Index(content, "\n\n")
  204. if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen {
  205. return strings.TrimSpace(content[:blankLine])
  206. } else if eol == -1 && utf8.RuneCountInString(content) <= maxTitleLen {
  207. return content
  208. }
  209. title, truncd := parse.TruncToWord(parse.PostLede(content, true), maxTitleLen)
  210. if truncd {
  211. title += "..."
  212. }
  213. return title
  214. }
  215. // Strip HTML tags with bluemonday's StrictPolicy, then unescape the HTML
  216. // entities added in by sanitizing the content.
  217. func stripHTMLWithoutEscaping(content string) string {
  218. return html.UnescapeString(bluemonday.StrictPolicy().Sanitize(content))
  219. }
  220. func getSanitizationPolicy() *bluemonday.Policy {
  221. policy := bluemonday.UGCPolicy()
  222. policy.AllowAttrs("src", "style").OnElements("iframe", "video", "audio")
  223. policy.AllowAttrs("src", "type").OnElements("source")
  224. policy.AllowAttrs("frameborder", "width", "height").Matching(bluemonday.Integer).OnElements("iframe")
  225. policy.AllowAttrs("allowfullscreen").OnElements("iframe")
  226. policy.AllowAttrs("controls", "loop", "muted", "autoplay").OnElements("video")
  227. policy.AllowAttrs("controls", "loop", "muted", "autoplay", "preload").OnElements("audio")
  228. policy.AllowAttrs("target").OnElements("a")
  229. policy.AllowAttrs("title").OnElements("abbr")
  230. policy.AllowAttrs("style", "class", "id").Globally()
  231. policy.AllowElements("header", "footer")
  232. policy.AllowURLSchemes("http", "https", "mailto", "xmpp")
  233. return policy
  234. }
  235. func sanitizePost(content string) string {
  236. return strings.Replace(content, "<", "&lt;", -1)
  237. }
  238. // postDescription generates a description based on the given post content,
  239. // title, and post ID. This doesn't consider a V2 post field, `title` when
  240. // choosing what to generate. In case a post has a title, this function will
  241. // fail, and logic should instead be implemented to skip this when there's no
  242. // title, like so:
  243. // var desc string
  244. // if title == "" {
  245. // desc = postDescription(content, title, friendlyId)
  246. // } else {
  247. // desc = shortPostDescription(content)
  248. // }
  249. func postDescription(content, title, friendlyId string) string {
  250. maxLen := 140
  251. if content == "" {
  252. content = "WriteFreely is a painless, simple, federated blogging platform."
  253. } else {
  254. fmtStr := "%s"
  255. truncation := 0
  256. if utf8.RuneCountInString(content) > maxLen {
  257. // Post is longer than the max description, so let's show a better description
  258. fmtStr = "%s..."
  259. truncation = 3
  260. }
  261. if title == friendlyId {
  262. // No specific title was found; simply truncate the post, starting at the beginning
  263. content = fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1))
  264. } else {
  265. // There was a title, so return a real description
  266. blankLine := strings.Index(content, "\n\n")
  267. if blankLine < 0 {
  268. blankLine = 0
  269. }
  270. truncd := stringmanip.Substring(content, blankLine, blankLine+maxLen-truncation)
  271. contentNoNL := strings.Replace(truncd, "\n", " ", -1)
  272. content = strings.TrimSpace(fmt.Sprintf(fmtStr, contentNoNL))
  273. }
  274. }
  275. return content
  276. }
  277. func shortPostDescription(content string) string {
  278. maxLen := 140
  279. fmtStr := "%s"
  280. truncation := 0
  281. if utf8.RuneCountInString(content) > maxLen {
  282. // Post is longer than the max description, so let's show a better description
  283. fmtStr = "%s..."
  284. truncation = 3
  285. }
  286. return strings.TrimSpace(fmt.Sprintf(fmtStr, strings.Replace(stringmanip.Substring(content, 0, maxLen-truncation), "\n", " ", -1)))
  287. }
  288. func handleRenderMarkdown(app *App, w http.ResponseWriter, r *http.Request) error {
  289. if !IsJSON(r) {
  290. return impart.HTTPError{Status: http.StatusUnsupportedMediaType, Message: "Markdown API only supports JSON requests"}
  291. }
  292. in := struct {
  293. CollectionURL string `json:"collection_url"`
  294. RawBody string `json:"raw_body"`
  295. }{}
  296. decoder := json.NewDecoder(r.Body)
  297. err := decoder.Decode(&in)
  298. if err != nil {
  299. log.Error("Couldn't parse markdown JSON request: %v", err)
  300. return ErrBadJSON
  301. }
  302. out := struct {
  303. Body string `json:"body"`
  304. }{
  305. Body: applyMarkdown([]byte(in.RawBody), in.CollectionURL, app.cfg),
  306. }
  307. return impart.WriteSuccess(w, out, http.StatusOK)
  308. }