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.

150 lines
3.8 KiB

  1. const qs = require('querystring')
  2. const _ = require('lodash')
  3. const crypto = require('crypto')
  4. const path = require('path')
  5. const localeSegmentRegex = /^[A-Z]{2}(-[A-Z]{2})?$/i
  6. const localeFolderRegex = /^([a-z]{2}(?:-[a-z]{2})?\/)?(.*)/i
  7. // eslint-disable-next-line no-control-regex
  8. const unsafeCharsRegex = /[\x00-\x1f\x80-\x9f\\"|<>:*?]/
  9. const contentToExt = {
  10. markdown: 'md',
  11. html: 'html'
  12. }
  13. const extToContent = _.invert(contentToExt)
  14. /* global WIKI */
  15. module.exports = {
  16. /**
  17. * Parse raw url path and make it safe
  18. */
  19. parsePath (rawPath, opts = {}) {
  20. let pathObj = {
  21. locale: WIKI.config.lang.code,
  22. path: 'home',
  23. private: false,
  24. privateNS: '',
  25. explicitLocale: false
  26. }
  27. // Clean Path
  28. rawPath = _.trim(qs.unescape(rawPath))
  29. if (_.startsWith(rawPath, '/')) { rawPath = rawPath.substring(1) }
  30. rawPath = rawPath.replace(unsafeCharsRegex, '')
  31. if (rawPath === '') { rawPath = 'home' }
  32. // Extract Info
  33. let pathParts = _.filter(_.split(rawPath, '/'), p => {
  34. p = _.trim(p)
  35. return !_.isEmpty(p) && p !== '..' && p !== '.'
  36. })
  37. if (pathParts[0].length === 1) {
  38. pathParts.shift()
  39. }
  40. if (localeSegmentRegex.test(pathParts[0])) {
  41. pathObj.locale = pathParts[0]
  42. pathObj.explicitLocale = true
  43. pathParts.shift()
  44. }
  45. // Strip extension
  46. if (opts.stripExt && pathParts.length > 0) {
  47. const lastPart = _.last(pathParts)
  48. if (lastPart.indexOf('.') > 0) {
  49. pathParts.pop()
  50. const lastPartMeta = path.parse(lastPart)
  51. pathParts.push(lastPartMeta.name)
  52. }
  53. }
  54. pathObj.path = _.join(pathParts, '/')
  55. return pathObj
  56. },
  57. /**
  58. * Generate unique hash from page
  59. */
  60. generateHash(opts) {
  61. return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
  62. },
  63. /**
  64. * Inject Page Metadata
  65. */
  66. injectPageMetadata(page) {
  67. let meta = [
  68. ['title', page.title],
  69. ['description', page.description],
  70. ['published', page.isPublished.toString()],
  71. ['date', page.updatedAt],
  72. ['tags', page.tags ? page.tags.map(t => t.tag).join(', ') : ''],
  73. ['editor', page.editorKey],
  74. ['dateCreated', page.createdAt]
  75. ]
  76. switch (page.contentType) {
  77. case 'markdown':
  78. return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content
  79. case 'html':
  80. return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
  81. case 'json':
  82. return {
  83. ...page.content,
  84. _meta: _.fromPairs(meta)
  85. }
  86. default:
  87. return page.content
  88. }
  89. },
  90. /**
  91. * Check if path is a reserved path
  92. */
  93. isReservedPath(rawPath) {
  94. const firstSection = _.head(rawPath.split('/'))
  95. if (firstSection.length <= 1) {
  96. return true
  97. } else if (localeSegmentRegex.test(firstSection)) {
  98. return true
  99. } else if (
  100. _.some(WIKI.data.reservedPaths, p => {
  101. return p === firstSection
  102. })) {
  103. return true
  104. } else {
  105. return false
  106. }
  107. },
  108. /**
  109. * Get file extension from content type
  110. */
  111. getFileExtension(contentType) {
  112. return _.get(contentToExt, contentType, 'txt')
  113. },
  114. /**
  115. * Get content type from file extension
  116. */
  117. getContentType (filePath) {
  118. const ext = _.last(filePath.split('.'))
  119. return _.get(extToContent, ext, false)
  120. },
  121. /**
  122. * Get Page Meta object from disk path
  123. */
  124. getPagePath (filePath) {
  125. let fpath = filePath
  126. if (process.platform === 'win32') {
  127. fpath = filePath.replace(/\\/g, '/')
  128. }
  129. let meta = {
  130. locale: WIKI.config.lang.code,
  131. path: _.initial(fpath.split('.')).join('')
  132. }
  133. const result = localeFolderRegex.exec(meta.path)
  134. if (result[1]) {
  135. meta = {
  136. locale: result[1].replace('/', ''),
  137. path: result[2]
  138. }
  139. }
  140. return meta
  141. }
  142. }