pages.mjs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. import { Model } from 'objection'
  2. import { find, get, has, initial, isEmpty, isString, last, pick } from 'lodash-es'
  3. import { Type as JSBinType } from 'js-binary'
  4. import { generateHash, getFileExtension, injectPageMetadata } from '../helpers/page.mjs'
  5. import path from 'node:path'
  6. import fse from 'fs-extra'
  7. import yaml from 'js-yaml'
  8. import striptags from 'striptags'
  9. import emojiRegex from 'emoji-regex'
  10. import he from 'he'
  11. import CleanCSS from 'clean-css'
  12. import TurndownService from 'turndown'
  13. import { gfm as turndownPluginGfm } from '@joplin/turndown-plugin-gfm'
  14. import cheerio from 'cheerio'
  15. import { Locale } from './locales.mjs'
  16. import { PageLink } from './pageLinks.mjs'
  17. import { Tag } from './tags.mjs'
  18. import { User } from './users.mjs'
  19. const pageRegex = /^[a-zA0-90-9-_/]*$/
  20. const frontmatterRegex = {
  21. html: /^(<!-{2}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{2}>)?(?:\n|\r)*([\w\W]*)*/,
  22. legacy: /^(<!-- TITLE: ?([\w\W]+?) ?-{2}>)?(?:\n|\r)?(<!-- SUBTITLE: ?([\w\W]+?) ?-{2}>)?(?:\n|\r)*([\w\W]*)*/i,
  23. markdown: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?(?:\n|\r)*([\w\W]*)*/
  24. }
  25. const punctuationRegex = /[!,:;/\\_+\-=()&#@<>$~%^*[\]{}"'|]+|(\.\s)|(\s\.)/ig
  26. // const htmlEntitiesRegex = /(&#[0-9]{3};)|(&#x[a-zA-Z0-9]{2};)/ig
  27. /**
  28. * Pages model
  29. */
  30. export class Page extends Model {
  31. static get tableName() { return 'pages' }
  32. static get jsonSchema () {
  33. return {
  34. type: 'object',
  35. required: ['path', 'title'],
  36. properties: {
  37. id: {type: 'string'},
  38. path: {type: 'string'},
  39. hash: {type: 'string'},
  40. title: {type: 'string'},
  41. description: {type: 'string'},
  42. publishState: {type: 'string'},
  43. publishStartDate: {type: 'string'},
  44. publishEndDate: {type: 'string'},
  45. content: {type: 'string'},
  46. contentType: {type: 'string'},
  47. render: {type: 'string'},
  48. siteId: {type: 'string'},
  49. createdAt: {type: 'string'},
  50. updatedAt: {type: 'string'}
  51. }
  52. }
  53. }
  54. static get jsonAttributes() {
  55. return ['config', 'historyData', 'relations', 'scripts', 'toc']
  56. }
  57. static get relationMappings() {
  58. return {
  59. tags: {
  60. relation: Model.ManyToManyRelation,
  61. modelClass: Tag,
  62. join: {
  63. from: 'pages.id',
  64. through: {
  65. from: 'pageTags.pageId',
  66. to: 'pageTags.tagId'
  67. },
  68. to: 'tags.id'
  69. }
  70. },
  71. links: {
  72. relation: Model.HasManyRelation,
  73. modelClass: PageLink,
  74. join: {
  75. from: 'pages.id',
  76. to: 'pageLinks.pageId'
  77. }
  78. },
  79. author: {
  80. relation: Model.BelongsToOneRelation,
  81. modelClass: User,
  82. join: {
  83. from: 'pages.authorId',
  84. to: 'users.id'
  85. }
  86. },
  87. creator: {
  88. relation: Model.BelongsToOneRelation,
  89. modelClass: User,
  90. join: {
  91. from: 'pages.creatorId',
  92. to: 'users.id'
  93. }
  94. },
  95. locale: {
  96. relation: Model.BelongsToOneRelation,
  97. modelClass: Locale,
  98. join: {
  99. from: 'pages.localeCode',
  100. to: 'locales.code'
  101. }
  102. }
  103. }
  104. }
  105. $beforeUpdate() {
  106. this.updatedAt = new Date().toISOString()
  107. }
  108. $beforeInsert() {
  109. this.createdAt = new Date().toISOString()
  110. this.updatedAt = new Date().toISOString()
  111. }
  112. /**
  113. * Solving the violates foreign key constraint using cascade strategy
  114. * using static hooks
  115. * @see https://vincit.github.io/objection.js/api/types/#type-statichookarguments
  116. */
  117. static async beforeDelete({ asFindQuery }) {
  118. const page = await asFindQuery().select('id')
  119. await WIKI.db.comments.query().delete().where('pageId', page[0].id)
  120. }
  121. /**
  122. * Cache Schema
  123. */
  124. static get cacheSchema() {
  125. return new JSBinType({
  126. id: 'string',
  127. authorId: 'string',
  128. authorName: 'string',
  129. createdAt: 'string',
  130. creatorId: 'string',
  131. creatorName: 'string',
  132. description: 'string',
  133. editor: 'string',
  134. publishState: 'string',
  135. publishEndDate: 'string',
  136. publishStartDate: 'string',
  137. render: 'string',
  138. siteId: 'string',
  139. tags: [
  140. {
  141. tag: 'string'
  142. }
  143. ],
  144. extra: {
  145. js: 'string',
  146. css: 'string'
  147. },
  148. title: 'string',
  149. toc: 'string',
  150. updatedAt: 'string'
  151. })
  152. }
  153. /**
  154. * Inject page metadata into contents
  155. *
  156. * @returns {string} Page Contents with Injected Metadata
  157. */
  158. injectMetadata () {
  159. return injectPageMetadata(this)
  160. }
  161. /**
  162. * Get the page's file extension based on content type
  163. *
  164. * @returns {string} File Extension
  165. */
  166. getFileExtension() {
  167. return getFileExtension(this.contentType)
  168. }
  169. /**
  170. * Parse injected page metadata from raw content
  171. *
  172. * @param {String} raw Raw file contents
  173. * @param {String} contentType Content Type
  174. * @returns {Object} Parsed Page Metadata with Raw Content
  175. */
  176. static parseMetadata (raw, contentType) {
  177. let result
  178. try {
  179. switch (contentType) {
  180. case 'markdown':
  181. result = frontmatterRegex.markdown.exec(raw)
  182. if (result[2]) {
  183. return {
  184. ...yaml.safeLoad(result[2]),
  185. content: result[3]
  186. }
  187. } else {
  188. // Attempt legacy v1 format
  189. result = frontmatterRegex.legacy.exec(raw)
  190. if (result[2]) {
  191. return {
  192. title: result[2],
  193. description: result[4],
  194. content: result[5]
  195. }
  196. }
  197. }
  198. break
  199. case 'html':
  200. result = frontmatterRegex.html.exec(raw)
  201. if (result[2]) {
  202. return {
  203. ...yaml.safeLoad(result[2]),
  204. content: result[3]
  205. }
  206. }
  207. break
  208. }
  209. } catch (err) {
  210. WIKI.logger.warn('Failed to parse page metadata. Invalid syntax.')
  211. }
  212. return {
  213. content: raw
  214. }
  215. }
  216. /**
  217. * Create a New Page
  218. *
  219. * @param {Object} opts Page Properties
  220. * @returns {Promise} Promise of the Page Model Instance
  221. */
  222. static async createPage(opts) {
  223. // -> Validate site
  224. if (!WIKI.sites[opts.siteId]) {
  225. throw new WIKI.Error.Custom('InvalidSiteId', 'Site ID is invalid.')
  226. }
  227. // -> Remove trailing slash
  228. if (opts.path.endsWith('/')) {
  229. opts.path = opts.path.slice(0, -1)
  230. }
  231. // -> Remove starting slash
  232. if (opts.path.startsWith('/')) {
  233. opts.path = opts.path.slice(1)
  234. }
  235. // -> Validate path
  236. if (!pageRegex.test(opts.path)) {
  237. throw new Error('ERR_INVALID_PATH')
  238. }
  239. opts.path = opts.path.toLowerCase()
  240. // const dotPath = opts.path.replaceAll('/', '.').replaceAll('-', '_')
  241. // -> Check for page access
  242. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  243. locale: opts.locale,
  244. path: opts.path
  245. })) {
  246. throw new WIKI.Error.PageDeleteForbidden()
  247. }
  248. // -> Check for duplicate
  249. const dupCheck = await WIKI.db.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
  250. if (dupCheck) {
  251. throw new WIKI.Error.PageDuplicateCreate()
  252. }
  253. // -> Check for empty content
  254. if (!opts.content || opts.content.trim().length < 1) {
  255. throw new WIKI.Error.PageEmptyContent()
  256. }
  257. // -> Format CSS Scripts
  258. let scriptCss = ''
  259. if (WIKI.auth.checkAccess(opts.user, ['write:styles'], {
  260. locale: opts.locale,
  261. path: opts.path
  262. })) {
  263. if (!isEmpty(opts.scriptCss)) {
  264. scriptCss = new CleanCSS({ inline: false }).minify(opts.scriptCss).styles
  265. } else {
  266. scriptCss = ''
  267. }
  268. }
  269. // -> Format JS Scripts
  270. let scriptJsLoad = ''
  271. let scriptJsUnload = ''
  272. if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
  273. locale: opts.locale,
  274. path: opts.path
  275. })) {
  276. scriptJsLoad = opts.scriptJsLoad || ''
  277. scriptJsUnload = opts.scriptJsUnload || ''
  278. }
  279. // -> Create page
  280. const page = await WIKI.db.pages.query().insert({
  281. authorId: opts.user.id,
  282. content: opts.content,
  283. creatorId: opts.user.id,
  284. config: {
  285. allowComments: opts.allowComments ?? true,
  286. allowContributions: opts.allowContributions ?? true,
  287. allowRatings: opts.allowRatings ?? true,
  288. showSidebar: opts.showSidebar ?? true,
  289. showTags: opts.showTags ?? true,
  290. showToc: opts.showToc ?? true,
  291. tocDepth: opts.tocDepth ?? WIKI.sites[opts.siteId].config?.defaults.tocDepth
  292. },
  293. contentType: WIKI.data.editors[opts.editor]?.contentType ?? 'text',
  294. description: opts.description,
  295. editor: opts.editor,
  296. hash: generateHash({ path: opts.path, locale: opts.locale }),
  297. icon: opts.icon,
  298. isBrowsable: opts.isBrowsable ?? true,
  299. localeCode: opts.locale,
  300. ownerId: opts.user.id,
  301. path: opts.path,
  302. publishState: opts.publishState,
  303. publishEndDate: opts.publishEndDate?.toISO(),
  304. publishStartDate: opts.publishStartDate?.toISO(),
  305. relations: opts.relations ?? [],
  306. siteId: opts.siteId,
  307. title: opts.title,
  308. toc: '[]',
  309. scripts: JSON.stringify({
  310. jsLoad: scriptJsLoad,
  311. jsUnload: scriptJsUnload,
  312. css: scriptCss
  313. })
  314. }).returning('*')
  315. // -> Save Tags
  316. if (opts.tags && opts.tags.length > 0) {
  317. await WIKI.db.tags.associateTags({ tags: opts.tags, page })
  318. }
  319. // -> Render page to HTML
  320. await WIKI.db.pages.renderPage(page)
  321. // -> Add to tree
  322. const pathParts = page.path.split('/')
  323. await WIKI.db.tree.addPage({
  324. id: page.id,
  325. parentPath: initial(pathParts).join('/'),
  326. fileName: last(pathParts),
  327. locale: page.localeCode,
  328. title: page.title,
  329. meta: {
  330. authorId: page.authorId,
  331. contentType: page.contentType,
  332. creatorId: page.creatorId,
  333. description: page.description,
  334. isBrowsable: page.isBrowsable,
  335. ownerId: page.ownerId,
  336. publishState: page.publishState,
  337. publishEndDate: page.publishEndDate,
  338. publishStartDate: page.publishStartDate
  339. },
  340. siteId: page.siteId
  341. })
  342. return page
  343. // TODO: Handle remaining flow
  344. // -> Rebuild page tree
  345. await WIKI.db.pages.rebuildTree()
  346. // -> Add to Search Index
  347. const pageContents = await WIKI.db.pages.query().findById(page.id).select('render')
  348. page.safeContent = WIKI.db.pages.cleanHTML(pageContents.render)
  349. await WIKI.data.searchEngine.created(page)
  350. // -> Add to Storage
  351. if (!opts.skipStorage) {
  352. await WIKI.db.storage.pageEvent({
  353. event: 'created',
  354. page
  355. })
  356. }
  357. // -> Reconnect Links
  358. await WIKI.db.pages.reconnectLinks({
  359. locale: page.localeCode,
  360. path: page.path,
  361. mode: 'create'
  362. })
  363. // -> Get latest updatedAt
  364. page.updatedAt = await WIKI.db.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)
  365. return page
  366. }
  367. /**
  368. * Update an Existing Page
  369. *
  370. * @param {Object} opts Page Properties
  371. * @returns {Promise} Promise of the Page Model Instance
  372. */
  373. static async updatePage(opts) {
  374. // -> Fetch original page
  375. const ogPage = await WIKI.db.pages.query().findById(opts.id)
  376. if (!ogPage) {
  377. throw new Error('ERR_PAGE_NOT_FOUND')
  378. }
  379. // -> Check for page access
  380. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  381. locale: ogPage.localeCode,
  382. path: ogPage.path
  383. })) {
  384. throw new Error('ERR_PAGE_UPDATE_FORBIDDEN')
  385. }
  386. const patch = {}
  387. const historyData = {
  388. action: 'updated',
  389. affectedFields: []
  390. }
  391. // -> Create version snapshot
  392. await WIKI.db.pageHistory.addVersion(ogPage)
  393. // -> Basic fields
  394. if ('title' in opts.patch) {
  395. patch.title = opts.patch.title.trim()
  396. historyData.affectedFields.push('title')
  397. if (patch.title.length < 1) {
  398. throw new Error('ERR_PAGE_TITLE_MISSING')
  399. }
  400. }
  401. if ('description' in opts.patch) {
  402. patch.description = opts.patch.description.trim()
  403. historyData.affectedFields.push('description')
  404. }
  405. if ('icon' in opts.patch) {
  406. patch.icon = opts.patch.icon.trim()
  407. historyData.affectedFields.push('icon')
  408. }
  409. if ('content' in opts.patch) {
  410. patch.content = opts.patch.content
  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 = 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 fse.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 = 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 fse.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 fse.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 fse.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. }