page.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. import { body } from 'express-validator';
  2. import mongoose from 'mongoose';
  3. import { SupportedTargetModel, SupportedAction } from '~/interfaces/activity';
  4. import XssOption from '~/services/xss/xssOption';
  5. import loggerFactory from '~/utils/logger';
  6. import { PathAlreadyExistsError } from '../models/errors';
  7. import UpdatePost from '../models/update-post';
  8. const { serializePageSecurely } = require('../models/serializers/page-serializer');
  9. const { serializeRevisionSecurely } = require('../models/serializers/revision-serializer');
  10. const { serializeUserSecurely } = require('../models/serializers/user-serializer');
  11. /**
  12. * @swagger
  13. * tags:
  14. * name: Pages
  15. */
  16. /**
  17. * @swagger
  18. *
  19. * components:
  20. * schemas:
  21. * Page:
  22. * description: Page
  23. * type: object
  24. * properties:
  25. * _id:
  26. * type: string
  27. * description: page ID
  28. * example: 5e07345972560e001761fa63
  29. * __v:
  30. * type: number
  31. * description: DB record version
  32. * example: 0
  33. * commentCount:
  34. * type: number
  35. * description: count of comments
  36. * example: 3
  37. * createdAt:
  38. * type: string
  39. * description: date created at
  40. * example: 2010-01-01T00:00:00.000Z
  41. * creator:
  42. * $ref: '#/components/schemas/User'
  43. * extended:
  44. * type: object
  45. * description: extend data
  46. * example: {}
  47. * grant:
  48. * type: number
  49. * description: grant
  50. * example: 1
  51. * grantedUsers:
  52. * type: array
  53. * description: granted users
  54. * items:
  55. * type: string
  56. * description: user ID
  57. * example: ["5ae5fccfc5577b0004dbd8ab"]
  58. * lastUpdateUser:
  59. * $ref: '#/components/schemas/User'
  60. * liker:
  61. * type: array
  62. * description: granted users
  63. * items:
  64. * type: string
  65. * description: user ID
  66. * example: []
  67. * path:
  68. * type: string
  69. * description: page path
  70. * example: /
  71. * revision:
  72. * $ref: '#/components/schemas/Revision'
  73. * status:
  74. * type: string
  75. * description: status
  76. * enum:
  77. * - 'wip'
  78. * - 'published'
  79. * - 'deleted'
  80. * - 'deprecated'
  81. * example: published
  82. * updatedAt:
  83. * type: string
  84. * description: date updated at
  85. * example: 2010-01-01T00:00:00.000Z
  86. *
  87. * UpdatePost:
  88. * description: UpdatePost
  89. * type: object
  90. * properties:
  91. * _id:
  92. * type: string
  93. * description: update post ID
  94. * example: 5e0734e472560e001761fa68
  95. * __v:
  96. * type: number
  97. * description: DB record version
  98. * example: 0
  99. * pathPattern:
  100. * type: string
  101. * description: path pattern
  102. * example: /test
  103. * patternPrefix:
  104. * type: string
  105. * description: patternPrefix prefix
  106. * example: /
  107. * patternPrefix2:
  108. * type: string
  109. * description: path
  110. * example: test
  111. * channel:
  112. * type: string
  113. * description: channel
  114. * example: general
  115. * provider:
  116. * type: string
  117. * description: provider
  118. * enum:
  119. * - slack
  120. * example: slack
  121. * creator:
  122. * $ref: '#/components/schemas/User'
  123. * createdAt:
  124. * type: string
  125. * description: date created at
  126. * example: 2010-01-01T00:00:00.000Z
  127. */
  128. /* eslint-disable no-use-before-define */
  129. module.exports = function(crowi, app) {
  130. const debug = require('debug')('growi:routes:page');
  131. const logger = loggerFactory('growi:routes:page');
  132. const { pathUtils } = require('@growi/core');
  133. const Page = crowi.model('Page');
  134. const User = crowi.model('User');
  135. const PageTagRelation = crowi.model('PageTagRelation');
  136. const GlobalNotificationSetting = crowi.model('GlobalNotificationSetting');
  137. const PageRedirect = mongoose.model('PageRedirect');
  138. const ApiResponse = require('../util/apiResponse');
  139. const { configManager, xssService } = crowi;
  140. const globalNotificationService = crowi.getGlobalNotificationService();
  141. const userNotificationService = crowi.getUserNotificationService();
  142. const activityEvent = crowi.event('activity');
  143. const Xss = require('~/services/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. // async function showPageForPresentation(req, res, next) {
  153. // const id = req.params.id;
  154. // const { revisionId } = req.query;
  155. // let page = await Page.findByIdAndViewer(id, req.user, null, true, true);
  156. // if (page == null) {
  157. // next();
  158. // }
  159. // // empty page
  160. // if (page.isEmpty) {
  161. // // redirect to page (path) url
  162. // const url = new URL('https://dummy.origin');
  163. // url.pathname = page.path;
  164. // Object.entries(req.query).forEach(([key, value], i) => {
  165. // url.searchParams.append(key, value);
  166. // });
  167. // return res.safeRedirect(urljoin(url.pathname, url.search));
  168. // }
  169. // const renderVars = {};
  170. // // populate
  171. // page = await page.populateDataToMakePresentation(revisionId);
  172. // if (page != null) {
  173. // addRenderVarsForPresentation(renderVars, page);
  174. // }
  175. // return res.render('page_presentation', renderVars);
  176. // }
  177. /**
  178. * switch action
  179. * - presentation mode
  180. * - by behaviorType
  181. */
  182. // actions.showPage = async function(req, res, next) {
  183. // // presentation mode
  184. // if (req.query.presentation) {
  185. // return showPageForPresentation(req, res, next);
  186. // }
  187. // // delegate to showPageForGrowiBehavior
  188. // return showPageForGrowiBehavior(req, res, next);
  189. // };
  190. const api = {};
  191. const validator = {};
  192. actions.api = api;
  193. actions.validator = validator;
  194. /**
  195. * @swagger
  196. *
  197. * /pages.list:
  198. * get:
  199. * tags: [Pages, CrowiCompatibles]
  200. * operationId: listPages
  201. * summary: /pages.list
  202. * description: Get list of pages
  203. * parameters:
  204. * - in: query
  205. * name: path
  206. * schema:
  207. * $ref: '#/components/schemas/Page/properties/path'
  208. * - in: query
  209. * name: user
  210. * schema:
  211. * $ref: '#/components/schemas/User/properties/username'
  212. * - in: query
  213. * name: limit
  214. * schema:
  215. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  216. * - in: query
  217. * name: offset
  218. * schema:
  219. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  220. * responses:
  221. * 200:
  222. * description: Succeeded to get list of pages.
  223. * content:
  224. * application/json:
  225. * schema:
  226. * properties:
  227. * ok:
  228. * $ref: '#/components/schemas/V1Response/properties/ok'
  229. * pages:
  230. * type: array
  231. * items:
  232. * $ref: '#/components/schemas/Page'
  233. * description: page list
  234. * 403:
  235. * $ref: '#/components/responses/403'
  236. * 500:
  237. * $ref: '#/components/responses/500'
  238. */
  239. /**
  240. * @api {get} /pages.list List pages by user
  241. * @apiName ListPage
  242. * @apiGroup Page
  243. *
  244. * @apiParam {String} path
  245. * @apiParam {String} user
  246. */
  247. api.list = async function(req, res) {
  248. const username = req.query.user || null;
  249. const path = req.query.path || null;
  250. const limit = +req.query.limit || 50;
  251. const offset = parseInt(req.query.offset) || 0;
  252. const queryOptions = { offset, limit: limit + 1 };
  253. // Accepts only one of these
  254. if (username === null && path === null) {
  255. return res.json(ApiResponse.error('Parameter user or path is required.'));
  256. }
  257. if (username !== null && path !== null) {
  258. return res.json(ApiResponse.error('Parameter user or path is required.'));
  259. }
  260. try {
  261. let result = null;
  262. if (path == null) {
  263. const user = await User.findUserByUsername(username);
  264. if (user === null) {
  265. throw new Error('The user not found.');
  266. }
  267. result = await Page.findListByCreator(user, req.user, queryOptions);
  268. }
  269. else {
  270. result = await Page.findListByStartWith(path, req.user, queryOptions);
  271. }
  272. if (result.pages.length > limit) {
  273. result.pages.pop();
  274. }
  275. result.pages.forEach((page) => {
  276. if (page.lastUpdateUser != null && page.lastUpdateUser instanceof User) {
  277. page.lastUpdateUser = serializeUserSecurely(page.lastUpdateUser);
  278. }
  279. });
  280. return res.json(ApiResponse.success(result));
  281. }
  282. catch (err) {
  283. return res.json(ApiResponse.error(err));
  284. }
  285. };
  286. // TODO If everything that depends on this route, delete it too
  287. api.create = async function(req, res) {
  288. const body = req.body.body || null;
  289. let pagePath = req.body.path || null;
  290. const grant = req.body.grant || null;
  291. const grantUserGroupId = req.body.grantUserGroupId || null;
  292. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  293. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  294. const slackChannels = req.body.slackChannels || null;
  295. const pageTags = req.body.pageTags || undefined;
  296. if (body === null || pagePath === null) {
  297. return res.json(ApiResponse.error('Parameters body and path are required.'));
  298. }
  299. // check whether path starts slash
  300. pagePath = pathUtils.addHeadingSlash(pagePath);
  301. // check page existence
  302. const isExist = await Page.count({ path: pagePath }) > 0;
  303. if (isExist) {
  304. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  305. }
  306. const options = { overwriteScopesOfDescendants };
  307. if (grant != null) {
  308. options.grant = grant;
  309. options.grantUserGroupId = grantUserGroupId;
  310. }
  311. const createdPage = await crowi.pageService.create(pagePath, body, req.user, options);
  312. let savedTags;
  313. if (pageTags != null) {
  314. await PageTagRelation.updatePageTags(createdPage.id, pageTags);
  315. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  316. }
  317. const result = {
  318. page: serializePageSecurely(createdPage),
  319. revision: serializeRevisionSecurely(createdPage.revision),
  320. tags: savedTags,
  321. };
  322. res.json(ApiResponse.success(result));
  323. // global notification
  324. try {
  325. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage, req.user);
  326. }
  327. catch (err) {
  328. logger.error('Create notification failed', err);
  329. }
  330. // user notification
  331. if (isSlackEnabled) {
  332. try {
  333. const results = await userNotificationService.fire(createdPage, req.user, slackChannels, 'create');
  334. results.forEach((result) => {
  335. if (result.status === 'rejected') {
  336. logger.error('Create user notification failed', result.reason);
  337. }
  338. });
  339. }
  340. catch (err) {
  341. logger.error('Create user notification failed', err);
  342. }
  343. }
  344. };
  345. /**
  346. * @swagger
  347. *
  348. * /pages.update:
  349. * post:
  350. * tags: [Pages, CrowiCompatibles]
  351. * operationId: updatePage
  352. * summary: /pages.update
  353. * description: Update page
  354. * requestBody:
  355. * content:
  356. * application/json:
  357. * schema:
  358. * properties:
  359. * body:
  360. * $ref: '#/components/schemas/Revision/properties/body'
  361. * page_id:
  362. * $ref: '#/components/schemas/Page/properties/_id'
  363. * revision_id:
  364. * $ref: '#/components/schemas/Revision/properties/_id'
  365. * grant:
  366. * $ref: '#/components/schemas/Page/properties/grant'
  367. * required:
  368. * - body
  369. * - page_id
  370. * - revision_id
  371. * responses:
  372. * 200:
  373. * description: Succeeded to update page.
  374. * content:
  375. * application/json:
  376. * schema:
  377. * properties:
  378. * ok:
  379. * $ref: '#/components/schemas/V1Response/properties/ok'
  380. * page:
  381. * $ref: '#/components/schemas/Page'
  382. * revision:
  383. * $ref: '#/components/schemas/Revision'
  384. * 403:
  385. * $ref: '#/components/responses/403'
  386. * 500:
  387. * $ref: '#/components/responses/500'
  388. */
  389. /**
  390. * @api {post} /pages.update Update page
  391. * @apiName UpdatePage
  392. * @apiGroup Page
  393. *
  394. * @apiParam {String} body
  395. * @apiParam {String} page_id
  396. * @apiParam {String} revision_id
  397. * @apiParam {String} grant
  398. *
  399. * In the case of the page exists:
  400. * - If revision_id is specified => update the page,
  401. * - If revision_id is not specified => force update by the new contents.
  402. */
  403. api.update = async function(req, res) {
  404. const pageBody = req.body.body ?? null;
  405. const pageId = req.body.page_id || null;
  406. const revisionId = req.body.revision_id || null;
  407. const grant = req.body.grant || null;
  408. const grantUserGroupId = req.body.grantUserGroupId || null;
  409. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  410. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  411. const slackChannels = req.body.slackChannels || null;
  412. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  413. const pageTags = req.body.pageTags || undefined;
  414. if (pageId === null || pageBody === null || revisionId === null) {
  415. return res.json(ApiResponse.error('page_id, body and revision_id are required.'));
  416. }
  417. // check page existence
  418. const isExist = await Page.count({ _id: pageId }) > 0;
  419. if (!isExist) {
  420. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  421. }
  422. // check revision
  423. const Revision = crowi.model('Revision');
  424. let page = await Page.findByIdAndViewer(pageId, req.user);
  425. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  426. const latestRevision = await Revision.findById(page.revision).populate('author');
  427. const returnLatestRevision = {
  428. revisionId: latestRevision._id.toString(),
  429. revisionBody: xss.process(latestRevision.body),
  430. createdAt: latestRevision.createdAt,
  431. user: serializeUserSecurely(latestRevision.author),
  432. };
  433. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'conflict', returnLatestRevision));
  434. }
  435. const options = { isSyncRevisionToHackmd, overwriteScopesOfDescendants };
  436. if (grant != null) {
  437. options.grant = grant;
  438. options.grantUserGroupId = grantUserGroupId;
  439. }
  440. const previousRevision = await Revision.findById(revisionId);
  441. try {
  442. page = await crowi.pageService.updatePage(page, pageBody, previousRevision.body, req.user, options);
  443. }
  444. catch (err) {
  445. logger.error('error on _api/pages.update', err);
  446. return res.json(ApiResponse.error(err));
  447. }
  448. let savedTags;
  449. if (pageTags != null) {
  450. const tagEvent = crowi.event('tag');
  451. await PageTagRelation.updatePageTags(pageId, pageTags);
  452. savedTags = await PageTagRelation.listTagNamesByPage(pageId);
  453. tagEvent.emit('update', page, savedTags);
  454. }
  455. const result = {
  456. page: serializePageSecurely(page),
  457. revision: serializeRevisionSecurely(page.revision),
  458. tags: savedTags,
  459. };
  460. res.json(ApiResponse.success(result));
  461. // global notification
  462. try {
  463. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_EDIT, page, req.user);
  464. }
  465. catch (err) {
  466. logger.error('Edit notification failed', err);
  467. }
  468. // user notification
  469. if (isSlackEnabled) {
  470. try {
  471. const results = await userNotificationService.fire(page, req.user, slackChannels, 'update', { previousRevision });
  472. results.forEach((result) => {
  473. if (result.status === 'rejected') {
  474. logger.error('Create user notification failed', result.reason);
  475. }
  476. });
  477. }
  478. catch (err) {
  479. logger.error('Create user notification failed', err);
  480. }
  481. }
  482. const parameters = {
  483. targetModel: SupportedTargetModel.MODEL_PAGE,
  484. target: page,
  485. action: SupportedAction.ACTION_PAGE_UPDATE,
  486. };
  487. activityEvent.emit('update', res.locals.activity._id, parameters, { path: page.path, creator: page.creator._id.toString() });
  488. };
  489. /**
  490. * @swagger
  491. *
  492. * /pages.exist:
  493. * get:
  494. * tags: [Pages]
  495. * operationId: getPageExistence
  496. * summary: /pages.exist
  497. * description: Get page existence
  498. * parameters:
  499. * - in: query
  500. * name: pagePaths
  501. * schema:
  502. * type: string
  503. * description: Page path list in JSON Array format
  504. * example: '["/", "/user/unknown"]'
  505. * responses:
  506. * 200:
  507. * description: Succeeded to get page existence.
  508. * content:
  509. * application/json:
  510. * schema:
  511. * properties:
  512. * ok:
  513. * $ref: '#/components/schemas/V1Response/properties/ok'
  514. * pages:
  515. * type: string
  516. * description: Properties of page path and existence
  517. * example: '{"/": true, "/user/unknown": false}'
  518. * 403:
  519. * $ref: '#/components/responses/403'
  520. * 500:
  521. * $ref: '#/components/responses/500'
  522. */
  523. /**
  524. * @api {get} /pages.exist Get if page exists
  525. * @apiName GetPage
  526. * @apiGroup Page
  527. *
  528. * @apiParam {String} pages (stringified JSON)
  529. */
  530. api.exist = async function(req, res) {
  531. const pagePaths = JSON.parse(req.query.pagePaths || '[]');
  532. const pages = {};
  533. await Promise.all(pagePaths.map(async(path) => {
  534. // check page existence
  535. const isExist = await Page.count({ path }) > 0;
  536. pages[path] = isExist;
  537. return;
  538. }));
  539. const result = { pages };
  540. return res.json(ApiResponse.success(result));
  541. };
  542. /**
  543. * @swagger
  544. *
  545. * /pages.getPageTag:
  546. * get:
  547. * tags: [Pages]
  548. * operationId: getPageTag
  549. * summary: /pages.getPageTag
  550. * description: Get page tag
  551. * parameters:
  552. * - in: query
  553. * name: pageId
  554. * schema:
  555. * $ref: '#/components/schemas/Page/properties/_id'
  556. * responses:
  557. * 200:
  558. * description: Succeeded to get page tags.
  559. * content:
  560. * application/json:
  561. * schema:
  562. * properties:
  563. * ok:
  564. * $ref: '#/components/schemas/V1Response/properties/ok'
  565. * tags:
  566. * $ref: '#/components/schemas/Tags'
  567. * 403:
  568. * $ref: '#/components/responses/403'
  569. * 500:
  570. * $ref: '#/components/responses/500'
  571. */
  572. /**
  573. * @api {get} /pages.getPageTag get page tags
  574. * @apiName GetPageTag
  575. * @apiGroup Page
  576. *
  577. * @apiParam {String} pageId
  578. */
  579. api.getPageTag = async function(req, res) {
  580. const result = {};
  581. try {
  582. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  583. }
  584. catch (err) {
  585. return res.json(ApiResponse.error(err));
  586. }
  587. return res.json(ApiResponse.success(result));
  588. };
  589. /**
  590. * @swagger
  591. *
  592. * /pages.updatePost:
  593. * get:
  594. * tags: [Pages, CrowiCompatibles]
  595. * operationId: getUpdatePostPage
  596. * summary: /pages.updatePost
  597. * description: Get UpdatePost setting list
  598. * parameters:
  599. * - in: query
  600. * name: path
  601. * schema:
  602. * $ref: '#/components/schemas/Page/properties/path'
  603. * responses:
  604. * 200:
  605. * description: Succeeded to get UpdatePost setting list.
  606. * content:
  607. * application/json:
  608. * schema:
  609. * properties:
  610. * ok:
  611. * $ref: '#/components/schemas/V1Response/properties/ok'
  612. * updatePost:
  613. * $ref: '#/components/schemas/UpdatePost'
  614. * 403:
  615. * $ref: '#/components/responses/403'
  616. * 500:
  617. * $ref: '#/components/responses/500'
  618. */
  619. /**
  620. * @api {get} /pages.updatePost
  621. * @apiName Get UpdatePost setting list
  622. * @apiGroup Page
  623. *
  624. * @apiParam {String} path
  625. */
  626. api.getUpdatePost = function(req, res) {
  627. const path = req.query.path;
  628. if (!path) {
  629. return res.json(ApiResponse.error({}));
  630. }
  631. UpdatePost.findSettingsByPath(path)
  632. .then((data) => {
  633. // eslint-disable-next-line no-param-reassign
  634. data = data.map((e) => {
  635. return e.channel;
  636. });
  637. debug('Found updatePost data', data);
  638. const result = { updatePost: data };
  639. return res.json(ApiResponse.success(result));
  640. })
  641. .catch((err) => {
  642. debug('Error occured while get setting', err);
  643. return res.json(ApiResponse.error({}));
  644. });
  645. };
  646. validator.remove = [
  647. body('completely')
  648. .custom(v => v === 'true' || v === true || v == null)
  649. .withMessage('The body property "completely" must be "true" or true. (Omit param for false)'),
  650. body('recursively')
  651. .custom(v => v === 'true' || v === true || v == null)
  652. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  653. ];
  654. /**
  655. * @api {post} /pages.remove Remove page
  656. * @apiName RemovePage
  657. * @apiGroup Page
  658. *
  659. * @apiParam {String} page_id Page Id.
  660. * @apiParam {String} revision_id
  661. */
  662. api.remove = async function(req, res) {
  663. const pageId = req.body.page_id;
  664. const previousRevision = req.body.revision_id || null;
  665. const { recursively: isRecursively, completely: isCompletely } = req.body;
  666. const options = {};
  667. const activityParameters = {
  668. ip: req.ip,
  669. endpoint: req.originalUrl,
  670. };
  671. const page = await Page.findByIdAndViewer(pageId, req.user, null, true);
  672. if (page == null) {
  673. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  674. }
  675. if (page.isEmpty && !isRecursively) {
  676. return res.json(ApiResponse.error('Empty pages cannot be single deleted', 'single_deletion_empty_pages'));
  677. }
  678. let creator;
  679. if (page.isEmpty) {
  680. // If empty, the creator is inherited from the closest non-empty ancestor page.
  681. const notEmptyClosestAncestor = await Page.findNonEmptyClosestAncestor(page.path);
  682. creator = notEmptyClosestAncestor.creator;
  683. }
  684. else {
  685. creator = page.creator;
  686. }
  687. debug('Delete page', page._id, page.path);
  688. try {
  689. if (isCompletely) {
  690. if (!crowi.pageService.canDeleteCompletely(page.path, creator, req.user, isRecursively)) {
  691. return res.json(ApiResponse.error('You can not delete this page completely', 'user_not_admin'));
  692. }
  693. await crowi.pageService.deleteCompletely(page, req.user, options, isRecursively, false, activityParameters);
  694. }
  695. else {
  696. // behave like not found
  697. const notRecursivelyAndEmpty = page.isEmpty && !isRecursively;
  698. if (notRecursivelyAndEmpty) {
  699. return res.json(ApiResponse.error(`Page '${pageId}' is not found.`, 'notfound'));
  700. }
  701. if (!page.isEmpty && !page.isUpdatable(previousRevision)) {
  702. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  703. }
  704. if (!crowi.pageService.canDelete(page.path, creator, req.user, isRecursively)) {
  705. return res.json(ApiResponse.error('You can not delete this page', 'user_not_admin'));
  706. }
  707. await crowi.pageService.deletePage(page, req.user, options, isRecursively, activityParameters);
  708. }
  709. }
  710. catch (err) {
  711. logger.error('Error occured while get setting', err);
  712. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  713. }
  714. debug('Page deleted', page.path);
  715. const result = {};
  716. result.path = page.path;
  717. result.isRecursively = isRecursively;
  718. result.isCompletely = isCompletely;
  719. res.json(ApiResponse.success(result));
  720. try {
  721. // global notification
  722. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page, req.user);
  723. }
  724. catch (err) {
  725. logger.error('Delete notification failed', err);
  726. }
  727. };
  728. validator.revertRemove = [
  729. body('recursively')
  730. .optional()
  731. .custom(v => v === 'true' || v === true || v == null)
  732. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  733. ];
  734. /**
  735. * @api {post} /pages.revertRemove Revert removed page
  736. * @apiName RevertRemovePage
  737. * @apiGroup Page
  738. *
  739. * @apiParam {String} page_id Page Id.
  740. */
  741. api.revertRemove = async function(req, res, options) {
  742. const pageId = req.body.page_id;
  743. // get recursively flag
  744. const isRecursively = req.body.recursively;
  745. const activityParameters = {
  746. ip: req.ip,
  747. endpoint: req.originalUrl,
  748. };
  749. let page;
  750. let descendantPages;
  751. try {
  752. page = await Page.findByIdAndViewer(pageId, req.user);
  753. if (page == null) {
  754. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  755. }
  756. page = await crowi.pageService.revertDeletedPage(page, req.user, {}, isRecursively, activityParameters);
  757. }
  758. catch (err) {
  759. if (err instanceof PathAlreadyExistsError) {
  760. logger.error('Path already exists', err);
  761. return res.json(ApiResponse.error(err, 'already_exists', err.targetPath));
  762. }
  763. logger.error('Error occured while get setting', err);
  764. return res.json(ApiResponse.error(err));
  765. }
  766. const result = {};
  767. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  768. return res.json(ApiResponse.success(result));
  769. };
  770. /**
  771. * @swagger
  772. *
  773. * /pages.duplicate:
  774. * post:
  775. * tags: [Pages]
  776. * operationId: duplicatePage
  777. * summary: /pages.duplicate
  778. * description: Duplicate page
  779. * requestBody:
  780. * content:
  781. * application/json:
  782. * schema:
  783. * properties:
  784. * page_id:
  785. * $ref: '#/components/schemas/Page/properties/_id'
  786. * new_path:
  787. * $ref: '#/components/schemas/Page/properties/path'
  788. * required:
  789. * - page_id
  790. * responses:
  791. * 200:
  792. * description: Succeeded to duplicate page.
  793. * content:
  794. * application/json:
  795. * schema:
  796. * properties:
  797. * ok:
  798. * $ref: '#/components/schemas/V1Response/properties/ok'
  799. * page:
  800. * $ref: '#/components/schemas/Page'
  801. * tags:
  802. * $ref: '#/components/schemas/Tags'
  803. * 403:
  804. * $ref: '#/components/responses/403'
  805. * 500:
  806. * $ref: '#/components/responses/500'
  807. */
  808. /**
  809. * @api {post} /pages.duplicate Duplicate page
  810. * @apiName DuplicatePage
  811. * @apiGroup Page
  812. *
  813. * @apiParam {String} page_id Page Id.
  814. * @apiParam {String} new_path New path name.
  815. */
  816. api.duplicate = async function(req, res) {
  817. const pageId = req.body.page_id;
  818. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  819. const page = await Page.findByIdAndViewer(pageId, req.user);
  820. if (page == null) {
  821. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  822. }
  823. // check whether path starts slash
  824. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  825. await page.populateDataToShowRevision();
  826. const originTags = await page.findRelatedTagsById();
  827. req.body.path = newPagePath;
  828. req.body.body = page.revision.body;
  829. req.body.grant = page.grant;
  830. req.body.grantedUsers = page.grantedUsers;
  831. req.body.grantUserGroupId = page.grantedGroup;
  832. req.body.pageTags = originTags;
  833. return api.create(req, res);
  834. };
  835. /**
  836. * @api {post} /pages.unlink Remove the redirecting page
  837. * @apiName UnlinkPage
  838. * @apiGroup Page
  839. *
  840. * @apiParam {String} page_id Page Id.
  841. * @apiParam {String} revision_id
  842. */
  843. api.unlink = async function(req, res) {
  844. const path = req.body.path;
  845. try {
  846. await PageRedirect.removePageRedirectsByToPath(path);
  847. logger.debug('Redirect Page deleted', path);
  848. }
  849. catch (err) {
  850. logger.error('Error occured while get setting', err);
  851. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  852. }
  853. const result = { path };
  854. return res.json(ApiResponse.success(result));
  855. };
  856. return actions;
  857. };