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.

835 lines
23 KiB

6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. const Model = require('objection').Model
  2. const _ = require('lodash')
  3. const JSBinType = require('js-binary').Type
  4. const pageHelper = require('../helpers/page')
  5. const path = require('path')
  6. const fs = require('fs-extra')
  7. const yaml = require('js-yaml')
  8. const striptags = require('striptags')
  9. const emojiRegex = require('emoji-regex')
  10. const he = require('he')
  11. /* global WIKI */
  12. const frontmatterRegex = {
  13. html: /^(<!-{2}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{2}>)?(?:\n|\r)*([\w\W]*)*/,
  14. legacy: /^(<!-- TITLE: ?([\w\W]+?) -{2}>)?(?:\n|\r)?(<!-- SUBTITLE: ?([\w\W]+?) -{2}>)?(?:\n|\r)*([\w\W]*)*/i,
  15. markdown: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?(?:\n|\r)*([\w\W]*)*/
  16. }
  17. const punctuationRegex = /[!,:;/\\_+\-=()&#@<>$~%^*[\]{}"'|]+|(\.\s)|(\s\.)/ig
  18. // const htmlEntitiesRegex = /(&#[0-9]{3};)|(&#x[a-zA-Z0-9]{2};)/ig
  19. /**
  20. * Pages model
  21. */
  22. module.exports = class Page extends Model {
  23. static get tableName() { return 'pages' }
  24. static get jsonSchema () {
  25. return {
  26. type: 'object',
  27. required: ['path', 'title'],
  28. properties: {
  29. id: {type: 'integer'},
  30. path: {type: 'string'},
  31. hash: {type: 'string'},
  32. title: {type: 'string'},
  33. description: {type: 'string'},
  34. isPublished: {type: 'boolean'},
  35. privateNS: {type: 'string'},
  36. publishStartDate: {type: 'string'},
  37. publishEndDate: {type: 'string'},
  38. content: {type: 'string'},
  39. contentType: {type: 'string'},
  40. createdAt: {type: 'string'},
  41. updatedAt: {type: 'string'}
  42. }
  43. }
  44. }
  45. static get relationMappings() {
  46. return {
  47. tags: {
  48. relation: Model.ManyToManyRelation,
  49. modelClass: require('./tags'),
  50. join: {
  51. from: 'pages.id',
  52. through: {
  53. from: 'pageTags.pageId',
  54. to: 'pageTags.tagId'
  55. },
  56. to: 'tags.id'
  57. }
  58. },
  59. links: {
  60. relation: Model.HasManyRelation,
  61. modelClass: require('./pageLinks'),
  62. join: {
  63. from: 'pages.id',
  64. to: 'pageLinks.pageId'
  65. }
  66. },
  67. author: {
  68. relation: Model.BelongsToOneRelation,
  69. modelClass: require('./users'),
  70. join: {
  71. from: 'pages.authorId',
  72. to: 'users.id'
  73. }
  74. },
  75. creator: {
  76. relation: Model.BelongsToOneRelation,
  77. modelClass: require('./users'),
  78. join: {
  79. from: 'pages.creatorId',
  80. to: 'users.id'
  81. }
  82. },
  83. editor: {
  84. relation: Model.BelongsToOneRelation,
  85. modelClass: require('./editors'),
  86. join: {
  87. from: 'pages.editorKey',
  88. to: 'editors.key'
  89. }
  90. },
  91. locale: {
  92. relation: Model.BelongsToOneRelation,
  93. modelClass: require('./locales'),
  94. join: {
  95. from: 'pages.localeCode',
  96. to: 'locales.code'
  97. }
  98. }
  99. }
  100. }
  101. $beforeUpdate() {
  102. this.updatedAt = new Date().toISOString()
  103. }
  104. $beforeInsert() {
  105. this.createdAt = new Date().toISOString()
  106. this.updatedAt = new Date().toISOString()
  107. }
  108. /**
  109. * Cache Schema
  110. */
  111. static get cacheSchema() {
  112. return new JSBinType({
  113. id: 'uint',
  114. authorId: 'uint',
  115. authorName: 'string',
  116. createdAt: 'string',
  117. creatorId: 'uint',
  118. creatorName: 'string',
  119. description: 'string',
  120. isPrivate: 'boolean',
  121. isPublished: 'boolean',
  122. publishEndDate: 'string',
  123. publishStartDate: 'string',
  124. render: 'string',
  125. tags: [
  126. {
  127. tag: 'string',
  128. title: 'string'
  129. }
  130. ],
  131. title: 'string',
  132. toc: 'string',
  133. updatedAt: 'string'
  134. })
  135. }
  136. /**
  137. * Inject page metadata into contents
  138. *
  139. * @returns {string} Page Contents with Injected Metadata
  140. */
  141. injectMetadata () {
  142. return pageHelper.injectPageMetadata(this)
  143. }
  144. /**
  145. * Get the page's file extension based on content type
  146. *
  147. * @returns {string} File Extension
  148. */
  149. getFileExtension() {
  150. return pageHelper.getFileExtension(this.contentType)
  151. }
  152. /**
  153. * Parse injected page metadata from raw content
  154. *
  155. * @param {String} raw Raw file contents
  156. * @param {String} contentType Content Type
  157. * @returns {Object} Parsed Page Metadata with Raw Content
  158. */
  159. static parseMetadata (raw, contentType) {
  160. let result
  161. switch (contentType) {
  162. case 'markdown':
  163. result = frontmatterRegex.markdown.exec(raw)
  164. if (result[2]) {
  165. return {
  166. ...yaml.safeLoad(result[2]),
  167. content: result[3]
  168. }
  169. } else {
  170. // Attempt legacy v1 format
  171. result = frontmatterRegex.legacy.exec(raw)
  172. if (result[2]) {
  173. return {
  174. title: result[2],
  175. description: result[4],
  176. content: result[5]
  177. }
  178. }
  179. }
  180. break
  181. case 'html':
  182. result = frontmatterRegex.html.exec(raw)
  183. if (result[2]) {
  184. return {
  185. ...yaml.safeLoad(result[2]),
  186. content: result[3]
  187. }
  188. }
  189. break
  190. }
  191. return {
  192. content: raw
  193. }
  194. }
  195. /**
  196. * Create a New Page
  197. *
  198. * @param {Object} opts Page Properties
  199. * @returns {Promise} Promise of the Page Model Instance
  200. */
  201. static async createPage(opts) {
  202. // -> Validate path
  203. if (opts.path.indexOf('.') >= 0 || opts.path.indexOf(' ') >= 0) {
  204. throw new WIKI.Error.PageIllegalPath()
  205. }
  206. // -> Check for page access
  207. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  208. locale: opts.locale,
  209. path: opts.path
  210. })) {
  211. throw new WIKI.Error.PageDeleteForbidden()
  212. }
  213. // -> Check for duplicate
  214. const dupCheck = await WIKI.models.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
  215. if (dupCheck) {
  216. throw new WIKI.Error.PageDuplicateCreate()
  217. }
  218. // -> Check for empty content
  219. if (!opts.content || _.trim(opts.content).length < 1) {
  220. throw new WIKI.Error.PageEmptyContent()
  221. }
  222. // -> Create page
  223. await WIKI.models.pages.query().insert({
  224. authorId: opts.user.id,
  225. content: opts.content,
  226. creatorId: opts.user.id,
  227. contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
  228. description: opts.description,
  229. editorKey: opts.editor,
  230. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
  231. isPrivate: opts.isPrivate,
  232. isPublished: opts.isPublished,
  233. localeCode: opts.locale,
  234. path: opts.path,
  235. publishEndDate: opts.publishEndDate || '',
  236. publishStartDate: opts.publishStartDate || '',
  237. title: opts.title,
  238. toc: '[]'
  239. })
  240. const page = await WIKI.models.pages.getPageFromDb({
  241. path: opts.path,
  242. locale: opts.locale,
  243. userId: opts.user.id,
  244. isPrivate: opts.isPrivate
  245. })
  246. // -> Save Tags
  247. if (opts.tags && opts.tags.length > 0) {
  248. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  249. }
  250. // -> Render page to HTML
  251. await WIKI.models.pages.renderPage(page)
  252. // -> Rebuild page tree
  253. await WIKI.models.pages.rebuildTree()
  254. // -> Add to Search Index
  255. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  256. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  257. await WIKI.data.searchEngine.created(page)
  258. // -> Add to Storage
  259. if (!opts.skipStorage) {
  260. await WIKI.models.storage.pageEvent({
  261. event: 'created',
  262. page
  263. })
  264. }
  265. // -> Reconnect Links
  266. await WIKI.models.pages.reconnectLinks({
  267. locale: page.localeCode,
  268. path: page.path,
  269. mode: 'create'
  270. })
  271. return page
  272. }
  273. /**
  274. * Update an Existing Page
  275. *
  276. * @param {Object} opts Page Properties
  277. * @returns {Promise} Promise of the Page Model Instance
  278. */
  279. static async updatePage(opts) {
  280. // -> Fetch original page
  281. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  282. if (!ogPage) {
  283. throw new Error('Invalid Page Id')
  284. }
  285. // -> Check for page access
  286. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  287. locale: opts.locale,
  288. path: opts.path
  289. })) {
  290. throw new WIKI.Error.PageUpdateForbidden()
  291. }
  292. // -> Check for empty content
  293. if (!opts.content || _.trim(opts.content).length < 1) {
  294. throw new WIKI.Error.PageEmptyContent()
  295. }
  296. // -> Create version snapshot
  297. await WIKI.models.pageHistory.addVersion({
  298. ...ogPage,
  299. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  300. action: 'updated'
  301. })
  302. // -> Update page
  303. await WIKI.models.pages.query().patch({
  304. authorId: opts.user.id,
  305. content: opts.content,
  306. description: opts.description,
  307. isPublished: opts.isPublished === true || opts.isPublished === 1,
  308. publishEndDate: opts.publishEndDate || '',
  309. publishStartDate: opts.publishStartDate || '',
  310. title: opts.title
  311. }).where('id', ogPage.id)
  312. let page = await WIKI.models.pages.getPageFromDb({
  313. path: ogPage.path,
  314. locale: ogPage.localeCode,
  315. userId: ogPage.authorId,
  316. isPrivate: ogPage.isPrivate
  317. })
  318. // -> Save Tags
  319. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  320. // -> Render page to HTML
  321. await WIKI.models.pages.renderPage(page)
  322. // -> Update Search Index
  323. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  324. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  325. await WIKI.data.searchEngine.updated(page)
  326. // -> Update on Storage
  327. if (!opts.skipStorage) {
  328. await WIKI.models.storage.pageEvent({
  329. event: 'updated',
  330. page
  331. })
  332. }
  333. // -> Perform move?
  334. if ((opts.locale && opts.locale !== page.localeCode) || (opts.path && opts.path !== page.path)) {
  335. await WIKI.models.pages.movePage({
  336. id: page.id,
  337. destinationLocale: opts.locale,
  338. destinationPath: opts.path,
  339. user: opts.user
  340. })
  341. } else {
  342. // -> Update title of page tree entry
  343. await WIKI.models.knex.table('pageTree').where({
  344. pageId: page.id
  345. }).update('title', page.title)
  346. }
  347. return page
  348. }
  349. /**
  350. * Move a Page
  351. *
  352. * @param {Object} opts Page Properties
  353. * @returns {Promise} Promise with no value
  354. */
  355. static async movePage(opts) {
  356. const page = await WIKI.models.pages.query().findById(opts.id)
  357. if (!page) {
  358. throw new WIKI.Error.PageNotFound()
  359. }
  360. // -> Check for source page access
  361. if (!WIKI.auth.checkAccess(opts.user, ['manage:pages'], {
  362. locale: page.sourceLocale,
  363. path: page.sourcePath
  364. })) {
  365. throw new WIKI.Error.PageMoveForbidden()
  366. }
  367. // -> Check for destination page access
  368. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  369. locale: opts.destinationLocale,
  370. path: opts.destinationPath
  371. })) {
  372. throw new WIKI.Error.PageMoveForbidden()
  373. }
  374. // -> Check for existing page at destination path
  375. const destPage = await await WIKI.models.pages.query().findOne({
  376. path: opts.destinationPath,
  377. localeCode: opts.destinationLocale
  378. })
  379. if (destPage) {
  380. throw new WIKI.Error.PagePathCollision()
  381. }
  382. // -> Create version snapshot
  383. await WIKI.models.pageHistory.addVersion({
  384. ...page,
  385. action: 'moved'
  386. })
  387. const destinationHash = pageHelper.generateHash({ path: opts.destinationPath, locale: opts.destinationLocale, privateNS: opts.isPrivate ? 'TODO' : '' })
  388. // -> Move page
  389. await WIKI.models.pages.query().patch({
  390. path: opts.destinationPath,
  391. localeCode: opts.destinationLocale,
  392. hash: destinationHash
  393. }).findById(page.id)
  394. await WIKI.models.pages.deletePageFromCache(page)
  395. // -> Rebuild page tree
  396. await WIKI.models.pages.rebuildTree()
  397. // -> Rename in Search Index
  398. await WIKI.data.searchEngine.renamed({
  399. ...page,
  400. destinationPath: opts.destinationPath,
  401. destinationLocaleCode: opts.destinationLocale,
  402. destinationHash
  403. })
  404. // -> Rename in Storage
  405. if (!opts.skipStorage) {
  406. await WIKI.models.storage.pageEvent({
  407. event: 'renamed',
  408. page: {
  409. ...page,
  410. destinationPath: opts.destinationPath,
  411. destinationLocaleCode: opts.destinationLocale,
  412. destinationHash,
  413. moveAuthorId: opts.user.id,
  414. moveAuthorName: opts.user.name,
  415. moveAuthorEmail: opts.user.email
  416. }
  417. })
  418. }
  419. // -> Reconnect Links
  420. await WIKI.models.pages.reconnectLinks({
  421. sourceLocale: page.localeCode,
  422. sourcePath: page.path,
  423. locale: opts.destinationLocale,
  424. path: opts.destinationPath,
  425. mode: 'move'
  426. })
  427. }
  428. /**
  429. * Delete an Existing Page
  430. *
  431. * @param {Object} opts Page Properties
  432. * @returns {Promise} Promise with no value
  433. */
  434. static async deletePage(opts) {
  435. let page
  436. if (_.has(opts, 'id')) {
  437. page = await WIKI.models.pages.query().findById(opts.id)
  438. } else {
  439. page = await await WIKI.models.pages.query().findOne({
  440. path: opts.path,
  441. localeCode: opts.locale
  442. })
  443. }
  444. if (!page) {
  445. throw new Error('Invalid Page Id')
  446. }
  447. // -> Check for page access
  448. if (!WIKI.auth.checkAccess(opts.user, ['delete:pages'], {
  449. locale: page.locale,
  450. path: page.path
  451. })) {
  452. throw new WIKI.Error.PageDeleteForbidden()
  453. }
  454. // -> Create version snapshot
  455. await WIKI.models.pageHistory.addVersion({
  456. ...page,
  457. action: 'deleted'
  458. })
  459. // -> Delete page
  460. await WIKI.models.pages.query().delete().where('id', page.id)
  461. await WIKI.models.pages.deletePageFromCache(page)
  462. // -> Rebuild page tree
  463. await WIKI.models.pages.rebuildTree()
  464. // -> Delete from Search Index
  465. await WIKI.data.searchEngine.deleted(page)
  466. // -> Delete from Storage
  467. if (!opts.skipStorage) {
  468. await WIKI.models.storage.pageEvent({
  469. event: 'deleted',
  470. page
  471. })
  472. }
  473. // -> Reconnect Links
  474. await WIKI.models.pages.reconnectLinks({
  475. locale: page.localeCode,
  476. path: page.path,
  477. mode: 'delete'
  478. })
  479. }
  480. /**
  481. * Reconnect links to new/move/deleted page
  482. *
  483. * @param {Object} opts - Page parameters
  484. * @param {string} opts.path - Page Path
  485. * @param {string} opts.locale - Page Locale Code
  486. * @param {string} [opts.sourcePath] - Previous Page Path (move only)
  487. * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
  488. * @param {string} opts.mode - Page Update mode (create, move, delete)
  489. * @returns {Promise} Promise with no value
  490. */
  491. static async reconnectLinks (opts) {
  492. const pageHref = `/${opts.locale}/${opts.path}`
  493. let replaceArgs = {
  494. from: '',
  495. to: ''
  496. }
  497. switch (opts.mode) {
  498. case 'create':
  499. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  500. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  501. break
  502. case 'move':
  503. const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
  504. replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-invalid-page">`
  505. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  506. break
  507. case 'delete':
  508. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  509. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  510. break
  511. default:
  512. return false
  513. }
  514. let affectedHashes = []
  515. // -> Perform replace and return affected page hashes (POSTGRES, MSSQL only)
  516. if (WIKI.config.db.type === 'postgres' || WIKI.config.db.type === 'mssql') {
  517. affectedHashes = await WIKI.models.pages.query()
  518. .returning('hash')
  519. .patch({
  520. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  521. })
  522. .whereIn('pages.id', function () {
  523. this.select('pageLinks.pageId').from('pageLinks').where({
  524. 'pageLinks.path': opts.path,
  525. 'pageLinks.localeCode': opts.locale
  526. })
  527. })
  528. .pluck('hash')
  529. } else {
  530. // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, SQLITE only)
  531. await WIKI.models.pages.query()
  532. .patch({
  533. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  534. })
  535. .whereIn('pages.id', function () {
  536. this.select('pageLinks.pageId').from('pageLinks').where({
  537. 'pageLinks.path': opts.path,
  538. 'pageLinks.localeCode': opts.locale
  539. })
  540. })
  541. affectedHashes = await WIKI.models.pages.query()
  542. .column('hash')
  543. .whereIn('pages.id', function () {
  544. this.select('pageLinks.pageId').from('pageLinks').where({
  545. 'pageLinks.path': opts.path,
  546. 'pageLinks.localeCode': opts.locale
  547. })
  548. })
  549. .pluck('hash')
  550. }
  551. for (const hash of affectedHashes) {
  552. await WIKI.models.pages.deletePageFromCache({ hash })
  553. }
  554. }
  555. /**
  556. * Rebuild page tree for new/updated/deleted page
  557. *
  558. * @returns {Promise} Promise with no value
  559. */
  560. static async rebuildTree() {
  561. const rebuildJob = await WIKI.scheduler.registerJob({
  562. name: 'rebuild-tree',
  563. immediate: true,
  564. worker: true
  565. })
  566. return rebuildJob.finished
  567. }
  568. /**
  569. * Trigger the rendering of a page
  570. *
  571. * @param {Object} page Page Model Instance
  572. * @returns {Promise} Promise with no value
  573. */
  574. static async renderPage(page) {
  575. const renderJob = await WIKI.scheduler.registerJob({
  576. name: 'render-page',
  577. immediate: true,
  578. worker: true
  579. }, page.id)
  580. return renderJob.finished
  581. }
  582. /**
  583. * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
  584. *
  585. * @param {Object} opts Page Properties
  586. * @returns {Promise} Promise of the Page Model Instance
  587. */
  588. static async getPage(opts) {
  589. // -> Get from cache first
  590. let page = await WIKI.models.pages.getPageFromCache(opts)
  591. if (!page) {
  592. // -> Get from DB
  593. page = await WIKI.models.pages.getPageFromDb(opts)
  594. if (page) {
  595. if (page.render) {
  596. // -> Save render to cache
  597. await WIKI.models.pages.savePageToCache(page)
  598. } else {
  599. // -> No render? Possible duplicate issue
  600. /* TODO: Detect duplicate and delete */
  601. throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
  602. }
  603. }
  604. }
  605. return page
  606. }
  607. /**
  608. * Fetch an Existing Page from the Database
  609. *
  610. * @param {Object} opts Page Properties
  611. * @returns {Promise} Promise of the Page Model Instance
  612. */
  613. static async getPageFromDb(opts) {
  614. const queryModeID = _.isNumber(opts)
  615. try {
  616. return WIKI.models.pages.query()
  617. .column([
  618. 'pages.*',
  619. {
  620. authorName: 'author.name',
  621. authorEmail: 'author.email',
  622. creatorName: 'creator.name',
  623. creatorEmail: 'creator.email'
  624. }
  625. ])
  626. .joinRelation('author')
  627. .joinRelation('creator')
  628. .eagerAlgorithm(Model.JoinEagerAlgorithm)
  629. .eager('tags(selectTags)', {
  630. selectTags: builder => {
  631. builder.select('tag', 'title')
  632. }
  633. })
  634. .where(queryModeID ? {
  635. 'pages.id': opts
  636. } : {
  637. 'pages.path': opts.path,
  638. 'pages.localeCode': opts.locale
  639. })
  640. // .andWhere(builder => {
  641. // if (queryModeID) return
  642. // builder.where({
  643. // 'pages.isPublished': true
  644. // }).orWhere({
  645. // 'pages.isPublished': false,
  646. // 'pages.authorId': opts.userId
  647. // })
  648. // })
  649. // .andWhere(builder => {
  650. // if (queryModeID) return
  651. // if (opts.isPrivate) {
  652. // builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  653. // } else {
  654. // builder.where({ 'pages.isPrivate': false })
  655. // }
  656. // })
  657. .first()
  658. } catch (err) {
  659. WIKI.logger.warn(err)
  660. throw err
  661. }
  662. }
  663. /**
  664. * Save a Page Model Instance to Cache
  665. *
  666. * @param {Object} page Page Model Instance
  667. * @returns {Promise} Promise with no value
  668. */
  669. static async savePageToCache(page) {
  670. const cachePath = path.join(process.cwd(), `data/cache/${page.hash}.bin`)
  671. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  672. id: page.id,
  673. authorId: page.authorId,
  674. authorName: page.authorName,
  675. createdAt: page.createdAt,
  676. creatorId: page.creatorId,
  677. creatorName: page.creatorName,
  678. description: page.description,
  679. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  680. isPublished: page.isPublished === 1 || page.isPublished === true,
  681. publishEndDate: page.publishEndDate,
  682. publishStartDate: page.publishStartDate,
  683. render: page.render,
  684. tags: page.tags.map(t => _.pick(t, ['tag', 'title'])),
  685. title: page.title,
  686. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  687. updatedAt: page.updatedAt
  688. }))
  689. }
  690. /**
  691. * Fetch an Existing Page from Cache
  692. *
  693. * @param {Object} opts Page Properties
  694. * @returns {Promise} Promise of the Page Model Instance
  695. */
  696. static async getPageFromCache(opts) {
  697. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  698. const cachePath = path.join(process.cwd(), `data/cache/${pageHash}.bin`)
  699. try {
  700. const pageBuffer = await fs.readFile(cachePath)
  701. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  702. return {
  703. ...page,
  704. path: opts.path,
  705. localeCode: opts.locale,
  706. isPrivate: opts.isPrivate
  707. }
  708. } catch (err) {
  709. if (err.code === 'ENOENT') {
  710. return false
  711. }
  712. WIKI.logger.error(err)
  713. throw err
  714. }
  715. }
  716. /**
  717. * Delete an Existing Page from Cache
  718. *
  719. * @param {Object} page Page Model Instance
  720. * @param {string} page.hash Hash of the Page
  721. * @returns {Promise} Promise with no value
  722. */
  723. static async deletePageFromCache(page) {
  724. return fs.remove(path.join(process.cwd(), `data/cache/${page.hash}.bin`))
  725. }
  726. /**
  727. * Flush the contents of the Cache
  728. */
  729. static async flushCache() {
  730. return fs.emptyDir(path.join(process.cwd(), `data/cache`))
  731. }
  732. /**
  733. * Migrate all pages from a source locale to the target locale
  734. *
  735. * @param {Object} opts Migration properties
  736. * @param {string} opts.sourceLocale Source Locale Code
  737. * @param {string} opts.targetLocale Target Locale Code
  738. * @returns {Promise} Promise with no value
  739. */
  740. static async migrateToLocale({ sourceLocale, targetLocale }) {
  741. return WIKI.models.pages.query()
  742. .patch({
  743. localeCode: targetLocale
  744. })
  745. .where({
  746. localeCode: sourceLocale
  747. })
  748. .whereNotExists(function() {
  749. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  750. })
  751. }
  752. /**
  753. * Clean raw HTML from content for use in search engines
  754. *
  755. * @param {string} rawHTML Raw HTML
  756. * @returns {string} Cleaned Content Text
  757. */
  758. static cleanHTML(rawHTML = '') {
  759. let data = striptags(rawHTML || '')
  760. .replace(emojiRegex(), '')
  761. // .replace(htmlEntitiesRegex, '')
  762. return he.decode(data)
  763. .replace(punctuationRegex, ' ')
  764. .replace(/(\r\n|\n|\r)/gm, ' ')
  765. .replace(/\s\s+/g, ' ')
  766. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  767. }
  768. }