page.ts 21 KB

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