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 = 0, // 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?, deleteExPageIfEmpty = false): 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. const isExPageEmpty = exPage.isEmpty;
  177. if (deleteExPageIfEmpty && isExPageEmpty) {
  178. await this.deleteOne({ _id: exPage._id });
  179. logger.warn('Deleted empty page since it was replaced with another page.');
  180. }
  181. };
  182. /**
  183. * Find parent or create parent if not exists.
  184. * It also updates parent of ancestors
  185. * @param path string
  186. * @returns Promise<PageDocument>
  187. */
  188. schema.statics.getParentAndFillAncestors = async function(path: string): Promise<PageDocument> {
  189. const parentPath = nodePath.dirname(path);
  190. const parent = await this.findOne({ path: parentPath }); // find the oldest parent which must always be the true parent
  191. if (parent != null) {
  192. return parent;
  193. }
  194. /*
  195. * Fill parents if parent is null
  196. */
  197. const ancestorPaths = collectAncestorPaths(path, [path]); // paths of parents need to be created
  198. // just create ancestors with empty pages
  199. await this.createEmptyPagesByPaths(ancestorPaths);
  200. // find ancestors
  201. const builder = new PageQueryBuilder(this.find(), true);
  202. const ancestors = await builder
  203. .addConditionToListByPathsArray(ancestorPaths)
  204. .addConditionToSortPagesByDescPath()
  205. .query
  206. .exec();
  207. const ancestorsMap = new Map(); // Map<path, page>
  208. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  209. // bulkWrite to update ancestors
  210. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  211. const operations = nonRootAncestors.map((page) => {
  212. const { path } = page;
  213. const parentPath = nodePath.dirname(path);
  214. return {
  215. updateOne: {
  216. filter: {
  217. path,
  218. },
  219. update: {
  220. parent: ancestorsMap.get(parentPath),
  221. },
  222. },
  223. };
  224. });
  225. await this.bulkWrite(operations);
  226. const createdParent = ancestorsMap.get(parentPath);
  227. return createdParent;
  228. };
  229. // Utility function to add viewer condition to PageQueryBuilder instance
  230. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  231. let relatedUserGroups = userGroups;
  232. if (user != null && relatedUserGroups == null) {
  233. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  234. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  235. }
  236. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, false);
  237. };
  238. /*
  239. * Find pages by ID and viewer.
  240. */
  241. schema.statics.findByIdsAndViewer = async function(pageIds: string[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]> {
  242. const baseQuery = this.find({ _id: { $in: pageIds } });
  243. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  244. await addViewerCondition(queryBuilder, user, userGroups);
  245. return queryBuilder.query.exec();
  246. };
  247. /*
  248. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  249. */
  250. schema.statics.findByPathAndViewer = async function(
  251. path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false,
  252. ): Promise<PageDocument | PageDocument[] | null> {
  253. if (path == null) {
  254. throw new Error('path is required.');
  255. }
  256. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  257. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  258. await addViewerCondition(queryBuilder, user, userGroups);
  259. return queryBuilder.query.exec();
  260. };
  261. /*
  262. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  263. * The result will include the target as well
  264. */
  265. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  266. let path;
  267. if (!hasSlash(pathOrId)) {
  268. const _id = pathOrId;
  269. const page = await this.findOne({ _id });
  270. if (page == null) throw new Error('Page not found.');
  271. path = page.path;
  272. }
  273. else {
  274. path = pathOrId;
  275. }
  276. const ancestorPaths = collectAncestorPaths(path);
  277. ancestorPaths.push(path); // include target
  278. // Do not populate
  279. const queryBuilder = new PageQueryBuilder(this.find(), true);
  280. await addViewerCondition(queryBuilder, user, userGroups);
  281. const _targetAndAncestors: PageDocument[] = await queryBuilder
  282. .addConditionAsMigrated()
  283. .addConditionToListByPathsArray(ancestorPaths)
  284. .addConditionToMinimizeDataForRendering()
  285. .addConditionToSortPagesByDescPath()
  286. .query
  287. .lean()
  288. .exec();
  289. // no same path pages
  290. const ancestorsMap = new Map<string, PageDocument>();
  291. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  292. const targetAndAncestors = Array.from(ancestorsMap.values());
  293. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  294. return { targetAndAncestors, rootPage };
  295. };
  296. /*
  297. * Find all children by parent's path or id. Using id should be prioritized
  298. */
  299. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  300. let queryBuilder: PageQueryBuilder;
  301. if (hasSlash(parentPathOrId)) {
  302. const path = parentPathOrId;
  303. const regexp = generateChildrenRegExp(path);
  304. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  305. }
  306. else {
  307. const parentId = parentPathOrId;
  308. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId } as any), true); // TODO: improve type
  309. }
  310. await addViewerCondition(queryBuilder, user, userGroups);
  311. return queryBuilder
  312. .addConditionToSortPagesByAscPath()
  313. .query
  314. .lean()
  315. .exec();
  316. };
  317. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  318. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  319. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  320. // get pages at once
  321. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  322. await addViewerCondition(queryBuilder, user, userGroups);
  323. const _pages = await queryBuilder
  324. .addConditionAsMigrated()
  325. .addConditionToMinimizeDataForRendering()
  326. .addConditionToSortPagesByAscPath()
  327. .query
  328. .lean()
  329. .exec();
  330. // mark target
  331. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  332. if (page.path === path) {
  333. page.isTarget = true;
  334. }
  335. return page;
  336. });
  337. /*
  338. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  339. */
  340. const pathToChildren: Record<string, PageDocument[]> = {};
  341. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  342. sortedPaths.every((path) => {
  343. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  344. if (children.length === 0) {
  345. return false; // break when children do not exist
  346. }
  347. pathToChildren[path] = children;
  348. return true;
  349. });
  350. return pathToChildren;
  351. };
  352. /*
  353. * Utils from obsolete-page.js
  354. */
  355. async function pushRevision(pageData, newRevision, user) {
  356. await newRevision.save();
  357. pageData.revision = newRevision;
  358. pageData.lastUpdateUser = user;
  359. pageData.updatedAt = Date.now();
  360. return pageData.save();
  361. }
  362. /**
  363. * add/subtract descendantCount of pages with provided paths by increment.
  364. * increment can be negative number
  365. */
  366. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  367. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  368. };
  369. /**
  370. * recount descendantCount of a page with the provided id and return it
  371. */
  372. schema.statics.recountDescendantCount = async function(id: ObjectIdLike):Promise<number> {
  373. const res = await this.aggregate(
  374. [
  375. {
  376. $match: {
  377. parent: id,
  378. },
  379. },
  380. {
  381. $project: {
  382. parent: 1,
  383. isEmpty: 1,
  384. descendantCount: 1,
  385. },
  386. },
  387. {
  388. $group: {
  389. _id: '$parent',
  390. sumOfDescendantCount: {
  391. $sum: '$descendantCount',
  392. },
  393. sumOfDocsCount: {
  394. $sum: {
  395. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  396. },
  397. },
  398. },
  399. },
  400. {
  401. $set: {
  402. descendantCount: {
  403. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  404. },
  405. },
  406. },
  407. ],
  408. );
  409. return res.length === 0 ? 0 : res[0].descendantCount;
  410. };
  411. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  412. const self = this;
  413. const target = await this.findById(pageId);
  414. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  415. const parent = await self.findOne({ _id: target.parent });
  416. if (parent == null) {
  417. return ancestors;
  418. }
  419. return findAncestorsRecursively(parent, [...ancestors, parent]);
  420. }
  421. return findAncestorsRecursively(target);
  422. };
  423. // TODO: write test code
  424. /**
  425. * Recursively removes empty pages at leaf position.
  426. * @param pageId ObjectIdLike
  427. * @returns Promise<void>
  428. */
  429. schema.statics.removeLeafEmptyPagesById = async function(pageId: ObjectIdLike): Promise<void> {
  430. const self = this;
  431. const initialLeafPage = await this.findById(pageId);
  432. if (initialLeafPage == null) {
  433. return;
  434. }
  435. if (!initialLeafPage.isEmpty) {
  436. return;
  437. }
  438. async function generatePageIdsToRemove(page, pageIds: ObjectIdLike[]): Promise<ObjectIdLike[]> {
  439. const nextPage = await self.findById(page.parent);
  440. if (nextPage == null) {
  441. return pageIds;
  442. }
  443. // delete leaf empty pages
  444. const isNextPageEmpty = nextPage.isEmpty;
  445. if (!isNextPageEmpty) {
  446. return pageIds;
  447. }
  448. const isSiblingsExist = await self.exists({ parent: nextPage.parent, _id: { $ne: nextPage._id } });
  449. if (isSiblingsExist) {
  450. return pageIds;
  451. }
  452. return generatePageIdsToRemove(nextPage, [...pageIds, nextPage._id]);
  453. }
  454. const initialPageIdsToRemove = [initialLeafPage._id];
  455. const pageIdsToRemove = await generatePageIdsToRemove(initialLeafPage, initialPageIdsToRemove);
  456. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  457. };
  458. schema.statics.findByPageIdsToEdit = async function(ids, user, shouldIncludeEmpty = false) {
  459. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }), shouldIncludeEmpty);
  460. await this.addConditionToFilteringByViewerToEdit(builder, user);
  461. const pages = await builder.query.lean().exec();
  462. return pages;
  463. };
  464. schema.statics.normalizeDescendantCountById = async function(pageId) {
  465. const children = await this.find({ parent: pageId });
  466. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  467. const sumChildPages = children.filter(p => !p.isEmpty).length;
  468. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  469. };
  470. export type PageCreateOptions = {
  471. format?: string
  472. grantUserGroupId?: ObjectIdLike
  473. grant?: number
  474. }
  475. /*
  476. * Merge obsolete page model methods and define new methods which depend on crowi instance
  477. */
  478. export default (crowi: Crowi): any => {
  479. let pageEvent;
  480. if (crowi != null) {
  481. pageEvent = crowi.event('page');
  482. }
  483. schema.statics.create = async function(path: string, body: string, user, options: PageCreateOptions = {}) {
  484. if (crowi.pageGrantService == null || crowi.configManager == null || crowi.pageService == null) {
  485. throw Error('Crowi is not setup');
  486. }
  487. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  488. // v4 compatible process
  489. if (!isV5Compatible) {
  490. return this.createV4(path, body, user, options);
  491. }
  492. const Page = this;
  493. const Revision = crowi.model('Revision');
  494. const {
  495. format = 'markdown', grantUserGroupId,
  496. } = options;
  497. let grant = options.grant;
  498. // sanitize path
  499. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  500. // throw if exists
  501. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  502. if (isExist) {
  503. throw new Error('Cannot create new page to existed path');
  504. }
  505. // force public
  506. if (isTopPage(path)) {
  507. grant = GRANT_PUBLIC;
  508. }
  509. // find an existing empty page
  510. const emptyPage = await Page.findOne({ path, isEmpty: true });
  511. /*
  512. * UserGroup & Owner validation
  513. */
  514. if (grant !== GRANT_RESTRICTED) {
  515. let isGrantNormalized = false;
  516. try {
  517. // It must check descendants as well if emptyTarget is not null
  518. const shouldCheckDescendants = emptyPage != null;
  519. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  520. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  521. }
  522. catch (err) {
  523. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  524. throw err;
  525. }
  526. if (!isGrantNormalized) {
  527. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  528. }
  529. }
  530. /*
  531. * update empty page if exists, if not, create a new page
  532. */
  533. let page;
  534. if (emptyPage != null) {
  535. page = emptyPage;
  536. const descendantCount = await this.recountDescendantCount(page._id);
  537. page.descendantCount = descendantCount;
  538. page.isEmpty = false;
  539. }
  540. else {
  541. page = new Page();
  542. }
  543. let parentId: IObjectId | string | null = null;
  544. const parent = await Page.getParentAndFillAncestors(path);
  545. if (!isTopPage(path)) {
  546. parentId = parent._id;
  547. }
  548. page.path = path;
  549. page.creator = user;
  550. page.lastUpdateUser = user;
  551. page.status = STATUS_PUBLISHED;
  552. // set parent to null when GRANT_RESTRICTED
  553. if (grant === GRANT_RESTRICTED) {
  554. page.parent = null;
  555. }
  556. else {
  557. page.parent = parentId;
  558. }
  559. page.applyScope(user, grant, grantUserGroupId);
  560. let savedPage = await page.save();
  561. await crowi.pageService.updateDescendantCountOfAncestors(page._id, 1, false);
  562. /*
  563. * After save
  564. */
  565. // Delete PageRedirect if exists
  566. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  567. try {
  568. await PageRedirect.deleteOne({ from: path });
  569. logger.warn(`Deleted page redirect after creating a new page at path "${path}".`);
  570. }
  571. catch (err) {
  572. // no throw
  573. logger.error('Failed to delete PageRedirect');
  574. }
  575. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  576. savedPage = await pushRevision(savedPage, newRevision, user);
  577. await savedPage.populateDataToShowRevision();
  578. pageEvent.emit('create', savedPage, user);
  579. return savedPage;
  580. };
  581. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  582. if (crowi.configManager == null || crowi.pageGrantService == null) {
  583. throw Error('Crowi is not set up');
  584. }
  585. const isPageMigrated = pageData.parent != null;
  586. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  587. if (!isV5Compatible || !isPageMigrated) {
  588. // v4 compatible process
  589. return this.updatePageV4(pageData, body, previousBody, user, options);
  590. }
  591. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  592. const grant = options.grant || pageData.grant; // use the previous data if absence
  593. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  594. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  595. const grantedUserIds = pageData.grantedUserIds || [user._id];
  596. const newPageData = pageData;
  597. if (grant === GRANT_RESTRICTED) {
  598. newPageData.parent = null;
  599. }
  600. else {
  601. /*
  602. * UserGroup & Owner validation
  603. */
  604. let isGrantNormalized = false;
  605. try {
  606. const shouldCheckDescendants = true;
  607. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(pageData.path, grant, grantedUserIds, grantUserGroupId, shouldCheckDescendants);
  608. }
  609. catch (err) {
  610. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  611. throw err;
  612. }
  613. if (!isGrantNormalized) {
  614. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  615. }
  616. }
  617. newPageData.applyScope(user, grant, grantUserGroupId);
  618. // update existing page
  619. let savedPage = await newPageData.save();
  620. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  621. savedPage = await pushRevision(savedPage, newRevision, user);
  622. await savedPage.populateDataToShowRevision();
  623. if (isSyncRevisionToHackmd) {
  624. savedPage = await this.syncRevisionToHackmd(savedPage);
  625. }
  626. pageEvent.emit('update', savedPage, user);
  627. return savedPage;
  628. };
  629. // add old page schema methods
  630. const pageSchema = getPageSchema(crowi);
  631. schema.methods = { ...pageSchema.methods, ...schema.methods };
  632. schema.statics = { ...pageSchema.statics, ...schema.statics };
  633. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  634. };
  635. /*
  636. * Aggregation utilities
  637. */
  638. // TODO: use the original type when upgraded https://github.com/Automattic/mongoose/blob/master/index.d.ts#L3090
  639. type PipelineStageMatch = {
  640. $match: AnyObject
  641. };
  642. export const generateGrantCondition = async(
  643. user, _userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  644. ): Promise<PipelineStageMatch> => {
  645. let userGroups = _userGroups;
  646. if (user != null && userGroups == null) {
  647. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  648. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  649. }
  650. const grantConditions: AnyObject[] = [
  651. { grant: null },
  652. { grant: GRANT_PUBLIC },
  653. ];
  654. if (showAnyoneKnowsLink) {
  655. grantConditions.push({ grant: GRANT_RESTRICTED });
  656. }
  657. if (showPagesRestrictedByOwner) {
  658. grantConditions.push(
  659. { grant: GRANT_SPECIFIED },
  660. { grant: GRANT_OWNER },
  661. );
  662. }
  663. else if (user != null) {
  664. grantConditions.push(
  665. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  666. { grant: GRANT_OWNER, grantedUsers: user._id },
  667. );
  668. }
  669. if (showPagesRestrictedByGroup) {
  670. grantConditions.push(
  671. { grant: GRANT_USER_GROUP },
  672. );
  673. }
  674. else if (userGroups != null && userGroups.length > 0) {
  675. grantConditions.push(
  676. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  677. );
  678. }
  679. return {
  680. $match: {
  681. $or: grantConditions,
  682. },
  683. };
  684. };