A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 

1686 рядки
44 KiB

  1. /*
  2. * Copyright © 2018-2021 Musing Studio 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. "database/sql"
  13. "encoding/json"
  14. "fmt"
  15. "github.com/writefreely/writefreely/spam"
  16. "html/template"
  17. "net/http"
  18. "net/url"
  19. "regexp"
  20. "strings"
  21. "time"
  22. "github.com/gorilla/mux"
  23. "github.com/guregu/null"
  24. "github.com/guregu/null/zero"
  25. "github.com/kylemcc/twitter-text-go/extract"
  26. "github.com/microcosm-cc/bluemonday"
  27. stripmd "github.com/writeas/go-strip-markdown/v2"
  28. "github.com/writeas/impart"
  29. "github.com/writeas/monday"
  30. "github.com/writeas/slug"
  31. "github.com/writeas/web-core/activitystreams"
  32. "github.com/writeas/web-core/bots"
  33. "github.com/writeas/web-core/converter"
  34. "github.com/writeas/web-core/i18n"
  35. "github.com/writeas/web-core/log"
  36. "github.com/writeas/web-core/tags"
  37. "github.com/writefreely/writefreely/page"
  38. "github.com/writefreely/writefreely/parse"
  39. )
  40. const (
  41. // Post ID length bounds
  42. minIDLen = 10
  43. maxIDLen = 10
  44. userPostIDLen = 10
  45. postIDLen = 10
  46. postMetaDateFormat = "2006-01-02 15:04:05"
  47. shortCodePaid = "<!--paid-->"
  48. )
  49. type (
  50. AnonymousPost struct {
  51. ID string
  52. Content string
  53. HTMLContent template.HTML
  54. Font string
  55. Language string
  56. Direction string
  57. Title string
  58. GenTitle string
  59. Description string
  60. Author string
  61. Views int64
  62. Images []string
  63. IsPlainText bool
  64. IsCode bool
  65. IsLinkable bool
  66. }
  67. AuthenticatedPost struct {
  68. ID string `json:"id" schema:"id"`
  69. Web bool `json:"web" schema:"web"`
  70. *SubmittedPost
  71. }
  72. // SubmittedPost represents a post supplied by a client for publishing or
  73. // updating. Since Title and Content can be updated to "", they are
  74. // pointers that can be easily tested to detect changes.
  75. SubmittedPost struct {
  76. Slug *string `json:"slug" schema:"slug"`
  77. Title *string `json:"title" schema:"title"`
  78. Content *string `json:"body" schema:"body"`
  79. Font string `json:"font" schema:"font"`
  80. IsRTL converter.NullJSONBool `json:"rtl" schema:"rtl"`
  81. Language converter.NullJSONString `json:"lang" schema:"lang"`
  82. Created *string `json:"created" schema:"created"`
  83. }
  84. // Post represents a post as found in the database.
  85. Post struct {
  86. ID string `db:"id" json:"id"`
  87. Slug null.String `db:"slug" json:"slug,omitempty"`
  88. Font string `db:"text_appearance" json:"appearance"`
  89. Language zero.String `db:"language" json:"language"`
  90. RTL zero.Bool `db:"rtl" json:"rtl"`
  91. Privacy int64 `db:"privacy" json:"-"`
  92. OwnerID null.Int `db:"owner_id" json:"-"`
  93. CollectionID null.Int `db:"collection_id" json:"-"`
  94. PinnedPosition null.Int `db:"pinned_position" json:"-"`
  95. Created time.Time `db:"created" json:"created"`
  96. Updated time.Time `db:"updated" json:"updated"`
  97. ViewCount int64 `db:"view_count" json:"-"`
  98. Title zero.String `db:"title" json:"title"`
  99. HTMLTitle template.HTML `db:"title" json:"-"`
  100. Content string `db:"content" json:"body"`
  101. HTMLContent template.HTML `db:"content" json:"-"`
  102. HTMLExcerpt template.HTML `db:"content" json:"-"`
  103. Tags []string `json:"tags"`
  104. Images []string `json:"images,omitempty"`
  105. IsPaid bool `json:"paid"`
  106. OwnerName string `json:"owner,omitempty"`
  107. }
  108. // PublicPost holds properties for a publicly returned post, i.e. a post in
  109. // a context where the viewer may not be the owner. As such, sensitive
  110. // metadata for the post is hidden and properties supporting the display of
  111. // the post are added.
  112. PublicPost struct {
  113. *Post
  114. IsSubdomain bool `json:"-"`
  115. IsTopLevel bool `json:"-"`
  116. DisplayDate string `json:"-"`
  117. Views int64 `json:"views"`
  118. Owner *PublicUser `json:"-"`
  119. IsOwner bool `json:"-"`
  120. URL string `json:"url,omitempty"`
  121. Collection *CollectionObj `json:"collection,omitempty"`
  122. }
  123. CollectionPostPage struct {
  124. *PublicPost
  125. page.StaticPage
  126. IsOwner bool
  127. IsPinned bool
  128. IsCustomDomain bool
  129. Monetization string
  130. Verification string
  131. PinnedPosts *[]PublicPost
  132. IsFound bool
  133. IsAdmin bool
  134. CanInvite bool
  135. Silenced bool
  136. // Helper field for Chorus mode
  137. CollAlias string
  138. }
  139. RawPost struct {
  140. Id, Slug string
  141. Title string
  142. Content string
  143. Views int64
  144. Font string
  145. Created time.Time
  146. Updated time.Time
  147. IsRTL sql.NullBool
  148. Language sql.NullString
  149. OwnerID int64
  150. CollectionID sql.NullInt64
  151. Found bool
  152. Gone bool
  153. }
  154. AnonymousAuthPost struct {
  155. ID string `json:"id"`
  156. Token string `json:"token"`
  157. }
  158. ClaimPostRequest struct {
  159. *AnonymousAuthPost
  160. CollectionAlias string `json:"collection"`
  161. CreateCollection bool `json:"create_collection"`
  162. // Generated properties
  163. Slug string `json:"-"`
  164. }
  165. ClaimPostResult struct {
  166. ID string `json:"id,omitempty"`
  167. Code int `json:"code,omitempty"`
  168. ErrorMessage string `json:"error_msg,omitempty"`
  169. Post *PublicPost `json:"post,omitempty"`
  170. }
  171. )
  172. func (p *Post) Direction() string {
  173. if p.RTL.Valid {
  174. if p.RTL.Bool {
  175. return "rtl"
  176. }
  177. return "ltr"
  178. }
  179. return "auto"
  180. }
  181. // DisplayTitle dynamically generates a title from the Post's contents if it
  182. // doesn't already have an explicit title.
  183. func (p *Post) DisplayTitle() string {
  184. if p.Title.String != "" {
  185. return p.Title.String
  186. }
  187. t := friendlyPostTitle(p.Content, p.ID)
  188. return t
  189. }
  190. // PlainDisplayTitle dynamically generates a title from the Post's contents if it
  191. // doesn't already have an explicit title.
  192. func (p *Post) PlainDisplayTitle() string {
  193. if t := stripmd.Strip(p.DisplayTitle()); t != "" {
  194. return t
  195. }
  196. return p.ID
  197. }
  198. // FormattedDisplayTitle dynamically generates a title from the Post's contents if it
  199. // doesn't already have an explicit title.
  200. func (p *Post) FormattedDisplayTitle() template.HTML {
  201. if p.HTMLTitle != "" {
  202. return p.HTMLTitle
  203. }
  204. return template.HTML(p.DisplayTitle())
  205. }
  206. // Summary gives a shortened summary of the post based on the post's title,
  207. // especially for display in a longer list of posts. It extracts a summary for
  208. // posts in the Title\n\nBody format, returning nothing if the entire was short
  209. // enough that the extracted title == extracted summary.
  210. func (p Post) Summary() string {
  211. if p.Content == "" {
  212. return ""
  213. }
  214. p.Content = stripHTMLWithoutEscaping(p.Content)
  215. // and Markdown
  216. p.Content = stripmd.StripOptions(p.Content, stripmd.Options{SkipImages: true})
  217. title := p.Title.String
  218. var desc string
  219. if title == "" {
  220. // No title, so generate one
  221. title = friendlyPostTitle(p.Content, p.ID)
  222. desc = postDescription(p.Content, title, p.ID)
  223. if desc == title {
  224. return ""
  225. }
  226. return desc
  227. }
  228. return shortPostDescription(p.Content)
  229. }
  230. func (p Post) SummaryHTML() template.HTML {
  231. return template.HTML(p.Summary())
  232. }
  233. // Excerpt shows any text that comes before a (more) tag.
  234. // TODO: use HTMLExcerpt in templates instead of this method
  235. func (p *Post) Excerpt() template.HTML {
  236. return p.HTMLExcerpt
  237. }
  238. func (p *Post) CreatedDate() string {
  239. return p.Created.Format("2006-01-02")
  240. }
  241. func (p *Post) Created8601() string {
  242. return p.Created.Format("2006-01-02T15:04:05Z")
  243. }
  244. func (p *Post) IsScheduled() bool {
  245. return p.Created.After(time.Now())
  246. }
  247. func (p *Post) HasTag(tag string) bool {
  248. // Regexp looks for tag and has a non-capturing group at the end looking
  249. // for the end of the word.
  250. // Assisted by: https://stackoverflow.com/a/35192941/1549194
  251. hasTag, _ := regexp.MatchString("#"+tag+`(?:[[:punct:]]|\s|\z)`, p.Content)
  252. return hasTag
  253. }
  254. func (p *Post) HasTitleLink() bool {
  255. if p.Title.String == "" {
  256. return false
  257. }
  258. hasLink, _ := regexp.MatchString(`([^!]+|^)\[.+\]\(.+\)`, p.Title.String)
  259. return hasLink
  260. }
  261. func (c CollectionPostPage) DisplayMonetization() string {
  262. if c.Collection == nil {
  263. log.Info("CollectionPostPage.DisplayMonetization: c.Collection is nil")
  264. return ""
  265. }
  266. return displayMonetization(c.Monetization, c.Collection.Alias)
  267. }
  268. func handleViewPost(app *App, w http.ResponseWriter, r *http.Request) error {
  269. vars := mux.Vars(r)
  270. friendlyID := vars["post"]
  271. // NOTE: until this is done better, be sure to keep this in parity with
  272. // isRaw() and viewCollectionPost()
  273. isJSON := strings.HasSuffix(friendlyID, ".json")
  274. isXML := strings.HasSuffix(friendlyID, ".xml")
  275. isCSS := strings.HasSuffix(friendlyID, ".css")
  276. isMarkdown := strings.HasSuffix(friendlyID, ".md")
  277. isRaw := strings.HasSuffix(friendlyID, ".txt") || isJSON || isXML || isCSS || isMarkdown
  278. // Display reserved page if that is requested resource
  279. if t, ok := pages[r.URL.Path[1:]+".tmpl"]; ok {
  280. return handleTemplatedPage(app, w, r, t)
  281. } else if (strings.Contains(r.URL.Path, ".") && !isRaw && !isMarkdown) || r.URL.Path == "/robots.txt" || r.URL.Path == "/manifest.json" {
  282. // Serve static file
  283. app.shttp.ServeHTTP(w, r)
  284. return nil
  285. }
  286. // Display collection if this is a collection
  287. c, _ := app.db.GetCollection(friendlyID)
  288. if c != nil {
  289. return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s/", friendlyID)}
  290. }
  291. // Normalize the URL, redirecting user to consistent post URL
  292. if friendlyID != strings.ToLower(friendlyID) {
  293. return impart.HTTPError{http.StatusMovedPermanently, fmt.Sprintf("/%s", strings.ToLower(friendlyID))}
  294. }
  295. ext := ""
  296. if isRaw {
  297. parts := strings.Split(friendlyID, ".")
  298. friendlyID = parts[0]
  299. if len(parts) > 1 {
  300. ext = "." + parts[1]
  301. }
  302. }
  303. var ownerID sql.NullInt64
  304. var title string
  305. var content string
  306. var font string
  307. var language []byte
  308. var rtl []byte
  309. var views int64
  310. var post *AnonymousPost
  311. var found bool
  312. var gone bool
  313. fixedID := slug.Make(friendlyID)
  314. if fixedID != friendlyID {
  315. return impart.HTTPError{http.StatusFound, fmt.Sprintf("/%s%s", fixedID, ext)}
  316. }
  317. err := app.db.QueryRow("SELECT owner_id, title, content, text_appearance, view_count, language, rtl FROM posts WHERE id = ?", friendlyID).Scan(&ownerID, &title, &content, &font, &views, &language, &rtl)
  318. switch {
  319. case err == sql.ErrNoRows:
  320. found = false
  321. // Output the error in the correct format
  322. if isJSON {
  323. content = "{\"error\": \"Post not found.\"}"
  324. } else if isRaw {
  325. content = "Post not found."
  326. } else {
  327. return ErrPostNotFound
  328. }
  329. case err != nil:
  330. found = false
  331. log.Error("Post loading err: %s\n", err)
  332. return ErrInternalGeneral
  333. default:
  334. found = true
  335. var d string
  336. if len(rtl) == 0 {
  337. d = "auto"
  338. } else if rtl[0] == 49 {
  339. // TODO: find a cleaner way to get this (possibly NULL) value
  340. d = "rtl"
  341. } else {
  342. d = "ltr"
  343. }
  344. generatedTitle := friendlyPostTitle(content, friendlyID)
  345. sanitizedContent := content
  346. if font != "code" {
  347. sanitizedContent = template.HTMLEscapeString(content)
  348. }
  349. var desc string
  350. if title == "" {
  351. desc = postDescription(content, title, friendlyID)
  352. } else {
  353. desc = shortPostDescription(content)
  354. }
  355. post = &AnonymousPost{
  356. ID: friendlyID,
  357. Content: sanitizedContent,
  358. Title: title,
  359. GenTitle: generatedTitle,
  360. Description: desc,
  361. Author: "",
  362. Font: font,
  363. IsPlainText: isRaw,
  364. IsCode: font == "code",
  365. IsLinkable: font != "code",
  366. Views: views,
  367. Language: string(language),
  368. Direction: d,
  369. }
  370. if !isRaw {
  371. post.HTMLContent = template.HTML(applyMarkdown([]byte(content), "", app.cfg))
  372. post.Images = extractImages(post.Content)
  373. }
  374. }
  375. var silenced bool
  376. if found {
  377. silenced, err = app.db.IsUserSilenced(ownerID.Int64)
  378. if err != nil {
  379. log.Error("view post: %v", err)
  380. }
  381. }
  382. // Check if post has been unpublished
  383. if title == "" && content == "" {
  384. gone = true
  385. if isJSON {
  386. content = "{\"error\": \"Post was unpublished.\"}"
  387. } else if isCSS {
  388. content = ""
  389. } else if isRaw {
  390. content = "Post was unpublished."
  391. } else {
  392. return ErrPostUnpublished
  393. }
  394. }
  395. var u = &User{}
  396. if isRaw {
  397. contentType := "text/plain"
  398. if isJSON {
  399. contentType = "application/json"
  400. } else if isCSS {
  401. contentType = "text/css"
  402. } else if isXML {
  403. contentType = "application/xml"
  404. } else if isMarkdown {
  405. contentType = "text/markdown"
  406. }
  407. w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType))
  408. if isMarkdown && post.Title != "" {
  409. fmt.Fprintf(w, "%s\n", post.Title)
  410. for i := 1; i <= len(post.Title); i++ {
  411. fmt.Fprintf(w, "=")
  412. }
  413. fmt.Fprintf(w, "\n\n")
  414. }
  415. fmt.Fprint(w, content)
  416. if !found {
  417. return ErrPostNotFound
  418. } else if gone {
  419. return ErrPostUnpublished
  420. }
  421. } else {
  422. var err error
  423. page := struct {
  424. *AnonymousPost
  425. page.StaticPage
  426. Username string
  427. IsOwner bool
  428. SiteURL string
  429. Silenced bool
  430. }{
  431. AnonymousPost: post,
  432. StaticPage: pageForReq(app, r),
  433. SiteURL: app.cfg.App.Host,
  434. }
  435. if u = getUserSession(app, r); u != nil {
  436. page.Username = u.Username
  437. page.IsOwner = ownerID.Valid && ownerID.Int64 == u.ID
  438. }
  439. if !page.IsOwner && silenced {
  440. return ErrPostNotFound
  441. }
  442. page.Silenced = silenced
  443. err = templates["post"].ExecuteTemplate(w, "post", page)
  444. if err != nil {
  445. log.Error("Post template execute error: %v", err)
  446. }
  447. }
  448. go func() {
  449. if u != nil && ownerID.Valid && ownerID.Int64 == u.ID {
  450. // Post is owned by someone; skip view increment since that person is viewing this post.
  451. return
  452. }
  453. // Update stats for non-raw post views
  454. if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) {
  455. _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE id = ?", friendlyID)
  456. if err != nil {
  457. log.Error("Unable to update posts count: %v", err)
  458. }
  459. }
  460. }()
  461. return nil
  462. }
  463. // API v2 funcs
  464. // newPost creates a new post with or without an owning Collection.
  465. //
  466. // Endpoints:
  467. // - /posts
  468. // - /posts?collection={alias}
  469. // - ? /collections/{alias}/posts
  470. func newPost(app *App, w http.ResponseWriter, r *http.Request) error {
  471. reqJSON := IsJSON(r)
  472. vars := mux.Vars(r)
  473. collAlias := vars["alias"]
  474. if collAlias == "" {
  475. collAlias = r.FormValue("collection")
  476. }
  477. accessToken := r.Header.Get("Authorization")
  478. if accessToken == "" {
  479. // TODO: remove this
  480. accessToken = r.FormValue("access_token")
  481. }
  482. // FIXME: determine web submission with Content-Type header
  483. var u *User
  484. var userID int64 = -1
  485. var username string
  486. if accessToken == "" {
  487. u = getUserSession(app, r)
  488. if u != nil {
  489. userID = u.ID
  490. username = u.Username
  491. }
  492. } else {
  493. userID = app.db.GetUserID(accessToken)
  494. }
  495. silenced, err := app.db.IsUserSilenced(userID)
  496. if err != nil {
  497. log.Error("new post: %v", err)
  498. }
  499. if silenced {
  500. return ErrUserSilenced
  501. }
  502. if userID == -1 {
  503. return ErrNotLoggedIn
  504. }
  505. if accessToken == "" && u == nil && collAlias != "" {
  506. return impart.HTTPError{http.StatusBadRequest, "Parameter `access_token` required."}
  507. }
  508. // Get post data
  509. var p *SubmittedPost
  510. if reqJSON {
  511. decoder := json.NewDecoder(r.Body)
  512. err = decoder.Decode(&p)
  513. if err != nil {
  514. log.Error("Couldn't parse new post JSON request: %v\n", err)
  515. return ErrBadJSON
  516. }
  517. if p.Title == nil {
  518. t := ""
  519. p.Title = &t
  520. }
  521. if strings.TrimSpace(*(p.Title)) == "" && (p.Content == nil || strings.TrimSpace(*(p.Content)) == "") {
  522. return ErrNoPublishableContent
  523. }
  524. if p.Content == nil {
  525. c := ""
  526. p.Content = &c
  527. }
  528. } else {
  529. post := r.FormValue("body")
  530. appearance := r.FormValue("font")
  531. title := r.FormValue("title")
  532. rtlValue := r.FormValue("rtl")
  533. langValue := r.FormValue("lang")
  534. if strings.TrimSpace(post) == "" {
  535. return ErrNoPublishableContent
  536. }
  537. var isRTL, rtlValid bool
  538. if rtlValue == "auto" && langValue != "" {
  539. isRTL = i18n.LangIsRTL(langValue)
  540. rtlValid = true
  541. } else {
  542. isRTL = rtlValue == "true"
  543. rtlValid = rtlValue != "" && langValue != ""
  544. }
  545. // Create a new post
  546. p = &SubmittedPost{
  547. Title: &title,
  548. Content: &post,
  549. Font: appearance,
  550. IsRTL: converter.NullJSONBool{sql.NullBool{Bool: isRTL, Valid: rtlValid}},
  551. Language: converter.NullJSONString{sql.NullString{String: langValue, Valid: langValue != ""}},
  552. }
  553. }
  554. if !p.isFontValid() {
  555. p.Font = "norm"
  556. }
  557. var newPost *PublicPost = &PublicPost{}
  558. var coll *Collection
  559. if accessToken != "" {
  560. newPost, err = app.db.CreateOwnedPost(p, accessToken, collAlias, app.cfg.App.Host)
  561. } else {
  562. //return ErrNotLoggedIn
  563. // TODO: verify user is logged in
  564. var collID int64
  565. if collAlias != "" {
  566. coll, err = app.db.GetCollection(collAlias)
  567. if err != nil {
  568. return err
  569. }
  570. coll.hostName = app.cfg.App.Host
  571. if coll.OwnerID != u.ID {
  572. return ErrForbiddenCollection
  573. }
  574. collID = coll.ID
  575. }
  576. // TODO: return PublicPost from createPost
  577. newPost.Post, err = app.db.CreatePost(userID, collID, p)
  578. }
  579. if err != nil {
  580. return err
  581. }
  582. if coll != nil {
  583. coll.ForPublic()
  584. newPost.Collection = &CollectionObj{Collection: *coll}
  585. }
  586. newPost.extractData()
  587. newPost.OwnerName = username
  588. newPost.URL = newPost.CanonicalURL(app.cfg.App.Host)
  589. // Write success now
  590. response := impart.WriteSuccess(w, newPost, http.StatusCreated)
  591. if newPost.Collection != nil {
  592. if !app.cfg.App.Private && app.cfg.App.Federation && !newPost.Created.After(time.Now()) {
  593. go federatePost(app, newPost, newPost.Collection.ID, false)
  594. }
  595. if app.cfg.Email.Enabled() && newPost.Collection.EmailSubsEnabled() {
  596. go app.db.InsertJob(&PostJob{
  597. PostID: newPost.ID,
  598. Action: "email",
  599. Delay: emailSendDelay,
  600. })
  601. }
  602. }
  603. return response
  604. }
  605. func existingPost(app *App, w http.ResponseWriter, r *http.Request) error {
  606. reqJSON := IsJSON(r)
  607. vars := mux.Vars(r)
  608. postID := vars["post"]
  609. p := AuthenticatedPost{ID: postID}
  610. var err error
  611. if reqJSON {
  612. // Decode JSON request
  613. decoder := json.NewDecoder(r.Body)
  614. err = decoder.Decode(&p)
  615. if err != nil {
  616. log.Error("Couldn't parse post update JSON request: %v\n", err)
  617. return ErrBadJSON
  618. }
  619. } else {
  620. err = r.ParseForm()
  621. if err != nil {
  622. log.Error("Couldn't parse post update form request: %v\n", err)
  623. return ErrBadFormData
  624. }
  625. // Can't decode to a nil SubmittedPost property, so create instance now
  626. p.SubmittedPost = &SubmittedPost{}
  627. err = app.formDecoder.Decode(&p, r.PostForm)
  628. if err != nil {
  629. log.Error("Couldn't decode post update form request: %v\n", err)
  630. return ErrBadFormData
  631. }
  632. }
  633. if p.Web {
  634. p.IsRTL.Valid = true
  635. }
  636. if p.SubmittedPost == nil {
  637. return ErrPostNoUpdatableVals
  638. }
  639. // Ensure an access token was given
  640. accessToken := r.Header.Get("Authorization")
  641. // Get user's cookie session if there's no token
  642. var u *User
  643. //var username string
  644. if accessToken == "" {
  645. u = getUserSession(app, r)
  646. if u != nil {
  647. //username = u.Username
  648. }
  649. }
  650. if u == nil && accessToken == "" {
  651. return ErrNoAccessToken
  652. }
  653. // Get user ID from current session or given access token, if one was given.
  654. var userID int64
  655. if u != nil {
  656. userID = u.ID
  657. } else if accessToken != "" {
  658. userID, err = AuthenticateUser(app.db, accessToken)
  659. if err != nil {
  660. return err
  661. }
  662. }
  663. silenced, err := app.db.IsUserSilenced(userID)
  664. if err != nil {
  665. log.Error("existing post: %v", err)
  666. }
  667. if silenced {
  668. return ErrUserSilenced
  669. }
  670. // Modify post struct
  671. p.ID = postID
  672. err = app.db.UpdateOwnedPost(&p, userID)
  673. if err != nil {
  674. if reqJSON {
  675. return err
  676. }
  677. if err, ok := err.(impart.HTTPError); ok {
  678. addSessionFlash(app, w, r, err.Message, nil)
  679. } else {
  680. addSessionFlash(app, w, r, err.Error(), nil)
  681. }
  682. }
  683. var pRes *PublicPost
  684. pRes, err = app.db.GetPost(p.ID, 0)
  685. if reqJSON {
  686. if err != nil {
  687. return err
  688. }
  689. pRes.extractData()
  690. }
  691. if pRes.CollectionID.Valid {
  692. coll, err := app.db.GetCollectionBy("id = ?", pRes.CollectionID.Int64)
  693. if err == nil && !app.cfg.App.Private && app.cfg.App.Federation {
  694. coll.hostName = app.cfg.App.Host
  695. pRes.Collection = &CollectionObj{Collection: *coll}
  696. go federatePost(app, pRes, pRes.Collection.ID, true)
  697. }
  698. }
  699. // Write success now
  700. if reqJSON {
  701. return impart.WriteSuccess(w, pRes, http.StatusOK)
  702. }
  703. addSessionFlash(app, w, r, "Changes saved.", nil)
  704. collectionAlias := vars["alias"]
  705. redirect := "/" + postID + "/meta"
  706. if collectionAlias != "" {
  707. collPre := "/" + collectionAlias
  708. if app.cfg.App.SingleUser {
  709. collPre = ""
  710. }
  711. redirect = collPre + "/" + pRes.Slug.String + "/edit/meta"
  712. } else {
  713. if app.cfg.App.SingleUser {
  714. redirect = "/d" + redirect
  715. }
  716. }
  717. w.Header().Set("Location", redirect)
  718. w.WriteHeader(http.StatusFound)
  719. return nil
  720. }
  721. func deletePost(app *App, w http.ResponseWriter, r *http.Request) error {
  722. vars := mux.Vars(r)
  723. friendlyID := vars["post"]
  724. editToken := r.FormValue("token")
  725. var ownerID int64
  726. var u *User
  727. accessToken := r.Header.Get("Authorization")
  728. if accessToken == "" && editToken == "" {
  729. u = getUserSession(app, r)
  730. if u == nil {
  731. return ErrNoAccessToken
  732. }
  733. }
  734. var res sql.Result
  735. var t *sql.Tx
  736. var err error
  737. var collID sql.NullInt64
  738. var coll *Collection
  739. var pp *PublicPost
  740. if editToken != "" {
  741. // TODO: SELECT owner_id, as well, and return appropriate error if NULL instead of running two queries
  742. var dummy int64
  743. err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ?", friendlyID).Scan(&dummy)
  744. switch {
  745. case err == sql.ErrNoRows:
  746. return impart.HTTPError{http.StatusNotFound, "Post not found."}
  747. }
  748. err = app.db.QueryRow("SELECT 1 FROM posts WHERE id = ? AND owner_id IS NULL", friendlyID).Scan(&dummy)
  749. switch {
  750. case err == sql.ErrNoRows:
  751. // Post already has an owner. This could provide a bad experience
  752. // for the user, but it's more important to ensure data isn't lost
  753. // unexpectedly. So prevent deletion via token.
  754. return impart.HTTPError{http.StatusConflict, "This post belongs to some user (hopefully yours). Please log in and delete it from that user's account."}
  755. }
  756. res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND modify_token = ? AND owner_id IS NULL", friendlyID, editToken)
  757. } else if accessToken != "" || u != nil {
  758. // Caller provided some way to authenticate; assume caller expects the
  759. // post to be deleted based on a specific post owner, thus we should
  760. // return corresponding errors.
  761. if accessToken != "" {
  762. ownerID = app.db.GetUserID(accessToken)
  763. if ownerID == -1 {
  764. return ErrBadAccessToken
  765. }
  766. } else {
  767. ownerID = u.ID
  768. }
  769. // TODO: don't make two queries
  770. var realOwnerID sql.NullInt64
  771. err = app.db.QueryRow("SELECT collection_id, owner_id FROM posts WHERE id = ?", friendlyID).Scan(&collID, &realOwnerID)
  772. if err != nil {
  773. return err
  774. }
  775. if !collID.Valid {
  776. // There's no collection; simply delete the post
  777. res, err = app.db.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID)
  778. } else {
  779. // Post belongs to a collection; do any additional clean up
  780. coll, err = app.db.GetCollectionBy("id = ?", collID.Int64)
  781. if err != nil {
  782. log.Error("Unable to get collection: %v", err)
  783. return err
  784. }
  785. if app.cfg.App.Federation {
  786. // First fetch full post for federation
  787. pp, err = app.db.GetOwnedPost(friendlyID, ownerID)
  788. if err != nil {
  789. log.Error("Unable to get owned post: %v", err)
  790. return err
  791. }
  792. collObj := &CollectionObj{Collection: *coll}
  793. pp.Collection = collObj
  794. }
  795. t, err = app.db.Begin()
  796. if err != nil {
  797. log.Error("No begin: %v", err)
  798. return err
  799. }
  800. res, err = t.Exec("DELETE FROM posts WHERE id = ? AND owner_id = ?", friendlyID, ownerID)
  801. }
  802. } else {
  803. return impart.HTTPError{http.StatusBadRequest, "No authenticated user or post token given."}
  804. }
  805. if err != nil {
  806. return err
  807. }
  808. affected, err := res.RowsAffected()
  809. if err != nil {
  810. if t != nil {
  811. t.Rollback()
  812. log.Error("Rows affected err! Rolling back")
  813. }
  814. return err
  815. } else if affected == 0 {
  816. if t != nil {
  817. t.Rollback()
  818. log.Error("No rows affected! Rolling back")
  819. }
  820. return impart.HTTPError{http.StatusForbidden, "Post not found, or you're not the owner."}
  821. }
  822. if t != nil {
  823. t.Commit()
  824. }
  825. if coll != nil && !app.cfg.App.Private && app.cfg.App.Federation {
  826. go deleteFederatedPost(app, pp, collID.Int64)
  827. }
  828. return impart.HTTPError{Status: http.StatusNoContent}
  829. }
  830. // addPost associates a post with the authenticated user.
  831. func addPost(app *App, w http.ResponseWriter, r *http.Request) error {
  832. var ownerID int64
  833. // Authenticate user
  834. at := r.Header.Get("Authorization")
  835. if at != "" {
  836. ownerID = app.db.GetUserID(at)
  837. if ownerID == -1 {
  838. return ErrBadAccessToken
  839. }
  840. } else {
  841. u := getUserSession(app, r)
  842. if u == nil {
  843. return ErrNotLoggedIn
  844. }
  845. ownerID = u.ID
  846. }
  847. silenced, err := app.db.IsUserSilenced(ownerID)
  848. if err != nil {
  849. log.Error("add post: %v", err)
  850. }
  851. if silenced {
  852. return ErrUserSilenced
  853. }
  854. // Parse claimed posts in format:
  855. // [{"id": "...", "token": "..."}]
  856. var claims *[]ClaimPostRequest
  857. decoder := json.NewDecoder(r.Body)
  858. err = decoder.Decode(&claims)
  859. if err != nil {
  860. return ErrBadJSONArray
  861. }
  862. vars := mux.Vars(r)
  863. collAlias := vars["alias"]
  864. // Update all given posts
  865. res, err := app.db.ClaimPosts(app.cfg, ownerID, collAlias, claims)
  866. if err != nil {
  867. return err
  868. }
  869. for _, pRes := range *res {
  870. if pRes.Code != http.StatusOK {
  871. continue
  872. }
  873. if !app.cfg.App.Private && app.cfg.App.Federation {
  874. if !pRes.Post.Created.After(time.Now()) {
  875. pRes.Post.Collection.hostName = app.cfg.App.Host
  876. go federatePost(app, pRes.Post, pRes.Post.Collection.ID, false)
  877. }
  878. }
  879. if app.cfg.Email.Enabled() && pRes.Post.Collection.EmailSubsEnabled() {
  880. go app.db.InsertJob(&PostJob{
  881. PostID: pRes.Post.ID,
  882. Action: "email",
  883. Delay: emailSendDelay,
  884. })
  885. }
  886. }
  887. return impart.WriteSuccess(w, res, http.StatusOK)
  888. }
  889. func dispersePost(app *App, w http.ResponseWriter, r *http.Request) error {
  890. var ownerID int64
  891. // Authenticate user
  892. at := r.Header.Get("Authorization")
  893. if at != "" {
  894. ownerID = app.db.GetUserID(at)
  895. if ownerID == -1 {
  896. return ErrBadAccessToken
  897. }
  898. } else {
  899. u := getUserSession(app, r)
  900. if u == nil {
  901. return ErrNotLoggedIn
  902. }
  903. ownerID = u.ID
  904. }
  905. // Parse posts in format:
  906. // ["..."]
  907. var postIDs []string
  908. decoder := json.NewDecoder(r.Body)
  909. err := decoder.Decode(&postIDs)
  910. if err != nil {
  911. return ErrBadJSONArray
  912. }
  913. // Update all given posts
  914. res, err := app.db.DispersePosts(ownerID, postIDs)
  915. if err != nil {
  916. return err
  917. }
  918. return impart.WriteSuccess(w, res, http.StatusOK)
  919. }
  920. type (
  921. PinPostResult struct {
  922. ID string `json:"id,omitempty"`
  923. Code int `json:"code,omitempty"`
  924. ErrorMessage string `json:"error_msg,omitempty"`
  925. }
  926. )
  927. // pinPost pins a post to a blog
  928. func pinPost(app *App, w http.ResponseWriter, r *http.Request) error {
  929. var userID int64
  930. // Authenticate user
  931. at := r.Header.Get("Authorization")
  932. if at != "" {
  933. userID = app.db.GetUserID(at)
  934. if userID == -1 {
  935. return ErrBadAccessToken
  936. }
  937. } else {
  938. u := getUserSession(app, r)
  939. if u == nil {
  940. return ErrNotLoggedIn
  941. }
  942. userID = u.ID
  943. }
  944. silenced, err := app.db.IsUserSilenced(userID)
  945. if err != nil {
  946. log.Error("pin post: %v", err)
  947. }
  948. if silenced {
  949. return ErrUserSilenced
  950. }
  951. // Parse request
  952. var posts []struct {
  953. ID string `json:"id"`
  954. Position int64 `json:"position"`
  955. }
  956. decoder := json.NewDecoder(r.Body)
  957. err = decoder.Decode(&posts)
  958. if err != nil {
  959. return ErrBadJSONArray
  960. }
  961. // Validate data
  962. vars := mux.Vars(r)
  963. collAlias := vars["alias"]
  964. coll, err := app.db.GetCollection(collAlias)
  965. if err != nil {
  966. return err
  967. }
  968. if coll.OwnerID != userID {
  969. return ErrForbiddenCollection
  970. }
  971. // Do (un)pinning
  972. isPinning := r.URL.Path[strings.LastIndex(r.URL.Path, "/"):] == "/pin"
  973. res := []PinPostResult{}
  974. for _, p := range posts {
  975. err = app.db.UpdatePostPinState(isPinning, p.ID, coll.ID, userID, p.Position)
  976. ppr := PinPostResult{ID: p.ID}
  977. if err != nil {
  978. ppr.Code = http.StatusInternalServerError
  979. // TODO: set error message
  980. } else {
  981. ppr.Code = http.StatusOK
  982. }
  983. res = append(res, ppr)
  984. }
  985. return impart.WriteSuccess(w, res, http.StatusOK)
  986. }
  987. func fetchPost(app *App, w http.ResponseWriter, r *http.Request) error {
  988. var collID int64
  989. var coll *Collection
  990. var err error
  991. vars := mux.Vars(r)
  992. if collAlias := vars["alias"]; collAlias != "" {
  993. // Fetch collection information, since an alias is provided
  994. coll, err = app.db.GetCollection(collAlias)
  995. if err != nil {
  996. return err
  997. }
  998. collID = coll.ID
  999. }
  1000. p, err := app.db.GetPost(vars["post"], collID)
  1001. if err != nil {
  1002. return err
  1003. }
  1004. if coll == nil && p.CollectionID.Valid {
  1005. // Collection post is getting fetched by post ID, not coll alias + post slug, so get coll info now.
  1006. coll, err = app.db.GetCollectionByID(p.CollectionID.Int64)
  1007. if err != nil {
  1008. return err
  1009. }
  1010. }
  1011. if coll != nil {
  1012. coll.hostName = app.cfg.App.Host
  1013. _, err = apiCheckCollectionPermissions(app, r, coll)
  1014. if err != nil {
  1015. return err
  1016. }
  1017. }
  1018. silenced, err := app.db.IsUserSilenced(p.OwnerID.Int64)
  1019. if err != nil {
  1020. log.Error("fetch post: %v", err)
  1021. }
  1022. if silenced {
  1023. return ErrPostNotFound
  1024. }
  1025. p.extractData()
  1026. if IsActivityPubRequest(r) {
  1027. if coll == nil {
  1028. // This is a draft post; 404 for now
  1029. // TODO: return ActivityObject
  1030. return impart.HTTPError{http.StatusNotFound, ""}
  1031. }
  1032. p.Collection = &CollectionObj{Collection: *coll}
  1033. po := p.ActivityObject(app)
  1034. po.Context = []interface{}{activitystreams.Namespace}
  1035. setCacheControl(w, apCacheTime)
  1036. return impart.RenderActivityJSON(w, po, http.StatusOK)
  1037. }
  1038. return impart.WriteSuccess(w, p, http.StatusOK)
  1039. }
  1040. func fetchPostProperty(app *App, w http.ResponseWriter, r *http.Request) error {
  1041. vars := mux.Vars(r)
  1042. p, err := app.db.GetPostProperty(vars["post"], 0, vars["property"])
  1043. if err != nil {
  1044. return err
  1045. }
  1046. return impart.WriteSuccess(w, p, http.StatusOK)
  1047. }
  1048. func (p *Post) processPost() PublicPost {
  1049. res := &PublicPost{Post: p, Views: 0}
  1050. res.Views = p.ViewCount
  1051. // TODO: move to own function
  1052. loc := monday.FuzzyLocale(p.Language.String)
  1053. res.DisplayDate = monday.Format(p.Created, monday.LongFormatsByLocale[loc], loc)
  1054. return *res
  1055. }
  1056. func (p *PublicPost) CanonicalURL(hostName string) string {
  1057. if p.Collection == nil || p.Collection.Alias == "" {
  1058. return hostName + "/" + p.ID + ".md"
  1059. }
  1060. return p.Collection.CanonicalURL() + p.Slug.String
  1061. }
  1062. func (pp *PublicPost) DisplayCanonicalURL() string {
  1063. us := pp.CanonicalURL(pp.Collection.hostName)
  1064. u, err := url.Parse(us)
  1065. if err != nil {
  1066. return us
  1067. }
  1068. return u.Hostname() + u.Path
  1069. }
  1070. func (p *PublicPost) ActivityObject(app *App) *activitystreams.Object {
  1071. cfg := app.cfg
  1072. var o *activitystreams.Object
  1073. if cfg.App.NotesOnly || strings.Index(p.Content, "\n\n") == -1 {
  1074. o = activitystreams.NewNoteObject()
  1075. } else {
  1076. o = activitystreams.NewArticleObject()
  1077. }
  1078. o.ID = p.Collection.FederatedAPIBase() + "api/posts/" + p.ID
  1079. o.Published = p.Created
  1080. o.URL = p.CanonicalURL(cfg.App.Host)
  1081. o.AttributedTo = p.Collection.FederatedAccount()
  1082. o.CC = []string{
  1083. p.Collection.FederatedAccount() + "/followers",
  1084. }
  1085. o.Name = p.DisplayTitle()
  1086. p.augmentContent()
  1087. if p.HTMLContent == template.HTML("") {
  1088. p.formatContent(cfg, false, false)
  1089. p.augmentReadingDestination()
  1090. }
  1091. o.Content = string(p.HTMLContent)
  1092. if p.Language.Valid {
  1093. o.ContentMap = map[string]string{
  1094. p.Language.String: string(p.HTMLContent),
  1095. }
  1096. }
  1097. if len(p.Tags) == 0 {
  1098. o.Tag = []activitystreams.Tag{}
  1099. } else {
  1100. var tagBaseURL string
  1101. if isSingleUser {
  1102. tagBaseURL = p.Collection.CanonicalURL() + "tag:"
  1103. } else {
  1104. if cfg.App.Chorus {
  1105. tagBaseURL = fmt.Sprintf("%s/read/t/", p.Collection.hostName)
  1106. } else {
  1107. tagBaseURL = fmt.Sprintf("%s/%s/tag:", p.Collection.hostName, p.Collection.Alias)
  1108. }
  1109. }
  1110. for _, t := range p.Tags {
  1111. o.Tag = append(o.Tag, activitystreams.Tag{
  1112. Type: activitystreams.TagHashtag,
  1113. HRef: tagBaseURL + t,
  1114. Name: "#" + t,
  1115. })
  1116. }
  1117. }
  1118. if len(p.Images) > 0 {
  1119. for _, i := range p.Images {
  1120. o.Attachment = append(o.Attachment, activitystreams.NewImageAttachment(i))
  1121. }
  1122. }
  1123. // Find mentioned users
  1124. mentionedUsers := make(map[string]string)
  1125. stripper := bluemonday.StrictPolicy()
  1126. content := stripper.Sanitize(p.Content)
  1127. mentions := mentionReg.FindAllString(content, -1)
  1128. for _, handle := range mentions {
  1129. actorIRI, err := app.db.GetProfilePageFromHandle(app, handle)
  1130. if err != nil {
  1131. log.Info("Couldn't find user '%s' locally or remotely", handle)
  1132. continue
  1133. }
  1134. mentionedUsers[handle] = actorIRI
  1135. }
  1136. for handle, iri := range mentionedUsers {
  1137. o.CC = append(o.CC, iri)
  1138. o.Tag = append(o.Tag, activitystreams.Tag{Type: "Mention", HRef: iri, Name: handle})
  1139. }
  1140. return o
  1141. }
  1142. // TODO: merge this into getSlugFromPost or phase it out
  1143. func getSlug(title, lang string) string {
  1144. return getSlugFromPost("", title, lang)
  1145. }
  1146. func getSlugFromPost(title, body, lang string) string {
  1147. if title == "" {
  1148. // Remove Markdown, so e.g. link URLs and image alt text don't make it into the slug
  1149. body = strings.TrimSpace(stripmd.StripOptions(body, stripmd.Options{SkipImages: true}))
  1150. title = postTitle(body, body)
  1151. }
  1152. title = parse.PostLede(title, false)
  1153. // Truncate lede if needed
  1154. title, _ = parse.TruncToWord(title, 80)
  1155. var s string
  1156. if lang != "" && len(lang) == 2 {
  1157. s = slug.MakeLang(title, lang)
  1158. } else {
  1159. s = slug.Make(title)
  1160. }
  1161. // Transliteration may cause the slug to expand past the limit, so truncate again
  1162. s, _ = parse.TruncToWord(s, 80)
  1163. return strings.TrimFunc(s, func(r rune) bool {
  1164. // TruncToWord doesn't respect words in a slug, since spaces are replaced
  1165. // with hyphens. So remove any trailing hyphens.
  1166. return r == '-'
  1167. })
  1168. }
  1169. // isFontValid returns whether or not the submitted post's appearance is valid.
  1170. func (p *SubmittedPost) isFontValid() bool {
  1171. validFonts := map[string]bool{
  1172. "norm": true,
  1173. "sans": true,
  1174. "mono": true,
  1175. "wrap": true,
  1176. "code": true,
  1177. }
  1178. _, valid := validFonts[p.Font]
  1179. return valid
  1180. }
  1181. func getRawPost(app *App, friendlyID string) *RawPost {
  1182. var content, font, title string
  1183. var isRTL sql.NullBool
  1184. var lang sql.NullString
  1185. var ownerID sql.NullInt64
  1186. var created, updated time.Time
  1187. err := app.db.QueryRow("SELECT title, content, text_appearance, language, rtl, created, updated, owner_id FROM posts WHERE id = ?", friendlyID).Scan(&title, &content, &font, &lang, &isRTL, &created, &updated, &ownerID)
  1188. switch {
  1189. case err == sql.ErrNoRows:
  1190. return &RawPost{Content: "", Found: false, Gone: false}
  1191. case err != nil:
  1192. log.Error("Unable to fetch getRawPost: %s", err)
  1193. return &RawPost{Content: "", Found: true, Gone: false}
  1194. }
  1195. return &RawPost{
  1196. Title: title,
  1197. Content: content,
  1198. Font: font,
  1199. Created: created,
  1200. Updated: updated,
  1201. IsRTL: isRTL,
  1202. Language: lang,
  1203. OwnerID: ownerID.Int64,
  1204. Found: true,
  1205. Gone: content == "" && title == "",
  1206. }
  1207. }
  1208. // TODO; return a Post!
  1209. func getRawCollectionPost(app *App, slug, collAlias string) *RawPost {
  1210. var id, title, content, font string
  1211. var isRTL sql.NullBool
  1212. var lang sql.NullString
  1213. var created, updated time.Time
  1214. var ownerID null.Int
  1215. var views int64
  1216. var err error
  1217. if app.cfg.App.SingleUser {
  1218. err = app.db.QueryRow("SELECT id, title, content, text_appearance, language, rtl, view_count, created, updated, owner_id FROM posts WHERE slug = ? AND collection_id = 1", slug).Scan(&id, &title, &content, &font, &lang, &isRTL, &views, &created, &updated, &ownerID)
  1219. } else {
  1220. err = app.db.QueryRow("SELECT id, title, content, text_appearance, language, rtl, view_count, created, updated, owner_id FROM posts WHERE slug = ? AND collection_id = (SELECT id FROM collections WHERE alias = ?)", slug, collAlias).Scan(&id, &title, &content, &font, &lang, &isRTL, &views, &created, &updated, &ownerID)
  1221. }
  1222. switch {
  1223. case err == sql.ErrNoRows:
  1224. return &RawPost{Content: "", Found: false, Gone: false}
  1225. case err != nil:
  1226. log.Error("Unable to fetch getRawCollectionPost: %s", err)
  1227. return &RawPost{Content: "", Found: true, Gone: false}
  1228. }
  1229. return &RawPost{
  1230. Id: id,
  1231. Slug: slug,
  1232. Title: title,
  1233. Content: content,
  1234. Font: font,
  1235. Created: created,
  1236. Updated: updated,
  1237. IsRTL: isRTL,
  1238. Language: lang,
  1239. OwnerID: ownerID.Int64,
  1240. Found: true,
  1241. Gone: content == "" && title == "",
  1242. Views: views,
  1243. }
  1244. }
  1245. func isRaw(r *http.Request) bool {
  1246. vars := mux.Vars(r)
  1247. slug := vars["slug"]
  1248. // NOTE: until this is done better, be sure to keep this in parity with
  1249. // isRaw in viewCollectionPost() and handleViewPost()
  1250. isJSON := strings.HasSuffix(slug, ".json")
  1251. isXML := strings.HasSuffix(slug, ".xml")
  1252. isMarkdown := strings.HasSuffix(slug, ".md")
  1253. return strings.HasSuffix(slug, ".txt") || isJSON || isXML || isMarkdown
  1254. }
  1255. func viewCollectionPost(app *App, w http.ResponseWriter, r *http.Request) error {
  1256. vars := mux.Vars(r)
  1257. slug := vars["slug"]
  1258. // NOTE: until this is done better, be sure to keep this in parity with
  1259. // isRaw() and handleViewPost()
  1260. isJSON := strings.HasSuffix(slug, ".json")
  1261. isXML := strings.HasSuffix(slug, ".xml")
  1262. isMarkdown := strings.HasSuffix(slug, ".md")
  1263. isRaw := strings.HasSuffix(slug, ".txt") || isJSON || isXML || isMarkdown
  1264. cr := &collectionReq{}
  1265. err := processCollectionRequest(cr, vars, w, r)
  1266. if err != nil {
  1267. return err
  1268. }
  1269. // Check for hellbanned users
  1270. u, err := checkUserForCollection(app, cr, r, true)
  1271. if err != nil {
  1272. return err
  1273. }
  1274. // Normalize the URL, redirecting user to consistent post URL
  1275. if slug != strings.ToLower(slug) {
  1276. loc := fmt.Sprintf("/%s", strings.ToLower(slug))
  1277. if !app.cfg.App.SingleUser {
  1278. loc = "/" + cr.alias + loc
  1279. }
  1280. return impart.HTTPError{http.StatusMovedPermanently, loc}
  1281. }
  1282. // Display collection if this is a collection
  1283. var c *Collection
  1284. if app.cfg.App.SingleUser {
  1285. c, err = app.db.GetCollectionByID(1)
  1286. } else {
  1287. c, err = app.db.GetCollection(cr.alias)
  1288. }
  1289. if err != nil {
  1290. if err, ok := err.(impart.HTTPError); ok {
  1291. if err.Status == http.StatusNotFound {
  1292. // Redirect if necessary
  1293. newAlias := app.db.GetCollectionRedirect(cr.alias)
  1294. if newAlias != "" {
  1295. return impart.HTTPError{http.StatusFound, "/" + newAlias + "/" + slug}
  1296. }
  1297. }
  1298. }
  1299. return err
  1300. }
  1301. c.hostName = app.cfg.App.Host
  1302. silenced, err := app.db.IsUserSilenced(c.OwnerID)
  1303. if err != nil {
  1304. log.Error("view collection post: %v", err)
  1305. }
  1306. // Check collection permissions
  1307. if c.IsPrivate() && (u == nil || u.ID != c.OwnerID) {
  1308. return ErrPostNotFound
  1309. }
  1310. if c.IsProtected() && (u == nil || u.ID != c.OwnerID) {
  1311. if silenced {
  1312. return ErrPostNotFound
  1313. } else if !isAuthorizedForCollection(app, c.Alias, r) {
  1314. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "/?g=" + slug}
  1315. }
  1316. }
  1317. cr.isCollOwner = u != nil && c.OwnerID == u.ID
  1318. if isRaw {
  1319. slug = strings.Split(slug, ".")[0]
  1320. }
  1321. // Fetch extra data about the Collection
  1322. // TODO: refactor out this logic, shared in collection.go:fetchCollection()
  1323. coll := NewCollectionObj(c)
  1324. owner, err := app.db.GetUserByID(coll.OwnerID)
  1325. if err != nil {
  1326. // Log the error and just continue
  1327. log.Error("Error getting user for collection: %v", err)
  1328. } else {
  1329. coll.Owner = owner
  1330. }
  1331. postFound := true
  1332. p, err := app.db.GetPost(slug, coll.ID)
  1333. if err != nil {
  1334. if err == ErrCollectionPageNotFound {
  1335. postFound = false
  1336. if slug == "feed" {
  1337. // User tried to access blog feed without a trailing slash, and
  1338. // there's no post with a slug "feed"
  1339. return impart.HTTPError{http.StatusFound, c.CanonicalURL() + "feed/"}
  1340. }
  1341. po := &Post{
  1342. Slug: null.NewString(slug, true),
  1343. Font: "norm",
  1344. Language: zero.NewString("en", true),
  1345. RTL: zero.NewBool(false, true),
  1346. Content: `<p class="msg">This page is missing.</p>
  1347. Are you sure it was ever here?`,
  1348. }
  1349. pp := po.processPost()
  1350. p = &pp
  1351. } else {
  1352. return err
  1353. }
  1354. }
  1355. // Check if the authenticated user is the post owner
  1356. p.IsOwner = u != nil && u.ID == p.OwnerID.Int64
  1357. p.Collection = coll
  1358. p.IsTopLevel = app.cfg.App.SingleUser
  1359. // Only allow a post owner or admin to view a post for silenced collections
  1360. if silenced && !p.IsOwner && (u == nil || !u.IsAdmin()) {
  1361. return ErrPostNotFound
  1362. }
  1363. // Check if post has been unpublished
  1364. if p.Content == "" && p.Title.String == "" {
  1365. return impart.HTTPError{http.StatusGone, "Post was unpublished."}
  1366. }
  1367. p.augmentContent()
  1368. // Serve collection post
  1369. if isRaw {
  1370. contentType := "text/plain"
  1371. if isJSON {
  1372. contentType = "application/json"
  1373. } else if isXML {
  1374. contentType = "application/xml"
  1375. } else if isMarkdown {
  1376. contentType = "text/markdown"
  1377. }
  1378. w.Header().Set("Content-Type", fmt.Sprintf("%s; charset=utf-8", contentType))
  1379. if !postFound {
  1380. w.WriteHeader(http.StatusNotFound)
  1381. fmt.Fprintf(w, "Post not found.")
  1382. // TODO: return error instead, so status is correctly reflected in logs
  1383. return nil
  1384. }
  1385. if isMarkdown && p.Title.String != "" {
  1386. fmt.Fprintf(w, "# %s\n\n", p.Title.String)
  1387. }
  1388. fmt.Fprint(w, p.Content)
  1389. } else if IsActivityPubRequest(r) {
  1390. if !postFound {
  1391. return ErrCollectionPageNotFound
  1392. }
  1393. p.extractData()
  1394. ap := p.ActivityObject(app)
  1395. ap.Context = []interface{}{activitystreams.Namespace}
  1396. setCacheControl(w, apCacheTime)
  1397. return impart.RenderActivityJSON(w, ap, http.StatusOK)
  1398. } else {
  1399. p.extractData()
  1400. p.Content = strings.Replace(p.Content, "<!--more-->", "", 1)
  1401. if app.cfg.Email.Enabled() && c.EmailSubsEnabled() {
  1402. // TODO: indicate plan is inactive or subs disabled when OWNER is viewing their own post.
  1403. if u != nil && u.IsEmailSubscriber(app, c.ID) {
  1404. p.Content = strings.Replace(p.Content, "<!--emailsub-->", `<p id="emailsub">You're subscribed to email updates. <a href="/api/collections/`+c.Alias+`/email/unsubscribe?slug=`+p.Slug.String+`">Unsubscribe</a>.</p>`, -1)
  1405. } else {
  1406. p.Content = strings.Replace(p.Content, "<!--emailsub-->", `<form method="post" id="emailsub" action="/api/collections/`+c.Alias+`/email/subscribe"><input type="hidden" name="slug" value="`+p.Slug.String+`" /><input type="hidden" name="web" value="1" /><div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="email" name="`+spam.HoneypotFieldName()+`" tabindex="-1" value="" /><input type="password" name="fake_password" tabindex="-1" placeholder="password" autocomplete="new-password" /></div><input type="email" name="email" placeholder="me@example.com" /><input type="submit" id="subscribe-btn" value="Subscribe" /></form>`, -1)
  1407. }
  1408. }
  1409. p.Content = strings.Replace(p.Content, "&lt;!--emailsub-->", "<!--emailsub-->", 1)
  1410. // TODO: move this to function
  1411. p.formatContent(app.cfg, cr.isCollOwner, true)
  1412. tp := CollectionPostPage{
  1413. PublicPost: p,
  1414. StaticPage: pageForReq(app, r),
  1415. IsOwner: cr.isCollOwner,
  1416. IsCustomDomain: cr.isCustomDomain,
  1417. IsFound: postFound,
  1418. Silenced: silenced,
  1419. CollAlias: c.Alias,
  1420. }
  1421. tp.IsAdmin = u != nil && u.IsAdmin()
  1422. tp.CanInvite = canUserInvite(app.cfg, tp.IsAdmin)
  1423. tp.PinnedPosts, _ = app.db.GetPinnedPosts(coll, p.IsOwner)
  1424. tp.IsPinned = len(*tp.PinnedPosts) > 0 && PostsContains(tp.PinnedPosts, p)
  1425. tp.Monetization = coll.Monetization
  1426. tp.Verification = coll.Verification
  1427. if !postFound {
  1428. w.WriteHeader(http.StatusNotFound)
  1429. }
  1430. postTmpl := "collection-post"
  1431. if app.cfg.App.Chorus {
  1432. postTmpl = "chorus-collection-post"
  1433. }
  1434. if err := templates[postTmpl].ExecuteTemplate(w, "post", tp); err != nil {
  1435. log.Error("Error in %s template: %v", postTmpl, err)
  1436. }
  1437. }
  1438. go func() {
  1439. if p.OwnerID.Valid {
  1440. // Post is owned by someone. Don't update stats if owner is viewing the post.
  1441. if u != nil && p.OwnerID.Int64 == u.ID {
  1442. return
  1443. }
  1444. }
  1445. // Update stats for non-raw post views
  1446. if !isRaw && r.Method != "HEAD" && !bots.IsBot(r.UserAgent()) {
  1447. _, err := app.db.Exec("UPDATE posts SET view_count = view_count + 1 WHERE slug = ? AND collection_id = ?", slug, coll.ID)
  1448. if err != nil {
  1449. log.Error("Unable to update posts count: %v", err)
  1450. }
  1451. }
  1452. }()
  1453. return nil
  1454. }
  1455. // TODO: move this to utils after making it more generic
  1456. func PostsContains(sl *[]PublicPost, s *PublicPost) bool {
  1457. for _, e := range *sl {
  1458. if e.ID == s.ID {
  1459. return true
  1460. }
  1461. }
  1462. return false
  1463. }
  1464. func (p *Post) extractData() {
  1465. p.Tags = tags.Extract(p.Content)
  1466. p.extractImages()
  1467. }
  1468. func (p *Post) IsSans() bool {
  1469. return p.Font == "sans"
  1470. }
  1471. func (p *Post) IsMonospace() bool {
  1472. return p.Font == "mono"
  1473. }
  1474. func (rp *RawPost) UserFacingCreated() string {
  1475. return rp.Created.Format(postMetaDateFormat)
  1476. }
  1477. func (rp *RawPost) Created8601() string {
  1478. return rp.Created.Format("2006-01-02T15:04:05Z")
  1479. }
  1480. func (rp *RawPost) Updated8601() string {
  1481. if rp.Updated.IsZero() {
  1482. return ""
  1483. }
  1484. return rp.Updated.Format("2006-01-02T15:04:05Z")
  1485. }
  1486. var imageURLRegex = regexp.MustCompile(`(?i)[^ ]+\.(gif|png|jpg|jpeg|image)$`)
  1487. func (p *Post) extractImages() {
  1488. p.Images = extractImages(p.Content)
  1489. }
  1490. func extractImages(content string) []string {
  1491. matches := extract.ExtractUrls(content)
  1492. urls := map[string]bool{}
  1493. for i := range matches {
  1494. uRaw := matches[i].Text
  1495. // Parse the extracted text so we can examine the path
  1496. u, err := url.Parse(uRaw)
  1497. if err != nil {
  1498. continue
  1499. }
  1500. // Ensure the path looks like it leads to an image file
  1501. if !imageURLRegex.MatchString(u.Path) {
  1502. continue
  1503. }
  1504. urls[uRaw] = true
  1505. }
  1506. resURLs := make([]string, 0)
  1507. for k := range urls {
  1508. resURLs = append(resURLs, k)
  1509. }
  1510. return resURLs
  1511. }