A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 

2439 rader
73 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. "database/sql"
  13. "fmt"
  14. "net/http"
  15. "strings"
  16. "time"
  17. "github.com/guregu/null"
  18. "github.com/guregu/null/zero"
  19. uuid "github.com/nu7hatch/gouuid"
  20. "github.com/writeas/impart"
  21. "github.com/writeas/nerds/store"
  22. "github.com/writeas/web-core/activitypub"
  23. "github.com/writeas/web-core/auth"
  24. "github.com/writeas/web-core/data"
  25. "github.com/writeas/web-core/id"
  26. "github.com/writeas/web-core/log"
  27. "github.com/writeas/web-core/query"
  28. "github.com/writeas/writefreely/author"
  29. "github.com/writeas/writefreely/config"
  30. "github.com/writeas/writefreely/key"
  31. )
  32. const (
  33. mySQLErrDuplicateKey = 1062
  34. driverMySQL = "mysql"
  35. driverSQLite = "sqlite3"
  36. )
  37. var (
  38. SQLiteEnabled bool
  39. )
  40. type writestore interface {
  41. CreateUser(*config.Config, *User, string) error
  42. UpdateUserEmail(keys *key.Keychain, userID int64, email string) error
  43. UpdateEncryptedUserEmail(int64, []byte) error
  44. GetUserByID(int64) (*User, error)
  45. GetUserForAuth(string) (*User, error)
  46. GetUserForAuthByID(int64) (*User, error)
  47. GetUserNameFromToken(string) (string, error)
  48. GetUserDataFromToken(string) (int64, string, error)
  49. GetAPIUser(header string) (*User, error)
  50. GetUserID(accessToken string) int64
  51. GetUserIDPrivilege(accessToken string) (userID int64, sudo bool)
  52. DeleteToken(accessToken []byte) error
  53. FetchLastAccessToken(userID int64) string
  54. GetAccessToken(userID int64) (string, error)
  55. GetTemporaryAccessToken(userID int64, validSecs int) (string, error)
  56. GetTemporaryOneTimeAccessToken(userID int64, validSecs int, oneTime bool) (string, error)
  57. DeleteAccount(userID int64) (l *string, err error)
  58. ChangeSettings(app *App, u *User, s *userSettings) error
  59. ChangePassphrase(userID int64, sudo bool, curPass string, hashedPass []byte) error
  60. GetCollections(u *User, hostName string) (*[]Collection, error)
  61. GetPublishableCollections(u *User, hostName string) (*[]Collection, error)
  62. GetMeStats(u *User) userMeStats
  63. GetTotalCollections() (int64, error)
  64. GetTotalPosts() (int64, error)
  65. GetTopPosts(u *User, alias string) (*[]PublicPost, error)
  66. GetAnonymousPosts(u *User) (*[]PublicPost, error)
  67. GetUserPosts(u *User) (*[]PublicPost, error)
  68. CreateOwnedPost(post *SubmittedPost, accessToken, collAlias, hostName string) (*PublicPost, error)
  69. CreatePost(userID, collID int64, post *SubmittedPost) (*Post, error)
  70. UpdateOwnedPost(post *AuthenticatedPost, userID int64) error
  71. GetEditablePost(id, editToken string) (*PublicPost, error)
  72. PostIDExists(id string) bool
  73. GetPost(id string, collectionID int64) (*PublicPost, error)
  74. GetOwnedPost(id string, ownerID int64) (*PublicPost, error)
  75. GetPostProperty(id string, collectionID int64, property string) (interface{}, error)
  76. CreateCollectionFromToken(*config.Config, string, string, string) (*Collection, error)
  77. CreateCollection(*config.Config, string, string, int64) (*Collection, error)
  78. GetCollectionBy(condition string, value interface{}) (*Collection, error)
  79. GetCollection(alias string) (*Collection, error)
  80. GetCollectionForPad(alias string) (*Collection, error)
  81. GetCollectionByID(id int64) (*Collection, error)
  82. UpdateCollection(c *SubmittedCollection, alias string) error
  83. DeleteCollection(alias string, userID int64) error
  84. UpdatePostPinState(pinned bool, postID string, collID, ownerID, pos int64) error
  85. GetLastPinnedPostPos(collID int64) int64
  86. GetPinnedPosts(coll *CollectionObj, includeFuture bool) (*[]PublicPost, error)
  87. RemoveCollectionRedirect(t *sql.Tx, alias string) error
  88. GetCollectionRedirect(alias string) (new string)
  89. IsCollectionAttributeOn(id int64, attr string) bool
  90. CollectionHasAttribute(id int64, attr string) bool
  91. CanCollect(cpr *ClaimPostRequest, userID int64) bool
  92. AttemptClaim(p *ClaimPostRequest, query string, params []interface{}, slugIdx int) (sql.Result, error)
  93. DispersePosts(userID int64, postIDs []string) (*[]ClaimPostResult, error)
  94. ClaimPosts(cfg *config.Config, userID int64, collAlias string, posts *[]ClaimPostRequest) (*[]ClaimPostResult, error)
  95. GetPostsCount(c *CollectionObj, includeFuture bool)
  96. GetPosts(cfg *config.Config, c *Collection, page int, includeFuture, forceRecentFirst, includePinned bool) (*[]PublicPost, error)
  97. GetPostsTagged(cfg *config.Config, c *Collection, tag string, page int, includeFuture bool) (*[]PublicPost, error)
  98. GetAPFollowers(c *Collection) (*[]RemoteUser, error)
  99. GetAPActorKeys(collectionID int64) ([]byte, []byte)
  100. CreateUserInvite(id string, userID int64, maxUses int, expires *time.Time) error
  101. GetUserInvites(userID int64) (*[]Invite, error)
  102. GetUserInvite(id string) (*Invite, error)
  103. GetUsersInvitedCount(id string) int64
  104. CreateInvitedUser(inviteID string, userID int64) error
  105. GetDynamicContent(id string) (*instanceContent, error)
  106. UpdateDynamicContent(id, title, content, contentType string) error
  107. GetAllUsers(page uint) (*[]User, error)
  108. GetAllUsersCount() int64
  109. GetUserLastPostTime(id int64) (*time.Time, error)
  110. GetCollectionLastPostTime(id int64) (*time.Time, error)
  111. DatabaseInitialized() bool
  112. }
  113. type datastore struct {
  114. *sql.DB
  115. driverName string
  116. }
  117. func (db *datastore) now() string {
  118. if db.driverName == driverSQLite {
  119. return "strftime('%Y-%m-%d %H:%M:%S','now')"
  120. }
  121. return "NOW()"
  122. }
  123. func (db *datastore) clip(field string, l int) string {
  124. if db.driverName == driverSQLite {
  125. return fmt.Sprintf("SUBSTR(%s, 0, %d)", field, l)
  126. }
  127. return fmt.Sprintf("LEFT(%s, %d)", field, l)
  128. }
  129. func (db *datastore) upsert(indexedCols ...string) string {
  130. if db.driverName == driverSQLite {
  131. // NOTE: SQLite UPSERT syntax only works in v3.24.0 (2018-06-04) or later
  132. // Leaving this for whenever we can upgrade and include it in our binary
  133. cc := strings.Join(indexedCols, ", ")
  134. return "ON CONFLICT(" + cc + ") DO UPDATE SET"
  135. }
  136. return "ON DUPLICATE KEY UPDATE"
  137. }
  138. func (db *datastore) dateSub(l int, unit string) string {
  139. if db.driverName == driverSQLite {
  140. return fmt.Sprintf("DATETIME('now', '-%d %s')", l, unit)
  141. }
  142. return fmt.Sprintf("DATE_SUB(NOW(), INTERVAL %d %s)", l, unit)
  143. }
  144. func (db *datastore) CreateUser(cfg *config.Config, u *User, collectionTitle string) error {
  145. if db.PostIDExists(u.Username) {
  146. return impart.HTTPError{http.StatusConflict, "Invalid collection name."}
  147. }
  148. // New users get a `users` and `collections` row.
  149. t, err := db.Begin()
  150. if err != nil {
  151. return err
  152. }
  153. // 1. Add to `users` table
  154. // NOTE: Assumes User's Password is already hashed!
  155. res, err := t.Exec("INSERT INTO users (username, password, email) VALUES (?, ?, ?)", u.Username, u.HashedPass, u.Email)
  156. if err != nil {
  157. t.Rollback()
  158. if db.isDuplicateKeyErr(err) {
  159. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  160. }
  161. log.Error("Rolling back users INSERT: %v\n", err)
  162. return err
  163. }
  164. u.ID, err = res.LastInsertId()
  165. if err != nil {
  166. t.Rollback()
  167. log.Error("Rolling back after LastInsertId: %v\n", err)
  168. return err
  169. }
  170. // 2. Create user's Collection
  171. if collectionTitle == "" {
  172. collectionTitle = u.Username
  173. }
  174. res, err = t.Exec("INSERT INTO collections (alias, title, description, privacy, owner_id, view_count) VALUES (?, ?, ?, ?, ?, ?)", u.Username, collectionTitle, "", defaultVisibility(cfg), u.ID, 0)
  175. if err != nil {
  176. t.Rollback()
  177. if db.isDuplicateKeyErr(err) {
  178. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  179. }
  180. log.Error("Rolling back collections INSERT: %v\n", err)
  181. return err
  182. }
  183. db.RemoveCollectionRedirect(t, u.Username)
  184. err = t.Commit()
  185. if err != nil {
  186. t.Rollback()
  187. log.Error("Rolling back after Commit(): %v\n", err)
  188. return err
  189. }
  190. return nil
  191. }
  192. // FIXME: We're returning errors inconsistently in this file. Do we use Errorf
  193. // for returned value, or impart?
  194. func (db *datastore) UpdateUserEmail(keys *key.Keychain, userID int64, email string) error {
  195. encEmail, err := data.Encrypt(keys.EmailKey, email)
  196. if err != nil {
  197. return fmt.Errorf("Couldn't encrypt email %s: %s\n", email, err)
  198. }
  199. return db.UpdateEncryptedUserEmail(userID, encEmail)
  200. }
  201. func (db *datastore) UpdateEncryptedUserEmail(userID int64, encEmail []byte) error {
  202. _, err := db.Exec("UPDATE users SET email = ? WHERE id = ?", encEmail, userID)
  203. if err != nil {
  204. return fmt.Errorf("Unable to update user email: %s", err)
  205. }
  206. return nil
  207. }
  208. func (db *datastore) CreateCollectionFromToken(cfg *config.Config, alias, title, accessToken string) (*Collection, error) {
  209. userID := db.GetUserID(accessToken)
  210. if userID == -1 {
  211. return nil, ErrBadAccessToken
  212. }
  213. return db.CreateCollection(cfg, alias, title, userID)
  214. }
  215. func (db *datastore) GetUserCollectionCount(userID int64) (uint64, error) {
  216. var collCount uint64
  217. err := db.QueryRow("SELECT COUNT(*) FROM collections WHERE owner_id = ?", userID).Scan(&collCount)
  218. switch {
  219. case err == sql.ErrNoRows:
  220. return 0, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user from database."}
  221. case err != nil:
  222. log.Error("Couldn't get collections count for user %d: %v", userID, err)
  223. return 0, err
  224. }
  225. return collCount, nil
  226. }
  227. func (db *datastore) CreateCollection(cfg *config.Config, alias, title string, userID int64) (*Collection, error) {
  228. if db.PostIDExists(alias) {
  229. return nil, impart.HTTPError{http.StatusConflict, "Invalid collection name."}
  230. }
  231. // All good, so create new collection
  232. res, err := db.Exec("INSERT INTO collections (alias, title, description, privacy, owner_id, view_count) VALUES (?, ?, ?, ?, ?, ?)", alias, title, "", defaultVisibility(cfg), userID, 0)
  233. if err != nil {
  234. if db.isDuplicateKeyErr(err) {
  235. return nil, impart.HTTPError{http.StatusConflict, "Collection already exists."}
  236. }
  237. log.Error("Couldn't add to collections: %v\n", err)
  238. return nil, err
  239. }
  240. c := &Collection{
  241. Alias: alias,
  242. Title: title,
  243. OwnerID: userID,
  244. PublicOwner: false,
  245. Public: defaultVisibility(cfg) == CollPublic,
  246. }
  247. c.ID, err = res.LastInsertId()
  248. if err != nil {
  249. log.Error("Couldn't get collection LastInsertId: %v\n", err)
  250. }
  251. return c, nil
  252. }
  253. func (db *datastore) GetUserByID(id int64) (*User, error) {
  254. u := &User{ID: id}
  255. err := db.QueryRow("SELECT username, password, email, created FROM users WHERE id = ?", id).Scan(&u.Username, &u.HashedPass, &u.Email, &u.Created)
  256. switch {
  257. case err == sql.ErrNoRows:
  258. return nil, ErrUserNotFound
  259. case err != nil:
  260. log.Error("Couldn't SELECT user password: %v", err)
  261. return nil, err
  262. }
  263. return u, nil
  264. }
  265. // DoesUserNeedAuth returns true if the user hasn't provided any methods for
  266. // authenticating with the account, such a passphrase or email address.
  267. // Any errors are reported to admin and silently quashed, returning false as the
  268. // result.
  269. func (db *datastore) DoesUserNeedAuth(id int64) bool {
  270. var pass, email []byte
  271. // Find out if user has an email set first
  272. err := db.QueryRow("SELECT password, email FROM users WHERE id = ?", id).Scan(&pass, &email)
  273. switch {
  274. case err == sql.ErrNoRows:
  275. // ERROR. Don't give false positives on needing auth methods
  276. return false
  277. case err != nil:
  278. // ERROR. Don't give false positives on needing auth methods
  279. log.Error("Couldn't SELECT user %d from users: %v", id, err)
  280. return false
  281. }
  282. // User doesn't need auth if there's an email
  283. return len(email) == 0 && len(pass) == 0
  284. }
  285. func (db *datastore) IsUserPassSet(id int64) (bool, error) {
  286. var pass []byte
  287. err := db.QueryRow("SELECT password FROM users WHERE id = ?", id).Scan(&pass)
  288. switch {
  289. case err == sql.ErrNoRows:
  290. return false, nil
  291. case err != nil:
  292. log.Error("Couldn't SELECT user %d from users: %v", id, err)
  293. return false, err
  294. }
  295. return len(pass) > 0, nil
  296. }
  297. func (db *datastore) GetUserForAuth(username string) (*User, error) {
  298. u := &User{Username: username}
  299. err := db.QueryRow("SELECT id, password, email, created FROM users WHERE username = ?", username).Scan(&u.ID, &u.HashedPass, &u.Email, &u.Created)
  300. switch {
  301. case err == sql.ErrNoRows:
  302. // Check if they've entered the wrong, unnormalized username
  303. username = getSlug(username, "")
  304. if username != u.Username {
  305. err = db.QueryRow("SELECT id FROM users WHERE username = ? LIMIT 1", username).Scan(&u.ID)
  306. if err == nil {
  307. return db.GetUserForAuth(username)
  308. }
  309. }
  310. return nil, ErrUserNotFound
  311. case err != nil:
  312. log.Error("Couldn't SELECT user password: %v", err)
  313. return nil, err
  314. }
  315. return u, nil
  316. }
  317. func (db *datastore) GetUserForAuthByID(userID int64) (*User, error) {
  318. u := &User{ID: userID}
  319. err := db.QueryRow("SELECT id, password, email, created FROM users WHERE id = ?", u.ID).Scan(&u.ID, &u.HashedPass, &u.Email, &u.Created)
  320. switch {
  321. case err == sql.ErrNoRows:
  322. return nil, ErrUserNotFound
  323. case err != nil:
  324. log.Error("Couldn't SELECT userForAuthByID: %v", err)
  325. return nil, err
  326. }
  327. return u, nil
  328. }
  329. func (db *datastore) GetUserNameFromToken(accessToken string) (string, error) {
  330. t := auth.GetToken(accessToken)
  331. if len(t) == 0 {
  332. return "", ErrNoAccessToken
  333. }
  334. var oneTime bool
  335. var username string
  336. err := db.QueryRow("SELECT username, one_time FROM accesstokens LEFT JOIN users ON user_id = id WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&username, &oneTime)
  337. switch {
  338. case err == sql.ErrNoRows:
  339. return "", ErrBadAccessToken
  340. case err != nil:
  341. return "", ErrInternalGeneral
  342. }
  343. // Delete token if it was one-time
  344. if oneTime {
  345. db.DeleteToken(t[:])
  346. }
  347. return username, nil
  348. }
  349. func (db *datastore) GetUserDataFromToken(accessToken string) (int64, string, error) {
  350. t := auth.GetToken(accessToken)
  351. if len(t) == 0 {
  352. return 0, "", ErrNoAccessToken
  353. }
  354. var userID int64
  355. var oneTime bool
  356. var username string
  357. err := db.QueryRow("SELECT user_id, username, one_time FROM accesstokens LEFT JOIN users ON user_id = id WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&userID, &username, &oneTime)
  358. switch {
  359. case err == sql.ErrNoRows:
  360. return 0, "", ErrBadAccessToken
  361. case err != nil:
  362. return 0, "", ErrInternalGeneral
  363. }
  364. // Delete token if it was one-time
  365. if oneTime {
  366. db.DeleteToken(t[:])
  367. }
  368. return userID, username, nil
  369. }
  370. func (db *datastore) GetAPIUser(header string) (*User, error) {
  371. uID := db.GetUserID(header)
  372. if uID == -1 {
  373. return nil, fmt.Errorf(ErrUserNotFound.Error())
  374. }
  375. return db.GetUserByID(uID)
  376. }
  377. // GetUserID takes a hexadecimal accessToken, parses it into its binary
  378. // representation, and gets any user ID associated with the token. If no user
  379. // is associated, -1 is returned.
  380. func (db *datastore) GetUserID(accessToken string) int64 {
  381. i, _ := db.GetUserIDPrivilege(accessToken)
  382. return i
  383. }
  384. func (db *datastore) GetUserIDPrivilege(accessToken string) (userID int64, sudo bool) {
  385. t := auth.GetToken(accessToken)
  386. if len(t) == 0 {
  387. return -1, false
  388. }
  389. var oneTime bool
  390. err := db.QueryRow("SELECT user_id, sudo, one_time FROM accesstokens WHERE token LIKE ? AND (expires IS NULL OR expires > "+db.now()+")", t).Scan(&userID, &sudo, &oneTime)
  391. switch {
  392. case err == sql.ErrNoRows:
  393. return -1, false
  394. case err != nil:
  395. return -1, false
  396. }
  397. // Delete token if it was one-time
  398. if oneTime {
  399. db.DeleteToken(t[:])
  400. }
  401. return
  402. }
  403. func (db *datastore) DeleteToken(accessToken []byte) error {
  404. res, err := db.Exec("DELETE FROM accesstokens WHERE token LIKE ?", accessToken)
  405. if err != nil {
  406. return err
  407. }
  408. rowsAffected, _ := res.RowsAffected()
  409. if rowsAffected == 0 {
  410. return impart.HTTPError{http.StatusNotFound, "Token is invalid or doesn't exist"}
  411. }
  412. return nil
  413. }
  414. // FetchLastAccessToken creates a new non-expiring, valid access token for the given
  415. // userID.
  416. func (db *datastore) FetchLastAccessToken(userID int64) string {
  417. var t []byte
  418. err := db.QueryRow("SELECT token FROM accesstokens WHERE user_id = ? AND (expires IS NULL OR expires > "+db.now()+") ORDER BY created DESC LIMIT 1", userID).Scan(&t)
  419. switch {
  420. case err == sql.ErrNoRows:
  421. return ""
  422. case err != nil:
  423. log.Error("Failed selecting from accesstoken: %v", err)
  424. return ""
  425. }
  426. u, err := uuid.Parse(t)
  427. if err != nil {
  428. return ""
  429. }
  430. return u.String()
  431. }
  432. // GetAccessToken creates a new non-expiring, valid access token for the given
  433. // userID.
  434. func (db *datastore) GetAccessToken(userID int64) (string, error) {
  435. return db.GetTemporaryOneTimeAccessToken(userID, 0, false)
  436. }
  437. // GetTemporaryAccessToken creates a new valid access token for the given
  438. // userID that remains valid for the given time in seconds. If validSecs is 0,
  439. // the access token doesn't automatically expire.
  440. func (db *datastore) GetTemporaryAccessToken(userID int64, validSecs int) (string, error) {
  441. return db.GetTemporaryOneTimeAccessToken(userID, validSecs, false)
  442. }
  443. // GetTemporaryOneTimeAccessToken creates a new valid access token for the given
  444. // userID that remains valid for the given time in seconds and can only be used
  445. // once if oneTime is true. If validSecs is 0, the access token doesn't
  446. // automatically expire.
  447. func (db *datastore) GetTemporaryOneTimeAccessToken(userID int64, validSecs int, oneTime bool) (string, error) {
  448. u, err := uuid.NewV4()
  449. if err != nil {
  450. log.Error("Unable to generate token: %v", err)
  451. return "", err
  452. }
  453. // Insert UUID to `accesstokens`
  454. binTok := u[:]
  455. expirationVal := "NULL"
  456. if validSecs > 0 {
  457. expirationVal = fmt.Sprintf("DATE_ADD("+db.now()+", INTERVAL %d SECOND)", validSecs)
  458. }
  459. _, err = db.Exec("INSERT INTO accesstokens (token, user_id, one_time, expires) VALUES (?, ?, ?, "+expirationVal+")", string(binTok), userID, oneTime)
  460. if err != nil {
  461. log.Error("Couldn't INSERT accesstoken: %v", err)
  462. return "", err
  463. }
  464. return u.String(), nil
  465. }
  466. func (db *datastore) CreateOwnedPost(post *SubmittedPost, accessToken, collAlias, hostName string) (*PublicPost, error) {
  467. var userID, collID int64 = -1, -1
  468. var coll *Collection
  469. var err error
  470. if accessToken != "" {
  471. userID = db.GetUserID(accessToken)
  472. if userID == -1 {
  473. return nil, ErrBadAccessToken
  474. }
  475. if collAlias != "" {
  476. coll, err = db.GetCollection(collAlias)
  477. if err != nil {
  478. return nil, err
  479. }
  480. coll.hostName = hostName
  481. if coll.OwnerID != userID {
  482. return nil, ErrForbiddenCollection
  483. }
  484. collID = coll.ID
  485. }
  486. }
  487. rp := &PublicPost{}
  488. rp.Post, err = db.CreatePost(userID, collID, post)
  489. if err != nil {
  490. return rp, err
  491. }
  492. if coll != nil {
  493. coll.ForPublic()
  494. rp.Collection = &CollectionObj{Collection: *coll}
  495. }
  496. return rp, nil
  497. }
  498. func (db *datastore) CreatePost(userID, collID int64, post *SubmittedPost) (*Post, error) {
  499. idLen := postIDLen
  500. friendlyID := store.GenerateFriendlyRandomString(idLen)
  501. // Handle appearance / font face
  502. appearance := post.Font
  503. if !post.isFontValid() {
  504. appearance = "norm"
  505. }
  506. var err error
  507. ownerID := sql.NullInt64{
  508. Valid: false,
  509. }
  510. ownerCollID := sql.NullInt64{
  511. Valid: false,
  512. }
  513. slug := sql.NullString{"", false}
  514. // If an alias was supplied, we'll add this to the collection as well.
  515. if userID > 0 {
  516. ownerID.Int64 = userID
  517. ownerID.Valid = true
  518. if collID > 0 {
  519. ownerCollID.Int64 = collID
  520. ownerCollID.Valid = true
  521. var slugVal string
  522. if post.Title != nil && *post.Title != "" {
  523. slugVal = getSlug(*post.Title, post.Language.String)
  524. if slugVal == "" {
  525. slugVal = getSlug(*post.Content, post.Language.String)
  526. }
  527. } else {
  528. slugVal = getSlug(*post.Content, post.Language.String)
  529. }
  530. if slugVal == "" {
  531. slugVal = friendlyID
  532. }
  533. slug = sql.NullString{slugVal, true}
  534. }
  535. }
  536. created := time.Now()
  537. if db.driverName == driverSQLite {
  538. // SQLite stores datetimes in UTC, so convert time.Now() to it here
  539. created = created.UTC()
  540. }
  541. if post.Created != nil {
  542. created, err = time.Parse("2006-01-02T15:04:05Z", *post.Created)
  543. if err != nil {
  544. log.Error("Unable to parse Created time '%s': %v", *post.Created, err)
  545. created = time.Now()
  546. if db.driverName == driverSQLite {
  547. // SQLite stores datetimes in UTC, so convert time.Now() to it here
  548. created = created.UTC()
  549. }
  550. }
  551. }
  552. stmt, err := db.Prepare("INSERT INTO posts (id, slug, title, content, text_appearance, language, rtl, privacy, owner_id, collection_id, created, updated, view_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + db.now() + ", ?)")
  553. if err != nil {
  554. return nil, err
  555. }
  556. defer stmt.Close()
  557. _, err = stmt.Exec(friendlyID, slug, post.Title, post.Content, appearance, post.Language, post.IsRTL, 0, ownerID, ownerCollID, created, 0)
  558. if err != nil {
  559. if db.isDuplicateKeyErr(err) {
  560. // Duplicate entry error; try a new slug
  561. // TODO: make this a little more robust
  562. slug = sql.NullString{id.GenSafeUniqueSlug(slug.String), true}
  563. _, err = stmt.Exec(friendlyID, slug, post.Title, post.Content, appearance, post.Language, post.IsRTL, 0, ownerID, ownerCollID, created, 0)
  564. if err != nil {
  565. return nil, handleFailedPostInsert(fmt.Errorf("Retried slug generation, still failed: %v", err))
  566. }
  567. } else {
  568. return nil, handleFailedPostInsert(err)
  569. }
  570. }
  571. // TODO: return Created field in proper format
  572. return &Post{
  573. ID: friendlyID,
  574. Slug: null.NewString(slug.String, slug.Valid),
  575. Font: appearance,
  576. Language: zero.NewString(post.Language.String, post.Language.Valid),
  577. RTL: zero.NewBool(post.IsRTL.Bool, post.IsRTL.Valid),
  578. OwnerID: null.NewInt(userID, true),
  579. CollectionID: null.NewInt(userID, true),
  580. Created: created.Truncate(time.Second).UTC(),
  581. Updated: time.Now().Truncate(time.Second).UTC(),
  582. Title: zero.NewString(*(post.Title), true),
  583. Content: *(post.Content),
  584. }, nil
  585. }
  586. // UpdateOwnedPost updates an existing post with only the given fields in the
  587. // supplied AuthenticatedPost.
  588. func (db *datastore) UpdateOwnedPost(post *AuthenticatedPost, userID int64) error {
  589. params := []interface{}{}
  590. var queryUpdates, sep, authCondition string
  591. if post.Slug != nil && *post.Slug != "" {
  592. queryUpdates += sep + "slug = ?"
  593. sep = ", "
  594. params = append(params, getSlug(*post.Slug, ""))
  595. }
  596. if post.Content != nil {
  597. queryUpdates += sep + "content = ?"
  598. sep = ", "
  599. params = append(params, post.Content)
  600. }
  601. if post.Title != nil {
  602. queryUpdates += sep + "title = ?"
  603. sep = ", "
  604. params = append(params, post.Title)
  605. }
  606. if post.Language.Valid {
  607. queryUpdates += sep + "language = ?"
  608. sep = ", "
  609. params = append(params, post.Language.String)
  610. }
  611. if post.IsRTL.Valid {
  612. queryUpdates += sep + "rtl = ?"
  613. sep = ", "
  614. params = append(params, post.IsRTL.Bool)
  615. }
  616. if post.Font != "" {
  617. queryUpdates += sep + "text_appearance = ?"
  618. sep = ", "
  619. params = append(params, post.Font)
  620. }
  621. if post.Created != nil {
  622. createTime, err := time.Parse(postMetaDateFormat, *post.Created)
  623. if err != nil {
  624. log.Error("Unable to parse Created date: %v", err)
  625. return fmt.Errorf("That's the incorrect format for Created date.")
  626. }
  627. queryUpdates += sep + "created = ?"
  628. sep = ", "
  629. params = append(params, createTime)
  630. }
  631. // WHERE parameters...
  632. // id = ?
  633. params = append(params, post.ID)
  634. // AND owner_id = ?
  635. authCondition = "(owner_id = ?)"
  636. params = append(params, userID)
  637. if queryUpdates == "" {
  638. return ErrPostNoUpdatableVals
  639. }
  640. queryUpdates += sep + "updated = " + db.now()
  641. res, err := db.Exec("UPDATE posts SET "+queryUpdates+" WHERE id = ? AND "+authCondition, params...)
  642. if err != nil {
  643. log.Error("Unable to update owned post: %v", err)
  644. return err
  645. }
  646. rowsAffected, _ := res.RowsAffected()
  647. if rowsAffected == 0 {
  648. // Show the correct error message if nothing was updated
  649. var dummy int
  650. err := db.QueryRow("SELECT 1 FROM posts WHERE id = ? AND "+authCondition, post.ID, params[len(params)-1]).Scan(&dummy)
  651. switch {
  652. case err == sql.ErrNoRows:
  653. return ErrUnauthorizedEditPost
  654. case err != nil:
  655. log.Error("Failed selecting from posts: %v", err)
  656. }
  657. return nil
  658. }
  659. return nil
  660. }
  661. func (db *datastore) GetCollectionBy(condition string, value interface{}) (*Collection, error) {
  662. c := &Collection{}
  663. // FIXME: change Collection to reflect database values. Add helper functions to get actual values
  664. var styleSheet, script, format zero.String
  665. row := db.QueryRow("SELECT id, alias, title, description, style_sheet, script, format, owner_id, privacy, view_count FROM collections WHERE "+condition, value)
  666. err := row.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &styleSheet, &script, &format, &c.OwnerID, &c.Visibility, &c.Views)
  667. switch {
  668. case err == sql.ErrNoRows:
  669. return nil, impart.HTTPError{http.StatusNotFound, "Collection doesn't exist."}
  670. case err != nil:
  671. log.Error("Failed selecting from collections: %v", err)
  672. return nil, err
  673. }
  674. c.StyleSheet = styleSheet.String
  675. c.Script = script.String
  676. c.Format = format.String
  677. c.Public = c.IsPublic()
  678. c.db = db
  679. return c, nil
  680. }
  681. func (db *datastore) GetCollection(alias string) (*Collection, error) {
  682. return db.GetCollectionBy("alias = ?", alias)
  683. }
  684. func (db *datastore) GetCollectionForPad(alias string) (*Collection, error) {
  685. c := &Collection{Alias: alias}
  686. row := db.QueryRow("SELECT id, alias, title, description, privacy FROM collections WHERE alias = ?", alias)
  687. err := row.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &c.Visibility)
  688. switch {
  689. case err == sql.ErrNoRows:
  690. return c, impart.HTTPError{http.StatusNotFound, "Collection doesn't exist."}
  691. case err != nil:
  692. log.Error("Failed selecting from collections: %v", err)
  693. return c, ErrInternalGeneral
  694. }
  695. c.Public = c.IsPublic()
  696. return c, nil
  697. }
  698. func (db *datastore) GetCollectionByID(id int64) (*Collection, error) {
  699. return db.GetCollectionBy("id = ?", id)
  700. }
  701. func (db *datastore) GetCollectionFromDomain(host string) (*Collection, error) {
  702. return db.GetCollectionBy("host = ?", host)
  703. }
  704. func (db *datastore) UpdateCollection(c *SubmittedCollection, alias string) error {
  705. q := query.NewUpdate().
  706. SetStringPtr(c.Title, "title").
  707. SetStringPtr(c.Description, "description").
  708. SetNullString(c.StyleSheet, "style_sheet").
  709. SetNullString(c.Script, "script")
  710. if c.Format != nil {
  711. cf := &CollectionFormat{Format: c.Format.String}
  712. if cf.Valid() {
  713. q.SetNullString(c.Format, "format")
  714. }
  715. }
  716. var updatePass bool
  717. if c.Visibility != nil && (collVisibility(*c.Visibility)&CollProtected == 0 || c.Pass != "") {
  718. q.SetIntPtr(c.Visibility, "privacy")
  719. if c.Pass != "" {
  720. updatePass = true
  721. }
  722. }
  723. // WHERE values
  724. q.Where("alias = ? AND owner_id = ?", alias, c.OwnerID)
  725. if q.Updates == "" {
  726. return ErrPostNoUpdatableVals
  727. }
  728. // Find any current domain
  729. var collID int64
  730. var rowsAffected int64
  731. var changed bool
  732. var res sql.Result
  733. err := db.QueryRow("SELECT id FROM collections WHERE alias = ?", alias).Scan(&collID)
  734. if err != nil {
  735. log.Error("Failed selecting from collections: %v. Some things won't work.", err)
  736. }
  737. // Update MathJax value
  738. if c.MathJax {
  739. if db.driverName == driverSQLite {
  740. _, err = db.Exec("INSERT OR REPLACE INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?)", collID, "render_mathjax", "1")
  741. } else {
  742. _, err = db.Exec("INSERT INTO collectionattributes (collection_id, attribute, value) VALUES (?, ?, ?) "+db.upsert("collection_id", "attribute")+" value = ?", collID, "render_mathjax", "1", "1")
  743. }
  744. if err != nil {
  745. log.Error("Unable to insert render_mathjax value: %v", err)
  746. return err
  747. }
  748. } else {
  749. _, err = db.Exec("DELETE FROM collectionattributes WHERE collection_id = ? AND attribute = ?", collID, "render_mathjax")
  750. if err != nil {
  751. log.Error("Unable to delete render_mathjax value: %v", err)
  752. return err
  753. }
  754. }
  755. // Update rest of the collection data
  756. res, err = db.Exec("UPDATE collections SET "+q.Updates+" WHERE "+q.Conditions, q.Params...)
  757. if err != nil {
  758. log.Error("Unable to update collection: %v", err)
  759. return err
  760. }
  761. rowsAffected, _ = res.RowsAffected()
  762. if !changed || rowsAffected == 0 {
  763. // Show the correct error message if nothing was updated
  764. var dummy int
  765. err := db.QueryRow("SELECT 1 FROM collections WHERE alias = ? AND owner_id = ?", alias, c.OwnerID).Scan(&dummy)
  766. switch {
  767. case err == sql.ErrNoRows:
  768. return ErrUnauthorizedEditPost
  769. case err != nil:
  770. log.Error("Failed selecting from collections: %v", err)
  771. }
  772. if !updatePass {
  773. return nil
  774. }
  775. }
  776. if updatePass {
  777. hashedPass, err := auth.HashPass([]byte(c.Pass))
  778. if err != nil {
  779. log.Error("Unable to create hash: %s", err)
  780. return impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."}
  781. }
  782. if db.driverName == driverSQLite {
  783. _, err = db.Exec("INSERT OR REPLACE INTO collectionpasswords (collection_id, password) VALUES ((SELECT id FROM collections WHERE alias = ?), ?)", alias, hashedPass)
  784. } else {
  785. _, err = db.Exec("INSERT INTO collectionpasswords (collection_id, password) VALUES ((SELECT id FROM collections WHERE alias = ?), ?) "+db.upsert("collection_id")+" password = ?", alias, hashedPass, hashedPass)
  786. }
  787. if err != nil {
  788. return err
  789. }
  790. }
  791. return nil
  792. }
  793. const postCols = "id, slug, text_appearance, language, rtl, privacy, owner_id, collection_id, pinned_position, created, updated, view_count, title, content"
  794. // getEditablePost returns a PublicPost with the given ID only if the given
  795. // edit token is valid for the post.
  796. func (db *datastore) GetEditablePost(id, editToken string) (*PublicPost, error) {
  797. // FIXME: code duplicated from getPost()
  798. // TODO: add slight logic difference to getPost / one func
  799. var ownerName sql.NullString
  800. p := &Post{}
  801. row := db.QueryRow("SELECT "+postCols+", (SELECT username FROM users WHERE users.id = posts.owner_id) AS username FROM posts WHERE id = ? LIMIT 1", id)
  802. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content, &ownerName)
  803. switch {
  804. case err == sql.ErrNoRows:
  805. return nil, ErrPostNotFound
  806. case err != nil:
  807. log.Error("Failed selecting from collections: %v", err)
  808. return nil, err
  809. }
  810. if p.Content == "" && p.Title.String == "" {
  811. return nil, ErrPostUnpublished
  812. }
  813. res := p.processPost()
  814. if ownerName.Valid {
  815. res.Owner = &PublicUser{Username: ownerName.String}
  816. }
  817. return &res, nil
  818. }
  819. func (db *datastore) PostIDExists(id string) bool {
  820. var dummy bool
  821. err := db.QueryRow("SELECT 1 FROM posts WHERE id = ?", id).Scan(&dummy)
  822. return err == nil && dummy
  823. }
  824. // GetPost gets a public-facing post object from the database. If collectionID
  825. // is > 0, the post will be retrieved by slug and collection ID, rather than
  826. // post ID.
  827. // TODO: break this into two functions:
  828. // - GetPost(id string)
  829. // - GetCollectionPost(slug string, collectionID int64)
  830. func (db *datastore) GetPost(id string, collectionID int64) (*PublicPost, error) {
  831. var ownerName sql.NullString
  832. p := &Post{}
  833. var row *sql.Row
  834. var where string
  835. params := []interface{}{id}
  836. if collectionID > 0 {
  837. where = "slug = ? AND collection_id = ?"
  838. params = append(params, collectionID)
  839. } else {
  840. where = "id = ?"
  841. }
  842. row = db.QueryRow("SELECT "+postCols+", (SELECT username FROM users WHERE users.id = posts.owner_id) AS username FROM posts WHERE "+where+" LIMIT 1", params...)
  843. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content, &ownerName)
  844. switch {
  845. case err == sql.ErrNoRows:
  846. if collectionID > 0 {
  847. return nil, ErrCollectionPageNotFound
  848. }
  849. return nil, ErrPostNotFound
  850. case err != nil:
  851. log.Error("Failed selecting from collections: %v", err)
  852. return nil, err
  853. }
  854. if p.Content == "" && p.Title.String == "" {
  855. return nil, ErrPostUnpublished
  856. }
  857. res := p.processPost()
  858. if ownerName.Valid {
  859. res.Owner = &PublicUser{Username: ownerName.String}
  860. }
  861. return &res, nil
  862. }
  863. // TODO: don't duplicate getPost() functionality
  864. func (db *datastore) GetOwnedPost(id string, ownerID int64) (*PublicPost, error) {
  865. p := &Post{}
  866. var row *sql.Row
  867. where := "id = ? AND owner_id = ?"
  868. params := []interface{}{id, ownerID}
  869. row = db.QueryRow("SELECT "+postCols+" FROM posts WHERE "+where+" LIMIT 1", params...)
  870. err := row.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  871. switch {
  872. case err == sql.ErrNoRows:
  873. return nil, ErrPostNotFound
  874. case err != nil:
  875. log.Error("Failed selecting from collections: %v", err)
  876. return nil, err
  877. }
  878. if p.Content == "" && p.Title.String == "" {
  879. return nil, ErrPostUnpublished
  880. }
  881. res := p.processPost()
  882. return &res, nil
  883. }
  884. func (db *datastore) GetPostProperty(id string, collectionID int64, property string) (interface{}, error) {
  885. propSelects := map[string]string{
  886. "views": "view_count AS views",
  887. }
  888. selectQuery, ok := propSelects[property]
  889. if !ok {
  890. return nil, impart.HTTPError{http.StatusBadRequest, fmt.Sprintf("Invalid property: %s.", property)}
  891. }
  892. var res interface{}
  893. var row *sql.Row
  894. if collectionID != 0 {
  895. row = db.QueryRow("SELECT "+selectQuery+" FROM posts WHERE slug = ? AND collection_id = ? LIMIT 1", id, collectionID)
  896. } else {
  897. row = db.QueryRow("SELECT "+selectQuery+" FROM posts WHERE id = ? LIMIT 1", id)
  898. }
  899. err := row.Scan(&res)
  900. switch {
  901. case err == sql.ErrNoRows:
  902. return nil, impart.HTTPError{http.StatusNotFound, "Post not found."}
  903. case err != nil:
  904. log.Error("Failed selecting post: %v", err)
  905. return nil, err
  906. }
  907. return res, nil
  908. }
  909. // GetPostsCount modifies the CollectionObj to include the correct number of
  910. // standard (non-pinned) posts. It will return future posts if `includeFuture`
  911. // is true.
  912. func (db *datastore) GetPostsCount(c *CollectionObj, includeFuture bool) {
  913. var count int64
  914. timeCondition := ""
  915. if !includeFuture {
  916. timeCondition = "AND created <= " + db.now()
  917. }
  918. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE collection_id = ? AND pinned_position IS NULL "+timeCondition, c.ID).Scan(&count)
  919. switch {
  920. case err == sql.ErrNoRows:
  921. c.TotalPosts = 0
  922. case err != nil:
  923. log.Error("Failed selecting from collections: %v", err)
  924. c.TotalPosts = 0
  925. }
  926. c.TotalPosts = int(count)
  927. }
  928. // GetPosts retrieves all posts for the given Collection.
  929. // It will return future posts if `includeFuture` is true.
  930. // It will include only standard (non-pinned) posts unless `includePinned` is true.
  931. // TODO: change includeFuture to isOwner, since that's how it's used
  932. func (db *datastore) GetPosts(cfg *config.Config, c *Collection, page int, includeFuture, forceRecentFirst, includePinned bool) (*[]PublicPost, error) {
  933. collID := c.ID
  934. cf := c.NewFormat()
  935. order := "DESC"
  936. if cf.Ascending() && !forceRecentFirst {
  937. order = "ASC"
  938. }
  939. pagePosts := cf.PostsPerPage()
  940. start := page*pagePosts - pagePosts
  941. if page == 0 {
  942. start = 0
  943. pagePosts = 1000
  944. }
  945. limitStr := ""
  946. if page > 0 {
  947. limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
  948. }
  949. timeCondition := ""
  950. if !includeFuture {
  951. timeCondition = "AND created <= " + db.now()
  952. }
  953. pinnedCondition := ""
  954. if !includePinned {
  955. pinnedCondition = "AND pinned_position IS NULL"
  956. }
  957. rows, err := db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? "+pinnedCondition+" "+timeCondition+" ORDER BY created "+order+limitStr, collID)
  958. if err != nil {
  959. log.Error("Failed selecting from posts: %v", err)
  960. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts."}
  961. }
  962. defer rows.Close()
  963. // TODO: extract this common row scanning logic for queries using `postCols`
  964. posts := []PublicPost{}
  965. for rows.Next() {
  966. p := &Post{}
  967. err = rows.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  968. if err != nil {
  969. log.Error("Failed scanning row: %v", err)
  970. break
  971. }
  972. p.extractData()
  973. p.formatContent(cfg, c, includeFuture)
  974. posts = append(posts, p.processPost())
  975. }
  976. err = rows.Err()
  977. if err != nil {
  978. log.Error("Error after Next() on rows: %v", err)
  979. }
  980. return &posts, nil
  981. }
  982. // GetPostsTagged retrieves all posts on the given Collection that contain the
  983. // given tag.
  984. // It will return future posts if `includeFuture` is true.
  985. // TODO: change includeFuture to isOwner, since that's how it's used
  986. func (db *datastore) GetPostsTagged(cfg *config.Config, c *Collection, tag string, page int, includeFuture bool) (*[]PublicPost, error) {
  987. collID := c.ID
  988. cf := c.NewFormat()
  989. order := "DESC"
  990. if cf.Ascending() {
  991. order = "ASC"
  992. }
  993. pagePosts := cf.PostsPerPage()
  994. start := page*pagePosts - pagePosts
  995. if page == 0 {
  996. start = 0
  997. pagePosts = 1000
  998. }
  999. limitStr := ""
  1000. if page > 0 {
  1001. limitStr = fmt.Sprintf(" LIMIT %d, %d", start, pagePosts)
  1002. }
  1003. timeCondition := ""
  1004. if !includeFuture {
  1005. timeCondition = "AND created <= " + db.now()
  1006. }
  1007. var rows *sql.Rows
  1008. var err error
  1009. if db.driverName == driverSQLite {
  1010. rows, err = db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? AND LOWER(content) regexp ? "+timeCondition+" ORDER BY created "+order+limitStr, collID, `.*#`+strings.ToLower(tag)+`\b.*`)
  1011. } else {
  1012. rows, err = db.Query("SELECT "+postCols+" FROM posts WHERE collection_id = ? AND LOWER(content) RLIKE ? "+timeCondition+" ORDER BY created "+order+limitStr, collID, "#"+strings.ToLower(tag)+"[[:>:]]")
  1013. }
  1014. if err != nil {
  1015. log.Error("Failed selecting from posts: %v", err)
  1016. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts."}
  1017. }
  1018. defer rows.Close()
  1019. // TODO: extract this common row scanning logic for queries using `postCols`
  1020. posts := []PublicPost{}
  1021. for rows.Next() {
  1022. p := &Post{}
  1023. err = rows.Scan(&p.ID, &p.Slug, &p.Font, &p.Language, &p.RTL, &p.Privacy, &p.OwnerID, &p.CollectionID, &p.PinnedPosition, &p.Created, &p.Updated, &p.ViewCount, &p.Title, &p.Content)
  1024. if err != nil {
  1025. log.Error("Failed scanning row: %v", err)
  1026. break
  1027. }
  1028. p.extractData()
  1029. p.formatContent(cfg, c, includeFuture)
  1030. posts = append(posts, p.processPost())
  1031. }
  1032. err = rows.Err()
  1033. if err != nil {
  1034. log.Error("Error after Next() on rows: %v", err)
  1035. }
  1036. return &posts, nil
  1037. }
  1038. func (db *datastore) GetAPFollowers(c *Collection) (*[]RemoteUser, error) {
  1039. rows, err := db.Query("SELECT actor_id, inbox, shared_inbox FROM remotefollows f INNER JOIN remoteusers u ON f.remote_user_id = u.id WHERE collection_id = ?", c.ID)
  1040. if err != nil {
  1041. log.Error("Failed selecting from followers: %v", err)
  1042. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve followers."}
  1043. }
  1044. defer rows.Close()
  1045. followers := []RemoteUser{}
  1046. for rows.Next() {
  1047. f := RemoteUser{}
  1048. err = rows.Scan(&f.ActorID, &f.Inbox, &f.SharedInbox)
  1049. followers = append(followers, f)
  1050. }
  1051. return &followers, nil
  1052. }
  1053. // CanCollect returns whether or not the given user can add the given post to a
  1054. // collection. This is true when a post is already owned by the user.
  1055. // NOTE: this is currently only used to potentially add owned posts to a
  1056. // collection. This has the SIDE EFFECT of also generating a slug for the post.
  1057. // FIXME: make this side effect more explicit (or extract it)
  1058. func (db *datastore) CanCollect(cpr *ClaimPostRequest, userID int64) bool {
  1059. var title, content string
  1060. var lang sql.NullString
  1061. err := db.QueryRow("SELECT title, content, language FROM posts WHERE id = ? AND owner_id = ?", cpr.ID, userID).Scan(&title, &content, &lang)
  1062. switch {
  1063. case err == sql.ErrNoRows:
  1064. return false
  1065. case err != nil:
  1066. log.Error("Failed on post CanCollect(%s, %d): %v", cpr.ID, userID, err)
  1067. return false
  1068. }
  1069. // Since we have the post content and the post is collectable, generate the
  1070. // post's slug now.
  1071. cpr.Slug = getSlugFromPost(title, content, lang.String)
  1072. return true
  1073. }
  1074. func (db *datastore) AttemptClaim(p *ClaimPostRequest, query string, params []interface{}, slugIdx int) (sql.Result, error) {
  1075. qRes, err := db.Exec(query, params...)
  1076. if err != nil {
  1077. if db.isDuplicateKeyErr(err) && slugIdx > -1 {
  1078. s := id.GenSafeUniqueSlug(p.Slug)
  1079. if s == p.Slug {
  1080. // Sanity check to prevent infinite recursion
  1081. return qRes, fmt.Errorf("GenSafeUniqueSlug generated nothing unique: %s", s)
  1082. }
  1083. p.Slug = s
  1084. params[slugIdx] = p.Slug
  1085. return db.AttemptClaim(p, query, params, slugIdx)
  1086. }
  1087. return qRes, fmt.Errorf("attemptClaim: %s", err)
  1088. }
  1089. return qRes, nil
  1090. }
  1091. func (db *datastore) DispersePosts(userID int64, postIDs []string) (*[]ClaimPostResult, error) {
  1092. postClaimReqs := map[string]bool{}
  1093. res := []ClaimPostResult{}
  1094. for i := range postIDs {
  1095. postID := postIDs[i]
  1096. r := ClaimPostResult{Code: 0, ErrorMessage: ""}
  1097. // Perform post validation
  1098. if postID == "" {
  1099. r.ErrorMessage = "Missing post ID. "
  1100. }
  1101. if _, ok := postClaimReqs[postID]; ok {
  1102. r.Code = 429
  1103. r.ErrorMessage = "You've already tried anonymizing this post."
  1104. r.ID = postID
  1105. res = append(res, r)
  1106. continue
  1107. }
  1108. postClaimReqs[postID] = true
  1109. var err error
  1110. // Get full post information to return
  1111. var fullPost *PublicPost
  1112. fullPost, err = db.GetPost(postID, 0)
  1113. if err != nil {
  1114. if err, ok := err.(impart.HTTPError); ok {
  1115. r.Code = err.Status
  1116. r.ErrorMessage = err.Message
  1117. r.ID = postID
  1118. res = append(res, r)
  1119. continue
  1120. } else {
  1121. log.Error("Error getting post in dispersePosts: %v", err)
  1122. }
  1123. }
  1124. if fullPost.OwnerID.Int64 != userID {
  1125. r.Code = http.StatusConflict
  1126. r.ErrorMessage = "Post is already owned by someone else."
  1127. r.ID = postID
  1128. res = append(res, r)
  1129. continue
  1130. }
  1131. var qRes sql.Result
  1132. var query string
  1133. var params []interface{}
  1134. // Do AND owner_id = ? for sanity.
  1135. // This should've been caught and returned with a good error message
  1136. // just above.
  1137. query = "UPDATE posts SET collection_id = NULL WHERE id = ? AND owner_id = ?"
  1138. params = []interface{}{postID, userID}
  1139. qRes, err = db.Exec(query, params...)
  1140. if err != nil {
  1141. r.Code = http.StatusInternalServerError
  1142. r.ErrorMessage = "A glitch happened on our end."
  1143. r.ID = postID
  1144. res = append(res, r)
  1145. log.Error("dispersePosts (post %s): %v", postID, err)
  1146. continue
  1147. }
  1148. // Post was successfully dispersed
  1149. r.Code = http.StatusOK
  1150. r.Post = fullPost
  1151. rowsAffected, _ := qRes.RowsAffected()
  1152. if rowsAffected == 0 {
  1153. // This was already claimed, but return 200
  1154. r.Code = http.StatusOK
  1155. }
  1156. res = append(res, r)
  1157. }
  1158. return &res, nil
  1159. }
  1160. func (db *datastore) ClaimPosts(cfg *config.Config, userID int64, collAlias string, posts *[]ClaimPostRequest) (*[]ClaimPostResult, error) {
  1161. postClaimReqs := map[string]bool{}
  1162. res := []ClaimPostResult{}
  1163. postCollAlias := collAlias
  1164. for i := range *posts {
  1165. p := (*posts)[i]
  1166. if &p == nil {
  1167. continue
  1168. }
  1169. r := ClaimPostResult{Code: 0, ErrorMessage: ""}
  1170. // Perform post validation
  1171. if p.ID == "" {
  1172. r.ErrorMessage = "Missing post ID `id`. "
  1173. }
  1174. if _, ok := postClaimReqs[p.ID]; ok {
  1175. r.Code = 429
  1176. r.ErrorMessage = "You've already tried claiming this post."
  1177. r.ID = p.ID
  1178. res = append(res, r)
  1179. continue
  1180. }
  1181. postClaimReqs[p.ID] = true
  1182. canCollect := db.CanCollect(&p, userID)
  1183. if !canCollect && p.Token == "" {
  1184. // TODO: ensure post isn't owned by anyone else when a valid modify
  1185. // token is given.
  1186. r.ErrorMessage += "Missing post Edit Token `token`."
  1187. }
  1188. if r.ErrorMessage != "" {
  1189. // Post validate failed
  1190. r.Code = http.StatusBadRequest
  1191. r.ID = p.ID
  1192. res = append(res, r)
  1193. continue
  1194. }
  1195. var err error
  1196. var qRes sql.Result
  1197. var query string
  1198. var params []interface{}
  1199. var slugIdx int = -1
  1200. var coll *Collection
  1201. if collAlias == "" {
  1202. // Posts are being claimed at /posts/claim, not
  1203. // /collections/{alias}/collect, so use given individual collection
  1204. // to associate post with.
  1205. postCollAlias = p.CollectionAlias
  1206. }
  1207. if postCollAlias != "" {
  1208. // Associate this post with a collection
  1209. if p.CreateCollection {
  1210. // This is a new collection
  1211. // TODO: consider removing this. This seriously complicates this
  1212. // method and adds another (unnecessary?) logic path.
  1213. coll, err = db.CreateCollection(cfg, postCollAlias, "", userID)
  1214. if err != nil {
  1215. if err, ok := err.(impart.HTTPError); ok {
  1216. r.Code = err.Status
  1217. r.ErrorMessage = err.Message
  1218. } else {
  1219. r.Code = http.StatusInternalServerError
  1220. r.ErrorMessage = "Unknown error occurred creating collection"
  1221. }
  1222. r.ID = p.ID
  1223. res = append(res, r)
  1224. continue
  1225. }
  1226. } else {
  1227. // Attempt to add to existing collection
  1228. coll, err = db.GetCollection(postCollAlias)
  1229. if err != nil {
  1230. if err, ok := err.(impart.HTTPError); ok {
  1231. if err.Status == http.StatusNotFound {
  1232. // Show obfuscated "forbidden" response, as if attempting to add to an
  1233. // unowned blog.
  1234. r.Code = ErrForbiddenCollection.Status
  1235. r.ErrorMessage = ErrForbiddenCollection.Message
  1236. } else {
  1237. r.Code = err.Status
  1238. r.ErrorMessage = err.Message
  1239. }
  1240. } else {
  1241. r.Code = http.StatusInternalServerError
  1242. r.ErrorMessage = "Unknown error occurred claiming post with collection"
  1243. }
  1244. r.ID = p.ID
  1245. res = append(res, r)
  1246. continue
  1247. }
  1248. if coll.OwnerID != userID {
  1249. r.Code = ErrForbiddenCollection.Status
  1250. r.ErrorMessage = ErrForbiddenCollection.Message
  1251. r.ID = p.ID
  1252. res = append(res, r)
  1253. continue
  1254. }
  1255. }
  1256. if p.Slug == "" {
  1257. p.Slug = p.ID
  1258. }
  1259. if canCollect {
  1260. // User already owns this post, so just add it to the given
  1261. // collection.
  1262. query = "UPDATE posts SET collection_id = ?, slug = ? WHERE id = ? AND owner_id = ?"
  1263. params = []interface{}{coll.ID, p.Slug, p.ID, userID}
  1264. slugIdx = 1
  1265. } else {
  1266. query = "UPDATE posts SET owner_id = ?, collection_id = ?, slug = ? WHERE id = ? AND modify_token = ? AND owner_id IS NULL"
  1267. params = []interface{}{userID, coll.ID, p.Slug, p.ID, p.Token}
  1268. slugIdx = 2
  1269. }
  1270. } else {
  1271. query = "UPDATE posts SET owner_id = ? WHERE id = ? AND modify_token = ? AND owner_id IS NULL"
  1272. params = []interface{}{userID, p.ID, p.Token}
  1273. }
  1274. qRes, err = db.AttemptClaim(&p, query, params, slugIdx)
  1275. if err != nil {
  1276. r.Code = http.StatusInternalServerError
  1277. r.ErrorMessage = "An unknown error occurred."
  1278. r.ID = p.ID
  1279. res = append(res, r)
  1280. log.Error("claimPosts (post %s): %v", p.ID, err)
  1281. continue
  1282. }
  1283. // Get full post information to return
  1284. var fullPost *PublicPost
  1285. if p.Token != "" {
  1286. fullPost, err = db.GetEditablePost(p.ID, p.Token)
  1287. } else {
  1288. fullPost, err = db.GetPost(p.ID, 0)
  1289. }
  1290. if err != nil {
  1291. if err, ok := err.(impart.HTTPError); ok {
  1292. r.Code = err.Status
  1293. r.ErrorMessage = err.Message
  1294. r.ID = p.ID
  1295. res = append(res, r)
  1296. continue
  1297. }
  1298. }
  1299. if fullPost.OwnerID.Int64 != userID {
  1300. r.Code = http.StatusConflict
  1301. r.ErrorMessage = "Post is already owned by someone else."
  1302. r.ID = p.ID
  1303. res = append(res, r)
  1304. continue
  1305. }
  1306. // Post was successfully claimed
  1307. r.Code = http.StatusOK
  1308. r.Post = fullPost
  1309. if coll != nil {
  1310. r.Post.Collection = &CollectionObj{Collection: *coll}
  1311. }
  1312. rowsAffected, _ := qRes.RowsAffected()
  1313. if rowsAffected == 0 {
  1314. // This was already claimed, but return 200
  1315. r.Code = http.StatusOK
  1316. }
  1317. res = append(res, r)
  1318. }
  1319. return &res, nil
  1320. }
  1321. func (db *datastore) UpdatePostPinState(pinned bool, postID string, collID, ownerID, pos int64) error {
  1322. if pos <= 0 || pos > 20 {
  1323. pos = db.GetLastPinnedPostPos(collID) + 1
  1324. if pos == -1 {
  1325. pos = 1
  1326. }
  1327. }
  1328. var err error
  1329. if pinned {
  1330. _, err = db.Exec("UPDATE posts SET pinned_position = ? WHERE id = ?", pos, postID)
  1331. } else {
  1332. _, err = db.Exec("UPDATE posts SET pinned_position = NULL WHERE id = ?", postID)
  1333. }
  1334. if err != nil {
  1335. log.Error("Unable to update pinned post: %v", err)
  1336. return err
  1337. }
  1338. return nil
  1339. }
  1340. func (db *datastore) GetLastPinnedPostPos(collID int64) int64 {
  1341. var lastPos sql.NullInt64
  1342. err := db.QueryRow("SELECT MAX(pinned_position) FROM posts WHERE collection_id = ? AND pinned_position IS NOT NULL", collID).Scan(&lastPos)
  1343. switch {
  1344. case err == sql.ErrNoRows:
  1345. return -1
  1346. case err != nil:
  1347. log.Error("Failed selecting from posts: %v", err)
  1348. return -1
  1349. }
  1350. if !lastPos.Valid {
  1351. return -1
  1352. }
  1353. return lastPos.Int64
  1354. }
  1355. func (db *datastore) GetPinnedPosts(coll *CollectionObj, includeFuture bool) (*[]PublicPost, error) {
  1356. // FIXME: sqlite-backed instances don't include ellipsis on truncated titles
  1357. timeCondition := ""
  1358. if !includeFuture {
  1359. timeCondition = "AND created <= " + db.now()
  1360. }
  1361. rows, err := db.Query("SELECT id, slug, title, "+db.clip("content", 80)+", pinned_position FROM posts WHERE collection_id = ? AND pinned_position IS NOT NULL "+timeCondition+" ORDER BY pinned_position ASC", coll.ID)
  1362. if err != nil {
  1363. log.Error("Failed selecting pinned posts: %v", err)
  1364. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve pinned posts."}
  1365. }
  1366. defer rows.Close()
  1367. posts := []PublicPost{}
  1368. for rows.Next() {
  1369. p := &Post{}
  1370. err = rows.Scan(&p.ID, &p.Slug, &p.Title, &p.Content, &p.PinnedPosition)
  1371. if err != nil {
  1372. log.Error("Failed scanning row: %v", err)
  1373. break
  1374. }
  1375. p.extractData()
  1376. pp := p.processPost()
  1377. pp.Collection = coll
  1378. posts = append(posts, pp)
  1379. }
  1380. return &posts, nil
  1381. }
  1382. func (db *datastore) GetCollections(u *User, hostName string) (*[]Collection, error) {
  1383. rows, err := db.Query("SELECT id, alias, title, description, privacy, view_count FROM collections WHERE owner_id = ? ORDER BY id ASC", u.ID)
  1384. if err != nil {
  1385. log.Error("Failed selecting from collections: %v", err)
  1386. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user collections."}
  1387. }
  1388. defer rows.Close()
  1389. colls := []Collection{}
  1390. for rows.Next() {
  1391. c := Collection{}
  1392. err = rows.Scan(&c.ID, &c.Alias, &c.Title, &c.Description, &c.Visibility, &c.Views)
  1393. if err != nil {
  1394. log.Error("Failed scanning row: %v", err)
  1395. break
  1396. }
  1397. c.hostName = hostName
  1398. c.URL = c.CanonicalURL()
  1399. c.Public = c.IsPublic()
  1400. colls = append(colls, c)
  1401. }
  1402. err = rows.Err()
  1403. if err != nil {
  1404. log.Error("Error after Next() on rows: %v", err)
  1405. }
  1406. return &colls, nil
  1407. }
  1408. func (db *datastore) GetPublishableCollections(u *User, hostName string) (*[]Collection, error) {
  1409. c, err := db.GetCollections(u, hostName)
  1410. if err != nil {
  1411. return nil, err
  1412. }
  1413. if len(*c) == 0 {
  1414. return nil, impart.HTTPError{http.StatusInternalServerError, "You don't seem to have any blogs; they might've moved to another account. Try logging out and logging into your other account."}
  1415. }
  1416. return c, nil
  1417. }
  1418. func (db *datastore) GetMeStats(u *User) userMeStats {
  1419. s := userMeStats{}
  1420. // User counts
  1421. colls, _ := db.GetUserCollectionCount(u.ID)
  1422. s.TotalCollections = colls
  1423. var articles, collPosts uint64
  1424. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ? AND collection_id IS NULL", u.ID).Scan(&articles)
  1425. if err != nil && err != sql.ErrNoRows {
  1426. log.Error("Couldn't get articles count for user %d: %v", u.ID, err)
  1427. }
  1428. s.TotalArticles = articles
  1429. err = db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ? AND collection_id IS NOT NULL", u.ID).Scan(&collPosts)
  1430. if err != nil && err != sql.ErrNoRows {
  1431. log.Error("Couldn't get coll posts count for user %d: %v", u.ID, err)
  1432. }
  1433. s.CollectionPosts = collPosts
  1434. return s
  1435. }
  1436. func (db *datastore) GetTotalCollections() (collCount int64, err error) {
  1437. err = db.QueryRow(`SELECT COUNT(*) FROM collections`).Scan(&collCount)
  1438. if err != nil {
  1439. log.Error("Unable to fetch collections count: %v", err)
  1440. }
  1441. return
  1442. }
  1443. func (db *datastore) GetTotalPosts() (postCount int64, err error) {
  1444. err = db.QueryRow(`SELECT COUNT(*) FROM posts`).Scan(&postCount)
  1445. if err != nil {
  1446. log.Error("Unable to fetch posts count: %v", err)
  1447. }
  1448. return
  1449. }
  1450. func (db *datastore) GetTopPosts(u *User, alias string) (*[]PublicPost, error) {
  1451. params := []interface{}{u.ID}
  1452. where := ""
  1453. if alias != "" {
  1454. where = " AND alias = ?"
  1455. params = append(params, alias)
  1456. }
  1457. rows, err := db.Query("SELECT p.id, p.slug, p.view_count, p.title, c.alias, c.title, c.description, c.view_count FROM posts p LEFT JOIN collections c ON p.collection_id = c.id WHERE p.owner_id = ?"+where+" ORDER BY p.view_count DESC, created DESC LIMIT 25", params...)
  1458. if err != nil {
  1459. log.Error("Failed selecting from posts: %v", err)
  1460. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user top posts."}
  1461. }
  1462. defer rows.Close()
  1463. posts := []PublicPost{}
  1464. var gotErr bool
  1465. for rows.Next() {
  1466. p := Post{}
  1467. c := Collection{}
  1468. var alias, title, description sql.NullString
  1469. var views sql.NullInt64
  1470. err = rows.Scan(&p.ID, &p.Slug, &p.ViewCount, &p.Title, &alias, &title, &description, &views)
  1471. if err != nil {
  1472. log.Error("Failed scanning User.getPosts() row: %v", err)
  1473. gotErr = true
  1474. break
  1475. }
  1476. p.extractData()
  1477. pubPost := p.processPost()
  1478. if alias.Valid && alias.String != "" {
  1479. c.Alias = alias.String
  1480. c.Title = title.String
  1481. c.Description = description.String
  1482. c.Views = views.Int64
  1483. pubPost.Collection = &CollectionObj{Collection: c}
  1484. }
  1485. posts = append(posts, pubPost)
  1486. }
  1487. err = rows.Err()
  1488. if err != nil {
  1489. log.Error("Error after Next() on rows: %v", err)
  1490. }
  1491. if gotErr && len(posts) == 0 {
  1492. // There were a lot of errors
  1493. return nil, impart.HTTPError{http.StatusInternalServerError, "Unable to get data."}
  1494. }
  1495. return &posts, nil
  1496. }
  1497. func (db *datastore) GetAnonymousPosts(u *User) (*[]PublicPost, error) {
  1498. rows, err := db.Query("SELECT id, view_count, title, created, updated, content FROM posts WHERE owner_id = ? AND collection_id IS NULL ORDER BY created DESC", u.ID)
  1499. if err != nil {
  1500. log.Error("Failed selecting from posts: %v", err)
  1501. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user anonymous posts."}
  1502. }
  1503. defer rows.Close()
  1504. posts := []PublicPost{}
  1505. for rows.Next() {
  1506. p := Post{}
  1507. err = rows.Scan(&p.ID, &p.ViewCount, &p.Title, &p.Created, &p.Updated, &p.Content)
  1508. if err != nil {
  1509. log.Error("Failed scanning row: %v", err)
  1510. break
  1511. }
  1512. p.extractData()
  1513. posts = append(posts, p.processPost())
  1514. }
  1515. err = rows.Err()
  1516. if err != nil {
  1517. log.Error("Error after Next() on rows: %v", err)
  1518. }
  1519. return &posts, nil
  1520. }
  1521. func (db *datastore) GetUserPosts(u *User) (*[]PublicPost, error) {
  1522. rows, err := db.Query("SELECT p.id, p.slug, p.view_count, p.title, p.created, p.updated, p.content, p.text_appearance, p.language, p.rtl, c.alias, c.title, c.description, c.view_count FROM posts p LEFT JOIN collections c ON collection_id = c.id WHERE p.owner_id = ? ORDER BY created ASC", u.ID)
  1523. if err != nil {
  1524. log.Error("Failed selecting from posts: %v", err)
  1525. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user posts."}
  1526. }
  1527. defer rows.Close()
  1528. posts := []PublicPost{}
  1529. var gotErr bool
  1530. for rows.Next() {
  1531. p := Post{}
  1532. c := Collection{}
  1533. var alias, title, description sql.NullString
  1534. var views sql.NullInt64
  1535. err = rows.Scan(&p.ID, &p.Slug, &p.ViewCount, &p.Title, &p.Created, &p.Updated, &p.Content, &p.Font, &p.Language, &p.RTL, &alias, &title, &description, &views)
  1536. if err != nil {
  1537. log.Error("Failed scanning User.getPosts() row: %v", err)
  1538. gotErr = true
  1539. break
  1540. }
  1541. p.extractData()
  1542. pubPost := p.processPost()
  1543. if alias.Valid && alias.String != "" {
  1544. c.Alias = alias.String
  1545. c.Title = title.String
  1546. c.Description = description.String
  1547. c.Views = views.Int64
  1548. pubPost.Collection = &CollectionObj{Collection: c}
  1549. }
  1550. posts = append(posts, pubPost)
  1551. }
  1552. err = rows.Err()
  1553. if err != nil {
  1554. log.Error("Error after Next() on rows: %v", err)
  1555. }
  1556. if gotErr && len(posts) == 0 {
  1557. // There were a lot of errors
  1558. return nil, impart.HTTPError{http.StatusInternalServerError, "Unable to get data."}
  1559. }
  1560. return &posts, nil
  1561. }
  1562. func (db *datastore) GetUserPostsCount(userID int64) int64 {
  1563. var count int64
  1564. err := db.QueryRow("SELECT COUNT(*) FROM posts WHERE owner_id = ?", userID).Scan(&count)
  1565. switch {
  1566. case err == sql.ErrNoRows:
  1567. return 0
  1568. case err != nil:
  1569. log.Error("Failed selecting posts count for user %d: %v", userID, err)
  1570. return 0
  1571. }
  1572. return count
  1573. }
  1574. // ChangeSettings takes a User and applies the changes in the given
  1575. // userSettings, MODIFYING THE USER with successful changes.
  1576. func (db *datastore) ChangeSettings(app *App, u *User, s *userSettings) error {
  1577. var errPass error
  1578. q := query.NewUpdate()
  1579. // Update email if given
  1580. if s.Email != "" {
  1581. encEmail, err := data.Encrypt(app.keys.EmailKey, s.Email)
  1582. if err != nil {
  1583. log.Error("Couldn't encrypt email %s: %s\n", s.Email, err)
  1584. return impart.HTTPError{http.StatusInternalServerError, "Unable to encrypt email address."}
  1585. }
  1586. q.SetBytes(encEmail, "email")
  1587. // Update the email if something goes awry updating the password
  1588. defer func() {
  1589. if errPass != nil {
  1590. db.UpdateEncryptedUserEmail(u.ID, encEmail)
  1591. }
  1592. }()
  1593. u.Email = zero.StringFrom(s.Email)
  1594. }
  1595. // Update username if given
  1596. var newUsername string
  1597. if s.Username != "" {
  1598. var ie *impart.HTTPError
  1599. newUsername, ie = getValidUsername(app, s.Username, u.Username)
  1600. if ie != nil {
  1601. // Username is invalid
  1602. return *ie
  1603. }
  1604. if !author.IsValidUsername(app.cfg, newUsername) {
  1605. // Ensure the username is syntactically correct.
  1606. return impart.HTTPError{http.StatusPreconditionFailed, "Username isn't valid."}
  1607. }
  1608. t, err := db.Begin()
  1609. if err != nil {
  1610. log.Error("Couldn't start username change transaction: %v", err)
  1611. return err
  1612. }
  1613. _, err = t.Exec("UPDATE users SET username = ? WHERE id = ?", newUsername, u.ID)
  1614. if err != nil {
  1615. t.Rollback()
  1616. if db.isDuplicateKeyErr(err) {
  1617. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  1618. }
  1619. log.Error("Unable to update users table: %v", err)
  1620. return ErrInternalGeneral
  1621. }
  1622. _, err = t.Exec("UPDATE collections SET alias = ? WHERE alias = ? AND owner_id = ?", newUsername, u.Username, u.ID)
  1623. if err != nil {
  1624. t.Rollback()
  1625. if db.isDuplicateKeyErr(err) {
  1626. return impart.HTTPError{http.StatusConflict, "Username is already taken."}
  1627. }
  1628. log.Error("Unable to update collection: %v", err)
  1629. return ErrInternalGeneral
  1630. }
  1631. // Keep track of name changes for redirection
  1632. db.RemoveCollectionRedirect(t, newUsername)
  1633. _, err = t.Exec("UPDATE collectionredirects SET new_alias = ? WHERE new_alias = ?", newUsername, u.Username)
  1634. if err != nil {
  1635. log.Error("Unable to update collectionredirects: %v", err)
  1636. }
  1637. _, err = t.Exec("INSERT INTO collectionredirects (prev_alias, new_alias) VALUES (?, ?)", u.Username, newUsername)
  1638. if err != nil {
  1639. log.Error("Unable to add new collectionredirect: %v", err)
  1640. }
  1641. err = t.Commit()
  1642. if err != nil {
  1643. t.Rollback()
  1644. log.Error("Rolling back after Commit(): %v\n", err)
  1645. return err
  1646. }
  1647. u.Username = newUsername
  1648. }
  1649. // Update passphrase if given
  1650. if s.NewPass != "" {
  1651. // Check if user has already set a password
  1652. var err error
  1653. u.HasPass, err = db.IsUserPassSet(u.ID)
  1654. if err != nil {
  1655. errPass = impart.HTTPError{http.StatusInternalServerError, "Unable to retrieve user data."}
  1656. return errPass
  1657. }
  1658. if u.HasPass {
  1659. // Check if currently-set password is correct
  1660. hashedPass := u.HashedPass
  1661. if len(hashedPass) == 0 {
  1662. authUser, err := db.GetUserForAuthByID(u.ID)
  1663. if err != nil {
  1664. errPass = err
  1665. return errPass
  1666. }
  1667. hashedPass = authUser.HashedPass
  1668. }
  1669. if !auth.Authenticated(hashedPass, []byte(s.OldPass)) {
  1670. errPass = impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  1671. return errPass
  1672. }
  1673. }
  1674. hashedPass, err := auth.HashPass([]byte(s.NewPass))
  1675. if err != nil {
  1676. errPass = impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."}
  1677. return errPass
  1678. }
  1679. q.SetBytes(hashedPass, "password")
  1680. }
  1681. // WHERE values
  1682. q.Append(u.ID)
  1683. if q.Updates == "" {
  1684. if s.Username == "" {
  1685. return ErrPostNoUpdatableVals
  1686. }
  1687. // Nothing to update except username. That was successful, so return now.
  1688. return nil
  1689. }
  1690. res, err := db.Exec("UPDATE users SET "+q.Updates+" WHERE id = ?", q.Params...)
  1691. if err != nil {
  1692. log.Error("Unable to update collection: %v", err)
  1693. return err
  1694. }
  1695. rowsAffected, _ := res.RowsAffected()
  1696. if rowsAffected == 0 {
  1697. // Show the correct error message if nothing was updated
  1698. var dummy int
  1699. err := db.QueryRow("SELECT 1 FROM users WHERE id = ?", u.ID).Scan(&dummy)
  1700. switch {
  1701. case err == sql.ErrNoRows:
  1702. return ErrUnauthorizedGeneral
  1703. case err != nil:
  1704. log.Error("Failed selecting from users: %v", err)
  1705. }
  1706. return nil
  1707. }
  1708. if s.NewPass != "" && !u.HasPass {
  1709. u.HasPass = true
  1710. }
  1711. return nil
  1712. }
  1713. func (db *datastore) ChangePassphrase(userID int64, sudo bool, curPass string, hashedPass []byte) error {
  1714. var dbPass []byte
  1715. err := db.QueryRow("SELECT password FROM users WHERE id = ?", userID).Scan(&dbPass)
  1716. switch {
  1717. case err == sql.ErrNoRows:
  1718. return ErrUserNotFound
  1719. case err != nil:
  1720. log.Error("Couldn't SELECT user password for change: %v", err)
  1721. return err
  1722. }
  1723. if !sudo && !auth.Authenticated(dbPass, []byte(curPass)) {
  1724. return impart.HTTPError{http.StatusUnauthorized, "Incorrect password."}
  1725. }
  1726. _, err = db.Exec("UPDATE users SET password = ? WHERE id = ?", hashedPass, userID)
  1727. if err != nil {
  1728. log.Error("Could not update passphrase: %v", err)
  1729. return err
  1730. }
  1731. return nil
  1732. }
  1733. func (db *datastore) RemoveCollectionRedirect(t *sql.Tx, alias string) error {
  1734. _, err := t.Exec("DELETE FROM collectionredirects WHERE prev_alias = ?", alias)
  1735. if err != nil {
  1736. log.Error("Unable to delete from collectionredirects: %v", err)
  1737. return err
  1738. }
  1739. return nil
  1740. }
  1741. func (db *datastore) GetCollectionRedirect(alias string) (new string) {
  1742. row := db.QueryRow("SELECT new_alias FROM collectionredirects WHERE prev_alias = ?", alias)
  1743. err := row.Scan(&new)
  1744. if err != nil && err != sql.ErrNoRows {
  1745. log.Error("Failed selecting from collectionredirects: %v", err)
  1746. }
  1747. return
  1748. }
  1749. func (db *datastore) DeleteCollection(alias string, userID int64) error {
  1750. c := &Collection{Alias: alias}
  1751. var username string
  1752. row := db.QueryRow("SELECT username FROM users WHERE id = ?", userID)
  1753. err := row.Scan(&username)
  1754. if err != nil {
  1755. return err
  1756. }
  1757. // Ensure user isn't deleting their main blog
  1758. if alias == username {
  1759. return impart.HTTPError{http.StatusForbidden, "You cannot currently delete your primary blog."}
  1760. }
  1761. row = db.QueryRow("SELECT id FROM collections WHERE alias = ? AND owner_id = ?", alias, userID)
  1762. err = row.Scan(&c.ID)
  1763. switch {
  1764. case err == sql.ErrNoRows:
  1765. return impart.HTTPError{http.StatusNotFound, "Collection doesn't exist or you're not allowed to delete it."}
  1766. case err != nil:
  1767. log.Error("Failed selecting from collections: %v", err)
  1768. return ErrInternalGeneral
  1769. }
  1770. t, err := db.Begin()
  1771. if err != nil {
  1772. return err
  1773. }
  1774. // Float all collection's posts
  1775. _, err = t.Exec("UPDATE posts SET collection_id = NULL WHERE collection_id = ? AND owner_id = ?", c.ID, userID)
  1776. if err != nil {
  1777. t.Rollback()
  1778. return err
  1779. }
  1780. // Remove redirects to or from this collection
  1781. _, err = t.Exec("DELETE FROM collectionredirects WHERE prev_alias = ? OR new_alias = ?", alias, alias)
  1782. if err != nil {
  1783. t.Rollback()
  1784. return err
  1785. }
  1786. // Remove any optional collection password
  1787. _, err = t.Exec("DELETE FROM collectionpasswords WHERE collection_id = ?", c.ID)
  1788. if err != nil {
  1789. t.Rollback()
  1790. return err
  1791. }
  1792. // Finally, delete collection itself
  1793. _, err = t.Exec("DELETE FROM collections WHERE id = ?", c.ID)
  1794. if err != nil {
  1795. t.Rollback()
  1796. return err
  1797. }
  1798. err = t.Commit()
  1799. if err != nil {
  1800. t.Rollback()
  1801. return err
  1802. }
  1803. return nil
  1804. }
  1805. func (db *datastore) IsCollectionAttributeOn(id int64, attr string) bool {
  1806. var v string
  1807. err := db.QueryRow("SELECT value FROM collectionattributes WHERE collection_id = ? AND attribute = ?", id, attr).Scan(&v)
  1808. switch {
  1809. case err == sql.ErrNoRows:
  1810. return false
  1811. case err != nil:
  1812. log.Error("Couldn't SELECT value in isCollectionAttributeOn for attribute '%s': %v", attr, err)
  1813. return false
  1814. }
  1815. return v == "1"
  1816. }
  1817. func (db *datastore) CollectionHasAttribute(id int64, attr string) bool {
  1818. var dummy string
  1819. err := db.QueryRow("SELECT value FROM collectionattributes WHERE collection_id = ? AND attribute = ?", id, attr).Scan(&dummy)
  1820. switch {
  1821. case err == sql.ErrNoRows:
  1822. return false
  1823. case err != nil:
  1824. log.Error("Couldn't SELECT value in collectionHasAttribute for attribute '%s': %v", attr, err)
  1825. return false
  1826. }
  1827. return true
  1828. }
  1829. func (db *datastore) DeleteAccount(userID int64) (l *string, err error) {
  1830. debug := ""
  1831. l = &debug
  1832. t, err := db.Begin()
  1833. if err != nil {
  1834. stringLogln(l, "Unable to begin: %v", err)
  1835. return
  1836. }
  1837. // Get all collections
  1838. rows, err := db.Query("SELECT id, alias FROM collections WHERE owner_id = ?", userID)
  1839. if err != nil {
  1840. t.Rollback()
  1841. stringLogln(l, "Unable to get collections: %v", err)
  1842. return
  1843. }
  1844. defer rows.Close()
  1845. colls := []Collection{}
  1846. var c Collection
  1847. for rows.Next() {
  1848. err = rows.Scan(&c.ID, &c.Alias)
  1849. if err != nil {
  1850. t.Rollback()
  1851. stringLogln(l, "Unable to scan collection cols: %v", err)
  1852. return
  1853. }
  1854. colls = append(colls, c)
  1855. }
  1856. var res sql.Result
  1857. for _, c := range colls {
  1858. // TODO: user deleteCollection() func
  1859. // Delete tokens
  1860. res, err = t.Exec("DELETE FROM collectionattributes WHERE collection_id = ?", c.ID)
  1861. if err != nil {
  1862. t.Rollback()
  1863. stringLogln(l, "Unable to delete attributes on %s: %v", c.Alias, err)
  1864. return
  1865. }
  1866. rs, _ := res.RowsAffected()
  1867. stringLogln(l, "Deleted %d for %s from collectionattributes", rs, c.Alias)
  1868. // Remove any optional collection password
  1869. res, err = t.Exec("DELETE FROM collectionpasswords WHERE collection_id = ?", c.ID)
  1870. if err != nil {
  1871. t.Rollback()
  1872. stringLogln(l, "Unable to delete passwords on %s: %v", c.Alias, err)
  1873. return
  1874. }
  1875. rs, _ = res.RowsAffected()
  1876. stringLogln(l, "Deleted %d for %s from collectionpasswords", rs, c.Alias)
  1877. // Remove redirects to this collection
  1878. res, err = t.Exec("DELETE FROM collectionredirects WHERE new_alias = ?", c.Alias)
  1879. if err != nil {
  1880. t.Rollback()
  1881. stringLogln(l, "Unable to delete redirects on %s: %v", c.Alias, err)
  1882. return
  1883. }
  1884. rs, _ = res.RowsAffected()
  1885. stringLogln(l, "Deleted %d for %s from collectionredirects", rs, c.Alias)
  1886. }
  1887. // Delete collections
  1888. res, err = t.Exec("DELETE FROM collections WHERE owner_id = ?", userID)
  1889. if err != nil {
  1890. t.Rollback()
  1891. stringLogln(l, "Unable to delete collections: %v", err)
  1892. return
  1893. }
  1894. rs, _ := res.RowsAffected()
  1895. stringLogln(l, "Deleted %d from collections", rs)
  1896. // Delete tokens
  1897. res, err = t.Exec("DELETE FROM accesstokens WHERE user_id = ?", userID)
  1898. if err != nil {
  1899. t.Rollback()
  1900. stringLogln(l, "Unable to delete access tokens: %v", err)
  1901. return
  1902. }
  1903. rs, _ = res.RowsAffected()
  1904. stringLogln(l, "Deleted %d from accesstokens", rs)
  1905. // Delete posts
  1906. res, err = t.Exec("DELETE FROM posts WHERE owner_id = ?", userID)
  1907. if err != nil {
  1908. t.Rollback()
  1909. stringLogln(l, "Unable to delete posts: %v", err)
  1910. return
  1911. }
  1912. rs, _ = res.RowsAffected()
  1913. stringLogln(l, "Deleted %d from posts", rs)
  1914. res, err = t.Exec("DELETE FROM userattributes WHERE user_id = ?", userID)
  1915. if err != nil {
  1916. t.Rollback()
  1917. stringLogln(l, "Unable to delete attributes: %v", err)
  1918. return
  1919. }
  1920. rs, _ = res.RowsAffected()
  1921. stringLogln(l, "Deleted %d from userattributes", rs)
  1922. res, err = t.Exec("DELETE FROM users WHERE id = ?", userID)
  1923. if err != nil {
  1924. t.Rollback()
  1925. stringLogln(l, "Unable to delete user: %v", err)
  1926. return
  1927. }
  1928. rs, _ = res.RowsAffected()
  1929. stringLogln(l, "Deleted %d from users", rs)
  1930. err = t.Commit()
  1931. if err != nil {
  1932. t.Rollback()
  1933. stringLogln(l, "Unable to commit: %v", err)
  1934. return
  1935. }
  1936. return
  1937. }
  1938. func (db *datastore) GetAPActorKeys(collectionID int64) ([]byte, []byte) {
  1939. var pub, priv []byte
  1940. err := db.QueryRow("SELECT public_key, private_key FROM collectionkeys WHERE collection_id = ?", collectionID).Scan(&pub, &priv)
  1941. switch {
  1942. case err == sql.ErrNoRows:
  1943. // Generate keys
  1944. pub, priv = activitypub.GenerateKeys()
  1945. _, err = db.Exec("INSERT INTO collectionkeys (collection_id, public_key, private_key) VALUES (?, ?, ?)", collectionID, pub, priv)
  1946. if err != nil {
  1947. log.Error("Unable to INSERT new activitypub keypair: %v", err)
  1948. return nil, nil
  1949. }
  1950. case err != nil:
  1951. log.Error("Couldn't SELECT collectionkeys: %v", err)
  1952. return nil, nil
  1953. }
  1954. return pub, priv
  1955. }
  1956. func (db *datastore) CreateUserInvite(id string, userID int64, maxUses int, expires *time.Time) error {
  1957. _, err := db.Exec("INSERT INTO userinvites (id, owner_id, max_uses, created, expires, inactive) VALUES (?, ?, ?, "+db.now()+", ?, 0)", id, userID, maxUses, expires)
  1958. return err
  1959. }
  1960. func (db *datastore) GetUserInvites(userID int64) (*[]Invite, error) {
  1961. rows, err := db.Query("SELECT id, max_uses, created, expires, inactive FROM userinvites WHERE owner_id = ? ORDER BY created DESC", userID)
  1962. if err != nil {
  1963. log.Error("Failed selecting from userinvites: %v", err)
  1964. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user invites."}
  1965. }
  1966. defer rows.Close()
  1967. is := []Invite{}
  1968. for rows.Next() {
  1969. i := Invite{}
  1970. err = rows.Scan(&i.ID, &i.MaxUses, &i.Created, &i.Expires, &i.Inactive)
  1971. is = append(is, i)
  1972. }
  1973. return &is, nil
  1974. }
  1975. func (db *datastore) GetUserInvite(id string) (*Invite, error) {
  1976. var i Invite
  1977. err := db.QueryRow("SELECT id, max_uses, created, expires, inactive FROM userinvites WHERE id = ?", id).Scan(&i.ID, &i.MaxUses, &i.Created, &i.Expires, &i.Inactive)
  1978. switch {
  1979. case err == sql.ErrNoRows:
  1980. return nil, impart.HTTPError{http.StatusNotFound, "Invite doesn't exist."}
  1981. case err != nil:
  1982. log.Error("Failed selecting invite: %v", err)
  1983. return nil, err
  1984. }
  1985. return &i, nil
  1986. }
  1987. func (db *datastore) GetUsersInvitedCount(id string) int64 {
  1988. var count int64
  1989. err := db.QueryRow("SELECT COUNT(*) FROM usersinvited WHERE invite_id = ?", id).Scan(&count)
  1990. switch {
  1991. case err == sql.ErrNoRows:
  1992. return 0
  1993. case err != nil:
  1994. log.Error("Failed selecting users invited count: %v", err)
  1995. return 0
  1996. }
  1997. return count
  1998. }
  1999. func (db *datastore) CreateInvitedUser(inviteID string, userID int64) error {
  2000. _, err := db.Exec("INSERT INTO usersinvited (invite_id, user_id) VALUES (?, ?)", inviteID, userID)
  2001. return err
  2002. }
  2003. func (db *datastore) GetInstancePages() ([]*instanceContent, error) {
  2004. return db.GetAllDynamicContent("page")
  2005. }
  2006. func (db *datastore) GetAllDynamicContent(t string) ([]*instanceContent, error) {
  2007. where := ""
  2008. params := []interface{}{}
  2009. if t != "" {
  2010. where = " WHERE content_type = ?"
  2011. params = append(params, t)
  2012. }
  2013. rows, err := db.Query("SELECT id, title, content, updated, content_type FROM appcontent"+where, params...)
  2014. if err != nil {
  2015. log.Error("Failed selecting from appcontent: %v", err)
  2016. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve instance pages."}
  2017. }
  2018. defer rows.Close()
  2019. pages := []*instanceContent{}
  2020. for rows.Next() {
  2021. c := &instanceContent{}
  2022. err = rows.Scan(&c.ID, &c.Title, &c.Content, &c.Updated, &c.Type)
  2023. if err != nil {
  2024. log.Error("Failed scanning row: %v", err)
  2025. break
  2026. }
  2027. pages = append(pages, c)
  2028. }
  2029. err = rows.Err()
  2030. if err != nil {
  2031. log.Error("Error after Next() on rows: %v", err)
  2032. }
  2033. return pages, nil
  2034. }
  2035. func (db *datastore) GetDynamicContent(id string) (*instanceContent, error) {
  2036. c := &instanceContent{
  2037. ID: id,
  2038. }
  2039. err := db.QueryRow("SELECT title, content, updated, content_type FROM appcontent WHERE id = ?", id).Scan(&c.Title, &c.Content, &c.Updated, &c.Type)
  2040. switch {
  2041. case err == sql.ErrNoRows:
  2042. return nil, nil
  2043. case err != nil:
  2044. log.Error("Couldn't SELECT FROM appcontent for id '%s': %v", id, err)
  2045. return nil, err
  2046. }
  2047. return c, nil
  2048. }
  2049. func (db *datastore) UpdateDynamicContent(id, title, content, contentType string) error {
  2050. var err error
  2051. if db.driverName == driverSQLite {
  2052. _, err = db.Exec("INSERT OR REPLACE INTO appcontent (id, title, content, updated, content_type) VALUES (?, ?, ?, "+db.now()+", ?)", id, title, content, contentType)
  2053. } else {
  2054. _, err = db.Exec("INSERT INTO appcontent (id, title, content, updated, content_type) VALUES (?, ?, ?, "+db.now()+", ?) "+db.upsert("id")+" title = ?, content = ?, updated = "+db.now(), id, title, content, contentType, title, content)
  2055. }
  2056. if err != nil {
  2057. log.Error("Unable to INSERT appcontent for '%s': %v", id, err)
  2058. }
  2059. return err
  2060. }
  2061. func (db *datastore) GetAllUsers(page uint) (*[]User, error) {
  2062. limitStr := fmt.Sprintf("0, %d", adminUsersPerPage)
  2063. if page > 1 {
  2064. limitStr = fmt.Sprintf("%d, %d", (page-1)*adminUsersPerPage, adminUsersPerPage)
  2065. }
  2066. rows, err := db.Query("SELECT id, username, created FROM users ORDER BY created DESC LIMIT " + limitStr)
  2067. if err != nil {
  2068. log.Error("Failed selecting from posts: %v", err)
  2069. return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve user posts."}
  2070. }
  2071. defer rows.Close()
  2072. users := []User{}
  2073. for rows.Next() {
  2074. u := User{}
  2075. err = rows.Scan(&u.ID, &u.Username, &u.Created)
  2076. if err != nil {
  2077. log.Error("Failed scanning GetAllUsers() row: %v", err)
  2078. break
  2079. }
  2080. users = append(users, u)
  2081. }
  2082. return &users, nil
  2083. }
  2084. func (db *datastore) GetAllUsersCount() int64 {
  2085. var count int64
  2086. err := db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
  2087. switch {
  2088. case err == sql.ErrNoRows:
  2089. return 0
  2090. case err != nil:
  2091. log.Error("Failed selecting all users count: %v", err)
  2092. return 0
  2093. }
  2094. return count
  2095. }
  2096. func (db *datastore) GetUserLastPostTime(id int64) (*time.Time, error) {
  2097. var t time.Time
  2098. err := db.QueryRow("SELECT created FROM posts WHERE owner_id = ? ORDER BY created DESC LIMIT 1", id).Scan(&t)
  2099. switch {
  2100. case err == sql.ErrNoRows:
  2101. return nil, nil
  2102. case err != nil:
  2103. log.Error("Failed selecting last post time from posts: %v", err)
  2104. return nil, err
  2105. }
  2106. return &t, nil
  2107. }
  2108. func (db *datastore) GetCollectionLastPostTime(id int64) (*time.Time, error) {
  2109. var t time.Time
  2110. err := db.QueryRow("SELECT created FROM posts WHERE collection_id = ? ORDER BY created DESC LIMIT 1", id).Scan(&t)
  2111. switch {
  2112. case err == sql.ErrNoRows:
  2113. return nil, nil
  2114. case err != nil:
  2115. log.Error("Failed selecting last post time from posts: %v", err)
  2116. return nil, err
  2117. }
  2118. return &t, nil
  2119. }
  2120. // DatabaseInitialized returns whether or not the current datastore has been
  2121. // initialized with the correct schema.
  2122. // Currently, it checks to see if the `users` table exists.
  2123. func (db *datastore) DatabaseInitialized() bool {
  2124. var dummy string
  2125. var err error
  2126. if db.driverName == driverSQLite {
  2127. err = db.QueryRow("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'users'").Scan(&dummy)
  2128. } else {
  2129. err = db.QueryRow("SHOW TABLES LIKE 'users'").Scan(&dummy)
  2130. }
  2131. switch {
  2132. case err == sql.ErrNoRows:
  2133. return false
  2134. case err != nil:
  2135. log.Error("Couldn't SHOW TABLES: %v", err)
  2136. return false
  2137. }
  2138. return true
  2139. }
  2140. func stringLogln(log *string, s string, v ...interface{}) {
  2141. *log += fmt.Sprintf(s+"\n", v...)
  2142. }
  2143. func handleFailedPostInsert(err error) error {
  2144. log.Error("Couldn't insert into posts: %v", err)
  2145. return err
  2146. }