page.js 45 KB

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