page.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  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.trashPageListShowWrapper = function(req, res) {
  446. // redirect to '/trash'
  447. return res.redirect('/trash');
  448. };
  449. /* eslint-enable no-else-return */
  450. /**
  451. * switch action by behaviorType
  452. */
  453. /* eslint-disable no-else-return */
  454. actions.trashPageShowWrapper = function(req, res) {
  455. // Crowi behavior for '/trash/*'
  456. return actions.deletedPageListShow(req, res);
  457. };
  458. /* eslint-enable no-else-return */
  459. /**
  460. * switch action by behaviorType
  461. */
  462. /* eslint-disable no-else-return */
  463. actions.deletedPageListShowWrapper = function(req, res) {
  464. const path = `/trash${getPathFromRequest(req)}`;
  465. return res.redirect(path);
  466. };
  467. /* eslint-enable no-else-return */
  468. actions.notFound = async function(req, res) {
  469. return _notFound(req, res);
  470. };
  471. actions.deletedPageListShow = async function(req, res) {
  472. // normalizePath makes '/trash/' -> '/trash'
  473. const path = pathUtils.normalizePath(`/trash${getPathFromRequest(req)}`);
  474. const limit = 50;
  475. const offset = parseInt(req.query.offset) || 0;
  476. const queryOptions = {
  477. offset,
  478. limit,
  479. includeTrashed: true,
  480. };
  481. const renderVars = {
  482. page: null,
  483. path,
  484. pages: [],
  485. };
  486. const result = await Page.findListWithDescendants(path, req.user, queryOptions);
  487. if (result.pages.length > limit) {
  488. result.pages.pop();
  489. }
  490. renderVars.pager = generatePager(result.offset, result.limit, result.totalCount);
  491. renderVars.pages = result.pages;
  492. res.render('layout-growi/page_list', renderVars);
  493. };
  494. /**
  495. * redirector
  496. */
  497. async function redirector(req, res, next, path) {
  498. const { redirectFrom } = req.query;
  499. const builder = new PageQueryBuilder(Page.find({ path }));
  500. await Page.addConditionToFilteringByViewerForList(builder, req.user);
  501. const pages = await builder.query.lean().clone().exec('find');
  502. if (pages.length >= 2) {
  503. // populate to list
  504. builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  505. const identicalPathPages = await builder.query.lean().exec('find');
  506. return res.render('layout-growi/identical-path-page', {
  507. identicalPathPages,
  508. redirectFrom,
  509. path,
  510. });
  511. }
  512. if (pages.length === 1) {
  513. if (pages[0].isEmpty) {
  514. return _notFound(req, res);
  515. }
  516. const url = new URL('https://dummy.origin');
  517. url.pathname = `/${pages[0]._id}`;
  518. Object.entries(req.query).forEach(([key, value], i) => {
  519. url.searchParams.append(key, value);
  520. });
  521. return res.safeRedirect(urljoin(url.pathname, url.search));
  522. }
  523. const isForbidden = await Page.exists({ path });
  524. if (isForbidden) {
  525. req.isForbidden = true;
  526. return _notFound(req, res);
  527. }
  528. // redirect by PageRedirect
  529. const pageRedirect = await PageRedirect.findOne({ fromPath: path });
  530. if (pageRedirect != null) {
  531. return res.safeRedirect(`${encodeURI(pageRedirect.toPath)}?redirectFrom=${encodeURIComponent(path)}`);
  532. }
  533. return _notFound(req, res);
  534. }
  535. actions.redirector = async function(req, res, next) {
  536. const path = getPathFromRequest(req);
  537. return redirector(req, res, next, path);
  538. };
  539. actions.redirectorWithEndOfSlash = async function(req, res, next) {
  540. const _path = getPathFromRequest(req);
  541. const path = pathUtils.removeTrailingSlash(_path);
  542. return redirector(req, res, next, path);
  543. };
  544. const api = {};
  545. const validator = {};
  546. actions.api = api;
  547. actions.validator = validator;
  548. /**
  549. * @swagger
  550. *
  551. * /pages.list:
  552. * get:
  553. * tags: [Pages, CrowiCompatibles]
  554. * operationId: listPages
  555. * summary: /pages.list
  556. * description: Get list of pages
  557. * parameters:
  558. * - in: query
  559. * name: path
  560. * schema:
  561. * $ref: '#/components/schemas/Page/properties/path'
  562. * - in: query
  563. * name: user
  564. * schema:
  565. * $ref: '#/components/schemas/User/properties/username'
  566. * - in: query
  567. * name: limit
  568. * schema:
  569. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/limit'
  570. * - in: query
  571. * name: offset
  572. * schema:
  573. * $ref: '#/components/schemas/V1PaginateResult/properties/meta/properties/offset'
  574. * responses:
  575. * 200:
  576. * description: Succeeded to get list of pages.
  577. * content:
  578. * application/json:
  579. * schema:
  580. * properties:
  581. * ok:
  582. * $ref: '#/components/schemas/V1Response/properties/ok'
  583. * pages:
  584. * type: array
  585. * items:
  586. * $ref: '#/components/schemas/Page'
  587. * description: page list
  588. * 403:
  589. * $ref: '#/components/responses/403'
  590. * 500:
  591. * $ref: '#/components/responses/500'
  592. */
  593. /**
  594. * @api {get} /pages.list List pages by user
  595. * @apiName ListPage
  596. * @apiGroup Page
  597. *
  598. * @apiParam {String} path
  599. * @apiParam {String} user
  600. */
  601. api.list = async function(req, res) {
  602. const username = req.query.user || null;
  603. const path = req.query.path || null;
  604. const limit = +req.query.limit || 50;
  605. const offset = parseInt(req.query.offset) || 0;
  606. const queryOptions = { offset, limit: limit + 1 };
  607. // Accepts only one of these
  608. if (username === null && path === null) {
  609. return res.json(ApiResponse.error('Parameter user or path is required.'));
  610. }
  611. if (username !== null && path !== null) {
  612. return res.json(ApiResponse.error('Parameter user or path is required.'));
  613. }
  614. try {
  615. let result = null;
  616. if (path == null) {
  617. const user = await User.findUserByUsername(username);
  618. if (user === null) {
  619. throw new Error('The user not found.');
  620. }
  621. result = await Page.findListByCreator(user, req.user, queryOptions);
  622. }
  623. else {
  624. result = await Page.findListByStartWith(path, req.user, queryOptions);
  625. }
  626. if (result.pages.length > limit) {
  627. result.pages.pop();
  628. }
  629. result.pages.forEach((page) => {
  630. if (page.lastUpdateUser != null && page.lastUpdateUser instanceof User) {
  631. page.lastUpdateUser = serializeUserSecurely(page.lastUpdateUser);
  632. }
  633. });
  634. return res.json(ApiResponse.success(result));
  635. }
  636. catch (err) {
  637. return res.json(ApiResponse.error(err));
  638. }
  639. };
  640. // TODO If everything that depends on this route, delete it too
  641. api.create = async function(req, res) {
  642. const body = req.body.body || null;
  643. let pagePath = req.body.path || null;
  644. const grant = req.body.grant || null;
  645. const grantUserGroupId = req.body.grantUserGroupId || null;
  646. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  647. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  648. const slackChannels = req.body.slackChannels || null;
  649. const pageTags = req.body.pageTags || undefined;
  650. if (body === null || pagePath === null) {
  651. return res.json(ApiResponse.error('Parameters body and path are required.'));
  652. }
  653. // check whether path starts slash
  654. pagePath = pathUtils.addHeadingSlash(pagePath);
  655. // check page existence
  656. const isExist = await Page.count({ path: pagePath }) > 0;
  657. if (isExist) {
  658. return res.json(ApiResponse.error('Page exists', 'already_exists'));
  659. }
  660. const options = {};
  661. if (grant != null) {
  662. options.grant = grant;
  663. options.grantUserGroupId = grantUserGroupId;
  664. }
  665. const createdPage = await Page.create(pagePath, body, req.user, options);
  666. let savedTags;
  667. if (pageTags != null) {
  668. await PageTagRelation.updatePageTags(createdPage.id, pageTags);
  669. savedTags = await PageTagRelation.listTagNamesByPage(createdPage.id);
  670. }
  671. const result = {
  672. page: serializePageSecurely(createdPage),
  673. revision: serializeRevisionSecurely(createdPage.revision),
  674. tags: savedTags,
  675. };
  676. res.json(ApiResponse.success(result));
  677. // update scopes for descendants
  678. if (overwriteScopesOfDescendants) {
  679. Page.applyScopesToDescendantsAsyncronously(createdPage, req.user);
  680. }
  681. // global notification
  682. try {
  683. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_CREATE, createdPage, req.user);
  684. }
  685. catch (err) {
  686. logger.error('Create notification failed', err);
  687. }
  688. // user notification
  689. if (isSlackEnabled) {
  690. try {
  691. const results = await userNotificationService.fire(createdPage, req.user, slackChannels, 'create');
  692. results.forEach((result) => {
  693. if (result.status === 'rejected') {
  694. logger.error('Create user notification failed', result.reason);
  695. }
  696. });
  697. }
  698. catch (err) {
  699. logger.error('Create user notification failed', err);
  700. }
  701. }
  702. };
  703. /**
  704. * @swagger
  705. *
  706. * /pages.update:
  707. * post:
  708. * tags: [Pages, CrowiCompatibles]
  709. * operationId: updatePage
  710. * summary: /pages.update
  711. * description: Update page
  712. * requestBody:
  713. * content:
  714. * application/json:
  715. * schema:
  716. * properties:
  717. * body:
  718. * $ref: '#/components/schemas/Revision/properties/body'
  719. * page_id:
  720. * $ref: '#/components/schemas/Page/properties/_id'
  721. * revision_id:
  722. * $ref: '#/components/schemas/Revision/properties/_id'
  723. * grant:
  724. * $ref: '#/components/schemas/Page/properties/grant'
  725. * required:
  726. * - body
  727. * - page_id
  728. * - revision_id
  729. * responses:
  730. * 200:
  731. * description: Succeeded to update page.
  732. * content:
  733. * application/json:
  734. * schema:
  735. * properties:
  736. * ok:
  737. * $ref: '#/components/schemas/V1Response/properties/ok'
  738. * page:
  739. * $ref: '#/components/schemas/Page'
  740. * revision:
  741. * $ref: '#/components/schemas/Revision'
  742. * 403:
  743. * $ref: '#/components/responses/403'
  744. * 500:
  745. * $ref: '#/components/responses/500'
  746. */
  747. /**
  748. * @api {post} /pages.update Update page
  749. * @apiName UpdatePage
  750. * @apiGroup Page
  751. *
  752. * @apiParam {String} body
  753. * @apiParam {String} page_id
  754. * @apiParam {String} revision_id
  755. * @apiParam {String} grant
  756. *
  757. * In the case of the page exists:
  758. * - If revision_id is specified => update the page,
  759. * - If revision_id is not specified => force update by the new contents.
  760. */
  761. api.update = async function(req, res) {
  762. const pageBody = req.body.body || null;
  763. const pageId = req.body.page_id || null;
  764. const revisionId = req.body.revision_id || null;
  765. const grant = req.body.grant || null;
  766. const grantUserGroupId = req.body.grantUserGroupId || null;
  767. const overwriteScopesOfDescendants = req.body.overwriteScopesOfDescendants || null;
  768. const isSlackEnabled = !!req.body.isSlackEnabled; // cast to boolean
  769. const slackChannels = req.body.slackChannels || null;
  770. const isSyncRevisionToHackmd = !!req.body.isSyncRevisionToHackmd; // cast to boolean
  771. const pageTags = req.body.pageTags || undefined;
  772. if (pageId === null || pageBody === null || revisionId === null) {
  773. return res.json(ApiResponse.error('page_id, body and revision_id are required.'));
  774. }
  775. // check page existence
  776. const isExist = await Page.count({ _id: pageId }) > 0;
  777. if (!isExist) {
  778. return res.json(ApiResponse.error(`Page('${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  779. }
  780. // check revision
  781. const Revision = crowi.model('Revision');
  782. let page = await Page.findByIdAndViewer(pageId, req.user);
  783. if (page != null && revisionId != null && !page.isUpdatable(revisionId)) {
  784. const latestRevision = await Revision.findById(page.revision).populate('author');
  785. const returnLatestRevision = {
  786. revisionId: latestRevision._id.toString(),
  787. revisionBody: xss.process(latestRevision.body),
  788. createdAt: latestRevision.createdAt,
  789. user: serializeUserSecurely(latestRevision.author),
  790. };
  791. return res.json(ApiResponse.error('Posted param "revisionId" is outdated.', 'conflict', returnLatestRevision));
  792. }
  793. const options = { isSyncRevisionToHackmd };
  794. if (grant != null) {
  795. options.grant = grant;
  796. options.grantUserGroupId = grantUserGroupId;
  797. }
  798. const previousRevision = await Revision.findById(revisionId);
  799. try {
  800. page = await Page.updatePage(page, pageBody, previousRevision.body, req.user, options);
  801. }
  802. catch (err) {
  803. logger.error('error on _api/pages.update', err);
  804. return res.json(ApiResponse.error(err));
  805. }
  806. let savedTags;
  807. if (pageTags != null) {
  808. const tagEvent = crowi.event('tag');
  809. await PageTagRelation.updatePageTags(pageId, pageTags);
  810. savedTags = await PageTagRelation.listTagNamesByPage(pageId);
  811. tagEvent.emit('update', page, savedTags);
  812. }
  813. const result = {
  814. page: serializePageSecurely(page),
  815. revision: serializeRevisionSecurely(page.revision),
  816. tags: savedTags,
  817. };
  818. res.json(ApiResponse.success(result));
  819. // update scopes for descendants
  820. if (overwriteScopesOfDescendants) {
  821. Page.applyScopesToDescendantsAsyncronously(page, req.user);
  822. }
  823. // global notification
  824. try {
  825. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_EDIT, page, req.user);
  826. }
  827. catch (err) {
  828. logger.error('Edit notification failed', err);
  829. }
  830. // user notification
  831. if (isSlackEnabled) {
  832. try {
  833. const results = await userNotificationService.fire(page, req.user, slackChannels, 'update', { previousRevision });
  834. results.forEach((result) => {
  835. if (result.status === 'rejected') {
  836. logger.error('Create user notification failed', result.reason);
  837. }
  838. });
  839. }
  840. catch (err) {
  841. logger.error('Create user notification failed', err);
  842. }
  843. }
  844. };
  845. /**
  846. * @swagger
  847. *
  848. * /pages.exist:
  849. * get:
  850. * tags: [Pages]
  851. * operationId: getPageExistence
  852. * summary: /pages.exist
  853. * description: Get page existence
  854. * parameters:
  855. * - in: query
  856. * name: pagePaths
  857. * schema:
  858. * type: string
  859. * description: Page path list in JSON Array format
  860. * example: '["/", "/user/unknown"]'
  861. * responses:
  862. * 200:
  863. * description: Succeeded to get page existence.
  864. * content:
  865. * application/json:
  866. * schema:
  867. * properties:
  868. * ok:
  869. * $ref: '#/components/schemas/V1Response/properties/ok'
  870. * pages:
  871. * type: string
  872. * description: Properties of page path and existence
  873. * example: '{"/": true, "/user/unknown": false}'
  874. * 403:
  875. * $ref: '#/components/responses/403'
  876. * 500:
  877. * $ref: '#/components/responses/500'
  878. */
  879. /**
  880. * @api {get} /pages.exist Get if page exists
  881. * @apiName GetPage
  882. * @apiGroup Page
  883. *
  884. * @apiParam {String} pages (stringified JSON)
  885. */
  886. api.exist = async function(req, res) {
  887. const pagePaths = JSON.parse(req.query.pagePaths || '[]');
  888. const pages = {};
  889. await Promise.all(pagePaths.map(async(path) => {
  890. // check page existence
  891. const isExist = await Page.count({ path }) > 0;
  892. pages[path] = isExist;
  893. return;
  894. }));
  895. const result = { pages };
  896. return res.json(ApiResponse.success(result));
  897. };
  898. /**
  899. * @swagger
  900. *
  901. * /pages.getPageTag:
  902. * get:
  903. * tags: [Pages]
  904. * operationId: getPageTag
  905. * summary: /pages.getPageTag
  906. * description: Get page tag
  907. * parameters:
  908. * - in: query
  909. * name: pageId
  910. * schema:
  911. * $ref: '#/components/schemas/Page/properties/_id'
  912. * responses:
  913. * 200:
  914. * description: Succeeded to get page tags.
  915. * content:
  916. * application/json:
  917. * schema:
  918. * properties:
  919. * ok:
  920. * $ref: '#/components/schemas/V1Response/properties/ok'
  921. * tags:
  922. * $ref: '#/components/schemas/Tags'
  923. * 403:
  924. * $ref: '#/components/responses/403'
  925. * 500:
  926. * $ref: '#/components/responses/500'
  927. */
  928. /**
  929. * @api {get} /pages.getPageTag get page tags
  930. * @apiName GetPageTag
  931. * @apiGroup Page
  932. *
  933. * @apiParam {String} pageId
  934. */
  935. api.getPageTag = async function(req, res) {
  936. const result = {};
  937. try {
  938. result.tags = await PageTagRelation.listTagNamesByPage(req.query.pageId);
  939. }
  940. catch (err) {
  941. return res.json(ApiResponse.error(err));
  942. }
  943. return res.json(ApiResponse.success(result));
  944. };
  945. /**
  946. * @swagger
  947. *
  948. * /pages.updatePost:
  949. * get:
  950. * tags: [Pages, CrowiCompatibles]
  951. * operationId: getUpdatePostPage
  952. * summary: /pages.updatePost
  953. * description: Get UpdatePost setting list
  954. * parameters:
  955. * - in: query
  956. * name: path
  957. * schema:
  958. * $ref: '#/components/schemas/Page/properties/path'
  959. * responses:
  960. * 200:
  961. * description: Succeeded to get UpdatePost setting list.
  962. * content:
  963. * application/json:
  964. * schema:
  965. * properties:
  966. * ok:
  967. * $ref: '#/components/schemas/V1Response/properties/ok'
  968. * updatePost:
  969. * $ref: '#/components/schemas/UpdatePost'
  970. * 403:
  971. * $ref: '#/components/responses/403'
  972. * 500:
  973. * $ref: '#/components/responses/500'
  974. */
  975. /**
  976. * @api {get} /pages.updatePost
  977. * @apiName Get UpdatePost setting list
  978. * @apiGroup Page
  979. *
  980. * @apiParam {String} path
  981. */
  982. api.getUpdatePost = function(req, res) {
  983. const path = req.query.path;
  984. if (!path) {
  985. return res.json(ApiResponse.error({}));
  986. }
  987. UpdatePost.findSettingsByPath(path)
  988. .then((data) => {
  989. // eslint-disable-next-line no-param-reassign
  990. data = data.map((e) => {
  991. return e.channel;
  992. });
  993. debug('Found updatePost data', data);
  994. const result = { updatePost: data };
  995. return res.json(ApiResponse.success(result));
  996. })
  997. .catch((err) => {
  998. debug('Error occured while get setting', err);
  999. return res.json(ApiResponse.error({}));
  1000. });
  1001. };
  1002. validator.remove = [
  1003. body('completely')
  1004. .custom(v => v === 'true' || v === true || v == null)
  1005. .withMessage('The body property "completely" must be "true" or true. (Omit param for false)'),
  1006. body('recursively')
  1007. .custom(v => v === 'true' || v === true || v == null)
  1008. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  1009. ];
  1010. /**
  1011. * @api {post} /pages.remove Remove page
  1012. * @apiName RemovePage
  1013. * @apiGroup Page
  1014. *
  1015. * @apiParam {String} page_id Page Id.
  1016. * @apiParam {String} revision_id
  1017. */
  1018. api.remove = async function(req, res) {
  1019. const pageId = req.body.page_id;
  1020. const previousRevision = req.body.revision_id || null;
  1021. const { recursively: isRecursively, completely: isCompletely } = req.body;
  1022. const options = {};
  1023. const page = await Page.findByIdAndViewerToEdit(pageId, req.user, true);
  1024. if (page == null) {
  1025. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1026. }
  1027. debug('Delete page', page._id, page.path);
  1028. try {
  1029. if (isCompletely) {
  1030. if (!crowi.pageService.canDeleteCompletely(page.creator, req.user)) {
  1031. return res.json(ApiResponse.error('You can not delete completely', 'user_not_admin'));
  1032. }
  1033. await crowi.pageService.deleteCompletely(page, req.user, options, isRecursively);
  1034. }
  1035. else {
  1036. // behave like not found
  1037. const notRecursivelyAndEmpty = page.isEmpty && !isRecursively;
  1038. if (notRecursivelyAndEmpty) {
  1039. return res.json(ApiResponse.error(`Page '${pageId}' is not found.`, 'notfound'));
  1040. }
  1041. if (!page.isEmpty && !page.isUpdatable(previousRevision)) {
  1042. return res.json(ApiResponse.error('Someone could update this page, so couldn\'t delete.', 'outdated'));
  1043. }
  1044. await crowi.pageService.deletePage(page, req.user, options, isRecursively);
  1045. }
  1046. }
  1047. catch (err) {
  1048. logger.error('Error occured while get setting', err);
  1049. return res.json(ApiResponse.error('Failed to delete page.', err.message));
  1050. }
  1051. debug('Page deleted', page.path);
  1052. const result = {};
  1053. result.path = page.path;
  1054. result.isRecursively = isRecursively;
  1055. result.isCompletely = isCompletely;
  1056. res.json(ApiResponse.success(result));
  1057. try {
  1058. // global notification
  1059. await globalNotificationService.fire(GlobalNotificationSetting.EVENT.PAGE_DELETE, page, req.user);
  1060. }
  1061. catch (err) {
  1062. logger.error('Delete notification failed', err);
  1063. }
  1064. };
  1065. validator.revertRemove = [
  1066. body('recursively')
  1067. .custom(v => v === 'true' || v === true || null)
  1068. .withMessage('The body property "recursively" must be "true" or true. (Omit param for false)'),
  1069. ];
  1070. /**
  1071. * @api {post} /pages.revertRemove Revert removed page
  1072. * @apiName RevertRemovePage
  1073. * @apiGroup Page
  1074. *
  1075. * @apiParam {String} page_id Page Id.
  1076. */
  1077. api.revertRemove = async function(req, res, options) {
  1078. const pageId = req.body.page_id;
  1079. // get recursively flag
  1080. const isRecursively = req.body.recursively;
  1081. let page;
  1082. try {
  1083. page = await Page.findByIdAndViewer(pageId, req.user);
  1084. if (page == null) {
  1085. throw new Error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden');
  1086. }
  1087. page = await crowi.pageService.revertDeletedPage(page, req.user, {}, isRecursively);
  1088. }
  1089. catch (err) {
  1090. logger.error('Error occured while get setting', err);
  1091. return res.json(ApiResponse.error('Failed to revert deleted page.'));
  1092. }
  1093. const result = {};
  1094. result.page = page; // TODO consider to use serializePageSecurely method -- 2018.08.06 Yuki Takei
  1095. return res.json(ApiResponse.success(result));
  1096. };
  1097. /**
  1098. * @swagger
  1099. *
  1100. * /pages.duplicate:
  1101. * post:
  1102. * tags: [Pages]
  1103. * operationId: duplicatePage
  1104. * summary: /pages.duplicate
  1105. * description: Duplicate page
  1106. * requestBody:
  1107. * content:
  1108. * application/json:
  1109. * schema:
  1110. * properties:
  1111. * page_id:
  1112. * $ref: '#/components/schemas/Page/properties/_id'
  1113. * new_path:
  1114. * $ref: '#/components/schemas/Page/properties/path'
  1115. * required:
  1116. * - page_id
  1117. * responses:
  1118. * 200:
  1119. * description: Succeeded to duplicate page.
  1120. * content:
  1121. * application/json:
  1122. * schema:
  1123. * properties:
  1124. * ok:
  1125. * $ref: '#/components/schemas/V1Response/properties/ok'
  1126. * page:
  1127. * $ref: '#/components/schemas/Page'
  1128. * tags:
  1129. * $ref: '#/components/schemas/Tags'
  1130. * 403:
  1131. * $ref: '#/components/responses/403'
  1132. * 500:
  1133. * $ref: '#/components/responses/500'
  1134. */
  1135. /**
  1136. * @api {post} /pages.duplicate Duplicate page
  1137. * @apiName DuplicatePage
  1138. * @apiGroup Page
  1139. *
  1140. * @apiParam {String} page_id Page Id.
  1141. * @apiParam {String} new_path New path name.
  1142. */
  1143. api.duplicate = async function(req, res) {
  1144. const pageId = req.body.page_id;
  1145. let newPagePath = pathUtils.normalizePath(req.body.new_path);
  1146. const page = await Page.findByIdAndViewer(pageId, req.user);
  1147. if (page == null) {
  1148. return res.json(ApiResponse.error(`Page '${pageId}' is not found or forbidden`, 'notfound_or_forbidden'));
  1149. }
  1150. // check whether path starts slash
  1151. newPagePath = pathUtils.addHeadingSlash(newPagePath);
  1152. await page.populateDataToShowRevision();
  1153. const originTags = await page.findRelatedTagsById();
  1154. req.body.path = newPagePath;
  1155. req.body.body = page.revision.body;
  1156. req.body.grant = page.grant;
  1157. req.body.grantedUsers = page.grantedUsers;
  1158. req.body.grantUserGroupId = page.grantedGroup;
  1159. req.body.pageTags = originTags;
  1160. return api.create(req, res);
  1161. };
  1162. /**
  1163. * @api {post} /pages.unlink Remove the redirecting page
  1164. * @apiName UnlinkPage
  1165. * @apiGroup Page
  1166. *
  1167. * @apiParam {String} page_id Page Id.
  1168. * @apiParam {String} revision_id
  1169. */
  1170. api.unlink = async function(req, res) {
  1171. const path = req.body.path;
  1172. try {
  1173. await PageRedirect.removePageRedirectByToPath(path);
  1174. logger.debug('Redirect Page deleted', path);
  1175. }
  1176. catch (err) {
  1177. logger.error('Error occured while get setting', err);
  1178. return res.json(ApiResponse.error('Failed to delete redirect page.'));
  1179. }
  1180. const result = { path };
  1181. return res.json(ApiResponse.success(result));
  1182. };
  1183. return actions;
  1184. };