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.

152 lines
3.9 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. rawPath = rawPath.replace(/\\/g, '').replace(/\/\//g, '').replace(/\.\.+/ig, '')
  33. // Extract Info
  34. let pathParts = _.filter(_.split(rawPath, '/'), p => {
  35. p = _.trim(p)
  36. return !_.isEmpty(p) && p !== '..' && p !== '.'
  37. })
  38. if (pathParts[0].length === 1) {
  39. pathParts.shift()
  40. }
  41. if (localeSegmentRegex.test(pathParts[0])) {
  42. pathObj.locale = pathParts[0]
  43. pathObj.explicitLocale = true
  44. pathParts.shift()
  45. }
  46. // Strip extension
  47. if (opts.stripExt && pathParts.length > 0) {
  48. const lastPart = _.last(pathParts)
  49. if (lastPart.indexOf('.') > 0) {
  50. pathParts.pop()
  51. const lastPartMeta = path.parse(lastPart)
  52. pathParts.push(lastPartMeta.name)
  53. }
  54. }
  55. pathObj.path = _.join(pathParts, '/')
  56. return pathObj
  57. },
  58. /**
  59. * Generate unique hash from page
  60. */
  61. generateHash(opts) {
  62. return crypto.createHash('sha1').update(`${opts.locale}|${opts.path}|${opts.privateNS}`).digest('hex')
  63. },
  64. /**
  65. * Inject Page Metadata
  66. */
  67. injectPageMetadata(page) {
  68. let meta = [
  69. ['title', page.title],
  70. ['description', page.description],
  71. ['published', page.isPublished.toString()],
  72. ['date', page.updatedAt],
  73. ['tags', page.tags ? page.tags.map(t => t.tag).join(', ') : ''],
  74. ['editor', page.editorKey],
  75. ['dateCreated', page.createdAt]
  76. ]
  77. switch (page.contentType) {
  78. case 'markdown':
  79. return '---\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n---\n\n' + page.content
  80. case 'html':
  81. return '<!--\n' + meta.map(mt => `${mt[0]}: ${mt[1]}`).join('\n') + '\n-->\n\n' + page.content
  82. case 'json':
  83. return {
  84. ...page.content,
  85. _meta: _.fromPairs(meta)
  86. }
  87. default:
  88. return page.content
  89. }
  90. },
  91. /**
  92. * Check if path is a reserved path
  93. */
  94. isReservedPath(rawPath) {
  95. const firstSection = _.head(rawPath.split('/'))
  96. if (firstSection.length <= 1) {
  97. return true
  98. } else if (localeSegmentRegex.test(firstSection)) {
  99. return true
  100. } else if (
  101. _.some(WIKI.data.reservedPaths, p => {
  102. return p === firstSection
  103. })) {
  104. return true
  105. } else {
  106. return false
  107. }
  108. },
  109. /**
  110. * Get file extension from content type
  111. */
  112. getFileExtension(contentType) {
  113. return _.get(contentToExt, contentType, 'txt')
  114. },
  115. /**
  116. * Get content type from file extension
  117. */
  118. getContentType (filePath) {
  119. const ext = _.last(filePath.split('.'))
  120. return _.get(extToContent, ext, false)
  121. },
  122. /**
  123. * Get Page Meta object from disk path
  124. */
  125. getPagePath (filePath) {
  126. let fpath = filePath
  127. if (process.platform === 'win32') {
  128. fpath = filePath.replace(/\\/g, '/')
  129. }
  130. let meta = {
  131. locale: WIKI.config.lang.code,
  132. path: _.initial(fpath.split('.')).join('')
  133. }
  134. const result = localeFolderRegex.exec(meta.path)
  135. if (result[1]) {
  136. meta = {
  137. locale: result[1].replace('/', ''),
  138. path: result[2]
  139. }
  140. }
  141. return meta
  142. }
  143. }