pages.mjs 40 KB

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