page.js 41 KB

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