pages.js 38 KB

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