pages.mjs 40 KB

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