A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 

2434 wiersze
73 KiB

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