page.js 41 KB

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