page.ts 25 KB

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