pages.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  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. // -> Get latest updatedAt
  272. page.updatedAt = await WIKI.models.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)
  273. return page
  274. }
  275. /**
  276. * Update an Existing Page
  277. *
  278. * @param {Object} opts Page Properties
  279. * @returns {Promise} Promise of the Page Model Instance
  280. */
  281. static async updatePage(opts) {
  282. // -> Fetch original page
  283. const ogPage = await WIKI.models.pages.query().findById(opts.id)
  284. if (!ogPage) {
  285. throw new Error('Invalid Page Id')
  286. }
  287. // -> Check for page access
  288. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  289. locale: opts.locale,
  290. path: opts.path
  291. })) {
  292. throw new WIKI.Error.PageUpdateForbidden()
  293. }
  294. // -> Check for empty content
  295. if (!opts.content || _.trim(opts.content).length < 1) {
  296. throw new WIKI.Error.PageEmptyContent()
  297. }
  298. // -> Create version snapshot
  299. await WIKI.models.pageHistory.addVersion({
  300. ...ogPage,
  301. isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
  302. action: opts.action ? opts.action : 'updated',
  303. versionDate: ogPage.updatedAt
  304. })
  305. // -> Update page
  306. await WIKI.models.pages.query().patch({
  307. authorId: opts.user.id,
  308. content: opts.content,
  309. description: opts.description,
  310. isPublished: opts.isPublished === true || opts.isPublished === 1,
  311. publishEndDate: opts.publishEndDate || '',
  312. publishStartDate: opts.publishStartDate || '',
  313. title: opts.title
  314. }).where('id', ogPage.id)
  315. let page = await WIKI.models.pages.getPageFromDb(ogPage.id)
  316. // -> Save Tags
  317. await WIKI.models.tags.associateTags({ tags: opts.tags, page })
  318. // -> Render page to HTML
  319. await WIKI.models.pages.renderPage(page)
  320. // -> Update Search Index
  321. const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
  322. page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
  323. await WIKI.data.searchEngine.updated(page)
  324. // -> Update on Storage
  325. if (!opts.skipStorage) {
  326. await WIKI.models.storage.pageEvent({
  327. event: 'updated',
  328. page
  329. })
  330. }
  331. // -> Perform move?
  332. if ((opts.locale && opts.locale !== page.localeCode) || (opts.path && opts.path !== page.path)) {
  333. await WIKI.models.pages.movePage({
  334. id: page.id,
  335. destinationLocale: opts.locale,
  336. destinationPath: opts.path,
  337. user: opts.user
  338. })
  339. } else {
  340. // -> Update title of page tree entry
  341. await WIKI.models.knex.table('pageTree').where({
  342. pageId: page.id
  343. }).update('title', page.title)
  344. }
  345. // -> Get latest updatedAt
  346. page.updatedAt = await WIKI.models.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)
  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. versionDate: page.updatedAt
  387. })
  388. const destinationHash = pageHelper.generateHash({ path: opts.destinationPath, locale: opts.destinationLocale, privateNS: opts.isPrivate ? 'TODO' : '' })
  389. // -> Move page
  390. await WIKI.models.pages.query().patch({
  391. path: opts.destinationPath,
  392. localeCode: opts.destinationLocale,
  393. hash: destinationHash
  394. }).findById(page.id)
  395. await WIKI.models.pages.deletePageFromCache(page)
  396. // -> Rebuild page tree
  397. await WIKI.models.pages.rebuildTree()
  398. // -> Rename in Search Index
  399. await WIKI.data.searchEngine.renamed({
  400. ...page,
  401. destinationPath: opts.destinationPath,
  402. destinationLocaleCode: opts.destinationLocale,
  403. destinationHash
  404. })
  405. // -> Rename in Storage
  406. if (!opts.skipStorage) {
  407. await WIKI.models.storage.pageEvent({
  408. event: 'renamed',
  409. page: {
  410. ...page,
  411. destinationPath: opts.destinationPath,
  412. destinationLocaleCode: opts.destinationLocale,
  413. destinationHash,
  414. moveAuthorId: opts.user.id,
  415. moveAuthorName: opts.user.name,
  416. moveAuthorEmail: opts.user.email
  417. }
  418. })
  419. }
  420. // -> Reconnect Links
  421. await WIKI.models.pages.reconnectLinks({
  422. sourceLocale: page.localeCode,
  423. sourcePath: page.path,
  424. locale: opts.destinationLocale,
  425. path: opts.destinationPath,
  426. mode: 'move'
  427. })
  428. }
  429. /**
  430. * Delete an Existing Page
  431. *
  432. * @param {Object} opts Page Properties
  433. * @returns {Promise} Promise with no value
  434. */
  435. static async deletePage(opts) {
  436. let page
  437. if (_.has(opts, 'id')) {
  438. page = await WIKI.models.pages.query().findById(opts.id)
  439. } else {
  440. page = await await WIKI.models.pages.query().findOne({
  441. path: opts.path,
  442. localeCode: opts.locale
  443. })
  444. }
  445. if (!page) {
  446. throw new Error('Invalid Page Id')
  447. }
  448. // -> Check for page access
  449. if (!WIKI.auth.checkAccess(opts.user, ['delete:pages'], {
  450. locale: page.locale,
  451. path: page.path
  452. })) {
  453. throw new WIKI.Error.PageDeleteForbidden()
  454. }
  455. // -> Create version snapshot
  456. await WIKI.models.pageHistory.addVersion({
  457. ...page,
  458. action: 'deleted',
  459. versionDate: page.updatedAt
  460. })
  461. // -> Delete page
  462. await WIKI.models.pages.query().delete().where('id', page.id)
  463. await WIKI.models.pages.deletePageFromCache(page)
  464. // -> Rebuild page tree
  465. await WIKI.models.pages.rebuildTree()
  466. // -> Delete from Search Index
  467. await WIKI.data.searchEngine.deleted(page)
  468. // -> Delete from Storage
  469. if (!opts.skipStorage) {
  470. await WIKI.models.storage.pageEvent({
  471. event: 'deleted',
  472. page
  473. })
  474. }
  475. // -> Reconnect Links
  476. await WIKI.models.pages.reconnectLinks({
  477. locale: page.localeCode,
  478. path: page.path,
  479. mode: 'delete'
  480. })
  481. }
  482. /**
  483. * Reconnect links to new/move/deleted page
  484. *
  485. * @param {Object} opts - Page parameters
  486. * @param {string} opts.path - Page Path
  487. * @param {string} opts.locale - Page Locale Code
  488. * @param {string} [opts.sourcePath] - Previous Page Path (move only)
  489. * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
  490. * @param {string} opts.mode - Page Update mode (create, move, delete)
  491. * @returns {Promise} Promise with no value
  492. */
  493. static async reconnectLinks (opts) {
  494. const pageHref = `/${opts.locale}/${opts.path}`
  495. let replaceArgs = {
  496. from: '',
  497. to: ''
  498. }
  499. switch (opts.mode) {
  500. case 'create':
  501. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  502. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  503. break
  504. case 'move':
  505. const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
  506. replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-invalid-page">`
  507. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  508. break
  509. case 'delete':
  510. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  511. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  512. break
  513. default:
  514. return false
  515. }
  516. let affectedHashes = []
  517. // -> Perform replace and return affected page hashes (POSTGRES only)
  518. if (WIKI.config.db.type === 'postgres') {
  519. const qryHashes = await WIKI.models.pages.query()
  520. .returning('hash')
  521. .patch({
  522. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  523. })
  524. .whereIn('pages.id', function () {
  525. this.select('pageLinks.pageId').from('pageLinks').where({
  526. 'pageLinks.path': opts.path,
  527. 'pageLinks.localeCode': opts.locale
  528. })
  529. })
  530. affectedHashes = qryHashes.map(h => h.hash)
  531. } else {
  532. // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, MSSQL, SQLITE only)
  533. await WIKI.models.pages.query()
  534. .patch({
  535. render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  536. })
  537. .whereIn('pages.id', function () {
  538. this.select('pageLinks.pageId').from('pageLinks').where({
  539. 'pageLinks.path': opts.path,
  540. 'pageLinks.localeCode': opts.locale
  541. })
  542. })
  543. const qryHashes = await WIKI.models.pages.query()
  544. .column('hash')
  545. .whereIn('pages.id', function () {
  546. this.select('pageLinks.pageId').from('pageLinks').where({
  547. 'pageLinks.path': opts.path,
  548. 'pageLinks.localeCode': opts.locale
  549. })
  550. })
  551. affectedHashes = qryHashes.map(h => h.hash)
  552. }
  553. for (const hash of affectedHashes) {
  554. await WIKI.models.pages.deletePageFromCache({ hash })
  555. }
  556. }
  557. /**
  558. * Rebuild page tree for new/updated/deleted page
  559. *
  560. * @returns {Promise} Promise with no value
  561. */
  562. static async rebuildTree() {
  563. const rebuildJob = await WIKI.scheduler.registerJob({
  564. name: 'rebuild-tree',
  565. immediate: true,
  566. worker: true
  567. })
  568. return rebuildJob.finished
  569. }
  570. /**
  571. * Trigger the rendering of a page
  572. *
  573. * @param {Object} page Page Model Instance
  574. * @returns {Promise} Promise with no value
  575. */
  576. static async renderPage(page) {
  577. const renderJob = await WIKI.scheduler.registerJob({
  578. name: 'render-page',
  579. immediate: true,
  580. worker: true
  581. }, page.id)
  582. return renderJob.finished
  583. }
  584. /**
  585. * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
  586. *
  587. * @param {Object} opts Page Properties
  588. * @returns {Promise} Promise of the Page Model Instance
  589. */
  590. static async getPage(opts) {
  591. // -> Get from cache first
  592. let page = await WIKI.models.pages.getPageFromCache(opts)
  593. if (!page) {
  594. // -> Get from DB
  595. page = await WIKI.models.pages.getPageFromDb(opts)
  596. if (page) {
  597. if (page.render) {
  598. // -> Save render to cache
  599. await WIKI.models.pages.savePageToCache(page)
  600. } else {
  601. // -> No render? Possible duplicate issue
  602. /* TODO: Detect duplicate and delete */
  603. throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
  604. }
  605. }
  606. }
  607. return page
  608. }
  609. /**
  610. * Fetch an Existing Page from the Database
  611. *
  612. * @param {Object} opts Page Properties
  613. * @returns {Promise} Promise of the Page Model Instance
  614. */
  615. static async getPageFromDb(opts) {
  616. const queryModeID = _.isNumber(opts)
  617. try {
  618. return WIKI.models.pages.query()
  619. .column([
  620. 'pages.id',
  621. 'pages.path',
  622. 'pages.hash',
  623. 'pages.title',
  624. 'pages.description',
  625. 'pages.isPrivate',
  626. 'pages.isPublished',
  627. 'pages.privateNS',
  628. 'pages.publishStartDate',
  629. 'pages.publishEndDate',
  630. 'pages.content',
  631. 'pages.render',
  632. 'pages.toc',
  633. 'pages.contentType',
  634. 'pages.createdAt',
  635. 'pages.updatedAt',
  636. 'pages.editorKey',
  637. 'pages.localeCode',
  638. 'pages.authorId',
  639. 'pages.creatorId',
  640. {
  641. authorName: 'author.name',
  642. authorEmail: 'author.email',
  643. creatorName: 'creator.name',
  644. creatorEmail: 'creator.email'
  645. }
  646. ])
  647. .joinRelated('author')
  648. .joinRelated('creator')
  649. .withGraphJoined('tags')
  650. .modifyGraph('tags', builder => {
  651. builder.select('tag', 'title')
  652. })
  653. .where(queryModeID ? {
  654. 'pages.id': opts
  655. } : {
  656. 'pages.path': opts.path,
  657. 'pages.localeCode': opts.locale
  658. })
  659. // .andWhere(builder => {
  660. // if (queryModeID) return
  661. // builder.where({
  662. // 'pages.isPublished': true
  663. // }).orWhere({
  664. // 'pages.isPublished': false,
  665. // 'pages.authorId': opts.userId
  666. // })
  667. // })
  668. // .andWhere(builder => {
  669. // if (queryModeID) return
  670. // if (opts.isPrivate) {
  671. // builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
  672. // } else {
  673. // builder.where({ 'pages.isPrivate': false })
  674. // }
  675. // })
  676. .first()
  677. } catch (err) {
  678. WIKI.logger.warn(err)
  679. throw err
  680. }
  681. }
  682. /**
  683. * Save a Page Model Instance to Cache
  684. *
  685. * @param {Object} page Page Model Instance
  686. * @returns {Promise} Promise with no value
  687. */
  688. static async savePageToCache(page) {
  689. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${page.hash}.bin`)
  690. await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
  691. id: page.id,
  692. authorId: page.authorId,
  693. authorName: page.authorName,
  694. createdAt: page.createdAt,
  695. creatorId: page.creatorId,
  696. creatorName: page.creatorName,
  697. description: page.description,
  698. isPrivate: page.isPrivate === 1 || page.isPrivate === true,
  699. isPublished: page.isPublished === 1 || page.isPublished === true,
  700. publishEndDate: page.publishEndDate,
  701. publishStartDate: page.publishStartDate,
  702. render: page.render,
  703. tags: page.tags.map(t => _.pick(t, ['tag', 'title'])),
  704. title: page.title,
  705. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  706. updatedAt: page.updatedAt
  707. }))
  708. }
  709. /**
  710. * Fetch an Existing Page from Cache
  711. *
  712. * @param {Object} opts Page Properties
  713. * @returns {Promise} Promise of the Page Model Instance
  714. */
  715. static async getPageFromCache(opts) {
  716. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
  717. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${pageHash}.bin`)
  718. try {
  719. const pageBuffer = await fs.readFile(cachePath)
  720. let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
  721. return {
  722. ...page,
  723. path: opts.path,
  724. localeCode: opts.locale,
  725. isPrivate: opts.isPrivate
  726. }
  727. } catch (err) {
  728. if (err.code === 'ENOENT') {
  729. return false
  730. }
  731. WIKI.logger.error(err)
  732. throw err
  733. }
  734. }
  735. /**
  736. * Delete an Existing Page from Cache
  737. *
  738. * @param {Object} page Page Model Instance
  739. * @param {string} page.hash Hash of the Page
  740. * @returns {Promise} Promise with no value
  741. */
  742. static async deletePageFromCache(page) {
  743. return fs.remove(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${page.hash}.bin`))
  744. }
  745. /**
  746. * Flush the contents of the Cache
  747. */
  748. static async flushCache() {
  749. return fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache`))
  750. }
  751. /**
  752. * Migrate all pages from a source locale to the target locale
  753. *
  754. * @param {Object} opts Migration properties
  755. * @param {string} opts.sourceLocale Source Locale Code
  756. * @param {string} opts.targetLocale Target Locale Code
  757. * @returns {Promise} Promise with no value
  758. */
  759. static async migrateToLocale({ sourceLocale, targetLocale }) {
  760. return WIKI.models.pages.query()
  761. .patch({
  762. localeCode: targetLocale
  763. })
  764. .where({
  765. localeCode: sourceLocale
  766. })
  767. .whereNotExists(function() {
  768. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  769. })
  770. }
  771. /**
  772. * Clean raw HTML from content for use in search engines
  773. *
  774. * @param {string} rawHTML Raw HTML
  775. * @returns {string} Cleaned Content Text
  776. */
  777. static cleanHTML(rawHTML = '') {
  778. let data = striptags(rawHTML || '', [], ' ')
  779. .replace(emojiRegex(), '')
  780. // .replace(htmlEntitiesRegex, '')
  781. return he.decode(data)
  782. .replace(punctuationRegex, ' ')
  783. .replace(/(\r\n|\n|\r)/gm, ' ')
  784. .replace(/\s\s+/g, ' ')
  785. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  786. }
  787. }