pages.mjs 40 KB

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