page.js 42 KB

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