page.js 41 KB

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