pages.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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. const CleanCSS = require('clean-css')
  12. const TurndownService = require('turndown')
  13. const turndownPluginGfm = require('@joplin/turndown-plugin-gfm').gfm
  14. const cheerio = require('cheerio')
  15. const pageRegex = /^[a-zA0-90-9-_/]*$/
  16. const frontmatterRegex = {
  17. html: /^(<!-{2}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{2}>)?(?:\n|\r)*([\w\W]*)*/,
  18. legacy: /^(<!-- TITLE: ?([\w\W]+?) ?-{2}>)?(?:\n|\r)?(<!-- SUBTITLE: ?([\w\W]+?) ?-{2}>)?(?:\n|\r)*([\w\W]*)*/i,
  19. markdown: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?(?:\n|\r)*([\w\W]*)*/
  20. }
  21. const punctuationRegex = /[!,:;/\\_+\-=()&#@<>$~%^*[\]{}"'|]+|(\.\s)|(\s\.)/ig
  22. // const htmlEntitiesRegex = /(&#[0-9]{3};)|(&#x[a-zA-Z0-9]{2};)/ig
  23. /**
  24. * Pages model
  25. */
  26. module.exports = class Page extends Model {
  27. static get tableName() { return 'pages' }
  28. static get jsonSchema () {
  29. return {
  30. type: 'object',
  31. required: ['path', 'title'],
  32. properties: {
  33. id: {type: 'string'},
  34. path: {type: 'string'},
  35. hash: {type: 'string'},
  36. title: {type: 'string'},
  37. description: {type: 'string'},
  38. publishState: {type: 'string'},
  39. publishStartDate: {type: 'string'},
  40. publishEndDate: {type: 'string'},
  41. content: {type: 'string'},
  42. contentType: {type: 'string'},
  43. render: {type: 'string'},
  44. siteId: {type: 'string'},
  45. createdAt: {type: 'string'},
  46. updatedAt: {type: 'string'}
  47. }
  48. }
  49. }
  50. static get jsonAttributes() {
  51. return ['config', 'historyData', 'relations', 'scripts', 'toc']
  52. }
  53. static get relationMappings() {
  54. return {
  55. tags: {
  56. relation: Model.ManyToManyRelation,
  57. modelClass: require('./tags'),
  58. join: {
  59. from: 'pages.id',
  60. through: {
  61. from: 'pageTags.pageId',
  62. to: 'pageTags.tagId'
  63. },
  64. to: 'tags.id'
  65. }
  66. },
  67. links: {
  68. relation: Model.HasManyRelation,
  69. modelClass: require('./pageLinks'),
  70. join: {
  71. from: 'pages.id',
  72. to: 'pageLinks.pageId'
  73. }
  74. },
  75. author: {
  76. relation: Model.BelongsToOneRelation,
  77. modelClass: require('./users'),
  78. join: {
  79. from: 'pages.authorId',
  80. to: 'users.id'
  81. }
  82. },
  83. creator: {
  84. relation: Model.BelongsToOneRelation,
  85. modelClass: require('./users'),
  86. join: {
  87. from: 'pages.creatorId',
  88. to: 'users.id'
  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. * Solving the violates foreign key constraint using cascade strategy
  110. * using static hooks
  111. * @see https://vincit.github.io/objection.js/api/types/#type-statichookarguments
  112. */
  113. static async beforeDelete({ asFindQuery }) {
  114. const page = await asFindQuery().select('id')
  115. await WIKI.db.comments.query().delete().where('pageId', page[0].id)
  116. }
  117. /**
  118. * Cache Schema
  119. */
  120. static get cacheSchema() {
  121. return new JSBinType({
  122. id: 'string',
  123. authorId: 'string',
  124. authorName: 'string',
  125. createdAt: 'string',
  126. creatorId: 'string',
  127. creatorName: 'string',
  128. description: 'string',
  129. editor: 'string',
  130. publishState: 'string',
  131. publishEndDate: 'string',
  132. publishStartDate: 'string',
  133. render: 'string',
  134. siteId: 'string',
  135. tags: [
  136. {
  137. tag: 'string'
  138. }
  139. ],
  140. extra: {
  141. js: 'string',
  142. css: 'string'
  143. },
  144. title: 'string',
  145. toc: 'string',
  146. updatedAt: 'string'
  147. })
  148. }
  149. /**
  150. * Inject page metadata into contents
  151. *
  152. * @returns {string} Page Contents with Injected Metadata
  153. */
  154. injectMetadata () {
  155. return pageHelper.injectPageMetadata(this)
  156. }
  157. /**
  158. * Get the page's file extension based on content type
  159. *
  160. * @returns {string} File Extension
  161. */
  162. getFileExtension() {
  163. return pageHelper.getFileExtension(this.contentType)
  164. }
  165. /**
  166. * Parse injected page metadata from raw content
  167. *
  168. * @param {String} raw Raw file contents
  169. * @param {String} contentType Content Type
  170. * @returns {Object} Parsed Page Metadata with Raw Content
  171. */
  172. static parseMetadata (raw, contentType) {
  173. let result
  174. try {
  175. switch (contentType) {
  176. case 'markdown':
  177. result = frontmatterRegex.markdown.exec(raw)
  178. if (result[2]) {
  179. return {
  180. ...yaml.safeLoad(result[2]),
  181. content: result[3]
  182. }
  183. } else {
  184. // Attempt legacy v1 format
  185. result = frontmatterRegex.legacy.exec(raw)
  186. if (result[2]) {
  187. return {
  188. title: result[2],
  189. description: result[4],
  190. content: result[5]
  191. }
  192. }
  193. }
  194. break
  195. case 'html':
  196. result = frontmatterRegex.html.exec(raw)
  197. if (result[2]) {
  198. return {
  199. ...yaml.safeLoad(result[2]),
  200. content: result[3]
  201. }
  202. }
  203. break
  204. }
  205. } catch (err) {
  206. WIKI.logger.warn('Failed to parse page metadata. Invalid syntax.')
  207. }
  208. return {
  209. content: raw
  210. }
  211. }
  212. /**
  213. * Create a New Page
  214. *
  215. * @param {Object} opts Page Properties
  216. * @returns {Promise} Promise of the Page Model Instance
  217. */
  218. static async createPage(opts) {
  219. // -> Validate site
  220. if (!WIKI.sites[opts.siteId]) {
  221. throw new WIKI.Error.Custom('InvalidSiteId', 'Site ID is invalid.')
  222. }
  223. // -> Remove trailing slash
  224. if (opts.path.endsWith('/')) {
  225. opts.path = opts.path.slice(0, -1)
  226. }
  227. // -> Remove starting slash
  228. if (opts.path.startsWith('/')) {
  229. opts.path = opts.path.slice(1)
  230. }
  231. // -> Validate path
  232. if (!pageRegex.test(opts.path)) {
  233. throw new Error('ERR_INVALID_PATH')
  234. }
  235. opts.path = opts.path.toLowerCase()
  236. // const dotPath = opts.path.replaceAll('/', '.').replaceAll('-', '_')
  237. // -> Check for page access
  238. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  239. locale: opts.locale,
  240. path: opts.path
  241. })) {
  242. throw new WIKI.Error.PageDeleteForbidden()
  243. }
  244. // -> Check for duplicate
  245. const dupCheck = await WIKI.db.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
  246. if (dupCheck) {
  247. throw new WIKI.Error.PageDuplicateCreate()
  248. }
  249. // -> Check for empty content
  250. if (!opts.content || _.trim(opts.content).length < 1) {
  251. throw new WIKI.Error.PageEmptyContent()
  252. }
  253. // -> Format CSS Scripts
  254. let scriptCss = ''
  255. if (WIKI.auth.checkAccess(opts.user, ['write:styles'], {
  256. locale: opts.locale,
  257. path: opts.path
  258. })) {
  259. if (!_.isEmpty(opts.scriptCss)) {
  260. scriptCss = new CleanCSS({ inline: false }).minify(opts.scriptCss).styles
  261. } else {
  262. scriptCss = ''
  263. }
  264. }
  265. // -> Format JS Scripts
  266. let scriptJsLoad = ''
  267. let scriptJsUnload = ''
  268. if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
  269. locale: opts.locale,
  270. path: opts.path
  271. })) {
  272. scriptJsLoad = opts.scriptJsLoad || ''
  273. scriptJsUnload = opts.scriptJsUnload || ''
  274. }
  275. // -> Create page
  276. const page = await WIKI.db.pages.query().insert({
  277. authorId: opts.user.id,
  278. content: opts.content,
  279. creatorId: opts.user.id,
  280. config: {
  281. allowComments: opts.allowComments ?? true,
  282. allowContributions: opts.allowContributions ?? true,
  283. allowRatings: opts.allowRatings ?? true,
  284. showSidebar: opts.showSidebar ?? true,
  285. showTags: opts.showTags ?? true,
  286. showToc: opts.showToc ?? true,
  287. tocDepth: opts.tocDepth ?? WIKI.sites[opts.siteId].config?.defaults.tocDepth
  288. },
  289. contentType: WIKI.data.editors[opts.editor]?.contentType ?? 'text',
  290. description: opts.description,
  291. editor: opts.editor,
  292. hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale }),
  293. icon: opts.icon,
  294. isBrowsable: opts.isBrowsable ?? true,
  295. localeCode: opts.locale,
  296. ownerId: opts.user.id,
  297. path: opts.path,
  298. publishState: opts.publishState,
  299. publishEndDate: opts.publishEndDate?.toISO(),
  300. publishStartDate: opts.publishStartDate?.toISO(),
  301. relations: opts.relations ?? [],
  302. render: opts.render ?? '',
  303. siteId: opts.siteId,
  304. title: opts.title,
  305. toc: '[]',
  306. scripts: JSON.stringify({
  307. jsLoad: scriptJsLoad,
  308. jsUnload: scriptJsUnload,
  309. css: scriptCss
  310. })
  311. }).returning('*')
  312. // -> Save Tags
  313. if (opts.tags && opts.tags.length > 0) {
  314. await WIKI.db.tags.associateTags({ tags: opts.tags, page })
  315. }
  316. // -> Render page to HTML
  317. await WIKI.db.pages.renderPage(page)
  318. // -> Add to tree
  319. const pathParts = page.path.split('/')
  320. await WIKI.db.tree.addPage({
  321. id: page.id,
  322. parentPath: _.initial(pathParts).join('/'),
  323. fileName: _.last(pathParts),
  324. locale: page.localeCode,
  325. title: page.title,
  326. meta: {
  327. authorId: page.authorId,
  328. contentType: page.contentType,
  329. creatorId: page.creatorId,
  330. description: page.description,
  331. isBrowsable: page.isBrowsable,
  332. ownerId: page.ownerId,
  333. publishState: page.publishState,
  334. publishEndDate: page.publishEndDate,
  335. publishStartDate: page.publishStartDate
  336. },
  337. siteId: page.siteId
  338. })
  339. return page
  340. // TODO: Handle remaining flow
  341. // -> Rebuild page tree
  342. await WIKI.db.pages.rebuildTree()
  343. // -> Add to Search Index
  344. const pageContents = await WIKI.db.pages.query().findById(page.id).select('render')
  345. page.safeContent = WIKI.db.pages.cleanHTML(pageContents.render)
  346. await WIKI.data.searchEngine.created(page)
  347. // -> Add to Storage
  348. if (!opts.skipStorage) {
  349. await WIKI.db.storage.pageEvent({
  350. event: 'created',
  351. page
  352. })
  353. }
  354. // -> Reconnect Links
  355. await WIKI.db.pages.reconnectLinks({
  356. locale: page.localeCode,
  357. path: page.path,
  358. mode: 'create'
  359. })
  360. // -> Get latest updatedAt
  361. page.updatedAt = await WIKI.db.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)
  362. return page
  363. }
  364. /**
  365. * Update an Existing Page
  366. *
  367. * @param {Object} opts Page Properties
  368. * @returns {Promise} Promise of the Page Model Instance
  369. */
  370. static async updatePage(opts) {
  371. // -> Fetch original page
  372. const ogPage = await WIKI.db.pages.query().findById(opts.id)
  373. if (!ogPage) {
  374. throw new Error('ERR_PAGE_NOT_FOUND')
  375. }
  376. // -> Check for page access
  377. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  378. locale: ogPage.localeCode,
  379. path: ogPage.path
  380. })) {
  381. throw new Error('ERR_PAGE_UPDATE_FORBIDDEN')
  382. }
  383. const patch = {}
  384. const historyData = {
  385. action: 'updated',
  386. affectedFields: []
  387. }
  388. // -> Create version snapshot
  389. await WIKI.db.pageHistory.addVersion(ogPage)
  390. // -> Basic fields
  391. if ('title' in opts.patch) {
  392. patch.title = opts.patch.title.trim()
  393. historyData.affectedFields.push('title')
  394. if (patch.title.length < 1) {
  395. throw new Error('ERR_PAGE_TITLE_MISSING')
  396. }
  397. }
  398. if ('description' in opts.patch) {
  399. patch.description = opts.patch.description.trim()
  400. historyData.affectedFields.push('description')
  401. }
  402. if ('icon' in opts.patch) {
  403. patch.icon = opts.patch.icon.trim()
  404. historyData.affectedFields.push('icon')
  405. }
  406. if ('content' in opts.patch) {
  407. patch.content = opts.patch.content
  408. if ('render' in opts.patch) {
  409. patch.render = opts.patch.render
  410. }
  411. historyData.affectedFields.push('content')
  412. }
  413. // -> Publish State
  414. if (opts.patch.publishState) {
  415. patch.publishState = opts.patch.publishState
  416. historyData.affectedFields.push('publishState')
  417. if (patch.publishState === 'scheduled' && (!opts.patch.publishStartDate || !opts.patch.publishEndDate)) {
  418. throw new Error('ERR_PAGE_MISSING_SCHEDULED_DATES')
  419. }
  420. }
  421. if (opts.patch.publishStartDate) {
  422. patch.publishStartDate = opts.patch.publishStartDate
  423. historyData.affectedFields.push('publishStartDate')
  424. }
  425. if (opts.patch.publishEndDate) {
  426. patch.publishEndDate = opts.patch.publishEndDate
  427. historyData.affectedFields.push('publishEndDate')
  428. }
  429. // -> Page Config
  430. if ('isBrowsable' in opts.patch) {
  431. patch.config = {
  432. ...patch.config ?? ogPage.config ?? {},
  433. isBrowsable: opts.patch.isBrowsable
  434. }
  435. historyData.affectedFields.push('isBrowsable')
  436. }
  437. if ('allowComments' in opts.patch) {
  438. patch.config = {
  439. ...patch.config ?? ogPage.config ?? {},
  440. allowComments: opts.patch.allowComments
  441. }
  442. historyData.affectedFields.push('allowComments')
  443. }
  444. if ('allowContributions' in opts.patch) {
  445. patch.config = {
  446. ...patch.config ?? ogPage.config ?? {},
  447. allowContributions: opts.patch.allowContributions
  448. }
  449. historyData.affectedFields.push('allowContributions')
  450. }
  451. if ('allowRatings' in opts.patch) {
  452. patch.config = {
  453. ...patch.config ?? ogPage.config ?? {},
  454. allowRatings: opts.patch.allowRatings
  455. }
  456. historyData.affectedFields.push('allowRatings')
  457. }
  458. if ('showSidebar' in opts.patch) {
  459. patch.config = {
  460. ...patch.config ?? ogPage.config ?? {},
  461. showSidebar: opts.patch.showSidebar
  462. }
  463. historyData.affectedFields.push('showSidebar')
  464. }
  465. if ('showTags' in opts.patch) {
  466. patch.config = {
  467. ...patch.config ?? ogPage.config ?? {},
  468. showTags: opts.patch.showTags
  469. }
  470. historyData.affectedFields.push('showTags')
  471. }
  472. if ('showToc' in opts.patch) {
  473. patch.config = {
  474. ...patch.config ?? ogPage.config ?? {},
  475. showToc: opts.patch.showToc
  476. }
  477. historyData.affectedFields.push('showToc')
  478. }
  479. if ('tocDepth' in opts.patch) {
  480. patch.config = {
  481. ...patch.config ?? ogPage.config ?? {},
  482. tocDepth: opts.patch.tocDepth
  483. }
  484. historyData.affectedFields.push('tocDepth')
  485. if (patch.config.tocDepth?.min < 1 || patch.config.tocDepth?.min > 6) {
  486. throw new Error('ERR_PAGE_INVALID_TOC_DEPTH')
  487. }
  488. if (patch.config.tocDepth?.max < 1 || patch.config.tocDepth?.max > 6) {
  489. throw new Error('ERR_PAGE_INVALID_TOC_DEPTH')
  490. }
  491. }
  492. // -> Relations
  493. if ('relations' in opts.patch) {
  494. patch.relations = opts.patch.relations.map(r => {
  495. if (r.label.length < 1) {
  496. throw new Error('ERR_PAGE_RELATION_LABEL_MISSING')
  497. } else if (r.label.length > 255) {
  498. throw new Error('ERR_PAGE_RELATION_LABEL_TOOLONG')
  499. } else if (r.icon.length > 255) {
  500. throw new Error('ERR_PAGE_RELATION_ICON_INVALID')
  501. } else if (r.target.length > 1024) {
  502. throw new Error('ERR_PAGE_RELATION_TARGET_INVALID')
  503. }
  504. return r
  505. })
  506. historyData.affectedFields.push('relations')
  507. }
  508. // -> Format CSS Scripts
  509. if (opts.patch.scriptCss) {
  510. if (WIKI.auth.checkAccess(opts.user, ['write:styles'], {
  511. locale: ogPage.localeCode,
  512. path: ogPage.path
  513. })) {
  514. patch.scripts = {
  515. ...patch.scripts ?? ogPage.scripts ?? {},
  516. css: !_.isEmpty(opts.patch.scriptCss) ? new CleanCSS({ inline: false }).minify(opts.patch.scriptCss).styles : ''
  517. }
  518. historyData.affectedFields.push('scripts.css')
  519. }
  520. }
  521. // -> Format JS Scripts
  522. if (opts.patch.scriptJsLoad) {
  523. if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
  524. locale: ogPage.localeCode,
  525. path: ogPage.path
  526. })) {
  527. patch.scripts = {
  528. ...patch.scripts ?? ogPage.scripts ?? {},
  529. jsLoad: opts.patch.scriptJsLoad ?? ''
  530. }
  531. historyData.affectedFields.push('scripts.jsLoad')
  532. }
  533. }
  534. if (opts.patch.scriptJsUnload) {
  535. if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
  536. locale: ogPage.localeCode,
  537. path: ogPage.path
  538. })) {
  539. patch.scripts = {
  540. ...patch.scripts ?? ogPage.scripts ?? {},
  541. jsUnload: opts.patch.scriptJsUnload ?? ''
  542. }
  543. historyData.affectedFields.push('scripts.jsUnload')
  544. }
  545. }
  546. // -> Tags
  547. if ('tags' in opts.patch) {
  548. historyData.affectedFields.push('tags')
  549. }
  550. // -> Update page
  551. await WIKI.db.pages.query().patch({
  552. ...patch,
  553. authorId: opts.user.id,
  554. historyData
  555. }).where('id', ogPage.id)
  556. let page = await WIKI.db.pages.getPageFromDb(ogPage.id)
  557. // -> Save Tags
  558. if (opts.patch.tags) {
  559. await WIKI.db.tags.associateTags({ tags: opts.patch.tags, page })
  560. }
  561. // -> Render page to HTML
  562. if (opts.patch.content) {
  563. await WIKI.db.pages.renderPage(page)
  564. }
  565. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  566. // -> Update tree
  567. await WIKI.db.knex('tree').where('id', page.id).update({
  568. title: page.title,
  569. meta: {
  570. authorId: page.authorId,
  571. contentType: page.contentType,
  572. creatorId: page.creatorId,
  573. description: page.description,
  574. isBrowsable: page.isBrowsable,
  575. ownerId: page.ownerId,
  576. publishState: page.publishState,
  577. publishEndDate: page.publishEndDate,
  578. publishStartDate: page.publishStartDate
  579. },
  580. updatedAt: page.updatedAt
  581. })
  582. // // -> Update Search Index
  583. // const pageContents = await WIKI.db.pages.query().findById(page.id).select('render')
  584. // page.safeContent = WIKI.db.pages.cleanHTML(pageContents.render)
  585. // await WIKI.data.searchEngine.updated(page)
  586. // -> Update on Storage
  587. // if (!opts.skipStorage) {
  588. // await WIKI.db.storage.pageEvent({
  589. // event: 'updated',
  590. // page
  591. // })
  592. // }
  593. // -> Perform move?
  594. if ((opts.locale && opts.locale !== page.localeCode) || (opts.path && opts.path !== page.path)) {
  595. // -> Check target path access
  596. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  597. locale: opts.locale,
  598. path: opts.path
  599. })) {
  600. throw new WIKI.Error.PageMoveForbidden()
  601. }
  602. await WIKI.db.pages.movePage({
  603. id: page.id,
  604. destinationLocale: opts.locale,
  605. destinationPath: opts.path,
  606. user: opts.user
  607. })
  608. }
  609. // -> Get latest updatedAt
  610. page.updatedAt = await WIKI.db.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)
  611. return page
  612. }
  613. /**
  614. * Convert an Existing Page
  615. *
  616. * @param {Object} opts Page Properties
  617. * @returns {Promise} Promise of the Page Model Instance
  618. */
  619. static async convertPage(opts) {
  620. // -> Fetch original page
  621. const ogPage = await WIKI.db.pages.query().findById(opts.id)
  622. if (!ogPage) {
  623. throw new Error('Invalid Page Id')
  624. }
  625. if (ogPage.editor === opts.editor) {
  626. throw new Error('Page is already using this editor. Nothing to convert.')
  627. }
  628. // -> Check for page access
  629. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  630. locale: ogPage.localeCode,
  631. path: ogPage.path
  632. })) {
  633. throw new WIKI.Error.PageUpdateForbidden()
  634. }
  635. // -> Check content type
  636. const sourceContentType = ogPage.contentType
  637. const targetContentType = _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text')
  638. const shouldConvert = sourceContentType !== targetContentType
  639. let convertedContent = null
  640. // -> Convert content
  641. if (shouldConvert) {
  642. // -> Markdown => HTML
  643. if (sourceContentType === 'markdown' && targetContentType === 'html') {
  644. if (!ogPage.render) {
  645. throw new Error('Aborted conversion because rendered page content is empty!')
  646. }
  647. convertedContent = ogPage.render
  648. const $ = cheerio.load(convertedContent, {
  649. decodeEntities: true
  650. })
  651. if ($.root().children().length > 0) {
  652. // Remove header anchors
  653. $('.toc-anchor').remove()
  654. // Attempt to convert tabsets
  655. $('tabset').each((tabI, tabElm) => {
  656. const tabHeaders = []
  657. // -> Extract templates
  658. $(tabElm).children('template').each((tmplI, tmplElm) => {
  659. if ($(tmplElm).attr('v-slot:tabs') === '') {
  660. $(tabElm).before('<ul class="tabset-headers">' + $(tmplElm).html() + '</ul>')
  661. } else {
  662. $(tabElm).after('<div class="markdown-tabset">' + $(tmplElm).html() + '</div>')
  663. }
  664. })
  665. // -> Parse tab headers
  666. $(tabElm).prev('.tabset-headers').children((i, elm) => {
  667. tabHeaders.push($(elm).html())
  668. })
  669. $(tabElm).prev('.tabset-headers').remove()
  670. // -> Inject tab headers
  671. $(tabElm).next('.markdown-tabset').children((i, elm) => {
  672. if (tabHeaders.length > i) {
  673. $(elm).prepend(`<h2>${tabHeaders[i]}</h2>`)
  674. }
  675. })
  676. $(tabElm).next('.markdown-tabset').prepend('<h1>Tabset</h1>')
  677. $(tabElm).remove()
  678. })
  679. convertedContent = $.html('body').replace('<body>', '').replace('</body>', '').replace(/&#x([0-9a-f]{1,6});/ig, (entity, code) => {
  680. code = parseInt(code, 16)
  681. // Don't unescape ASCII characters, assuming they're encoded for a good reason
  682. if (code < 0x80) return entity
  683. return String.fromCodePoint(code)
  684. })
  685. }
  686. // -> HTML => Markdown
  687. } else if (sourceContentType === 'html' && targetContentType === 'markdown') {
  688. const td = new TurndownService({
  689. bulletListMarker: '-',
  690. codeBlockStyle: 'fenced',
  691. emDelimiter: '*',
  692. fence: '```',
  693. headingStyle: 'atx',
  694. hr: '---',
  695. linkStyle: 'inlined',
  696. preformattedCode: true,
  697. strongDelimiter: '**'
  698. })
  699. td.use(turndownPluginGfm)
  700. td.keep(['kbd'])
  701. td.addRule('subscript', {
  702. filter: ['sub'],
  703. replacement: c => `~${c}~`
  704. })
  705. td.addRule('superscript', {
  706. filter: ['sup'],
  707. replacement: c => `^${c}^`
  708. })
  709. td.addRule('underline', {
  710. filter: ['u'],
  711. replacement: c => `_${c}_`
  712. })
  713. td.addRule('taskList', {
  714. filter: (n, o) => {
  715. return n.nodeName === 'INPUT' && n.getAttribute('type') === 'checkbox'
  716. },
  717. replacement: (c, n) => {
  718. return n.getAttribute('checked') ? '[x] ' : '[ ] '
  719. }
  720. })
  721. td.addRule('removeTocAnchors', {
  722. filter: (n, o) => {
  723. return n.nodeName === 'A' && n.classList.contains('toc-anchor')
  724. },
  725. replacement: c => ''
  726. })
  727. convertedContent = td.turndown(ogPage.content)
  728. // -> Unsupported
  729. } else {
  730. throw new Error('Unsupported source / destination content types combination.')
  731. }
  732. }
  733. // -> Create version snapshot
  734. if (shouldConvert) {
  735. await WIKI.db.pageHistory.addVersion({
  736. ...ogPage,
  737. action: 'updated',
  738. versionDate: ogPage.updatedAt
  739. })
  740. }
  741. // -> Update page
  742. await WIKI.db.pages.query().patch({
  743. contentType: targetContentType,
  744. editor: opts.editor,
  745. ...(convertedContent ? { content: convertedContent } : {})
  746. }).where('id', ogPage.id)
  747. const page = await WIKI.db.pages.getPageFromDb(ogPage.id)
  748. await WIKI.db.pages.deletePageFromCache(page.hash)
  749. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  750. // -> Update on Storage
  751. await WIKI.db.storage.pageEvent({
  752. event: 'updated',
  753. page
  754. })
  755. }
  756. /**
  757. * Move a Page
  758. *
  759. * @param {Object} opts Page Properties
  760. * @returns {Promise} Promise with no value
  761. */
  762. static async movePage(opts) {
  763. let page
  764. if (_.has(opts, 'id')) {
  765. page = await WIKI.db.pages.query().findById(opts.id)
  766. } else {
  767. page = await WIKI.db.pages.query().findOne({
  768. path: opts.path,
  769. localeCode: opts.locale
  770. })
  771. }
  772. if (!page) {
  773. throw new WIKI.Error.PageNotFound()
  774. }
  775. // -> Validate path
  776. if (opts.destinationPath.includes('.') || opts.destinationPath.includes(' ') || opts.destinationPath.includes('\\') || opts.destinationPath.includes('//')) {
  777. throw new WIKI.Error.PageIllegalPath()
  778. }
  779. // -> Remove trailing slash
  780. if (opts.destinationPath.endsWith('/')) {
  781. opts.destinationPath = opts.destinationPath.slice(0, -1)
  782. }
  783. // -> Remove starting slash
  784. if (opts.destinationPath.startsWith('/')) {
  785. opts.destinationPath = opts.destinationPath.slice(1)
  786. }
  787. // -> Check for source page access
  788. if (!WIKI.auth.checkAccess(opts.user, ['manage:pages'], {
  789. locale: page.localeCode,
  790. path: page.path
  791. })) {
  792. throw new WIKI.Error.PageMoveForbidden()
  793. }
  794. // -> Check for destination page access
  795. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  796. locale: opts.destinationLocale,
  797. path: opts.destinationPath
  798. })) {
  799. throw new WIKI.Error.PageMoveForbidden()
  800. }
  801. // -> Check for existing page at destination path
  802. const destPage = await WIKI.db.pages.query().findOne({
  803. path: opts.destinationPath,
  804. localeCode: opts.destinationLocale
  805. })
  806. if (destPage) {
  807. throw new WIKI.Error.PagePathCollision()
  808. }
  809. // -> Create version snapshot
  810. await WIKI.db.pageHistory.addVersion({
  811. ...page,
  812. action: 'moved',
  813. versionDate: page.updatedAt
  814. })
  815. const destinationHash = pageHelper.generateHash({ path: opts.destinationPath, locale: opts.destinationLocale })
  816. // -> Move page
  817. const destinationTitle = (page.title === page.path ? opts.destinationPath : page.title)
  818. await WIKI.db.pages.query().patch({
  819. path: opts.destinationPath,
  820. localeCode: opts.destinationLocale,
  821. title: destinationTitle,
  822. hash: destinationHash
  823. }).findById(page.id)
  824. await WIKI.db.pages.deletePageFromCache(page.hash)
  825. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  826. // -> Rebuild page tree
  827. await WIKI.db.pages.rebuildTree()
  828. // -> Rename in Search Index
  829. const pageContents = await WIKI.db.pages.query().findById(page.id).select('render')
  830. page.safeContent = WIKI.db.pages.cleanHTML(pageContents.render)
  831. await WIKI.data.searchEngine.renamed({
  832. ...page,
  833. destinationPath: opts.destinationPath,
  834. destinationLocaleCode: opts.destinationLocale,
  835. destinationHash
  836. })
  837. // -> Rename in Storage
  838. if (!opts.skipStorage) {
  839. await WIKI.db.storage.pageEvent({
  840. event: 'renamed',
  841. page: {
  842. ...page,
  843. destinationPath: opts.destinationPath,
  844. destinationLocaleCode: opts.destinationLocale,
  845. destinationHash,
  846. moveAuthorId: opts.user.id,
  847. moveAuthorName: opts.user.name,
  848. moveAuthorEmail: opts.user.email
  849. }
  850. })
  851. }
  852. // -> Reconnect Links : Changing old links to the new path
  853. await WIKI.db.pages.reconnectLinks({
  854. sourceLocale: page.localeCode,
  855. sourcePath: page.path,
  856. locale: opts.destinationLocale,
  857. path: opts.destinationPath,
  858. mode: 'move'
  859. })
  860. // -> Reconnect Links : Validate invalid links to the new path
  861. await WIKI.db.pages.reconnectLinks({
  862. locale: opts.destinationLocale,
  863. path: opts.destinationPath,
  864. mode: 'create'
  865. })
  866. }
  867. /**
  868. * Delete an Existing Page
  869. *
  870. * @param {Object} opts Page Properties
  871. * @returns {Promise} Promise with no value
  872. */
  873. static async deletePage(opts) {
  874. const page = await WIKI.db.pages.getPageFromDb(_.has(opts, 'id') ? opts.id : opts)
  875. if (!page) {
  876. throw new WIKI.Error.PageNotFound()
  877. }
  878. // -> Check for page access
  879. if (!WIKI.auth.checkAccess(opts.user, ['delete:pages'], {
  880. locale: page.locale,
  881. path: page.path
  882. })) {
  883. throw new WIKI.Error.PageDeleteForbidden()
  884. }
  885. // -> Create version snapshot
  886. await WIKI.db.pageHistory.addVersion({
  887. ...page,
  888. action: 'deleted',
  889. versionDate: page.updatedAt
  890. })
  891. // -> Delete page
  892. await WIKI.db.pages.query().delete().where('id', page.id)
  893. await WIKI.db.knex('tree').where('id', page.id).del()
  894. await WIKI.db.pages.deletePageFromCache(page.hash)
  895. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  896. // -> Delete from Search Index
  897. await WIKI.data.searchEngine.deleted(page)
  898. // -> Delete from Storage
  899. if (!opts.skipStorage) {
  900. await WIKI.db.storage.pageEvent({
  901. event: 'deleted',
  902. page
  903. })
  904. }
  905. // -> Reconnect Links
  906. await WIKI.db.pages.reconnectLinks({
  907. locale: page.localeCode,
  908. path: page.path,
  909. mode: 'delete'
  910. })
  911. }
  912. /**
  913. * Reconnect links to new/move/deleted page
  914. *
  915. * @param {Object} opts - Page parameters
  916. * @param {string} opts.path - Page Path
  917. * @param {string} opts.locale - Page Locale Code
  918. * @param {string} [opts.sourcePath] - Previous Page Path (move only)
  919. * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
  920. * @param {string} opts.mode - Page Update mode (create, move, delete)
  921. * @returns {Promise} Promise with no value
  922. */
  923. static async reconnectLinks (opts) {
  924. const pageHref = `/${opts.locale}/${opts.path}`
  925. let replaceArgs = {
  926. from: '',
  927. to: ''
  928. }
  929. switch (opts.mode) {
  930. case 'create':
  931. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  932. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  933. break
  934. case 'move':
  935. const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
  936. replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-valid-page">`
  937. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  938. break
  939. case 'delete':
  940. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  941. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  942. break
  943. default:
  944. return false
  945. }
  946. let affectedHashes = []
  947. // -> Perform replace and return affected page hashes (POSTGRES only)
  948. if (WIKI.config.db.type === 'postgres') {
  949. const qryHashes = await WIKI.db.pages.query()
  950. .returning('hash')
  951. .patch({
  952. render: WIKI.db.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  953. })
  954. .whereIn('pages.id', function () {
  955. this.select('pageLinks.pageId').from('pageLinks').where({
  956. 'pageLinks.path': opts.path,
  957. 'pageLinks.localeCode': opts.locale
  958. })
  959. })
  960. affectedHashes = qryHashes.map(h => h.hash)
  961. } else {
  962. // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, MSSQL, SQLITE only)
  963. await WIKI.db.pages.query()
  964. .patch({
  965. render: WIKI.db.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  966. })
  967. .whereIn('pages.id', function () {
  968. this.select('pageLinks.pageId').from('pageLinks').where({
  969. 'pageLinks.path': opts.path,
  970. 'pageLinks.localeCode': opts.locale
  971. })
  972. })
  973. const qryHashes = await WIKI.db.pages.query()
  974. .column('hash')
  975. .whereIn('pages.id', function () {
  976. this.select('pageLinks.pageId').from('pageLinks').where({
  977. 'pageLinks.path': opts.path,
  978. 'pageLinks.localeCode': opts.locale
  979. })
  980. })
  981. affectedHashes = qryHashes.map(h => h.hash)
  982. }
  983. for (const hash of affectedHashes) {
  984. await WIKI.db.pages.deletePageFromCache(hash)
  985. WIKI.events.outbound.emit('deletePageFromCache', hash)
  986. }
  987. }
  988. /**
  989. * Rebuild page tree for new/updated/deleted page
  990. *
  991. * @returns {Promise} Promise with no value
  992. */
  993. static async rebuildTree() {
  994. const rebuildJob = await WIKI.scheduler.registerJob({
  995. name: 'rebuild-tree',
  996. immediate: true,
  997. worker: true
  998. })
  999. return rebuildJob.finished
  1000. }
  1001. /**
  1002. * Trigger the rendering of a page
  1003. *
  1004. * @param {Object} page Page Model Instance
  1005. * @returns {Promise} Promise with no value
  1006. */
  1007. static async renderPage(page) {
  1008. const renderJob = await WIKI.scheduler.addJob({
  1009. task: 'render-page',
  1010. payload: {
  1011. id: page.id
  1012. },
  1013. maxRetries: 0,
  1014. promise: true
  1015. })
  1016. return renderJob.promise
  1017. }
  1018. /**
  1019. * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
  1020. *
  1021. * @param {Object} opts Page Properties
  1022. * @returns {Promise} Promise of the Page Model Instance
  1023. */
  1024. static async getPage(opts) {
  1025. return WIKI.db.pages.getPageFromDb(opts)
  1026. // -> Get from cache first
  1027. let page = await WIKI.db.pages.getPageFromCache(opts)
  1028. if (!page) {
  1029. // -> Get from DB
  1030. page = await WIKI.db.pages.getPageFromDb(opts)
  1031. if (page) {
  1032. if (page.render) {
  1033. // -> Save render to cache
  1034. await WIKI.db.pages.savePageToCache(page)
  1035. } else {
  1036. // -> No render? Possible duplicate issue
  1037. /* TODO: Detect duplicate and delete */
  1038. throw new Error('Error while fetching page. No rendered version of this page exists. Try to edit the page and save it again.')
  1039. }
  1040. }
  1041. }
  1042. return page
  1043. }
  1044. /**
  1045. * Fetch an Existing Page from the Database
  1046. *
  1047. * @param {Object} opts Page Properties
  1048. * @returns {Promise} Promise of the Page Model Instance
  1049. */
  1050. static async getPageFromDb(opts) {
  1051. const queryModeID = typeof opts === 'string'
  1052. try {
  1053. return WIKI.db.pages.query()
  1054. .column([
  1055. 'pages.*',
  1056. {
  1057. authorName: 'author.name',
  1058. authorEmail: 'author.email',
  1059. creatorName: 'creator.name',
  1060. creatorEmail: 'creator.email'
  1061. }
  1062. ])
  1063. .joinRelated('author')
  1064. .joinRelated('creator')
  1065. .withGraphJoined('tags')
  1066. .modifyGraph('tags', builder => {
  1067. builder.select('tag')
  1068. })
  1069. .where(queryModeID ? {
  1070. 'pages.id': opts
  1071. } : {
  1072. 'pages.siteId': opts.siteId,
  1073. 'pages.path': opts.path,
  1074. 'pages.localeCode': opts.locale
  1075. })
  1076. // .andWhere(builder => {
  1077. // if (queryModeID) return
  1078. // builder.where({
  1079. // 'pages.isPublished': true
  1080. // }).orWhere({
  1081. // 'pages.isPublished': false,
  1082. // 'pages.authorId': opts.userId
  1083. // })
  1084. // })
  1085. .first()
  1086. } catch (err) {
  1087. WIKI.logger.warn(err)
  1088. throw err
  1089. }
  1090. }
  1091. /**
  1092. * Save a Page Model Instance to Cache
  1093. *
  1094. * @param {Object} page Page Model Instance
  1095. * @returns {Promise} Promise with no value
  1096. */
  1097. static async savePageToCache(page) {
  1098. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${page.hash}.bin`)
  1099. await fs.outputFile(cachePath, WIKI.db.pages.cacheSchema.encode({
  1100. id: page.id,
  1101. authorId: page.authorId,
  1102. authorName: page.authorName,
  1103. createdAt: page.createdAt.toISOString(),
  1104. creatorId: page.creatorId,
  1105. creatorName: page.creatorName,
  1106. description: page.description,
  1107. editor: page.editor,
  1108. extra: {
  1109. css: _.get(page, 'extra.css', ''),
  1110. js: _.get(page, 'extra.js', '')
  1111. },
  1112. publishState: page.publishState ?? '',
  1113. publishEndDate: page.publishEndDate ?? '',
  1114. publishStartDate: page.publishStartDate ?? '',
  1115. render: page.render,
  1116. siteId: page.siteId,
  1117. tags: page.tags.map(t => _.pick(t, ['tag'])),
  1118. title: page.title,
  1119. toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  1120. updatedAt: page.updatedAt.toISOString()
  1121. }))
  1122. }
  1123. /**
  1124. * Fetch an Existing Page from Cache
  1125. *
  1126. * @param {Object} opts Page Properties
  1127. * @returns {Promise} Promise of the Page Model Instance
  1128. */
  1129. static async getPageFromCache(opts) {
  1130. const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale })
  1131. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${pageHash}.bin`)
  1132. try {
  1133. const pageBuffer = await fs.readFile(cachePath)
  1134. let page = WIKI.db.pages.cacheSchema.decode(pageBuffer)
  1135. return {
  1136. ...page,
  1137. path: opts.path,
  1138. localeCode: opts.locale
  1139. }
  1140. } catch (err) {
  1141. if (err.code === 'ENOENT') {
  1142. return false
  1143. }
  1144. WIKI.logger.error(err)
  1145. throw err
  1146. }
  1147. }
  1148. /**
  1149. * Delete an Existing Page from Cache
  1150. *
  1151. * @param {String} page Page Unique Hash
  1152. * @returns {Promise} Promise with no value
  1153. */
  1154. static async deletePageFromCache(hash) {
  1155. return fs.remove(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${hash}.bin`))
  1156. }
  1157. /**
  1158. * Flush the contents of the Cache
  1159. */
  1160. static async flushCache() {
  1161. return fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache`))
  1162. }
  1163. /**
  1164. * Migrate all pages from a source locale to the target locale
  1165. *
  1166. * @param {Object} opts Migration properties
  1167. * @param {string} opts.sourceLocale Source Locale Code
  1168. * @param {string} opts.targetLocale Target Locale Code
  1169. * @returns {Promise} Promise with no value
  1170. */
  1171. static async migrateToLocale({ sourceLocale, targetLocale }) {
  1172. return WIKI.db.pages.query()
  1173. .patch({
  1174. localeCode: targetLocale
  1175. })
  1176. .where({
  1177. localeCode: sourceLocale
  1178. })
  1179. .whereNotExists(function() {
  1180. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  1181. })
  1182. }
  1183. /**
  1184. * Clean raw HTML from content for use in search engines
  1185. *
  1186. * @param {string} rawHTML Raw HTML
  1187. * @returns {string} Cleaned Content Text
  1188. */
  1189. static cleanHTML(rawHTML = '') {
  1190. let data = striptags(rawHTML || '', [], ' ')
  1191. .replace(emojiRegex(), '')
  1192. // .replace(htmlEntitiesRegex, '')
  1193. return he.decode(data)
  1194. .replace(punctuationRegex, ' ')
  1195. .replace(/(\r\n|\n|\r)/gm, ' ')
  1196. .replace(/\s\s+/g, ' ')
  1197. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  1198. }
  1199. /**
  1200. * Subscribe to HA propagation events
  1201. */
  1202. static subscribeToEvents() {
  1203. WIKI.events.inbound.on('deletePageFromCache', hash => {
  1204. WIKI.db.pages.deletePageFromCache(hash)
  1205. })
  1206. WIKI.events.inbound.on('flushCache', () => {
  1207. WIKI.db.pages.flushCache()
  1208. })
  1209. }
  1210. }