pages.js 34 KB

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