pages.mjs 40 KB

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