page.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import mongoose, {
  3. Schema, Model, Document, AnyObject,
  4. } from 'mongoose';
  5. import mongoosePaginate from 'mongoose-paginate-v2';
  6. import uniqueValidator from 'mongoose-unique-validator';
  7. import nodePath from 'path';
  8. import { getOrCreateModel, pagePathUtils } from '@growi/core';
  9. import loggerFactory from '../../utils/logger';
  10. import Crowi from '../crowi';
  11. import { IPage } from '../../interfaces/page';
  12. import { getPageSchema, PageQueryBuilder } from './obsolete-page';
  13. import { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  14. const { isTopPage, collectAncestorPaths } = pagePathUtils;
  15. const logger = loggerFactory('growi:models:page');
  16. /*
  17. * define schema
  18. */
  19. const GRANT_PUBLIC = 1;
  20. const GRANT_RESTRICTED = 2;
  21. const GRANT_SPECIFIED = 3; // DEPRECATED
  22. const GRANT_OWNER = 4;
  23. const GRANT_USER_GROUP = 5;
  24. const PAGE_GRANT_ERROR = 1;
  25. const STATUS_PUBLISHED = 'published';
  26. const STATUS_DELETED = 'deleted';
  27. export interface PageDocument extends IPage, Document {}
  28. type TargetAndAncestorsResult = {
  29. targetAndAncestors: PageDocument[]
  30. rootPage: PageDocument
  31. }
  32. export type CreateMethod = (path: string, body: string, user, options) => Promise<PageDocument & { _id: any }>
  33. export interface PageModel extends Model<PageDocument> {
  34. [x: string]: any; // for obsolete methods
  35. createEmptyPagesByPaths(paths: string[], publicOnly?: boolean): Promise<void>
  36. getParentAndFillAncestors(path: string): Promise<PageDocument & { _id: any }>
  37. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument[]>
  38. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  39. findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups?): Promise<PageDocument[]>
  40. findAncestorsChildrenByPathAndViewer(path: string, user, userGroups?): Promise<Record<string, PageDocument[]>>
  41. PageQueryBuilder: typeof PageQueryBuilder
  42. GRANT_PUBLIC
  43. GRANT_RESTRICTED
  44. GRANT_SPECIFIED
  45. GRANT_OWNER
  46. GRANT_USER_GROUP
  47. PAGE_GRANT_ERROR
  48. STATUS_PUBLISHED
  49. STATUS_DELETED
  50. }
  51. type IObjectId = mongoose.Types.ObjectId;
  52. const ObjectId = mongoose.Schema.Types.ObjectId;
  53. const schema = new Schema<PageDocument, PageModel>({
  54. parent: {
  55. type: ObjectId, ref: 'Page', index: true, default: null,
  56. },
  57. descendantCount: { type: Number, default: 0 },
  58. isEmpty: { type: Boolean, default: false },
  59. path: {
  60. type: String, required: true, index: true,
  61. },
  62. revision: { type: ObjectId, ref: 'Revision' },
  63. redirectTo: { type: String, index: true },
  64. status: { type: String, default: STATUS_PUBLISHED, index: true },
  65. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  66. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  67. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  68. creator: { type: ObjectId, ref: 'User', index: true },
  69. lastUpdateUser: { type: ObjectId, ref: 'User' },
  70. liker: [{ type: ObjectId, ref: 'User' }],
  71. seenUsers: [{ type: ObjectId, ref: 'User' }],
  72. commentCount: { type: Number, default: 0 },
  73. slackChannels: { type: String },
  74. pageIdOnHackmd: { type: String },
  75. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  76. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  77. createdAt: { type: Date, default: new Date() },
  78. updatedAt: { type: Date, default: new Date() },
  79. deleteUser: { type: ObjectId, ref: 'User' },
  80. deletedAt: { type: Date },
  81. }, {
  82. toJSON: { getters: true },
  83. toObject: { getters: true },
  84. });
  85. // apply plugins
  86. schema.plugin(mongoosePaginate);
  87. schema.plugin(uniqueValidator);
  88. const hasSlash = (str: string): boolean => {
  89. return str.includes('/');
  90. };
  91. /*
  92. * Generate RegExp instance for one level lower path
  93. */
  94. const generateChildrenRegExp = (path: string): RegExp => {
  95. // https://regex101.com/r/laJGzj/1
  96. // ex. /any_level1
  97. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  98. // https://regex101.com/r/mrDJrx/1
  99. // ex. /parent/any_child OR /any_level1
  100. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  101. };
  102. /*
  103. * Create empty pages if the page in paths didn't exist
  104. */
  105. schema.statics.createEmptyPagesByPaths = async function(paths: string[], publicOnly = false): Promise<void> {
  106. // find existing parents
  107. const builder = new PageQueryBuilder(this.find(publicOnly ? { grant: GRANT_PUBLIC } : {}, { _id: 0, path: 1 }), true);
  108. const existingPages = await builder
  109. .addConditionToListByPathsArray(paths)
  110. .query
  111. .lean()
  112. .exec();
  113. const existingPagePaths = existingPages.map(page => page.path);
  114. // paths to create empty pages
  115. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  116. // insertMany empty pages
  117. try {
  118. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  119. }
  120. catch (err) {
  121. logger.error('Failed to insert empty pages.', err);
  122. throw err;
  123. }
  124. };
  125. schema.statics.createEmptyPage = async function(
  126. path: string, parent: any, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
  127. ): Promise<PageDocument & { _id: any }> {
  128. if (parent == null) {
  129. throw Error('parent must not be null');
  130. }
  131. const Page = this;
  132. const page = new Page();
  133. page.path = path;
  134. page.isEmpty = true;
  135. page.parent = parent;
  136. return page.save();
  137. };
  138. /**
  139. * Replace an existing page with an empty page.
  140. * It updates the children's parent to the new empty page's _id.
  141. * @param exPage a page document to be replaced
  142. * @returns Promise<void>
  143. */
  144. schema.statics.replaceTargetWithEmptyPage = async function(exPage): Promise<void> {
  145. // find parent
  146. const parent = await this.findOne({ _id: exPage.parent });
  147. if (parent == null) {
  148. throw Error('parent to update does not exist. Prepare parent first.');
  149. }
  150. // create empty page at path
  151. const newTarget = await this.createEmptyPage(exPage.path, parent);
  152. // find children by ex-page _id
  153. const children = await this.find({ parent: exPage._id });
  154. // bulkWrite
  155. const operationForNewTarget = {
  156. updateOne: {
  157. filter: { _id: newTarget._id },
  158. update: {
  159. parent: parent._id,
  160. },
  161. },
  162. };
  163. const operationsForChildren = {
  164. updateMany: {
  165. filter: {
  166. _id: { $in: children.map(d => d._id) },
  167. },
  168. update: {
  169. parent: newTarget._id,
  170. },
  171. },
  172. };
  173. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  174. };
  175. /**
  176. * Find parent or create parent if not exists.
  177. * It also updates parent of ancestors
  178. * @param path string
  179. * @returns Promise<PageDocument>
  180. */
  181. schema.statics.getParentAndFillAncestors = async function(path: string): Promise<PageDocument> {
  182. const parentPath = nodePath.dirname(path);
  183. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  184. if (parent != null) {
  185. return parent;
  186. }
  187. /*
  188. * Fill parents if parent is null
  189. */
  190. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  191. // just create ancestors with empty pages
  192. await this.createEmptyPagesByPaths(ancestorPaths);
  193. // find ancestors
  194. const builder = new PageQueryBuilder(this.find(), true);
  195. const ancestors = await builder
  196. .addConditionToListByPathsArray(ancestorPaths)
  197. .addConditionToSortPagesByDescPath()
  198. .query
  199. .exec();
  200. const ancestorsMap = new Map(); // Map<path, page>
  201. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  202. // bulkWrite to update ancestors
  203. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  204. const operations = nonRootAncestors.map((page) => {
  205. const { path } = page;
  206. const parentPath = nodePath.dirname(path);
  207. return {
  208. updateOne: {
  209. filter: {
  210. path,
  211. },
  212. update: {
  213. parent: ancestorsMap.get(parentPath),
  214. },
  215. },
  216. };
  217. });
  218. await this.bulkWrite(operations);
  219. const createdParent = ancestorsMap.get(parentPath);
  220. return createdParent;
  221. };
  222. // Utility function to add viewer condition to PageQueryBuilder instance
  223. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  224. let relatedUserGroups = userGroups;
  225. if (user != null && relatedUserGroups == null) {
  226. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  227. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  228. }
  229. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, false);
  230. };
  231. /*
  232. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  233. */
  234. schema.statics.findByPathAndViewer = async function(
  235. path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false,
  236. ): Promise<PageDocument | PageDocument[] | null> {
  237. if (path == null) {
  238. throw new Error('path is required.');
  239. }
  240. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  241. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  242. await addViewerCondition(queryBuilder, user, userGroups);
  243. return queryBuilder.query.exec();
  244. };
  245. /*
  246. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  247. * The result will include the target as well
  248. */
  249. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  250. let path;
  251. if (!hasSlash(pathOrId)) {
  252. const _id = pathOrId;
  253. const page = await this.findOne({ _id });
  254. if (page == null) throw new Error('Page not found.');
  255. path = page.path;
  256. }
  257. else {
  258. path = pathOrId;
  259. }
  260. const ancestorPaths = collectAncestorPaths(path);
  261. ancestorPaths.push(path); // include target
  262. // Do not populate
  263. const queryBuilder = new PageQueryBuilder(this.find(), true);
  264. await addViewerCondition(queryBuilder, user, userGroups);
  265. const _targetAndAncestors: PageDocument[] = await queryBuilder
  266. .addConditionAsMigrated()
  267. .addConditionToListByPathsArray(ancestorPaths)
  268. .addConditionToMinimizeDataForRendering()
  269. .addConditionToSortPagesByDescPath()
  270. .query
  271. .lean()
  272. .exec();
  273. // no same path pages
  274. const ancestorsMap = new Map<string, PageDocument>();
  275. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  276. const targetAndAncestors = Array.from(ancestorsMap.values());
  277. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  278. return { targetAndAncestors, rootPage };
  279. };
  280. /*
  281. * Find all children by parent's path or id. Using id should be prioritized
  282. */
  283. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  284. let queryBuilder: PageQueryBuilder;
  285. if (hasSlash(parentPathOrId)) {
  286. const path = parentPathOrId;
  287. const regexp = generateChildrenRegExp(path);
  288. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  289. }
  290. else {
  291. const parentId = parentPathOrId;
  292. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId } as any), true); // TODO: improve type
  293. }
  294. await addViewerCondition(queryBuilder, user, userGroups);
  295. return queryBuilder
  296. .addConditionToSortPagesByAscPath()
  297. .query
  298. .lean()
  299. .exec();
  300. };
  301. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  302. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  303. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  304. // get pages at once
  305. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  306. await addViewerCondition(queryBuilder, user, userGroups);
  307. const _pages = await queryBuilder
  308. .addConditionAsMigrated()
  309. .addConditionToMinimizeDataForRendering()
  310. .addConditionToSortPagesByAscPath()
  311. .query
  312. .lean()
  313. .exec();
  314. // mark target
  315. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  316. if (page.path === path) {
  317. page.isTarget = true;
  318. }
  319. return page;
  320. });
  321. /*
  322. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  323. */
  324. const pathToChildren: Record<string, PageDocument[]> = {};
  325. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  326. sortedPaths.every((path) => {
  327. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  328. if (children.length === 0) {
  329. return false; // break when children do not exist
  330. }
  331. pathToChildren[path] = children;
  332. return true;
  333. });
  334. return pathToChildren;
  335. };
  336. /*
  337. * Utils from obsolete-page.js
  338. */
  339. async function pushRevision(pageData, newRevision, user) {
  340. await newRevision.save();
  341. pageData.revision = newRevision;
  342. pageData.lastUpdateUser = user;
  343. pageData.updatedAt = Date.now();
  344. return pageData.save();
  345. }
  346. /**
  347. * return aggregate condition to get following pages
  348. * - page that has the same path as the provided path
  349. * - pages that are descendants of the above page
  350. * pages without parent will be ignored
  351. */
  352. schema.statics.getAggrConditionForPageWithProvidedPathAndDescendants = function(path:string) {
  353. let match;
  354. if (isTopPage(path)) {
  355. match = {
  356. // https://regex101.com/r/Kip2rV/1
  357. $match: { $or: [{ path: { $regex: '^/.*' }, parent: { $ne: null } }, { path: '/' }] },
  358. };
  359. }
  360. else {
  361. match = {
  362. // https://regex101.com/r/mJvGrG/1
  363. $match: { path: { $regex: `^${path}(/.*|$)` }, parent: { $ne: null } },
  364. };
  365. }
  366. return [
  367. match,
  368. {
  369. $project: {
  370. path: 1,
  371. parent: 1,
  372. field_length: { $strLenCP: '$path' },
  373. },
  374. },
  375. { $sort: { field_length: -1 } },
  376. { $project: { field_length: 0 } },
  377. ];
  378. };
  379. /**
  380. * add/subtract descendantCount of pages with provided paths by increment.
  381. * increment can be negative number
  382. */
  383. schema.statics.incrementDescendantCountOfPaths = async function(paths:string[], increment: number):Promise<void> {
  384. const pages = await this.aggregate([{ $match: { path: { $in: paths } } }]);
  385. const operations = pages.map((page) => {
  386. return {
  387. updateOne: {
  388. filter: { path: page.path },
  389. update: { descendantCount: page.descendantCount + increment },
  390. },
  391. };
  392. });
  393. await this.bulkWrite(operations);
  394. };
  395. // update descendantCount of a page with provided id
  396. schema.statics.recountDescendantCountOfSelfAndDescendants = async function(id:mongoose.Types.ObjectId):Promise<void> {
  397. const res = await this.aggregate(
  398. [
  399. {
  400. $match: {
  401. parent: id,
  402. },
  403. },
  404. {
  405. $project: {
  406. path: 1,
  407. parent: 1,
  408. descendantCount: 1,
  409. },
  410. },
  411. {
  412. $group: {
  413. _id: '$parent',
  414. sumOfDescendantCount: {
  415. $sum: '$descendantCount',
  416. },
  417. sumOfDocsCount: {
  418. $sum: 1,
  419. },
  420. },
  421. },
  422. {
  423. $set: {
  424. descendantCount: {
  425. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  426. },
  427. },
  428. },
  429. ],
  430. );
  431. const query = { descendantCount: res.length === 0 ? 0 : res[0].descendantCount };
  432. await this.findByIdAndUpdate(id, query);
  433. };
  434. export type PageCreateOptions = {
  435. format?: string
  436. grantUserGroupId?: ObjectIdLike
  437. grant?: number
  438. }
  439. /*
  440. * Merge obsolete page model methods and define new methods which depend on crowi instance
  441. */
  442. export default (crowi: Crowi): any => {
  443. let pageEvent;
  444. if (crowi != null) {
  445. pageEvent = crowi.event('page');
  446. }
  447. schema.statics.create = async function(path: string, body: string, user, options: PageCreateOptions = {}) {
  448. if (crowi.pageGrantService == null || crowi.configManager == null) {
  449. throw Error('Crowi is not setup');
  450. }
  451. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  452. // v4 compatible process
  453. if (!isV5Compatible) {
  454. return this.createV4(path, body, user, options);
  455. }
  456. const Page = this;
  457. const Revision = crowi.model('Revision');
  458. const {
  459. format = 'markdown', grantUserGroupId,
  460. } = options;
  461. let grant = options.grant;
  462. // sanitize path
  463. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  464. // throw if exists
  465. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  466. if (isExist) {
  467. throw new Error('Cannot create new page to existed path');
  468. }
  469. // force public
  470. if (isTopPage(path)) {
  471. grant = GRANT_PUBLIC;
  472. }
  473. // find an existing empty page
  474. const emptyPage = await Page.findOne({ path, isEmpty: true });
  475. /*
  476. * UserGroup & Owner validation
  477. */
  478. if (grant !== GRANT_RESTRICTED) {
  479. let isGrantNormalized = false;
  480. try {
  481. // It must check descendants as well if emptyTarget is not null
  482. const shouldCheckDescendants = emptyPage != null;
  483. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  484. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  485. }
  486. catch (err) {
  487. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  488. throw err;
  489. }
  490. if (!isGrantNormalized) {
  491. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  492. }
  493. }
  494. /*
  495. * update empty page if exists, if not, create a new page
  496. */
  497. let page;
  498. if (emptyPage != null) {
  499. page = emptyPage;
  500. page.isEmpty = false;
  501. }
  502. else {
  503. page = new Page();
  504. }
  505. let parentId: IObjectId | string | null = null;
  506. const parent = await Page.getParentAndFillAncestors(path);
  507. if (!isTopPage(path)) {
  508. parentId = parent._id;
  509. }
  510. page.path = path;
  511. page.creator = user;
  512. page.lastUpdateUser = user;
  513. page.status = STATUS_PUBLISHED;
  514. // set parent to null when GRANT_RESTRICTED
  515. if (grant === GRANT_RESTRICTED) {
  516. page.parent = null;
  517. }
  518. else {
  519. page.parent = parentId;
  520. }
  521. page.applyScope(user, grant, grantUserGroupId);
  522. let savedPage = await page.save();
  523. /*
  524. * After save
  525. */
  526. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  527. const revision = await pushRevision(savedPage, newRevision, user);
  528. savedPage = await this.findByPath(revision.path);
  529. await savedPage.populateDataToShowRevision();
  530. pageEvent.emit('create', savedPage, user);
  531. return savedPage;
  532. };
  533. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  534. if (crowi.configManager == null || crowi.pageGrantService == null) {
  535. throw Error('Crowi is not set up');
  536. }
  537. const isPageMigrated = pageData.parent != null;
  538. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  539. if (!isV5Compatible || !isPageMigrated) {
  540. // v4 compatible process
  541. return this.updatePageV4(pageData, body, previousBody, user, options);
  542. }
  543. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  544. const grant = options.grant || pageData.grant; // use the previous data if absence
  545. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  546. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  547. const grantedUserIds = pageData.grantedUserIds || [user._id];
  548. const newPageData = pageData;
  549. if (grant === GRANT_RESTRICTED) {
  550. newPageData.parent = null;
  551. }
  552. else {
  553. /*
  554. * UserGroup & Owner validation
  555. */
  556. let isGrantNormalized = false;
  557. try {
  558. const shouldCheckDescendants = true;
  559. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(pageData.path, grant, grantedUserIds, grantUserGroupId, shouldCheckDescendants);
  560. }
  561. catch (err) {
  562. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  563. throw err;
  564. }
  565. if (!isGrantNormalized) {
  566. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  567. }
  568. }
  569. newPageData.applyScope(user, grant, grantUserGroupId);
  570. // update existing page
  571. let savedPage = await newPageData.save();
  572. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  573. const revision = await pushRevision(savedPage, newRevision, user);
  574. savedPage = await this.findByPath(revision.path);
  575. await savedPage.populateDataToShowRevision();
  576. if (isSyncRevisionToHackmd) {
  577. savedPage = await this.syncRevisionToHackmd(savedPage);
  578. }
  579. pageEvent.emit('update', savedPage, user);
  580. return savedPage;
  581. };
  582. // add old page schema methods
  583. const pageSchema = getPageSchema(crowi);
  584. schema.methods = { ...pageSchema.methods, ...schema.methods };
  585. schema.statics = { ...pageSchema.statics, ...schema.statics };
  586. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  587. };
  588. /*
  589. * Aggregation utilities
  590. */
  591. // TODO: use the original type when upgraded https://github.com/Automattic/mongoose/blob/master/index.d.ts#L3090
  592. type PipelineStageMatch = {
  593. $match: AnyObject
  594. };
  595. export const generateGrantCondition = async(
  596. user, _userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  597. ): Promise<PipelineStageMatch> => {
  598. let userGroups = _userGroups;
  599. if (user != null && userGroups == null) {
  600. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  601. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  602. }
  603. const grantConditions: AnyObject[] = [
  604. { grant: null },
  605. { grant: GRANT_PUBLIC },
  606. ];
  607. if (showAnyoneKnowsLink) {
  608. grantConditions.push({ grant: GRANT_RESTRICTED });
  609. }
  610. if (showPagesRestrictedByOwner) {
  611. grantConditions.push(
  612. { grant: GRANT_SPECIFIED },
  613. { grant: GRANT_OWNER },
  614. );
  615. }
  616. else if (user != null) {
  617. grantConditions.push(
  618. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  619. { grant: GRANT_OWNER, grantedUsers: user._id },
  620. );
  621. }
  622. if (showPagesRestrictedByGroup) {
  623. grantConditions.push(
  624. { grant: GRANT_USER_GROUP },
  625. );
  626. }
  627. else if (userGroups != null && userGroups.length > 0) {
  628. grantConditions.push(
  629. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  630. );
  631. }
  632. return {
  633. $match: {
  634. $or: grantConditions,
  635. },
  636. };
  637. };