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

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