pages.mjs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. import { Model } from 'objection'
  2. import { find, get, has, isEmpty, isString, 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 || _.trim(opts.content).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. render: opts.render ?? '',
  307. siteId: opts.siteId,
  308. title: opts.title,
  309. toc: '[]',
  310. scripts: JSON.stringify({
  311. jsLoad: scriptJsLoad,
  312. jsUnload: scriptJsUnload,
  313. css: scriptCss
  314. })
  315. }).returning('*')
  316. // -> Save Tags
  317. if (opts.tags && opts.tags.length > 0) {
  318. await WIKI.db.tags.associateTags({ tags: opts.tags, page })
  319. }
  320. // -> Render page to HTML
  321. await WIKI.db.pages.renderPage(page)
  322. // -> Add to tree
  323. const pathParts = page.path.split('/')
  324. await WIKI.db.tree.addPage({
  325. id: page.id,
  326. parentPath: _.initial(pathParts).join('/'),
  327. fileName: _.last(pathParts),
  328. locale: page.localeCode,
  329. title: page.title,
  330. meta: {
  331. authorId: page.authorId,
  332. contentType: page.contentType,
  333. creatorId: page.creatorId,
  334. description: page.description,
  335. isBrowsable: page.isBrowsable,
  336. ownerId: page.ownerId,
  337. publishState: page.publishState,
  338. publishEndDate: page.publishEndDate,
  339. publishStartDate: page.publishStartDate
  340. },
  341. siteId: page.siteId
  342. })
  343. return page
  344. // TODO: Handle remaining flow
  345. // -> Rebuild page tree
  346. await WIKI.db.pages.rebuildTree()
  347. // -> Add to Search Index
  348. const pageContents = await WIKI.db.pages.query().findById(page.id).select('render')
  349. page.safeContent = WIKI.db.pages.cleanHTML(pageContents.render)
  350. await WIKI.data.searchEngine.created(page)
  351. // -> Add to Storage
  352. if (!opts.skipStorage) {
  353. await WIKI.db.storage.pageEvent({
  354. event: 'created',
  355. page
  356. })
  357. }
  358. // -> Reconnect Links
  359. await WIKI.db.pages.reconnectLinks({
  360. locale: page.localeCode,
  361. path: page.path,
  362. mode: 'create'
  363. })
  364. // -> Get latest updatedAt
  365. page.updatedAt = await WIKI.db.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)
  366. return page
  367. }
  368. /**
  369. * Update an Existing Page
  370. *
  371. * @param {Object} opts Page Properties
  372. * @returns {Promise} Promise of the Page Model Instance
  373. */
  374. static async updatePage(opts) {
  375. // -> Fetch original page
  376. const ogPage = await WIKI.db.pages.query().findById(opts.id)
  377. if (!ogPage) {
  378. throw new Error('ERR_PAGE_NOT_FOUND')
  379. }
  380. // -> Check for page access
  381. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  382. locale: ogPage.localeCode,
  383. path: ogPage.path
  384. })) {
  385. throw new Error('ERR_PAGE_UPDATE_FORBIDDEN')
  386. }
  387. const patch = {}
  388. const historyData = {
  389. action: 'updated',
  390. affectedFields: []
  391. }
  392. // -> Create version snapshot
  393. await WIKI.db.pageHistory.addVersion(ogPage)
  394. // -> Basic fields
  395. if ('title' in opts.patch) {
  396. patch.title = opts.patch.title.trim()
  397. historyData.affectedFields.push('title')
  398. if (patch.title.length < 1) {
  399. throw new Error('ERR_PAGE_TITLE_MISSING')
  400. }
  401. }
  402. if ('description' in opts.patch) {
  403. patch.description = opts.patch.description.trim()
  404. historyData.affectedFields.push('description')
  405. }
  406. if ('icon' in opts.patch) {
  407. patch.icon = opts.patch.icon.trim()
  408. historyData.affectedFields.push('icon')
  409. }
  410. if ('content' in opts.patch) {
  411. patch.content = opts.patch.content
  412. if ('render' in opts.patch) {
  413. patch.render = opts.patch.render
  414. }
  415. historyData.affectedFields.push('content')
  416. }
  417. // -> Publish State
  418. if (opts.patch.publishState) {
  419. patch.publishState = opts.patch.publishState
  420. historyData.affectedFields.push('publishState')
  421. if (patch.publishState === 'scheduled' && (!opts.patch.publishStartDate || !opts.patch.publishEndDate)) {
  422. throw new Error('ERR_PAGE_MISSING_SCHEDULED_DATES')
  423. }
  424. }
  425. if (opts.patch.publishStartDate) {
  426. patch.publishStartDate = opts.patch.publishStartDate
  427. historyData.affectedFields.push('publishStartDate')
  428. }
  429. if (opts.patch.publishEndDate) {
  430. patch.publishEndDate = opts.patch.publishEndDate
  431. historyData.affectedFields.push('publishEndDate')
  432. }
  433. // -> Page Config
  434. if ('isBrowsable' in opts.patch) {
  435. patch.config = {
  436. ...patch.config ?? ogPage.config ?? {},
  437. isBrowsable: opts.patch.isBrowsable
  438. }
  439. historyData.affectedFields.push('isBrowsable')
  440. }
  441. if ('allowComments' in opts.patch) {
  442. patch.config = {
  443. ...patch.config ?? ogPage.config ?? {},
  444. allowComments: opts.patch.allowComments
  445. }
  446. historyData.affectedFields.push('allowComments')
  447. }
  448. if ('allowContributions' in opts.patch) {
  449. patch.config = {
  450. ...patch.config ?? ogPage.config ?? {},
  451. allowContributions: opts.patch.allowContributions
  452. }
  453. historyData.affectedFields.push('allowContributions')
  454. }
  455. if ('allowRatings' in opts.patch) {
  456. patch.config = {
  457. ...patch.config ?? ogPage.config ?? {},
  458. allowRatings: opts.patch.allowRatings
  459. }
  460. historyData.affectedFields.push('allowRatings')
  461. }
  462. if ('showSidebar' in opts.patch) {
  463. patch.config = {
  464. ...patch.config ?? ogPage.config ?? {},
  465. showSidebar: opts.patch.showSidebar
  466. }
  467. historyData.affectedFields.push('showSidebar')
  468. }
  469. if ('showTags' in opts.patch) {
  470. patch.config = {
  471. ...patch.config ?? ogPage.config ?? {},
  472. showTags: opts.patch.showTags
  473. }
  474. historyData.affectedFields.push('showTags')
  475. }
  476. if ('showToc' in opts.patch) {
  477. patch.config = {
  478. ...patch.config ?? ogPage.config ?? {},
  479. showToc: opts.patch.showToc
  480. }
  481. historyData.affectedFields.push('showToc')
  482. }
  483. if ('tocDepth' in opts.patch) {
  484. patch.config = {
  485. ...patch.config ?? ogPage.config ?? {},
  486. tocDepth: opts.patch.tocDepth
  487. }
  488. historyData.affectedFields.push('tocDepth')
  489. if (patch.config.tocDepth?.min < 1 || patch.config.tocDepth?.min > 6) {
  490. throw new Error('ERR_PAGE_INVALID_TOC_DEPTH')
  491. }
  492. if (patch.config.tocDepth?.max < 1 || patch.config.tocDepth?.max > 6) {
  493. throw new Error('ERR_PAGE_INVALID_TOC_DEPTH')
  494. }
  495. }
  496. // -> Relations
  497. if ('relations' in opts.patch) {
  498. patch.relations = opts.patch.relations.map(r => {
  499. if (r.label.length < 1) {
  500. throw new Error('ERR_PAGE_RELATION_LABEL_MISSING')
  501. } else if (r.label.length > 255) {
  502. throw new Error('ERR_PAGE_RELATION_LABEL_TOOLONG')
  503. } else if (r.icon.length > 255) {
  504. throw new Error('ERR_PAGE_RELATION_ICON_INVALID')
  505. } else if (r.target.length > 1024) {
  506. throw new Error('ERR_PAGE_RELATION_TARGET_INVALID')
  507. }
  508. return r
  509. })
  510. historyData.affectedFields.push('relations')
  511. }
  512. // -> Format CSS Scripts
  513. if (opts.patch.scriptCss) {
  514. if (WIKI.auth.checkAccess(opts.user, ['write:styles'], {
  515. locale: ogPage.localeCode,
  516. path: ogPage.path
  517. })) {
  518. patch.scripts = {
  519. ...patch.scripts ?? ogPage.scripts ?? {},
  520. css: !isEmpty(opts.patch.scriptCss) ? new CleanCSS({ inline: false }).minify(opts.patch.scriptCss).styles : ''
  521. }
  522. historyData.affectedFields.push('scripts.css')
  523. }
  524. }
  525. // -> Format JS Scripts
  526. if (opts.patch.scriptJsLoad) {
  527. if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
  528. locale: ogPage.localeCode,
  529. path: ogPage.path
  530. })) {
  531. patch.scripts = {
  532. ...patch.scripts ?? ogPage.scripts ?? {},
  533. jsLoad: opts.patch.scriptJsLoad ?? ''
  534. }
  535. historyData.affectedFields.push('scripts.jsLoad')
  536. }
  537. }
  538. if (opts.patch.scriptJsUnload) {
  539. if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
  540. locale: ogPage.localeCode,
  541. path: ogPage.path
  542. })) {
  543. patch.scripts = {
  544. ...patch.scripts ?? ogPage.scripts ?? {},
  545. jsUnload: opts.patch.scriptJsUnload ?? ''
  546. }
  547. historyData.affectedFields.push('scripts.jsUnload')
  548. }
  549. }
  550. // -> Tags
  551. if ('tags' in opts.patch) {
  552. historyData.affectedFields.push('tags')
  553. }
  554. // -> Update page
  555. await WIKI.db.pages.query().patch({
  556. ...patch,
  557. authorId: opts.user.id,
  558. historyData
  559. }).where('id', ogPage.id)
  560. let page = await WIKI.db.pages.getPageFromDb(ogPage.id)
  561. // -> Save Tags
  562. if (opts.patch.tags) {
  563. await WIKI.db.tags.associateTags({ tags: opts.patch.tags, page })
  564. }
  565. // -> Render page to HTML
  566. if (opts.patch.content) {
  567. await WIKI.db.pages.renderPage(page)
  568. }
  569. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  570. // -> Update tree
  571. await WIKI.db.knex('tree').where('id', page.id).update({
  572. title: page.title,
  573. meta: {
  574. authorId: page.authorId,
  575. contentType: page.contentType,
  576. creatorId: page.creatorId,
  577. description: page.description,
  578. isBrowsable: page.isBrowsable,
  579. ownerId: page.ownerId,
  580. publishState: page.publishState,
  581. publishEndDate: page.publishEndDate,
  582. publishStartDate: page.publishStartDate
  583. },
  584. updatedAt: page.updatedAt
  585. })
  586. // // -> Update Search Index
  587. // const pageContents = await WIKI.db.pages.query().findById(page.id).select('render')
  588. // page.safeContent = WIKI.db.pages.cleanHTML(pageContents.render)
  589. // await WIKI.data.searchEngine.updated(page)
  590. // -> Update on Storage
  591. // if (!opts.skipStorage) {
  592. // await WIKI.db.storage.pageEvent({
  593. // event: 'updated',
  594. // page
  595. // })
  596. // }
  597. // -> Perform move?
  598. if ((opts.locale && opts.locale !== page.localeCode) || (opts.path && opts.path !== page.path)) {
  599. // -> Check target path access
  600. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  601. locale: opts.locale,
  602. path: opts.path
  603. })) {
  604. throw new WIKI.Error.PageMoveForbidden()
  605. }
  606. await WIKI.db.pages.movePage({
  607. id: page.id,
  608. destinationLocale: opts.locale,
  609. destinationPath: opts.path,
  610. user: opts.user
  611. })
  612. }
  613. // -> Get latest updatedAt
  614. page.updatedAt = await WIKI.db.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)
  615. return page
  616. }
  617. /**
  618. * Convert an Existing Page
  619. *
  620. * @param {Object} opts Page Properties
  621. * @returns {Promise} Promise of the Page Model Instance
  622. */
  623. static async convertPage(opts) {
  624. // -> Fetch original page
  625. const ogPage = await WIKI.db.pages.query().findById(opts.id)
  626. if (!ogPage) {
  627. throw new Error('Invalid Page Id')
  628. }
  629. if (ogPage.editor === opts.editor) {
  630. throw new Error('Page is already using this editor. Nothing to convert.')
  631. }
  632. // -> Check for page access
  633. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  634. locale: ogPage.localeCode,
  635. path: ogPage.path
  636. })) {
  637. throw new WIKI.Error.PageUpdateForbidden()
  638. }
  639. // -> Check content type
  640. const sourceContentType = ogPage.contentType
  641. const targetContentType = get(find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text')
  642. const shouldConvert = sourceContentType !== targetContentType
  643. let convertedContent = null
  644. // -> Convert content
  645. if (shouldConvert) {
  646. // -> Markdown => HTML
  647. if (sourceContentType === 'markdown' && targetContentType === 'html') {
  648. if (!ogPage.render) {
  649. throw new Error('Aborted conversion because rendered page content is empty!')
  650. }
  651. convertedContent = ogPage.render
  652. const $ = cheerio.load(convertedContent, {
  653. decodeEntities: true
  654. })
  655. if ($.root().children().length > 0) {
  656. // Remove header anchors
  657. $('.toc-anchor').remove()
  658. // Attempt to convert tabsets
  659. $('tabset').each((tabI, tabElm) => {
  660. const tabHeaders = []
  661. // -> Extract templates
  662. $(tabElm).children('template').each((tmplI, tmplElm) => {
  663. if ($(tmplElm).attr('v-slot:tabs') === '') {
  664. $(tabElm).before('<ul class="tabset-headers">' + $(tmplElm).html() + '</ul>')
  665. } else {
  666. $(tabElm).after('<div class="markdown-tabset">' + $(tmplElm).html() + '</div>')
  667. }
  668. })
  669. // -> Parse tab headers
  670. $(tabElm).prev('.tabset-headers').children((i, elm) => {
  671. tabHeaders.push($(elm).html())
  672. })
  673. $(tabElm).prev('.tabset-headers').remove()
  674. // -> Inject tab headers
  675. $(tabElm).next('.markdown-tabset').children((i, elm) => {
  676. if (tabHeaders.length > i) {
  677. $(elm).prepend(`<h2>${tabHeaders[i]}</h2>`)
  678. }
  679. })
  680. $(tabElm).next('.markdown-tabset').prepend('<h1>Tabset</h1>')
  681. $(tabElm).remove()
  682. })
  683. convertedContent = $.html('body').replace('<body>', '').replace('</body>', '').replace(/&#x([0-9a-f]{1,6});/ig, (entity, code) => {
  684. code = parseInt(code, 16)
  685. // Don't unescape ASCII characters, assuming they're encoded for a good reason
  686. if (code < 0x80) return entity
  687. return String.fromCodePoint(code)
  688. })
  689. }
  690. // -> HTML => Markdown
  691. } else if (sourceContentType === 'html' && targetContentType === 'markdown') {
  692. const td = new TurndownService({
  693. bulletListMarker: '-',
  694. codeBlockStyle: 'fenced',
  695. emDelimiter: '*',
  696. fence: '```',
  697. headingStyle: 'atx',
  698. hr: '---',
  699. linkStyle: 'inlined',
  700. preformattedCode: true,
  701. strongDelimiter: '**'
  702. })
  703. td.use(turndownPluginGfm)
  704. td.keep(['kbd'])
  705. td.addRule('subscript', {
  706. filter: ['sub'],
  707. replacement: c => `~${c}~`
  708. })
  709. td.addRule('superscript', {
  710. filter: ['sup'],
  711. replacement: c => `^${c}^`
  712. })
  713. td.addRule('underline', {
  714. filter: ['u'],
  715. replacement: c => `_${c}_`
  716. })
  717. td.addRule('taskList', {
  718. filter: (n, o) => {
  719. return n.nodeName === 'INPUT' && n.getAttribute('type') === 'checkbox'
  720. },
  721. replacement: (c, n) => {
  722. return n.getAttribute('checked') ? '[x] ' : '[ ] '
  723. }
  724. })
  725. td.addRule('removeTocAnchors', {
  726. filter: (n, o) => {
  727. return n.nodeName === 'A' && n.classList.contains('toc-anchor')
  728. },
  729. replacement: c => ''
  730. })
  731. convertedContent = td.turndown(ogPage.content)
  732. // -> Unsupported
  733. } else {
  734. throw new Error('Unsupported source / destination content types combination.')
  735. }
  736. }
  737. // -> Create version snapshot
  738. if (shouldConvert) {
  739. await WIKI.db.pageHistory.addVersion({
  740. ...ogPage,
  741. action: 'updated',
  742. versionDate: ogPage.updatedAt
  743. })
  744. }
  745. // -> Update page
  746. await WIKI.db.pages.query().patch({
  747. contentType: targetContentType,
  748. editor: opts.editor,
  749. ...(convertedContent ? { content: convertedContent } : {})
  750. }).where('id', ogPage.id)
  751. const page = await WIKI.db.pages.getPageFromDb(ogPage.id)
  752. await WIKI.db.pages.deletePageFromCache(page.hash)
  753. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  754. // -> Update on Storage
  755. await WIKI.db.storage.pageEvent({
  756. event: 'updated',
  757. page
  758. })
  759. }
  760. /**
  761. * Move a Page
  762. *
  763. * @param {Object} opts Page Properties
  764. * @returns {Promise} Promise with no value
  765. */
  766. static async movePage(opts) {
  767. let page
  768. if (has(opts, 'id')) {
  769. page = await WIKI.db.pages.query().findById(opts.id)
  770. } else {
  771. page = await WIKI.db.pages.query().findOne({
  772. path: opts.path,
  773. localeCode: opts.locale
  774. })
  775. }
  776. if (!page) {
  777. throw new WIKI.Error.PageNotFound()
  778. }
  779. // -> Validate path
  780. if (opts.destinationPath.includes('.') || opts.destinationPath.includes(' ') || opts.destinationPath.includes('\\') || opts.destinationPath.includes('//')) {
  781. throw new WIKI.Error.PageIllegalPath()
  782. }
  783. // -> Remove trailing slash
  784. if (opts.destinationPath.endsWith('/')) {
  785. opts.destinationPath = opts.destinationPath.slice(0, -1)
  786. }
  787. // -> Remove starting slash
  788. if (opts.destinationPath.startsWith('/')) {
  789. opts.destinationPath = opts.destinationPath.slice(1)
  790. }
  791. // -> Check for source page access
  792. if (!WIKI.auth.checkAccess(opts.user, ['manage:pages'], {
  793. locale: page.localeCode,
  794. path: page.path
  795. })) {
  796. throw new WIKI.Error.PageMoveForbidden()
  797. }
  798. // -> Check for destination page access
  799. if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
  800. locale: opts.destinationLocale,
  801. path: opts.destinationPath
  802. })) {
  803. throw new WIKI.Error.PageMoveForbidden()
  804. }
  805. // -> Check for existing page at destination path
  806. const destPage = await WIKI.db.pages.query().findOne({
  807. path: opts.destinationPath,
  808. localeCode: opts.destinationLocale
  809. })
  810. if (destPage) {
  811. throw new WIKI.Error.PagePathCollision()
  812. }
  813. // -> Create version snapshot
  814. await WIKI.db.pageHistory.addVersion({
  815. ...page,
  816. action: 'moved',
  817. versionDate: page.updatedAt
  818. })
  819. const destinationHash = generateHash({ path: opts.destinationPath, locale: opts.destinationLocale })
  820. // -> Move page
  821. const destinationTitle = (page.title === page.path ? opts.destinationPath : page.title)
  822. await WIKI.db.pages.query().patch({
  823. path: opts.destinationPath,
  824. localeCode: opts.destinationLocale,
  825. title: destinationTitle,
  826. hash: destinationHash
  827. }).findById(page.id)
  828. await WIKI.db.pages.deletePageFromCache(page.hash)
  829. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  830. // -> Rebuild page tree
  831. await WIKI.db.pages.rebuildTree()
  832. // -> Rename in Search Index
  833. const pageContents = await WIKI.db.pages.query().findById(page.id).select('render')
  834. page.safeContent = WIKI.db.pages.cleanHTML(pageContents.render)
  835. await WIKI.data.searchEngine.renamed({
  836. ...page,
  837. destinationPath: opts.destinationPath,
  838. destinationLocaleCode: opts.destinationLocale,
  839. destinationHash
  840. })
  841. // -> Rename in Storage
  842. if (!opts.skipStorage) {
  843. await WIKI.db.storage.pageEvent({
  844. event: 'renamed',
  845. page: {
  846. ...page,
  847. destinationPath: opts.destinationPath,
  848. destinationLocaleCode: opts.destinationLocale,
  849. destinationHash,
  850. moveAuthorId: opts.user.id,
  851. moveAuthorName: opts.user.name,
  852. moveAuthorEmail: opts.user.email
  853. }
  854. })
  855. }
  856. // -> Reconnect Links : Changing old links to the new path
  857. await WIKI.db.pages.reconnectLinks({
  858. sourceLocale: page.localeCode,
  859. sourcePath: page.path,
  860. locale: opts.destinationLocale,
  861. path: opts.destinationPath,
  862. mode: 'move'
  863. })
  864. // -> Reconnect Links : Validate invalid links to the new path
  865. await WIKI.db.pages.reconnectLinks({
  866. locale: opts.destinationLocale,
  867. path: opts.destinationPath,
  868. mode: 'create'
  869. })
  870. }
  871. /**
  872. * Delete an Existing Page
  873. *
  874. * @param {Object} opts Page Properties
  875. * @returns {Promise} Promise with no value
  876. */
  877. static async deletePage(opts) {
  878. const page = await WIKI.db.pages.getPageFromDb(has(opts, 'id') ? opts.id : opts)
  879. if (!page) {
  880. throw new WIKI.Error.PageNotFound()
  881. }
  882. // -> Check for page access
  883. if (!WIKI.auth.checkAccess(opts.user, ['delete:pages'], {
  884. locale: page.locale,
  885. path: page.path
  886. })) {
  887. throw new WIKI.Error.PageDeleteForbidden()
  888. }
  889. // -> Create version snapshot
  890. await WIKI.db.pageHistory.addVersion({
  891. ...page,
  892. action: 'deleted',
  893. versionDate: page.updatedAt
  894. })
  895. // -> Delete page
  896. await WIKI.db.pages.query().delete().where('id', page.id)
  897. await WIKI.db.knex('tree').where('id', page.id).del()
  898. await WIKI.db.pages.deletePageFromCache(page.hash)
  899. WIKI.events.outbound.emit('deletePageFromCache', page.hash)
  900. // -> Delete from Search Index
  901. await WIKI.data.searchEngine.deleted(page)
  902. // -> Delete from Storage
  903. if (!opts.skipStorage) {
  904. await WIKI.db.storage.pageEvent({
  905. event: 'deleted',
  906. page
  907. })
  908. }
  909. // -> Reconnect Links
  910. await WIKI.db.pages.reconnectLinks({
  911. locale: page.localeCode,
  912. path: page.path,
  913. mode: 'delete'
  914. })
  915. }
  916. /**
  917. * Reconnect links to new/move/deleted page
  918. *
  919. * @param {Object} opts - Page parameters
  920. * @param {string} opts.path - Page Path
  921. * @param {string} opts.locale - Page Locale Code
  922. * @param {string} [opts.sourcePath] - Previous Page Path (move only)
  923. * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
  924. * @param {string} opts.mode - Page Update mode (create, move, delete)
  925. * @returns {Promise} Promise with no value
  926. */
  927. static async reconnectLinks (opts) {
  928. const pageHref = `/${opts.locale}/${opts.path}`
  929. let replaceArgs = {
  930. from: '',
  931. to: ''
  932. }
  933. switch (opts.mode) {
  934. case 'create':
  935. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  936. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  937. break
  938. case 'move':
  939. const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
  940. replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-valid-page">`
  941. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  942. break
  943. case 'delete':
  944. replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
  945. replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
  946. break
  947. default:
  948. return false
  949. }
  950. let affectedHashes = []
  951. // -> Perform replace and return affected page hashes (POSTGRES only)
  952. if (WIKI.config.db.type === 'postgres') {
  953. const qryHashes = await WIKI.db.pages.query()
  954. .returning('hash')
  955. .patch({
  956. render: WIKI.db.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  957. })
  958. .whereIn('pages.id', function () {
  959. this.select('pageLinks.pageId').from('pageLinks').where({
  960. 'pageLinks.path': opts.path,
  961. 'pageLinks.localeCode': opts.locale
  962. })
  963. })
  964. affectedHashes = qryHashes.map(h => h.hash)
  965. } else {
  966. // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, MSSQL, SQLITE only)
  967. await WIKI.db.pages.query()
  968. .patch({
  969. render: WIKI.db.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
  970. })
  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. const qryHashes = await WIKI.db.pages.query()
  978. .column('hash')
  979. .whereIn('pages.id', function () {
  980. this.select('pageLinks.pageId').from('pageLinks').where({
  981. 'pageLinks.path': opts.path,
  982. 'pageLinks.localeCode': opts.locale
  983. })
  984. })
  985. affectedHashes = qryHashes.map(h => h.hash)
  986. }
  987. for (const hash of affectedHashes) {
  988. await WIKI.db.pages.deletePageFromCache(hash)
  989. WIKI.events.outbound.emit('deletePageFromCache', hash)
  990. }
  991. }
  992. /**
  993. * Rebuild page tree for new/updated/deleted page
  994. *
  995. * @returns {Promise} Promise with no value
  996. */
  997. static async rebuildTree() {
  998. const rebuildJob = await WIKI.scheduler.registerJob({
  999. name: 'rebuild-tree',
  1000. immediate: true,
  1001. worker: true
  1002. })
  1003. return rebuildJob.finished
  1004. }
  1005. /**
  1006. * Trigger the rendering of a page
  1007. *
  1008. * @param {Object} page Page Model Instance
  1009. * @returns {Promise} Promise with no value
  1010. */
  1011. static async renderPage(page) {
  1012. const renderJob = await WIKI.scheduler.addJob({
  1013. task: 'render-page',
  1014. payload: {
  1015. id: page.id
  1016. },
  1017. maxRetries: 0,
  1018. promise: true
  1019. })
  1020. return renderJob.promise
  1021. }
  1022. /**
  1023. * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
  1024. *
  1025. * @param {Object} opts Page Properties
  1026. * @returns {Promise} Promise of the Page Model Instance
  1027. */
  1028. static async getPage(opts) {
  1029. return WIKI.db.pages.getPageFromDb(opts)
  1030. // -> Get from cache first
  1031. let page = await WIKI.db.pages.getPageFromCache(opts)
  1032. if (!page) {
  1033. // -> Get from DB
  1034. page = await WIKI.db.pages.getPageFromDb(opts)
  1035. if (page) {
  1036. if (page.render) {
  1037. // -> Save render to cache
  1038. await WIKI.db.pages.savePageToCache(page)
  1039. } else {
  1040. // -> No render? Possible duplicate issue
  1041. /* TODO: Detect duplicate and delete */
  1042. throw new Error('Error while fetching page. No rendered version of this page exists. Try to edit the page and save it again.')
  1043. }
  1044. }
  1045. }
  1046. return page
  1047. }
  1048. /**
  1049. * Fetch an Existing Page from the Database
  1050. *
  1051. * @param {Object} opts Page Properties
  1052. * @returns {Promise} Promise of the Page Model Instance
  1053. */
  1054. static async getPageFromDb(opts) {
  1055. const queryModeID = typeof opts === 'string'
  1056. try {
  1057. return WIKI.db.pages.query()
  1058. .column([
  1059. 'pages.*',
  1060. {
  1061. authorName: 'author.name',
  1062. authorEmail: 'author.email',
  1063. creatorName: 'creator.name',
  1064. creatorEmail: 'creator.email'
  1065. }
  1066. ])
  1067. .joinRelated('author')
  1068. .joinRelated('creator')
  1069. .withGraphJoined('tags')
  1070. .modifyGraph('tags', builder => {
  1071. builder.select('tag')
  1072. })
  1073. .where(queryModeID ? {
  1074. 'pages.id': opts
  1075. } : {
  1076. 'pages.siteId': opts.siteId,
  1077. 'pages.path': opts.path,
  1078. 'pages.localeCode': opts.locale
  1079. })
  1080. // .andWhere(builder => {
  1081. // if (queryModeID) return
  1082. // builder.where({
  1083. // 'pages.isPublished': true
  1084. // }).orWhere({
  1085. // 'pages.isPublished': false,
  1086. // 'pages.authorId': opts.userId
  1087. // })
  1088. // })
  1089. .first()
  1090. } catch (err) {
  1091. WIKI.logger.warn(err)
  1092. throw err
  1093. }
  1094. }
  1095. /**
  1096. * Save a Page Model Instance to Cache
  1097. *
  1098. * @param {Object} page Page Model Instance
  1099. * @returns {Promise} Promise with no value
  1100. */
  1101. static async savePageToCache(page) {
  1102. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${page.hash}.bin`)
  1103. await fse.outputFile(cachePath, WIKI.db.pages.cacheSchema.encode({
  1104. id: page.id,
  1105. authorId: page.authorId,
  1106. authorName: page.authorName,
  1107. createdAt: page.createdAt.toISOString(),
  1108. creatorId: page.creatorId,
  1109. creatorName: page.creatorName,
  1110. description: page.description,
  1111. editor: page.editor,
  1112. extra: {
  1113. css: get(page, 'extra.css', ''),
  1114. js: get(page, 'extra.js', '')
  1115. },
  1116. publishState: page.publishState ?? '',
  1117. publishEndDate: page.publishEndDate ?? '',
  1118. publishStartDate: page.publishStartDate ?? '',
  1119. render: page.render,
  1120. siteId: page.siteId,
  1121. tags: page.tags.map(t => pick(t, ['tag'])),
  1122. title: page.title,
  1123. toc: isString(page.toc) ? page.toc : JSON.stringify(page.toc),
  1124. updatedAt: page.updatedAt.toISOString()
  1125. }))
  1126. }
  1127. /**
  1128. * Fetch an Existing Page from Cache
  1129. *
  1130. * @param {Object} opts Page Properties
  1131. * @returns {Promise} Promise of the Page Model Instance
  1132. */
  1133. static async getPageFromCache(opts) {
  1134. const pageHash = generateHash({ path: opts.path, locale: opts.locale })
  1135. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${pageHash}.bin`)
  1136. try {
  1137. const pageBuffer = await fse.readFile(cachePath)
  1138. let page = WIKI.db.pages.cacheSchema.decode(pageBuffer)
  1139. return {
  1140. ...page,
  1141. path: opts.path,
  1142. localeCode: opts.locale
  1143. }
  1144. } catch (err) {
  1145. if (err.code === 'ENOENT') {
  1146. return false
  1147. }
  1148. WIKI.logger.error(err)
  1149. throw err
  1150. }
  1151. }
  1152. /**
  1153. * Delete an Existing Page from Cache
  1154. *
  1155. * @param {String} page Page Unique Hash
  1156. * @returns {Promise} Promise with no value
  1157. */
  1158. static async deletePageFromCache(hash) {
  1159. return fse.remove(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${hash}.bin`))
  1160. }
  1161. /**
  1162. * Flush the contents of the Cache
  1163. */
  1164. static async flushCache() {
  1165. return fse.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache`))
  1166. }
  1167. /**
  1168. * Migrate all pages from a source locale to the target locale
  1169. *
  1170. * @param {Object} opts Migration properties
  1171. * @param {string} opts.sourceLocale Source Locale Code
  1172. * @param {string} opts.targetLocale Target Locale Code
  1173. * @returns {Promise} Promise with no value
  1174. */
  1175. static async migrateToLocale({ sourceLocale, targetLocale }) {
  1176. return WIKI.db.pages.query()
  1177. .patch({
  1178. localeCode: targetLocale
  1179. })
  1180. .where({
  1181. localeCode: sourceLocale
  1182. })
  1183. .whereNotExists(function() {
  1184. this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
  1185. })
  1186. }
  1187. /**
  1188. * Clean raw HTML from content for use in search engines
  1189. *
  1190. * @param {string} rawHTML Raw HTML
  1191. * @returns {string} Cleaned Content Text
  1192. */
  1193. static cleanHTML(rawHTML = '') {
  1194. let data = striptags(rawHTML || '', [], ' ')
  1195. .replace(emojiRegex(), '')
  1196. // .replace(htmlEntitiesRegex, '')
  1197. return he.decode(data)
  1198. .replace(punctuationRegex, ' ')
  1199. .replace(/(\r\n|\n|\r)/gm, ' ')
  1200. .replace(/\s\s+/g, ' ')
  1201. .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  1202. }
  1203. /**
  1204. * Subscribe to HA propagation events
  1205. */
  1206. static subscribeToEvents() {
  1207. WIKI.events.inbound.on('deletePageFromCache', hash => {
  1208. WIKI.db.pages.deletePageFromCache(hash)
  1209. })
  1210. WIKI.events.inbound.on('flushCache', () => {
  1211. WIKI.db.pages.flushCache()
  1212. })
  1213. }
  1214. }