page.js 45 KB

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