page.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. const { serializePageSecurely } = require('../models/serializers/page-serializer');
  2. const { serializeRevisionSecurely } = require('../models/serializers/revision-serializer');
  3. /**
  4. * @swagger
  5. * tags:
  6. * name: Pages
  7. */
  8. /**
  9. * @swagger
  10. *
  11. * components:
  12. * schemas:
  13. * Page:
  14. * description: Page
  15. * type: object
  16. * properties:
  17. * _id:
  18. * type: string
  19. * description: page ID
  20. * example: 5e07345972560e001761fa63
  21. * __v:
  22. * type: number
  23. * description: DB record version
  24. * example: 0
  25. * commentCount:
  26. * type: number
  27. * description: count of comments
  28. * example: 3
  29. * createdAt:
  30. * type: string
  31. * description: date created at
  32. * example: 2010-01-01T00:00:00.000Z
  33. * creator:
  34. * $ref: '#/components/schemas/User'
  35. * extended:
  36. * type: object
  37. * description: extend data
  38. * example: {}
  39. * grant:
  40. * type: number
  41. * description: grant
  42. * example: 1
  43. * grantedUsers:
  44. * type: array
  45. * description: granted users
  46. * items:
  47. * type: string
  48. * description: user ID
  49. * example: ["5ae5fccfc5577b0004dbd8ab"]
  50. * lastUpdateUser:
  51. * $ref: '#/components/schemas/User'
  52. * liker:
  53. * type: array
  54. * description: granted users
  55. * items:
  56. * type: string
  57. * description: user ID
  58. * example: []
  59. * path:
  60. * type: string
  61. * description: page path
  62. * example: /
  63. * redirectTo:
  64. * type: string
  65. * description: redirect path
  66. * example: ""
  67. * revision:
  68. * $ref: '#/components/schemas/Revision'
  69. * status:
  70. * type: string
  71. * description: status
  72. * enum:
  73. * - 'wip'
  74. * - 'published'
  75. * - 'deleted'
  76. * - 'deprecated'
  77. * example: published
  78. * updatedAt:
  79. * type: string
  80. * description: date updated at
  81. * example: 2010-01-01T00:00:00.000Z
  82. *
  83. * UpdatePost:
  84. * description: UpdatePost
  85. * type: object
  86. * properties:
  87. * _id:
  88. * type: string
  89. * description: update post ID
  90. * example: 5e0734e472560e001761fa68
  91. * __v:
  92. * type: number
  93. * description: DB record version
  94. * example: 0
  95. * pathPattern:
  96. * type: string
  97. * description: path pattern
  98. * example: /test
  99. * patternPrefix:
  100. * type: string
  101. * description: patternPrefix prefix
  102. * example: /
  103. * patternPrefix2:
  104. * type: string
  105. * description: path
  106. * example: test
  107. * channel:
  108. * type: string
  109. * description: channel
  110. * example: general
  111. * provider:
  112. * type: string
  113. * description: provider
  114. * enum:
  115. * - slack
  116. * example: slack
  117. * creator:
  118. * $ref: '#/components/schemas/User'
  119. * createdAt:
  120. * type: string
  121. * description: date created at
  122. * example: 2010-01-01T00:00:00.000Z
  123. */
  124. /* eslint-disable no-use-before-define */
  125. module.exports = function(crowi, app) {
  126. const debug = require('debug')('growi:routes:page');
  127. const logger = require('@alias/logger')('growi:routes:page');
  128. const swig = require('swig-templates');
  129. const pathUtils = require('growi-commons').pathUtils;
  130. const Page = crowi.model('Page');
  131. const User = crowi.model('User');
  132. const Bookmark = crowi.model('Bookmark');
  133. const PageTagRelation = crowi.model('PageTagRelation');
  134. const UpdatePost = crowi.model('UpdatePost');
  135. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  136. const ShareLink = crowi.model('ShareLink');
  137. const ApiResponse = require('../util/apiResponse');
  138. const getToday = require('../util/getToday');
  139. const { slackNotificationService, configManager } = crowi;
  140. const interceptorManager = crowi.getInterceptorManager();
  141. const globalNotificationService = crowi.getGlobalNotificationService();
  142. const XssOption = require('../../lib/service/xss/xssOption');
  143. const Xss = require('../../lib/service/xss/index');
  144. const initializedConfig = {
  145. isEnabledXssPrevention: crowi.configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  146. tagWhiteList: crowi.xssService.getTagWhiteList(),
  147. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  148. };
  149. const xssOption = new XssOption(initializedConfig);
  150. const xss = new Xss(xssOption);
  151. const actions = {};
  152. function getPathFromRequest(req) {
  153. return pathUtils.normalizePath(req.params[0] || '');
  154. }
  155. function isUserPage(path) {
  156. if (path.match(/^\/user\/[^/]+\/?$/)) {
  157. return true;
  158. }
  159. return false;
  160. }
  161. function generatePager(offset, limit, totalCount) {
  162. let prev = null;
  163. if (offset > 0) {
  164. prev = offset - limit;
  165. if (prev < 0) {
  166. prev = 0;
  167. }
  168. }
  169. let next = offset + limit;
  170. if (totalCount < next) {
  171. next = null;
  172. }
  173. return {
  174. prev,
  175. next,
  176. offset,
  177. };
  178. }
  179. // user notification
  180. // TODO create '/service/user-notification' module
  181. /**
  182. *
  183. * @param {Page} page
  184. * @param {User} user
  185. * @param {string} slackChannelsStr comma separated string. e.g. 'general,channel1,channel2'
  186. * @param {boolean} updateOrCreate
  187. * @param {string} previousRevision
  188. */
  189. async function notifyToSlackByUser(page, user, slackChannelsStr, updateOrCreate, previousRevision) {
  190. await page.updateSlackChannel(slackChannelsStr)
  191. .catch((err) => {
  192. logger.error('Error occured in updating slack channels: ', err);
  193. });
  194. if (slackNotificationService.hasSlackConfig()) {
  195. const slackChannels = slackChannelsStr != null ? slackChannelsStr.split(',') : [null];
  196. const promises = slackChannels.map((chan) => {
  197. return crowi.slack.postPage(page, user, chan, updateOrCreate, previousRevision);
  198. });
  199. Promise.all(promises)
  200. .catch((err) => {
  201. logger.error('Error occured in sending slack notification: ', err);
  202. });
  203. }
  204. }
  205. function addRenderVarsForPage(renderVars, page) {
  206. renderVars.page = page;
  207. renderVars.revision = page.revision;
  208. renderVars.pageIdOnHackmd = page.pageIdOnHackmd;
  209. renderVars.revisionHackmdSynced = page.revisionHackmdSynced;
  210. renderVars.hasDraftOnHackmd = page.hasDraftOnHackmd;
  211. if (page.creator != null) {
  212. renderVars.page.creator = renderVars.page.creator.toObject();
  213. }
  214. if (page.revision.author != null) {
  215. renderVars.revision.author = renderVars.revision.author.toObject();
  216. }
  217. }
  218. function addRenderVarsForPresentation(renderVars, page) {
  219. // sanitize page.revision.body
  220. if (crowi.configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention')) {
  221. const preventXssRevision = xss.process(page.revision.body);
  222. page.revision.body = preventXssRevision;
  223. }
  224. renderVars.page = page;
  225. renderVars.revision = page.revision;
  226. }
  227. async function addRenderVarsForUserPage(renderVars, page, requestUser) {
  228. const userData = await User.findUserByUsername(User.getUsernameByPath(page.path));
  229. if (userData != null) {
  230. renderVars.pageUser = userData.toObject();
  231. renderVars.bookmarkList = await Bookmark.findByUser(userData, { limit: 10, populatePage: true, requestUser });
  232. }
  233. }
  234. function addRenderVarsForScope(renderVars, page) {
  235. renderVars.grant = page.grant;
  236. renderVars.grantedGroupId = page.grantedGroup ? page.grantedGroup.id : null;
  237. renderVars.grantedGroupName = page.grantedGroup ? page.grantedGroup.name : null;
  238. }
  239. async function addRenderVarsForSlack(renderVars, page) {
  240. renderVars.slack = await getSlackChannels(page);
  241. }
  242. async function addRenderVarsForDescendants(renderVars, path, requestUser, offset, limit, isRegExpEscapedFromPath) {
  243. const SEENER_THRESHOLD = 10;
  244. const queryOptions = {
  245. offset,
  246. limit,
  247. includeTrashed: path.startsWith('/trash/'),
  248. isRegExpEscapedFromPath,
  249. };
  250. const result = await Page.findListWithDescendants(path, requestUser, queryOptions);
  251. if (result.pages.length > limit) {
  252. result.pages.pop();
  253. }
  254. renderVars.viewConfig = {
  255. seener_threshold: SEENER_THRESHOLD,
  256. };
  257. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  258. renderVars.pages = result.pages;
  259. }
  260. function replacePlaceholdersOfTemplate(template, req) {
  261. if (req.user == null) {
  262. return '';
  263. }
  264. const definitions = {
  265. pagepath: getPathFromRequest(req),
  266. username: req.user.name,
  267. today: getToday(),
  268. };
  269. const compiledTemplate = swig.compile(template);
  270. return compiledTemplate(definitions);
  271. }
  272. async function showPageForPresentation(req, res, next) {
  273. const path = getPathFromRequest(req);
  274. const { revisionId } = req.query;
  275. let page = await Page.findByPathAndViewer(path, req.user);
  276. if (page == null) {
  277. next();
  278. }
  279. const renderVars = {};
  280. // populate
  281. page = await page.populateDataToMakePresentation(revisionId);
  282. if (page != null) {
  283. addRenderVarsForPresentation(renderVars, page);
  284. }
  285. return res.render('page_presentation', renderVars);
  286. }
  287. async function showTopPage(req, res, next) {
  288. const portalPath = req.path;
  289. const revisionId = req.query.revision;
  290. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  291. const view = `layout-${layoutName}/page_list`;
  292. const renderVars = { path: portalPath };
  293. let portalPage = await Page.findByPathAndViewer(portalPath, req.user);
  294. portalPage.initLatestRevisionField(revisionId);
  295. // add user to seen users
  296. if (req.user != null) {
  297. portalPage = await portalPage.seen(req.user);
  298. }
  299. // populate
  300. portalPage = await portalPage.populateDataToShowRevision();
  301. addRenderVarsForPage(renderVars, portalPage);
  302. await addRenderVarsForSlack(renderVars, portalPage);
  303. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: portalPage._id });
  304. renderVars.sharelinksNumber = sharelinksNumber;
  305. const limit = 50;
  306. const offset = parseInt(req.query.offset) || 0;
  307. await addRenderVarsForDescendants(renderVars, portalPath, req.user, offset, limit);
  308. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  309. return res.render(view, renderVars);
  310. }
  311. async function showPageForGrowiBehavior(req, res, next) {
  312. const path = getPathFromRequest(req);
  313. const revisionId = req.query.revision;
  314. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  315. let page = await Page.findByPathAndViewer(path, req.user);
  316. if (page == null) {
  317. // check the page is forbidden or just does not exist.
  318. req.isForbidden = await Page.count({ path }) > 0;
  319. return next();
  320. }
  321. if (page.redirectTo) {
  322. debug(`Redirect to '${page.redirectTo}'`);
  323. return res.redirect(`${encodeURI(page.redirectTo)}?redirectFrom=${encodeURIComponent(path)}`);
  324. }
  325. logger.debug('Page is found when processing pageShowForGrowiBehavior', page._id, page.path);
  326. const limit = 50;
  327. const offset = parseInt(req.query.offset) || 0;
  328. const renderVars = {};
  329. let view = `layout-${layoutName}/page`;
  330. page.initLatestRevisionField(revisionId);
  331. // add user to seen users
  332. if (req.user != null) {
  333. page = await page.seen(req.user);
  334. }
  335. // populate
  336. page = await page.populateDataToShowRevision();
  337. addRenderVarsForPage(renderVars, page);
  338. addRenderVarsForScope(renderVars, page);
  339. await addRenderVarsForSlack(renderVars, page);
  340. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  341. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
  342. renderVars.sharelinksNumber = sharelinksNumber;
  343. if (isUserPage(page.path)) {
  344. // change template
  345. view = `layout-${layoutName}/user_page`;
  346. await addRenderVarsForUserPage(renderVars, page, req.user);
  347. }
  348. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  349. return res.render(view, renderVars);
  350. }
  351. const getSlackChannels = async(page) => {
  352. if (page.extended.slack) {
  353. return page.extended.slack;
  354. }
  355. const data = await UpdatePost.findSettingsByPath(page.path);
  356. const channels = data.map((e) => { return e.channel }).join(', ');
  357. return channels;
  358. };
  359. actions.showTopPage = function(req, res) {
  360. return showTopPage(req, res);
  361. };
  362. /**
  363. * Redirect to the page without trailing slash
  364. */
  365. actions.showPageWithEndOfSlash = function(req, res, next) {
  366. return res.redirect(pathUtils.removeTrailingSlash(req.path));
  367. };
  368. /**
  369. * switch action
  370. * - presentation mode
  371. * - by behaviorType
  372. */
  373. actions.showPage = async function(req, res, next) {
  374. // presentation mode
  375. if (req.query.presentation) {
  376. return showPageForPresentation(req, res, next);
  377. }
  378. // delegate to showPageForGrowiBehavior
  379. return showPageForGrowiBehavior(req, res, next);
  380. };
  381. actions.showSharedPage = async function(req, res, next) {
  382. const { linkId } = req.params;
  383. const revisionId = req.query.revision;
  384. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  385. const shareLink = await ShareLink.findOne({ _id: linkId }).populate('relatedPage');
  386. if (shareLink == null || shareLink.relatedPage == null) {
  387. // page or sharelink are not found
  388. return res.render(`layout-${layoutName}/not_found_shared_page`);
  389. }
  390. const renderVars = {};
  391. renderVars.sharelink = shareLink;
  392. // check if share link is expired
  393. if (shareLink.isExpired()) {
  394. // page is not found
  395. return res.render(`layout-${layoutName}/expired_shared_page`, renderVars);
  396. }
  397. let page = shareLink.relatedPage;
  398. // presentation mode
  399. if (req.query.presentation) {
  400. page = await page.populateDataToMakePresentation(revisionId);
  401. // populate
  402. addRenderVarsForPage(renderVars, page);
  403. return res.render('page_presentation', renderVars);
  404. }
  405. page.initLatestRevisionField(revisionId);
  406. // populate
  407. page = await page.populateDataToShowRevision();
  408. addRenderVarsForPage(renderVars, page);
  409. addRenderVarsForScope(renderVars, page);
  410. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  411. return res.render(`layout-${layoutName}/shared_page`, renderVars);
  412. };
  413. /**
  414. * switch action by behaviorType
  415. */
  416. /* eslint-disable no-else-return */
  417. actions.trashPageListShowWrapper = function(req, res) {
  418. // redirect to '/trash'
  419. return res.redirect('/trash');
  420. };
  421. /* eslint-enable no-else-return */
  422. /**
  423. * switch action by behaviorType
  424. */
  425. /* eslint-disable no-else-return */
  426. actions.trashPageShowWrapper = function(req, res) {
  427. // Crowi behavior for '/trash/*'
  428. return actions.deletedPageListShow(req, res);
  429. };
  430. /* eslint-enable no-else-return */
  431. /**
  432. * switch action by behaviorType
  433. */
  434. /* eslint-disable no-else-return */
  435. actions.deletedPageListShowWrapper = function(req, res) {
  436. const path = `/trash${getPathFromRequest(req)}`;
  437. return res.redirect(path);
  438. };
  439. /* eslint-enable no-else-return */
  440. actions.notFound = async function(req, res) {
  441. const path = getPathFromRequest(req);
  442. const isCreatable = Page.isCreatableName(path);
  443. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  444. let view;
  445. const renderVars = { path };
  446. if (!isCreatable) {
  447. view = `layout-${layoutName}/not_creatable`;
  448. }
  449. else if (req.isForbidden) {
  450. view = `layout-${layoutName}/forbidden`;
  451. }
  452. else {
  453. view = `layout-${layoutName}/not_found`;
  454. // retrieve templates
  455. if (req.user != null) {
  456. const template = await Page.findTemplate(path);
  457. if (template.templateBody) {
  458. const body = replacePlaceholdersOfTemplate(template.templateBody, req);
  459. const tags = template.templateTags;
  460. renderVars.template = body;
  461. renderVars.templateTags = tags;
  462. }
  463. }
  464. // add scope variables by ancestor page
  465. const ancestor = await Page.findAncestorByPathAndViewer(path, req.user);
  466. if (ancestor != null) {
  467. await ancestor.populate('grantedGroup').execPopulate();
  468. addRenderVarsForScope(renderVars, ancestor);
  469. }
  470. }
  471. const limit = 50;
  472. const offset = parseInt(req.query.offset) || 0;
  473. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  474. return res.render(view, renderVars);
  475. };
  476. actions.deletedPageListShow = async function(req, res) {
  477. // normalizePath makes '/trash/' -> '/trash'
  478. const path = pathUtils.normalizePath(`/trash${getPathFromRequest(req)}`);
  479. const layoutName = configManager.getConfig('crowi', 'customize:layout');
  480. const limit = 50;
  481. const offset = parseInt(req.query.offset) || 0;
  482. const queryOptions = {
  483. offset,
  484. limit,
  485. includeTrashed: true,
  486. };
  487. const renderVars = {
  488. page: null,
  489. path,
  490. pages: [],
  491. };
  492. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  493. if (result.pages.length > limit) {
  494. result.pages.pop();
  495. }
  496. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  497. renderVars.pages = result.pages;
  498. res.render(`layout-${layoutName}/page_list`, renderVars);
  499. };
  500. /**
  501. * redirector
  502. */
  503. actions.redirector = async function(req, res) {
  504. const id = req.params.id;
  505. const page = await Page.findByIdAndViewer(id, req.user);
  506. if (page != null) {
  507. return res.redirect(encodeURI(page.path));
  508. }
  509. return res.redirect('/');
  510. };
  511. const api = {};
  512. actions.api = api;
  513. /**
  514. * @swagger
  515. *
  516. * /pages.list:
  517. * get:
  518. * tags: [Pages, CrowiCompatibles]
  519. * operationId: listPages
  520. * summary: /pages.list
  521. * description: Get list of pages
  522. * parameters:
  523. * - in: query
  524. * name: path
  525. * schema:
  526. * $ref: '#/components/schemas/Page/properties/path'
  527. * - in: query
  528. * name: user
  529. * schema:
  530. * $ref: '#/components/schemas/User/properties/username'
  531. * - in: query
  532. * name: limit
  533. * schema:
  534. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  535. * - in: query
  536. * name: offset
  537. * schema:
  538. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  539. * responses:
  540. * 200:
  541. * description: Succeeded to get list of pages.
  542. * content:
  543. * application/json:
  544. * schema:
  545. * properties:
  546. * ok:
  547. * $ref: '#/components/schemas/V1Response/properties/ok'
  548. * pages:
  549. * type: array
  550. * items:
  551. * $ref: '#/components/schemas/Page'
  552. * description: page list
  553. * 403:
  554. * $ref: '#/components/responses/403'
  555. * 500:
  556. * $ref: '#/components/responses/500'
  557. */
  558. /**
  559. * @api {get} /pages.list List pages by user
  560. * @apiName ListPage
  561. * @apiGroup Page
  562. *
  563. * @apiParam {String} path
  564. * @apiParam {String} user
  565. */
  566. api.list = async function(req, res) {
  567. const username = req.query.user || null;
  568. const path = req.query.path || null;
  569. const limit = +req.query.limit || 50;
  570. const offset = parseInt(req.query.offset) || 0;
  571. const queryOptions = { offset, limit: limit + 1 };
  572. // Accepts only one of these
  573. if (username === null && path === null) {
  574. return res.json(ApiResponse.error('Parameter user or path is required.'));
  575. }
  576. if (username !== null && path !== null) {
  577. return res.json(ApiResponse.error('Parameter user or path is required.'));
  578. }
  579. try {
  580. let result = null;
  581. if (path == null) {
  582. const user = await User.findUserByUsername(username);
  583. if (user === null) {
  584. throw new Error('The user not found.');
  585. }
  586. result = await Page.findListByCreator(user, req.user, queryOptions);
  587. }
  588. else {
  589. result = await Page.findListByStartWith(path, req.user, queryOptions);
  590. }
  591. if (result.pages.length > limit) {
  592. result.pages.pop();
  593. }
  594. return res.json(ApiResponse.success(result));
  595. }
  596. catch (err) {
  597. return res.json(ApiResponse.error(err));
  598. }
  599. };
  600. // TODO If everything that depends on this route, delete it too
  601. api.create = async function(req, res) {
  602. const body = req.body.body || null;
  603. let pagePath = req.body.path || null;
  604. const grant = req.body.grant || null;
  605. const grantUserGroupId = req.body.grantUserGroupId || null;
  606. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  607. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  608. const slackChannels = req.body.slackChannels || null;
  609. const socketClientId = req.body.socketClientId || undefined;
  610. const pageTags = req.body.pageTags || undefined;
  611. if (body === null || pagePath === null) {
  612. return res.json(ApiResponse.error('Parameters body and path are required.'));
  613. }
  614. // check whether path starts slash
  615. pagePath = pathUtils.addHeadingSlash(pagePath);
  616. // check page existence
  617. const isExist = await Page.count({ path: pagePath }) > 0;
  618. if (isExist) {
  619. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  620. }
  621. const options = { socketClientId };
  622. if (grant != null) {
  623. options.grant = grant;
  624. options.grantUserGroupId = grantUserGroupId;
  625. }
  626. const createdPage = await Page.create(pagePath, body, req.user, options);
  627. let savedTags;
  628. if (pageTags != null) {
  629. await PageTagRelation.updatePageTags(createdPage.id, pageTags);
  630. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  631. }
  632. const result = {
  633. page: serializePageSecurely(createdPage),
  634. revision: serializeRevisionSecurely(createdPage.revision),
  635. tags: savedTags,
  636. };
  637. res.json(ApiResponse.success(result));
  638. // update scopes for descendants
  639. if (overwriteScopesOfDescendants) {
  640. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  641. }
  642. // global notification
  643. try {
  644. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage, req.user);
  645. }
  646. catch (err) {
  647. logger.error('Create notification failed', err);
  648. }
  649. // user notification
  650. if (isSlackEnabled) {
  651. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  652. }
  653. };
  654. /**
  655. * @swagger
  656. *
  657. * /pages.update:
  658. * post:
  659. * tags: [Pages, CrowiCompatibles]
  660. * operationId: updatePage
  661. * summary: /pages.update
  662. * description: Update page
  663. * requestBody:
  664. * content:
  665. * application/json:
  666. * schema:
  667. * properties:
  668. * body:
  669. * $ref: '#/components/schemas/Revision/properties/body'
  670. * page_id:
  671. * $ref: '#/components/schemas/Page/properties/_id'
  672. * revision_id:
  673. * $ref: '#/components/schemas/Revision/properties/_id'
  674. * grant:
  675. * $ref: '#/components/schemas/Page/properties/grant'
  676. * required:
  677. * - body
  678. * - page_id
  679. * - revision_id
  680. * responses:
  681. * 200:
  682. * description: Succeeded to update page.
  683. * content:
  684. * application/json:
  685. * schema:
  686. * properties:
  687. * ok:
  688. * $ref: '#/components/schemas/V1Response/properties/ok'
  689. * page:
  690. * $ref: '#/components/schemas/Page'
  691. * revision:
  692. * $ref: '#/components/schemas/Revision'
  693. * 403:
  694. * $ref: '#/components/responses/403'
  695. * 500:
  696. * $ref: '#/components/responses/500'
  697. */
  698. /**
  699. * @api {post} /pages.update Update page
  700. * @apiName UpdatePage
  701. * @apiGroup Page
  702. *
  703. * @apiParam {String} body
  704. * @apiParam {String} page_id
  705. * @apiParam {String} revision_id
  706. * @apiParam {String} grant
  707. *
  708. * In the case of the page exists:
  709. * - If revision_id is specified => update the page,
  710. * - If revision_id is not specified => force update by the new contents.
  711. */
  712. api.update = async function(req, res) {
  713. const pageBody = req.body.body || null;
  714. const pageId = req.body.page_id || null;
  715. const revisionId = req.body.revision_id || null;
  716. const grant = req.body.grant || null;
  717. const grantUserGroupId = req.body.grantUserGroupId || null;
  718. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  719. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  720. const slackChannels = req.body.slackChannels || null;
  721. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  722. const socketClientId = req.body.socketClientId || undefined;
  723. const pageTags = req.body.pageTags || undefined;
  724. if (pageId === null || pageBody === null || revisionId === null) {
  725. return res.json(ApiResponse.error('page_id, body and revision_id are required.'));
  726. }
  727. // check page existence
  728. const isExist = await Page.count({ _id: pageId }) > 0;
  729. if (!isExist) {
  730. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  731. }
  732. // check revision
  733. let page = await Page.findByIdAndViewer(pageId, req.user);
  734. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  735. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  736. }
  737. const options = { isSyncRevisionToHackmd, socketClientId };
  738. if (grant != null) {
  739. options.grant = grant;
  740. options.grantUserGroupId = grantUserGroupId;
  741. }
  742. const Revision = crowi.model('Revision');
  743. const previousRevision = await Revision.findById(revisionId);
  744. try {
  745. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  746. }
  747. catch (err) {
  748. logger.error('error on _api/pages.update', err);
  749. return res.json(ApiResponse.error(err));
  750. }
  751. let savedTags;
  752. if (pageTags != null) {
  753. await PageTagRelation.updatePageTags(pageId, pageTags);
  754. savedTags = await PageTagRelation.listTagNamesByPage(pageId);
  755. }
  756. const result = {
  757. page: serializePageSecurely(page),
  758. revision: serializeRevisionSecurely(page.revision),
  759. tags: savedTags,
  760. };
  761. res.json(ApiResponse.success(result));
  762. // update scopes for descendants
  763. if (overwriteScopesOfDescendants) {
  764. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  765. }
  766. // global notification
  767. try {
  768. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_EDIT, page, req.user);
  769. }
  770. catch (err) {
  771. logger.error('Edit notification failed', err);
  772. }
  773. // user notification
  774. if (isSlackEnabled) {
  775. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  776. }
  777. };
  778. /**
  779. * @swagger
  780. *
  781. * /pages.get:
  782. * get:
  783. * tags: [Pages, CrowiCompatibles]
  784. * operationId: getPage
  785. * summary: /pages.get
  786. * description: Get page data
  787. * parameters:
  788. * - in: query
  789. * name: page_id
  790. * schema:
  791. * $ref: '#/components/schemas/Page/properties/_id'
  792. * - in: query
  793. * name: path
  794. * schema:
  795. * $ref: '#/components/schemas/Page/properties/path'
  796. * - in: query
  797. * name: revision_id
  798. * schema:
  799. * $ref: '#/components/schemas/Revision/properties/_id'
  800. * responses:
  801. * 200:
  802. * description: Succeeded to get page data.
  803. * content:
  804. * application/json:
  805. * schema:
  806. * properties:
  807. * ok:
  808. * $ref: '#/components/schemas/V1Response/properties/ok'
  809. * page:
  810. * $ref: '#/components/schemas/Page'
  811. * 403:
  812. * $ref: '#/components/responses/403'
  813. * 500:
  814. * $ref: '#/components/responses/500'
  815. */
  816. /**
  817. * @api {get} /pages.get Get page data
  818. * @apiName GetPage
  819. * @apiGroup Page
  820. *
  821. * @apiParam {String} page_id
  822. * @apiParam {String} path
  823. * @apiParam {String} revision_id
  824. */
  825. api.get = async function(req, res) {
  826. const pagePath = req.query.path || null;
  827. const pageId = req.query.page_id || null; // TODO: handling
  828. if (!pageId && !pagePath) {
  829. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  830. }
  831. let page;
  832. try {
  833. if (pageId) { // prioritized
  834. page = await Page.findByIdAndViewer(pageId, req.user);
  835. }
  836. else if (pagePath) {
  837. page = await Page.findByPathAndViewer(pagePath, req.user);
  838. }
  839. if (page == null) {
  840. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  841. }
  842. page.initLatestRevisionField();
  843. // populate
  844. page = await page.populateDataToShowRevision();
  845. }
  846. catch (err) {
  847. return res.json(ApiResponse.error(err));
  848. }
  849. const result = {};
  850. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  851. return res.json(ApiResponse.success(result));
  852. };
  853. /**
  854. * @swagger
  855. *
  856. * /pages.exist:
  857. * get:
  858. * tags: [Pages]
  859. * operationId: getPageExistence
  860. * summary: /pages.exist
  861. * description: Get page existence
  862. * parameters:
  863. * - in: query
  864. * name: pagePaths
  865. * schema:
  866. * type: string
  867. * description: Page path list in JSON Array format
  868. * example: '["/", "/user/unknown"]'
  869. * responses:
  870. * 200:
  871. * description: Succeeded to get page existence.
  872. * content:
  873. * application/json:
  874. * schema:
  875. * properties:
  876. * ok:
  877. * $ref: '#/components/schemas/V1Response/properties/ok'
  878. * pages:
  879. * type: string
  880. * description: Properties of page path and existence
  881. * example: '{"/": true, "/user/unknown": false}'
  882. * 403:
  883. * $ref: '#/components/responses/403'
  884. * 500:
  885. * $ref: '#/components/responses/500'
  886. */
  887. /**
  888. * @api {get} /pages.exist Get if page exists
  889. * @apiName GetPage
  890. * @apiGroup Page
  891. *
  892. * @apiParam {String} pages (stringified JSON)
  893. */
  894. api.exist = async function(req, res) {
  895. const pagePaths = JSON.parse(req.query.pagePaths || '[]');
  896. const pages = {};
  897. await Promise.all(pagePaths.map(async(path) => {
  898. // check page existence
  899. const isExist = await Page.count({ path }) > 0;
  900. pages[path] = isExist;
  901. return;
  902. }));
  903. const result = { pages };
  904. return res.json(ApiResponse.success(result));
  905. };
  906. /**
  907. * @swagger
  908. *
  909. * /pages.getPageTag:
  910. * get:
  911. * tags: [Pages]
  912. * operationId: getPageTag
  913. * summary: /pages.getPageTag
  914. * description: Get page tag
  915. * parameters:
  916. * - in: query
  917. * name: pageId
  918. * schema:
  919. * $ref: '#/components/schemas/Page/properties/_id'
  920. * responses:
  921. * 200:
  922. * description: Succeeded to get page tags.
  923. * content:
  924. * application/json:
  925. * schema:
  926. * properties:
  927. * ok:
  928. * $ref: '#/components/schemas/V1Response/properties/ok'
  929. * tags:
  930. * $ref: '#/components/schemas/Tags'
  931. * 403:
  932. * $ref: '#/components/responses/403'
  933. * 500:
  934. * $ref: '#/components/responses/500'
  935. */
  936. /**
  937. * @api {get} /pages.getPageTag get page tags
  938. * @apiName GetPageTag
  939. * @apiGroup Page
  940. *
  941. * @apiParam {String} pageId
  942. */
  943. api.getPageTag = async function(req, res) {
  944. const result = {};
  945. try {
  946. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  947. }
  948. catch (err) {
  949. return res.json(ApiResponse.error(err));
  950. }
  951. return res.json(ApiResponse.success(result));
  952. };
  953. /**
  954. * @swagger
  955. *
  956. * /pages.updatePost:
  957. * get:
  958. * tags: [Pages, CrowiCompatibles]
  959. * operationId: getUpdatePostPage
  960. * summary: /pages.updatePost
  961. * description: Get UpdatePost setting list
  962. * parameters:
  963. * - in: query
  964. * name: path
  965. * schema:
  966. * $ref: '#/components/schemas/Page/properties/path'
  967. * responses:
  968. * 200:
  969. * description: Succeeded to get UpdatePost setting list.
  970. * content:
  971. * application/json:
  972. * schema:
  973. * properties:
  974. * ok:
  975. * $ref: '#/components/schemas/V1Response/properties/ok'
  976. * updatePost:
  977. * $ref: '#/components/schemas/UpdatePost'
  978. * 403:
  979. * $ref: '#/components/responses/403'
  980. * 500:
  981. * $ref: '#/components/responses/500'
  982. */
  983. /**
  984. * @api {get} /pages.updatePost
  985. * @apiName Get UpdatePost setting list
  986. * @apiGroup Page
  987. *
  988. * @apiParam {String} path
  989. */
  990. api.getUpdatePost = function(req, res) {
  991. const path = req.query.path;
  992. const UpdatePost = crowi.model('UpdatePost');
  993. if (!path) {
  994. return res.json(ApiResponse.error({}));
  995. }
  996. UpdatePost.findSettingsByPath(path)
  997. .then((data) => {
  998. // eslint-disable-next-line no-param-reassign
  999. data = data.map((e) => {
  1000. return e.channel;
  1001. });
  1002. debug('Found updatePost data', data);
  1003. const result = { updatePost: data };
  1004. return res.json(ApiResponse.success(result));
  1005. })
  1006. .catch((err) => {
  1007. debug('Error occured while get setting', err);
  1008. return res.json(ApiResponse.error({}));
  1009. });
  1010. };
  1011. /**
  1012. * @api {post} /pages.remove Remove page
  1013. * @apiName RemovePage
  1014. * @apiGroup Page
  1015. *
  1016. * @apiParam {String} page_id Page Id.
  1017. * @apiParam {String} revision_id
  1018. */
  1019. api.remove = async function(req, res) {
  1020. const pageId = req.body.page_id;
  1021. const previousRevision = req.body.revision_id || null;
  1022. const socketClientId = req.body.socketClientId || undefined;
  1023. // get completely flag
  1024. const isCompletely = (req.body.completely != null);
  1025. // get recursively flag
  1026. const isRecursively = (req.body.recursively != null);
  1027. const options = { socketClientId };
  1028. const page = await Page.findByIdAndViewer(pageId, req.user);
  1029. if (page == null) {
  1030. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1031. }
  1032. debug('Delete page', page._id, page.path);
  1033. try {
  1034. if (isCompletely) {
  1035. if (!req.user.canDeleteCompletely(page.creator)) {
  1036. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  1037. }
  1038. if (isRecursively) {
  1039. await crowi.pageService.completelyDeletePageRecursively(page, req.user, options);
  1040. }
  1041. else {
  1042. await crowi.pageService.completelyDeletePage(page, req.user, options);
  1043. }
  1044. }
  1045. else {
  1046. if (!page.isUpdatable(previousRevision)) {
  1047. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1048. }
  1049. if (isRecursively) {
  1050. await Page.deletePageRecursively(page, req.user, options);
  1051. }
  1052. else {
  1053. await Page.deletePage(page, req.user, options);
  1054. }
  1055. }
  1056. }
  1057. catch (err) {
  1058. logger.error('Error occured while get setting', err);
  1059. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  1060. }
  1061. debug('Page deleted', page.path);
  1062. const result = {};
  1063. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  1064. res.json(ApiResponse.success(result));
  1065. try {
  1066. // global notification
  1067. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page, req.user);
  1068. }
  1069. catch (err) {
  1070. logger.error('Delete notification failed', err);
  1071. }
  1072. };
  1073. /**
  1074. * @api {post} /pages.revertRemove Revert removed page
  1075. * @apiName RevertRemovePage
  1076. * @apiGroup Page
  1077. *
  1078. * @apiParam {String} page_id Page Id.
  1079. */
  1080. api.revertRemove = async function(req, res, options) {
  1081. const pageId = req.body.page_id;
  1082. const socketClientId = req.body.socketClientId || undefined;
  1083. // get recursively flag
  1084. const isRecursively = (req.body.recursively != null);
  1085. let page;
  1086. try {
  1087. page = await Page.findByIdAndViewer(pageId, req.user);
  1088. if (page == null) {
  1089. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  1090. }
  1091. if (isRecursively) {
  1092. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  1093. }
  1094. else {
  1095. page = await crowi.pageService.revertDeletedPage(page, req.user, { socketClientId });
  1096. }
  1097. }
  1098. catch (err) {
  1099. logger.error('Error occured while get setting', err);
  1100. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  1101. }
  1102. const result = {};
  1103. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  1104. return res.json(ApiResponse.success(result));
  1105. };
  1106. /**
  1107. * @swagger
  1108. *
  1109. * /pages.rename:
  1110. * post:
  1111. * tags: [Pages, CrowiCompatibles]
  1112. * operationId: renamePage
  1113. * summary: /pages.rename
  1114. * description: Rename page
  1115. * requestBody:
  1116. * content:
  1117. * application/json:
  1118. * schema:
  1119. * properties:
  1120. * page_id:
  1121. * $ref: '#/components/schemas/Page/properties/_id'
  1122. * path:
  1123. * $ref: '#/components/schemas/Page/properties/path'
  1124. * revision_id:
  1125. * $ref: '#/components/schemas/Revision/properties/_id'
  1126. * new_path:
  1127. * type: string
  1128. * description: new path
  1129. * example: /user/alice/new_test
  1130. * create_redirect:
  1131. * type: boolean
  1132. * description: whether redirect page
  1133. * required:
  1134. * - page_id
  1135. * responses:
  1136. * 200:
  1137. * description: Succeeded to rename page.
  1138. * content:
  1139. * application/json:
  1140. * schema:
  1141. * properties:
  1142. * ok:
  1143. * $ref: '#/components/schemas/V1Response/properties/ok'
  1144. * page:
  1145. * $ref: '#/components/schemas/Page'
  1146. * 403:
  1147. * $ref: '#/components/responses/403'
  1148. * 500:
  1149. * $ref: '#/components/responses/500'
  1150. */
  1151. /**
  1152. * @api {post} /pages.rename Rename page
  1153. * @apiName RenamePage
  1154. * @apiGroup Page
  1155. *
  1156. * @apiParam {String} page_id Page Id.
  1157. * @apiParam {String} path
  1158. * @apiParam {String} revision_id
  1159. * @apiParam {String} new_path New path name.
  1160. * @apiParam {Bool} create_redirect
  1161. */
  1162. api.rename = async function(req, res) {
  1163. const pageId = req.body.page_id;
  1164. const previousRevision = req.body.revision_id || null;
  1165. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1166. const options = {
  1167. createRedirectPage: (req.body.create_redirect != null),
  1168. updateMetadata: (req.body.remain_metadata == null),
  1169. socketClientId: +req.body.socketClientId || undefined,
  1170. };
  1171. const isRecursively = (req.body.recursively != null);
  1172. if (!Page.isCreatableName(newPagePath)) {
  1173. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  1174. }
  1175. // check whether path starts slash
  1176. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1177. const isExist = await Page.count({ path: newPagePath }) > 0;
  1178. if (isExist) {
  1179. // if page found, cannot cannot rename to that path
  1180. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  1181. }
  1182. let page;
  1183. try {
  1184. page = await Page.findByIdAndViewer(pageId, req.user);
  1185. if (page == null) {
  1186. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1187. }
  1188. if (!page.isUpdatable(previousRevision)) {
  1189. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1190. }
  1191. if (isRecursively) {
  1192. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  1193. }
  1194. else {
  1195. page = await Page.rename(page, newPagePath, req.user, options);
  1196. }
  1197. }
  1198. catch (err) {
  1199. logger.error(err);
  1200. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  1201. }
  1202. const result = {};
  1203. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  1204. res.json(ApiResponse.success(result));
  1205. try {
  1206. // global notification
  1207. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_MOVE, page, req.user, {
  1208. oldPath: req.body.path,
  1209. });
  1210. }
  1211. catch (err) {
  1212. logger.error('Move notification failed', err);
  1213. }
  1214. return page;
  1215. };
  1216. /**
  1217. * @swagger
  1218. *
  1219. * /pages.duplicate:
  1220. * post:
  1221. * tags: [Pages]
  1222. * operationId: duplicatePage
  1223. * summary: /pages.duplicate
  1224. * description: Duplicate page
  1225. * requestBody:
  1226. * content:
  1227. * application/json:
  1228. * schema:
  1229. * properties:
  1230. * page_id:
  1231. * $ref: '#/components/schemas/Page/properties/_id'
  1232. * new_path:
  1233. * $ref: '#/components/schemas/Page/properties/path'
  1234. * required:
  1235. * - page_id
  1236. * responses:
  1237. * 200:
  1238. * description: Succeeded to duplicate page.
  1239. * content:
  1240. * application/json:
  1241. * schema:
  1242. * properties:
  1243. * ok:
  1244. * $ref: '#/components/schemas/V1Response/properties/ok'
  1245. * page:
  1246. * $ref: '#/components/schemas/Page'
  1247. * tags:
  1248. * $ref: '#/components/schemas/Tags'
  1249. * 403:
  1250. * $ref: '#/components/responses/403'
  1251. * 500:
  1252. * $ref: '#/components/responses/500'
  1253. */
  1254. /**
  1255. * @api {post} /pages.duplicate Duplicate page
  1256. * @apiName DuplicatePage
  1257. * @apiGroup Page
  1258. *
  1259. * @apiParam {String} page_id Page Id.
  1260. * @apiParam {String} new_path New path name.
  1261. */
  1262. api.duplicate = async function(req, res) {
  1263. const pageId = req.body.page_id;
  1264. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1265. const page = await Page.findByIdAndViewer(pageId, req.user);
  1266. if (page == null) {
  1267. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1268. }
  1269. // check whether path starts slash
  1270. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1271. await page.populateDataToShowRevision();
  1272. const originTags = await page.findRelatedTagsById();
  1273. req.body.path = newPagePath;
  1274. req.body.body = page.revision.body;
  1275. req.body.grant = page.grant;
  1276. req.body.grantedUsers = page.grantedUsers;
  1277. req.body.grantUserGroupId = page.grantedGroup;
  1278. req.body.pageTags = originTags;
  1279. return api.create(req, res);
  1280. };
  1281. /**
  1282. * @api {post} /pages.unlink Remove the redirecting page
  1283. * @apiName UnlinkPage
  1284. * @apiGroup Page
  1285. *
  1286. * @apiParam {String} page_id Page Id.
  1287. * @apiParam {String} revision_id
  1288. */
  1289. api.unlink = async function(req, res) {
  1290. const path = req.body.path;
  1291. try {
  1292. await Page.removeRedirectOriginPageByPath(path);
  1293. logger.debug('Redirect Page deleted', path);
  1294. }
  1295. catch (err) {
  1296. logger.error('Error occured while get setting', err);
  1297. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1298. }
  1299. const result = { path };
  1300. return res.json(ApiResponse.success(result));
  1301. };
  1302. return actions;
  1303. };