2
0

pages.mjs 40 KB

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