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.
 
 
 
 
 

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