page.js 30 KB

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