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.
 
 
 
 
 

2787 lines
85 KiB

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