page.ts 26 KB

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