pages.mjs 40 KB

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