pages.mjs 40 KB

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