pages.js 33 KB

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