pages.js 33 KB

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