page.js 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  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, xssService } = 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: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  146. tagWhiteList: xssService.getTagWhiteList(),
  147. attrWhiteList: 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 view = 'layout-growi/page_list';
  291. const renderVars = { path: portalPath };
  292. let portalPage = await Page.findByPathAndViewer(portalPath, req.user);
  293. portalPage.initLatestRevisionField(revisionId);
  294. // add user to seen users
  295. if (req.user != null) {
  296. portalPage = await portalPage.seen(req.user);
  297. }
  298. // populate
  299. portalPage = await portalPage.populateDataToShowRevision();
  300. addRenderVarsForPage(renderVars, portalPage);
  301. await addRenderVarsForSlack(renderVars, portalPage);
  302. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: portalPage._id });
  303. renderVars.sharelinksNumber = sharelinksNumber;
  304. const limit = 50;
  305. const offset = parseInt(req.query.offset) || 0;
  306. await addRenderVarsForDescendants(renderVars, portalPath, req.user, offset, limit);
  307. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  308. return res.render(view, renderVars);
  309. }
  310. async function showPageForGrowiBehavior(req, res, next) {
  311. const path = getPathFromRequest(req);
  312. const revisionId = req.query.revision;
  313. let page = await Page.findByPathAndViewer(path, req.user);
  314. if (page == null) {
  315. // check the page is forbidden or just does not exist.
  316. req.isForbidden = await Page.count({ path }) > 0;
  317. return next();
  318. }
  319. if (page.redirectTo) {
  320. debug(`Redirect to '${page.redirectTo}'`);
  321. return res.redirect(`${encodeURI(page.redirectTo)}?redirectFrom=${encodeURIComponent(path)}`);
  322. }
  323. logger.debug('Page is found when processing pageShowForGrowiBehavior', page._id, page.path);
  324. const limit = 50;
  325. const offset = parseInt(req.query.offset) || 0;
  326. const renderVars = {};
  327. let view = 'layout-growi/page';
  328. page.initLatestRevisionField(revisionId);
  329. // add user to seen users
  330. if (req.user != null) {
  331. page = await page.seen(req.user);
  332. }
  333. // populate
  334. page = await page.populateDataToShowRevision();
  335. addRenderVarsForPage(renderVars, page);
  336. addRenderVarsForScope(renderVars, page);
  337. await addRenderVarsForSlack(renderVars, page);
  338. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  339. const sharelinksNumber = await ShareLink.countDocuments({ relatedPage: page._id });
  340. renderVars.sharelinksNumber = sharelinksNumber;
  341. if (isUserPage(page.path)) {
  342. // change template
  343. view = 'layout-growi/user_page';
  344. await addRenderVarsForUserPage(renderVars, page, req.user);
  345. }
  346. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  347. return res.render(view, renderVars);
  348. }
  349. const getSlackChannels = async(page) => {
  350. if (page.extended.slack) {
  351. return page.extended.slack;
  352. }
  353. const data = await UpdatePost.findSettingsByPath(page.path);
  354. const channels = data.map((e) => { return e.channel }).join(', ');
  355. return channels;
  356. };
  357. actions.showTopPage = function(req, res) {
  358. return showTopPage(req, res);
  359. };
  360. /**
  361. * Redirect to the page without trailing slash
  362. */
  363. actions.showPageWithEndOfSlash = function(req, res, next) {
  364. return res.redirect(pathUtils.removeTrailingSlash(req.path));
  365. };
  366. /**
  367. * switch action
  368. * - presentation mode
  369. * - by behaviorType
  370. */
  371. actions.showPage = async function(req, res, next) {
  372. // presentation mode
  373. if (req.query.presentation) {
  374. return showPageForPresentation(req, res, next);
  375. }
  376. // delegate to showPageForGrowiBehavior
  377. return showPageForGrowiBehavior(req, res, next);
  378. };
  379. actions.showSharedPage = async function(req, res, next) {
  380. const { linkId } = req.params;
  381. const revisionId = req.query.revision;
  382. const shareLink = await ShareLink.findOne({ _id: linkId }).populate('relatedPage');
  383. if (shareLink == null || shareLink.relatedPage == null) {
  384. // page or sharelink are not found
  385. return res.render('layout-growi/not_found_shared_page');
  386. }
  387. const renderVars = {};
  388. renderVars.sharelink = shareLink;
  389. // check if share link is expired
  390. if (shareLink.isExpired()) {
  391. // page is not found
  392. return res.render('layout-growi/expired_shared_page', renderVars);
  393. }
  394. let page = shareLink.relatedPage;
  395. // presentation mode
  396. if (req.query.presentation) {
  397. page = await page.populateDataToMakePresentation(revisionId);
  398. // populate
  399. addRenderVarsForPage(renderVars, page);
  400. return res.render('page_presentation', renderVars);
  401. }
  402. page.initLatestRevisionField(revisionId);
  403. // populate
  404. page = await page.populateDataToShowRevision();
  405. addRenderVarsForPage(renderVars, page);
  406. addRenderVarsForScope(renderVars, page);
  407. await interceptorManager.process('beforeRenderPage', req, res, renderVars);
  408. return res.render('layout-growi/shared_page', renderVars);
  409. };
  410. /**
  411. * switch action by behaviorType
  412. */
  413. /* eslint-disable no-else-return */
  414. actions.trashPageListShowWrapper = function(req, res) {
  415. // redirect to '/trash'
  416. return res.redirect('/trash');
  417. };
  418. /* eslint-enable no-else-return */
  419. /**
  420. * switch action by behaviorType
  421. */
  422. /* eslint-disable no-else-return */
  423. actions.trashPageShowWrapper = function(req, res) {
  424. // Crowi behavior for '/trash/*'
  425. return actions.deletedPageListShow(req, res);
  426. };
  427. /* eslint-enable no-else-return */
  428. /**
  429. * switch action by behaviorType
  430. */
  431. /* eslint-disable no-else-return */
  432. actions.deletedPageListShowWrapper = function(req, res) {
  433. const path = `/trash${getPathFromRequest(req)}`;
  434. return res.redirect(path);
  435. };
  436. /* eslint-enable no-else-return */
  437. actions.notFound = async function(req, res) {
  438. const path = getPathFromRequest(req);
  439. const isCreatable = Page.isCreatableName(path);
  440. let view;
  441. const renderVars = { path };
  442. if (!isCreatable) {
  443. view = 'layout-growi/not_creatable';
  444. }
  445. else if (req.isForbidden) {
  446. view = 'layout-growi/forbidden';
  447. }
  448. else {
  449. view = 'layout-growi/not_found';
  450. // retrieve templates
  451. if (req.user != null) {
  452. const template = await Page.findTemplate(path);
  453. if (template.templateBody) {
  454. const body = replacePlaceholdersOfTemplate(template.templateBody, req);
  455. const tags = template.templateTags;
  456. renderVars.template = body;
  457. renderVars.templateTags = tags;
  458. }
  459. }
  460. // add scope variables by ancestor page
  461. const ancestor = await Page.findAncestorByPathAndViewer(path, req.user);
  462. if (ancestor != null) {
  463. await ancestor.populate('grantedGroup').execPopulate();
  464. addRenderVarsForScope(renderVars, ancestor);
  465. }
  466. }
  467. const limit = 50;
  468. const offset = parseInt(req.query.offset) || 0;
  469. await addRenderVarsForDescendants(renderVars, path, req.user, offset, limit, true);
  470. return res.render(view, renderVars);
  471. };
  472. actions.deletedPageListShow = async function(req, res) {
  473. // normalizePath makes '/trash/' -> '/trash'
  474. const path = pathUtils.normalizePath(`/trash${getPathFromRequest(req)}`);
  475. const limit = 50;
  476. const offset = parseInt(req.query.offset) || 0;
  477. const queryOptions = {
  478. offset,
  479. limit,
  480. includeTrashed: true,
  481. };
  482. const renderVars = {
  483. page: null,
  484. path,
  485. pages: [],
  486. };
  487. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  488. if (result.pages.length > limit) {
  489. result.pages.pop();
  490. }
  491. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  492. renderVars.pages = result.pages;
  493. res.render('layout-growi/page_list', renderVars);
  494. };
  495. /**
  496. * redirector
  497. */
  498. actions.redirector = async function(req, res) {
  499. const id = req.params.id;
  500. const page = await Page.findByIdAndViewer(id, req.user);
  501. if (page != null) {
  502. return res.redirect(encodeURI(page.path));
  503. }
  504. return res.redirect('/');
  505. };
  506. const api = {};
  507. actions.api = api;
  508. /**
  509. * @swagger
  510. *
  511. * /pages.list:
  512. * get:
  513. * tags: [Pages, CrowiCompatibles]
  514. * operationId: listPages
  515. * summary: /pages.list
  516. * description: Get list of pages
  517. * parameters:
  518. * - in: query
  519. * name: path
  520. * schema:
  521. * $ref: '#/components/schemas/Page/properties/path'
  522. * - in: query
  523. * name: user
  524. * schema:
  525. * $ref: '#/components/schemas/User/properties/username'
  526. * - in: query
  527. * name: limit
  528. * schema:
  529. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  530. * - in: query
  531. * name: offset
  532. * schema:
  533. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  534. * responses:
  535. * 200:
  536. * description: Succeeded to get list of pages.
  537. * content:
  538. * application/json:
  539. * schema:
  540. * properties:
  541. * ok:
  542. * $ref: '#/components/schemas/V1Response/properties/ok'
  543. * pages:
  544. * type: array
  545. * items:
  546. * $ref: '#/components/schemas/Page'
  547. * description: page list
  548. * 403:
  549. * $ref: '#/components/responses/403'
  550. * 500:
  551. * $ref: '#/components/responses/500'
  552. */
  553. /**
  554. * @api {get} /pages.list List pages by user
  555. * @apiName ListPage
  556. * @apiGroup Page
  557. *
  558. * @apiParam {String} path
  559. * @apiParam {String} user
  560. */
  561. api.list = async function(req, res) {
  562. const username = req.query.user || null;
  563. const path = req.query.path || null;
  564. const limit = +req.query.limit || 50;
  565. const offset = parseInt(req.query.offset) || 0;
  566. const queryOptions = { offset, limit: limit + 1 };
  567. // Accepts only one of these
  568. if (username === null && path === null) {
  569. return res.json(ApiResponse.error('Parameter user or path is required.'));
  570. }
  571. if (username !== null && path !== null) {
  572. return res.json(ApiResponse.error('Parameter user or path is required.'));
  573. }
  574. try {
  575. let result = null;
  576. if (path == null) {
  577. const user = await User.findUserByUsername(username);
  578. if (user === null) {
  579. throw new Error('The user not found.');
  580. }
  581. result = await Page.findListByCreator(user, req.user, queryOptions);
  582. }
  583. else {
  584. result = await Page.findListByStartWith(path, req.user, queryOptions);
  585. }
  586. if (result.pages.length > limit) {
  587. result.pages.pop();
  588. }
  589. return res.json(ApiResponse.success(result));
  590. }
  591. catch (err) {
  592. return res.json(ApiResponse.error(err));
  593. }
  594. };
  595. // TODO If everything that depends on this route, delete it too
  596. api.create = async function(req, res) {
  597. const body = req.body.body || null;
  598. let pagePath = req.body.path || null;
  599. const grant = req.body.grant || null;
  600. const grantUserGroupId = req.body.grantUserGroupId || null;
  601. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  602. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  603. const slackChannels = req.body.slackChannels || null;
  604. const socketClientId = req.body.socketClientId || undefined;
  605. const pageTags = req.body.pageTags || undefined;
  606. if (body === null || pagePath === null) {
  607. return res.json(ApiResponse.error('Parameters body and path are required.'));
  608. }
  609. // check whether path starts slash
  610. pagePath = pathUtils.addHeadingSlash(pagePath);
  611. // check page existence
  612. const isExist = await Page.count({ path: pagePath }) > 0;
  613. if (isExist) {
  614. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  615. }
  616. const options = { socketClientId };
  617. if (grant != null) {
  618. options.grant = grant;
  619. options.grantUserGroupId = grantUserGroupId;
  620. }
  621. const createdPage = await Page.create(pagePath, body, req.user, options);
  622. let savedTags;
  623. if (pageTags != null) {
  624. await PageTagRelation.updatePageTags(createdPage.id, pageTags);
  625. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  626. }
  627. const result = {
  628. page: serializePageSecurely(createdPage),
  629. revision: serializeRevisionSecurely(createdPage.revision),
  630. tags: savedTags,
  631. };
  632. res.json(ApiResponse.success(result));
  633. // update scopes for descendants
  634. if (overwriteScopesOfDescendants) {
  635. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  636. }
  637. // global notification
  638. try {
  639. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage, req.user);
  640. }
  641. catch (err) {
  642. logger.error('Create notification failed', err);
  643. }
  644. // user notification
  645. if (isSlackEnabled) {
  646. await notifyToSlackByUser(createdPage, req.user, slackChannels, 'create', false);
  647. }
  648. };
  649. /**
  650. * @swagger
  651. *
  652. * /pages.update:
  653. * post:
  654. * tags: [Pages, CrowiCompatibles]
  655. * operationId: updatePage
  656. * summary: /pages.update
  657. * description: Update page
  658. * requestBody:
  659. * content:
  660. * application/json:
  661. * schema:
  662. * properties:
  663. * body:
  664. * $ref: '#/components/schemas/Revision/properties/body'
  665. * page_id:
  666. * $ref: '#/components/schemas/Page/properties/_id'
  667. * revision_id:
  668. * $ref: '#/components/schemas/Revision/properties/_id'
  669. * grant:
  670. * $ref: '#/components/schemas/Page/properties/grant'
  671. * required:
  672. * - body
  673. * - page_id
  674. * - revision_id
  675. * responses:
  676. * 200:
  677. * description: Succeeded to update page.
  678. * content:
  679. * application/json:
  680. * schema:
  681. * properties:
  682. * ok:
  683. * $ref: '#/components/schemas/V1Response/properties/ok'
  684. * page:
  685. * $ref: '#/components/schemas/Page'
  686. * revision:
  687. * $ref: '#/components/schemas/Revision'
  688. * 403:
  689. * $ref: '#/components/responses/403'
  690. * 500:
  691. * $ref: '#/components/responses/500'
  692. */
  693. /**
  694. * @api {post} /pages.update Update page
  695. * @apiName UpdatePage
  696. * @apiGroup Page
  697. *
  698. * @apiParam {String} body
  699. * @apiParam {String} page_id
  700. * @apiParam {String} revision_id
  701. * @apiParam {String} grant
  702. *
  703. * In the case of the page exists:
  704. * - If revision_id is specified => update the page,
  705. * - If revision_id is not specified => force update by the new contents.
  706. */
  707. api.update = async function(req, res) {
  708. const pageBody = req.body.body || null;
  709. const pageId = req.body.page_id || null;
  710. const revisionId = req.body.revision_id || null;
  711. const grant = req.body.grant || null;
  712. const grantUserGroupId = req.body.grantUserGroupId || null;
  713. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  714. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  715. const slackChannels = req.body.slackChannels || null;
  716. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  717. const socketClientId = req.body.socketClientId || undefined;
  718. const pageTags = req.body.pageTags || undefined;
  719. if (pageId === null || pageBody === null || revisionId === null) {
  720. return res.json(ApiResponse.error('page_id, body and revision_id are required.'));
  721. }
  722. // check page existence
  723. const isExist = await Page.count({ _id: pageId }) > 0;
  724. if (!isExist) {
  725. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  726. }
  727. // check revision
  728. let page = await Page.findByIdAndViewer(pageId, req.user);
  729. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  730. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'outdated'));
  731. }
  732. const options = { isSyncRevisionToHackmd, socketClientId };
  733. if (grant != null) {
  734. options.grant = grant;
  735. options.grantUserGroupId = grantUserGroupId;
  736. }
  737. const Revision = crowi.model('Revision');
  738. const previousRevision = await Revision.findById(revisionId);
  739. try {
  740. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  741. }
  742. catch (err) {
  743. logger.error('error on _api/pages.update', err);
  744. return res.json(ApiResponse.error(err));
  745. }
  746. let savedTags;
  747. if (pageTags != null) {
  748. await PageTagRelation.updatePageTags(pageId, pageTags);
  749. savedTags = await PageTagRelation.listTagNamesByPage(pageId);
  750. }
  751. const result = {
  752. page: serializePageSecurely(page),
  753. revision: serializeRevisionSecurely(page.revision),
  754. tags: savedTags,
  755. };
  756. res.json(ApiResponse.success(result));
  757. // update scopes for descendants
  758. if (overwriteScopesOfDescendants) {
  759. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  760. }
  761. // global notification
  762. try {
  763. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_EDIT, page, req.user);
  764. }
  765. catch (err) {
  766. logger.error('Edit notification failed', err);
  767. }
  768. // user notification
  769. if (isSlackEnabled) {
  770. await notifyToSlackByUser(page, req.user, slackChannels, 'update', previousRevision);
  771. }
  772. };
  773. /**
  774. * @swagger
  775. *
  776. * /pages.get:
  777. * get:
  778. * tags: [Pages, CrowiCompatibles]
  779. * operationId: getPage
  780. * summary: /pages.get
  781. * description: Get page data
  782. * parameters:
  783. * - in: query
  784. * name: page_id
  785. * schema:
  786. * $ref: '#/components/schemas/Page/properties/_id'
  787. * - in: query
  788. * name: path
  789. * schema:
  790. * $ref: '#/components/schemas/Page/properties/path'
  791. * - in: query
  792. * name: revision_id
  793. * schema:
  794. * $ref: '#/components/schemas/Revision/properties/_id'
  795. * responses:
  796. * 200:
  797. * description: Succeeded to get page data.
  798. * content:
  799. * application/json:
  800. * schema:
  801. * properties:
  802. * ok:
  803. * $ref: '#/components/schemas/V1Response/properties/ok'
  804. * page:
  805. * $ref: '#/components/schemas/Page'
  806. * 403:
  807. * $ref: '#/components/responses/403'
  808. * 500:
  809. * $ref: '#/components/responses/500'
  810. */
  811. /**
  812. * @api {get} /pages.get Get page data
  813. * @apiName GetPage
  814. * @apiGroup Page
  815. *
  816. * @apiParam {String} page_id
  817. * @apiParam {String} path
  818. * @apiParam {String} revision_id
  819. */
  820. api.get = async function(req, res) {
  821. const pagePath = req.query.path || null;
  822. const pageId = req.query.page_id || null; // TODO: handling
  823. if (!pageId && !pagePath) {
  824. return res.json(ApiResponse.error(new Error('Parameter path or page_id is required.')));
  825. }
  826. let page;
  827. try {
  828. if (pageId) { // prioritized
  829. page = await Page.findByIdAndViewer(pageId, req.user);
  830. }
  831. else if (pagePath) {
  832. page = await Page.findByPathAndViewer(pagePath, req.user);
  833. }
  834. if (page == null) {
  835. throw new Error(`Page '${pageId || pagePath}' is not found or forbidden`, 'notfound_or_forbidden');
  836. }
  837. page.initLatestRevisionField();
  838. // populate
  839. page = await page.populateDataToShowRevision();
  840. }
  841. catch (err) {
  842. return res.json(ApiResponse.error(err));
  843. }
  844. const result = {};
  845. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  846. return res.json(ApiResponse.success(result));
  847. };
  848. /**
  849. * @swagger
  850. *
  851. * /pages.exist:
  852. * get:
  853. * tags: [Pages]
  854. * operationId: getPageExistence
  855. * summary: /pages.exist
  856. * description: Get page existence
  857. * parameters:
  858. * - in: query
  859. * name: pagePaths
  860. * schema:
  861. * type: string
  862. * description: Page path list in JSON Array format
  863. * example: '["/", "/user/unknown"]'
  864. * responses:
  865. * 200:
  866. * description: Succeeded to get page existence.
  867. * content:
  868. * application/json:
  869. * schema:
  870. * properties:
  871. * ok:
  872. * $ref: '#/components/schemas/V1Response/properties/ok'
  873. * pages:
  874. * type: string
  875. * description: Properties of page path and existence
  876. * example: '{"/": true, "/user/unknown": false}'
  877. * 403:
  878. * $ref: '#/components/responses/403'
  879. * 500:
  880. * $ref: '#/components/responses/500'
  881. */
  882. /**
  883. * @api {get} /pages.exist Get if page exists
  884. * @apiName GetPage
  885. * @apiGroup Page
  886. *
  887. * @apiParam {String} pages (stringified JSON)
  888. */
  889. api.exist = async function(req, res) {
  890. const pagePaths = JSON.parse(req.query.pagePaths || '[]');
  891. const pages = {};
  892. await Promise.all(pagePaths.map(async(path) => {
  893. // check page existence
  894. const isExist = await Page.count({ path }) > 0;
  895. pages[path] = isExist;
  896. return;
  897. }));
  898. const result = { pages };
  899. return res.json(ApiResponse.success(result));
  900. };
  901. /**
  902. * @swagger
  903. *
  904. * /pages.getPageTag:
  905. * get:
  906. * tags: [Pages]
  907. * operationId: getPageTag
  908. * summary: /pages.getPageTag
  909. * description: Get page tag
  910. * parameters:
  911. * - in: query
  912. * name: pageId
  913. * schema:
  914. * $ref: '#/components/schemas/Page/properties/_id'
  915. * responses:
  916. * 200:
  917. * description: Succeeded to get page tags.
  918. * content:
  919. * application/json:
  920. * schema:
  921. * properties:
  922. * ok:
  923. * $ref: '#/components/schemas/V1Response/properties/ok'
  924. * tags:
  925. * $ref: '#/components/schemas/Tags'
  926. * 403:
  927. * $ref: '#/components/responses/403'
  928. * 500:
  929. * $ref: '#/components/responses/500'
  930. */
  931. /**
  932. * @api {get} /pages.getPageTag get page tags
  933. * @apiName GetPageTag
  934. * @apiGroup Page
  935. *
  936. * @apiParam {String} pageId
  937. */
  938. api.getPageTag = async function(req, res) {
  939. const result = {};
  940. try {
  941. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  942. }
  943. catch (err) {
  944. return res.json(ApiResponse.error(err));
  945. }
  946. return res.json(ApiResponse.success(result));
  947. };
  948. /**
  949. * @swagger
  950. *
  951. * /pages.updatePost:
  952. * get:
  953. * tags: [Pages, CrowiCompatibles]
  954. * operationId: getUpdatePostPage
  955. * summary: /pages.updatePost
  956. * description: Get UpdatePost setting list
  957. * parameters:
  958. * - in: query
  959. * name: path
  960. * schema:
  961. * $ref: '#/components/schemas/Page/properties/path'
  962. * responses:
  963. * 200:
  964. * description: Succeeded to get UpdatePost setting list.
  965. * content:
  966. * application/json:
  967. * schema:
  968. * properties:
  969. * ok:
  970. * $ref: '#/components/schemas/V1Response/properties/ok'
  971. * updatePost:
  972. * $ref: '#/components/schemas/UpdatePost'
  973. * 403:
  974. * $ref: '#/components/responses/403'
  975. * 500:
  976. * $ref: '#/components/responses/500'
  977. */
  978. /**
  979. * @api {get} /pages.updatePost
  980. * @apiName Get UpdatePost setting list
  981. * @apiGroup Page
  982. *
  983. * @apiParam {String} path
  984. */
  985. api.getUpdatePost = function(req, res) {
  986. const path = req.query.path;
  987. const UpdatePost = crowi.model('UpdatePost');
  988. if (!path) {
  989. return res.json(ApiResponse.error({}));
  990. }
  991. UpdatePost.findSettingsByPath(path)
  992. .then((data) => {
  993. // eslint-disable-next-line no-param-reassign
  994. data = data.map((e) => {
  995. return e.channel;
  996. });
  997. debug('Found updatePost data', data);
  998. const result = { updatePost: data };
  999. return res.json(ApiResponse.success(result));
  1000. })
  1001. .catch((err) => {
  1002. debug('Error occured while get setting', err);
  1003. return res.json(ApiResponse.error({}));
  1004. });
  1005. };
  1006. /**
  1007. * @api {post} /pages.remove Remove page
  1008. * @apiName RemovePage
  1009. * @apiGroup Page
  1010. *
  1011. * @apiParam {String} page_id Page Id.
  1012. * @apiParam {String} revision_id
  1013. */
  1014. api.remove = async function(req, res) {
  1015. const pageId = req.body.page_id;
  1016. const previousRevision = req.body.revision_id || null;
  1017. const socketClientId = req.body.socketClientId || undefined;
  1018. // get completely flag
  1019. const isCompletely = (req.body.completely != null);
  1020. // get recursively flag
  1021. const isRecursively = (req.body.recursively != null);
  1022. const options = { socketClientId };
  1023. const page = await Page.findByIdAndViewer(pageId, req.user);
  1024. if (page == null) {
  1025. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1026. }
  1027. debug('Delete page', page._id, page.path);
  1028. try {
  1029. if (isCompletely) {
  1030. if (!req.user.canDeleteCompletely(page.creator)) {
  1031. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  1032. }
  1033. if (isRecursively) {
  1034. await Page.completelyDeletePageRecursively(page, req.user, options);
  1035. }
  1036. else {
  1037. await Page.completelyDeletePage(page, req.user, options);
  1038. }
  1039. }
  1040. else {
  1041. if (!page.isUpdatable(previousRevision)) {
  1042. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1043. }
  1044. if (isRecursively) {
  1045. await Page.deletePageRecursively(page, req.user, options);
  1046. }
  1047. else {
  1048. await Page.deletePage(page, req.user, options);
  1049. }
  1050. }
  1051. }
  1052. catch (err) {
  1053. logger.error('Error occured while get setting', err);
  1054. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  1055. }
  1056. debug('Page deleted', page.path);
  1057. const result = {};
  1058. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  1059. res.json(ApiResponse.success(result));
  1060. try {
  1061. // global notification
  1062. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page, req.user);
  1063. }
  1064. catch (err) {
  1065. logger.error('Delete notification failed', err);
  1066. }
  1067. };
  1068. /**
  1069. * @api {post} /pages.revertRemove Revert removed page
  1070. * @apiName RevertRemovePage
  1071. * @apiGroup Page
  1072. *
  1073. * @apiParam {String} page_id Page Id.
  1074. */
  1075. api.revertRemove = async function(req, res, options) {
  1076. const pageId = req.body.page_id;
  1077. const socketClientId = req.body.socketClientId || undefined;
  1078. // get recursively flag
  1079. const isRecursively = (req.body.recursively != null);
  1080. let page;
  1081. try {
  1082. page = await Page.findByIdAndViewer(pageId, req.user);
  1083. if (page == null) {
  1084. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  1085. }
  1086. if (isRecursively) {
  1087. page = await Page.revertDeletedPageRecursively(page, req.user, { socketClientId });
  1088. }
  1089. else {
  1090. page = await Page.revertDeletedPage(page, req.user, { socketClientId });
  1091. }
  1092. }
  1093. catch (err) {
  1094. logger.error('Error occured while get setting', err);
  1095. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  1096. }
  1097. const result = {};
  1098. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  1099. return res.json(ApiResponse.success(result));
  1100. };
  1101. /**
  1102. * @swagger
  1103. *
  1104. * /pages.rename:
  1105. * post:
  1106. * tags: [Pages, CrowiCompatibles]
  1107. * operationId: renamePage
  1108. * summary: /pages.rename
  1109. * description: Rename page
  1110. * requestBody:
  1111. * content:
  1112. * application/json:
  1113. * schema:
  1114. * properties:
  1115. * page_id:
  1116. * $ref: '#/components/schemas/Page/properties/_id'
  1117. * path:
  1118. * $ref: '#/components/schemas/Page/properties/path'
  1119. * revision_id:
  1120. * $ref: '#/components/schemas/Revision/properties/_id'
  1121. * new_path:
  1122. * type: string
  1123. * description: new path
  1124. * example: /user/alice/new_test
  1125. * create_redirect:
  1126. * type: boolean
  1127. * description: whether redirect page
  1128. * required:
  1129. * - page_id
  1130. * responses:
  1131. * 200:
  1132. * description: Succeeded to rename page.
  1133. * content:
  1134. * application/json:
  1135. * schema:
  1136. * properties:
  1137. * ok:
  1138. * $ref: '#/components/schemas/V1Response/properties/ok'
  1139. * page:
  1140. * $ref: '#/components/schemas/Page'
  1141. * 403:
  1142. * $ref: '#/components/responses/403'
  1143. * 500:
  1144. * $ref: '#/components/responses/500'
  1145. */
  1146. /**
  1147. * @api {post} /pages.rename Rename page
  1148. * @apiName RenamePage
  1149. * @apiGroup Page
  1150. *
  1151. * @apiParam {String} page_id Page Id.
  1152. * @apiParam {String} path
  1153. * @apiParam {String} revision_id
  1154. * @apiParam {String} new_path New path name.
  1155. * @apiParam {Bool} create_redirect
  1156. */
  1157. api.rename = async function(req, res) {
  1158. const pageId = req.body.page_id;
  1159. const previousRevision = req.body.revision_id || null;
  1160. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1161. const options = {
  1162. createRedirectPage: (req.body.create_redirect != null),
  1163. updateMetadata: (req.body.remain_metadata == null),
  1164. socketClientId: +req.body.socketClientId || undefined,
  1165. };
  1166. const isRecursively = (req.body.recursively != null);
  1167. if (!Page.isCreatableName(newPagePath)) {
  1168. return res.json(ApiResponse.error(`Could not use the path '${newPagePath})'`, 'invalid_path'));
  1169. }
  1170. // check whether path starts slash
  1171. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1172. const isExist = await Page.count({ path: newPagePath }) > 0;
  1173. if (isExist) {
  1174. // if page found, cannot cannot rename to that path
  1175. return res.json(ApiResponse.error(`'new_path=${newPagePath}' already exists`, 'already_exists'));
  1176. }
  1177. let page;
  1178. try {
  1179. page = await Page.findByIdAndViewer(pageId, req.user);
  1180. if (page == null) {
  1181. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1182. }
  1183. if (!page.isUpdatable(previousRevision)) {
  1184. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1185. }
  1186. if (isRecursively) {
  1187. page = await Page.renameRecursively(page, newPagePath, req.user, options);
  1188. }
  1189. else {
  1190. page = await Page.rename(page, newPagePath, req.user, options);
  1191. }
  1192. }
  1193. catch (err) {
  1194. logger.error(err);
  1195. return res.json(ApiResponse.error('Failed to update page.', 'unknown'));
  1196. }
  1197. const result = {};
  1198. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  1199. res.json(ApiResponse.success(result));
  1200. try {
  1201. // global notification
  1202. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_MOVE, page, req.user, {
  1203. oldPath: req.body.path,
  1204. });
  1205. }
  1206. catch (err) {
  1207. logger.error('Move notification failed', err);
  1208. }
  1209. return page;
  1210. };
  1211. /**
  1212. * @swagger
  1213. *
  1214. * /pages.duplicate:
  1215. * post:
  1216. * tags: [Pages]
  1217. * operationId: duplicatePage
  1218. * summary: /pages.duplicate
  1219. * description: Duplicate page
  1220. * requestBody:
  1221. * content:
  1222. * application/json:
  1223. * schema:
  1224. * properties:
  1225. * page_id:
  1226. * $ref: '#/components/schemas/Page/properties/_id'
  1227. * new_path:
  1228. * $ref: '#/components/schemas/Page/properties/path'
  1229. * required:
  1230. * - page_id
  1231. * responses:
  1232. * 200:
  1233. * description: Succeeded to duplicate page.
  1234. * content:
  1235. * application/json:
  1236. * schema:
  1237. * properties:
  1238. * ok:
  1239. * $ref: '#/components/schemas/V1Response/properties/ok'
  1240. * page:
  1241. * $ref: '#/components/schemas/Page'
  1242. * tags:
  1243. * $ref: '#/components/schemas/Tags'
  1244. * 403:
  1245. * $ref: '#/components/responses/403'
  1246. * 500:
  1247. * $ref: '#/components/responses/500'
  1248. */
  1249. /**
  1250. * @api {post} /pages.duplicate Duplicate page
  1251. * @apiName DuplicatePage
  1252. * @apiGroup Page
  1253. *
  1254. * @apiParam {String} page_id Page Id.
  1255. * @apiParam {String} new_path New path name.
  1256. */
  1257. api.duplicate = async function(req, res) {
  1258. const pageId = req.body.page_id;
  1259. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1260. const page = await Page.findByIdAndViewer(pageId, req.user);
  1261. if (page == null) {
  1262. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1263. }
  1264. // check whether path starts slash
  1265. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1266. await page.populateDataToShowRevision();
  1267. const originTags = await page.findRelatedTagsById();
  1268. req.body.path = newPagePath;
  1269. req.body.body = page.revision.body;
  1270. req.body.grant = page.grant;
  1271. req.body.grantedUsers = page.grantedUsers;
  1272. req.body.grantUserGroupId = page.grantedGroup;
  1273. req.body.pageTags = originTags;
  1274. return api.create(req, res);
  1275. };
  1276. /**
  1277. * @api {post} /pages.unlink Remove the redirecting page
  1278. * @apiName UnlinkPage
  1279. * @apiGroup Page
  1280. *
  1281. * @apiParam {String} page_id Page Id.
  1282. * @apiParam {String} revision_id
  1283. */
  1284. api.unlink = async function(req, res) {
  1285. const path = req.body.path;
  1286. try {
  1287. await Page.removeRedirectOriginPageByPath(path);
  1288. logger.debug('Redirect Page deleted', path);
  1289. }
  1290. catch (err) {
  1291. logger.error('Error occured while get setting', err);
  1292. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1293. }
  1294. const result = { path };
  1295. return res.json(ApiResponse.success(result));
  1296. };
  1297. return actions;
  1298. };