You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1158 lines
34 KiB

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