pages.mjs 40 KB

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