page.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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. if (page == null) throw new Error('Page not found.');
  278. path = page.path;
  279. }
  280. else {
  281. path = pathOrId;
  282. }
  283. const ancestorPaths = collectAncestorPaths(path);
  284. ancestorPaths.push(path); // include target
  285. // Do not populate
  286. const queryBuilder = new PageQueryBuilder(this.find(), true);
  287. await addViewerCondition(queryBuilder, user, userGroups);
  288. const _targetAndAncestors: PageDocument[] = await queryBuilder
  289. .addConditionAsMigrated()
  290. .addConditionToListByPathsArray(ancestorPaths)
  291. .addConditionToMinimizeDataForRendering()
  292. .addConditionToSortPagesByDescPath()
  293. .query
  294. .lean()
  295. .exec();
  296. // no same path pages
  297. const ancestorsMap = new Map<string, PageDocument>();
  298. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  299. const targetAndAncestors = Array.from(ancestorsMap.values());
  300. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  301. return { targetAndAncestors, rootPage };
  302. };
  303. /*
  304. * Find all children by parent's path or id. Using id should be prioritized
  305. */
  306. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  307. let queryBuilder: PageQueryBuilder;
  308. if (hasSlash(parentPathOrId)) {
  309. const path = parentPathOrId;
  310. const regexp = generateChildrenRegExp(path);
  311. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  312. }
  313. else {
  314. const parentId = parentPathOrId;
  315. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId } as any), true); // TODO: improve type
  316. }
  317. await addViewerCondition(queryBuilder, user, userGroups);
  318. return queryBuilder
  319. .addConditionToSortPagesByAscPath()
  320. .query
  321. .lean()
  322. .exec();
  323. };
  324. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  325. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  326. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  327. // get pages at once
  328. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  329. await addViewerCondition(queryBuilder, user, userGroups);
  330. const _pages = await queryBuilder
  331. .addConditionAsMigrated()
  332. .addConditionToMinimizeDataForRendering()
  333. .addConditionToSortPagesByAscPath()
  334. .query
  335. .lean()
  336. .exec();
  337. // mark target
  338. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  339. if (page.path === path) {
  340. page.isTarget = true;
  341. }
  342. return page;
  343. });
  344. /*
  345. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  346. */
  347. const pathToChildren: Record<string, PageDocument[]> = {};
  348. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  349. sortedPaths.every((path) => {
  350. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  351. if (children.length === 0) {
  352. return false; // break when children do not exist
  353. }
  354. pathToChildren[path] = children;
  355. return true;
  356. });
  357. return pathToChildren;
  358. };
  359. /*
  360. * Utils from obsolete-page.js
  361. */
  362. async function pushRevision(pageData, newRevision, user) {
  363. await newRevision.save();
  364. pageData.revision = newRevision;
  365. pageData.lastUpdateUser = user;
  366. pageData.updatedAt = Date.now();
  367. return pageData.save();
  368. }
  369. /**
  370. * add/subtract descendantCount of pages with provided paths by increment.
  371. * increment can be negative number
  372. */
  373. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  374. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  375. };
  376. /**
  377. * recount descendantCount of a page with the provided id and return it
  378. */
  379. schema.statics.recountDescendantCount = async function(id: ObjectIdLike):Promise<number> {
  380. const res = await this.aggregate(
  381. [
  382. {
  383. $match: {
  384. parent: id,
  385. },
  386. },
  387. {
  388. $project: {
  389. parent: 1,
  390. isEmpty: 1,
  391. descendantCount: 1,
  392. },
  393. },
  394. {
  395. $group: {
  396. _id: '$parent',
  397. sumOfDescendantCount: {
  398. $sum: '$descendantCount',
  399. },
  400. sumOfDocsCount: {
  401. $sum: {
  402. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  403. },
  404. },
  405. },
  406. },
  407. {
  408. $set: {
  409. descendantCount: {
  410. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  411. },
  412. },
  413. },
  414. ],
  415. );
  416. return res.length === 0 ? 0 : res[0].descendantCount;
  417. };
  418. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  419. const self = this;
  420. const target = await this.findById(pageId);
  421. if (target == null) {
  422. throw Error('Target not found');
  423. }
  424. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  425. const parent = await self.findOne({ _id: target.parent });
  426. if (parent == null) {
  427. return ancestors;
  428. }
  429. return findAncestorsRecursively(parent, [...ancestors, parent]);
  430. }
  431. return findAncestorsRecursively(target);
  432. };
  433. // TODO: write test code
  434. /**
  435. * Recursively removes empty pages at leaf position.
  436. * @param pageId ObjectIdLike
  437. * @returns Promise<void>
  438. */
  439. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  440. const self = this;
  441. const initialPage = await this.findById(pageId);
  442. if (initialPage == null) {
  443. return;
  444. }
  445. if (!initialPage.isEmpty) {
  446. return;
  447. }
  448. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  449. if (!page.isEmpty) {
  450. return pageIds;
  451. }
  452. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  453. if (isChildrenOtherThanTargetExist) {
  454. return pageIds;
  455. }
  456. pageIds.push(page._id);
  457. const nextPage = await self.findById(page.parent);
  458. if (nextPage == null) {
  459. return pageIds;
  460. }
  461. return generatePageIdsToRemove(page, nextPage, pageIds);
  462. }
  463. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  464. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  465. };
  466. schema.statics.findByPageIdsToEdit = async function(ids, user, shouldIncludeEmpty = false) {
  467. const builder = new PageQueryBuilder(this.find({ _id: { $in: ids } }), shouldIncludeEmpty);
  468. await this.addConditionToFilteringByViewerToEdit(builder, user);
  469. const pages = await builder.query.exec();
  470. return pages;
  471. };
  472. schema.statics.normalizeDescendantCountById = async function(pageId) {
  473. const children = await this.find({ parent: pageId });
  474. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  475. const sumChildPages = children.filter(p => !p.isEmpty).length;
  476. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  477. };
  478. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  479. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  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 || crowi.pageService == null || crowi.pageOperationService == 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 canOperate = await crowi.pageOperationService.canOperate(false, null, path);
  504. if (!canOperate) {
  505. throw Error(`Cannot operate create to path "${path}" right now.`);
  506. }
  507. const Page = this;
  508. const Revision = crowi.model('Revision');
  509. const {
  510. format = 'markdown', grantUserGroupId,
  511. } = options;
  512. let grant = options.grant;
  513. // sanitize path
  514. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  515. // throw if exists
  516. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  517. if (isExist) {
  518. throw new Error('Cannot create new page to existed path');
  519. }
  520. // force public
  521. if (isTopPage(path)) {
  522. grant = GRANT_PUBLIC;
  523. }
  524. // find an existing empty page
  525. const emptyPage = await Page.findOne({ path, isEmpty: true });
  526. /*
  527. * UserGroup & Owner validation
  528. */
  529. if (grant !== GRANT_RESTRICTED) {
  530. let isGrantNormalized = false;
  531. try {
  532. // It must check descendants as well if emptyTarget is not null
  533. const shouldCheckDescendants = emptyPage != null;
  534. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  535. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  536. }
  537. catch (err) {
  538. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  539. throw err;
  540. }
  541. if (!isGrantNormalized) {
  542. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  543. }
  544. }
  545. /*
  546. * update empty page if exists, if not, create a new page
  547. */
  548. let page;
  549. if (emptyPage != null) {
  550. page = emptyPage;
  551. const descendantCount = await this.recountDescendantCount(page._id);
  552. page.descendantCount = descendantCount;
  553. page.isEmpty = false;
  554. }
  555. else {
  556. page = new Page();
  557. }
  558. let parentId: IObjectId | string | null = null;
  559. const parent = await Page.getParentAndFillAncestors(path);
  560. if (!isTopPage(path)) {
  561. parentId = parent._id;
  562. }
  563. page.path = path;
  564. page.creator = user;
  565. page.lastUpdateUser = user;
  566. page.status = STATUS_PUBLISHED;
  567. // set parent to null when GRANT_RESTRICTED
  568. if (grant === GRANT_RESTRICTED) {
  569. page.parent = null;
  570. }
  571. else {
  572. page.parent = parentId;
  573. }
  574. page.applyScope(user, grant, grantUserGroupId);
  575. let savedPage = await page.save();
  576. /*
  577. * After save
  578. */
  579. // Delete PageRedirect if exists
  580. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  581. try {
  582. await PageRedirect.deleteOne({ fromPath: path });
  583. logger.warn(`Deleted page redirect after creating a new page at path "${path}".`);
  584. }
  585. catch (err) {
  586. // no throw
  587. logger.error('Failed to delete PageRedirect');
  588. }
  589. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  590. savedPage = await pushRevision(savedPage, newRevision, user);
  591. await savedPage.populateDataToShowRevision();
  592. pageEvent.emit('create', savedPage, user);
  593. // update descendantCount asynchronously
  594. await crowi.pageService.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  595. return savedPage;
  596. };
  597. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  598. if (crowi.configManager == null || crowi.pageGrantService == null) {
  599. throw Error('Crowi is not set up');
  600. }
  601. const isPageMigrated = pageData.parent != null;
  602. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  603. if (!isV5Compatible || !isPageMigrated) {
  604. // v4 compatible process
  605. return this.updatePageV4(pageData, body, previousBody, user, options);
  606. }
  607. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  608. const grant = options.grant || pageData.grant; // use the previous data if absence
  609. const grantUserGroupId = options.grantUserGroupId || pageData.grantUserGroupId; // use the previous data if absence
  610. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  611. const grantedUserIds = pageData.grantedUserIds || [user._id];
  612. const newPageData = pageData;
  613. if (grant === GRANT_RESTRICTED) {
  614. newPageData.parent = null;
  615. }
  616. else {
  617. /*
  618. * UserGroup & Owner validation
  619. */
  620. let isGrantNormalized = false;
  621. try {
  622. const shouldCheckDescendants = true;
  623. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(pageData.path, grant, grantedUserIds, grantUserGroupId, shouldCheckDescendants);
  624. }
  625. catch (err) {
  626. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  627. throw err;
  628. }
  629. if (!isGrantNormalized) {
  630. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  631. }
  632. }
  633. newPageData.applyScope(user, grant, grantUserGroupId);
  634. // update existing page
  635. let savedPage = await newPageData.save();
  636. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  637. savedPage = await pushRevision(savedPage, newRevision, user);
  638. await savedPage.populateDataToShowRevision();
  639. if (isSyncRevisionToHackmd) {
  640. savedPage = await this.syncRevisionToHackmd(savedPage);
  641. }
  642. pageEvent.emit('update', savedPage, user);
  643. return savedPage;
  644. };
  645. // add old page schema methods
  646. const pageSchema = getPageSchema(crowi);
  647. schema.methods = { ...pageSchema.methods, ...schema.methods };
  648. schema.statics = { ...pageSchema.statics, ...schema.statics };
  649. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  650. };
  651. /*
  652. * Aggregation utilities
  653. */
  654. // TODO: use the original type when upgraded https://github.com/Automattic/mongoose/blob/master/index.d.ts#L3090
  655. type PipelineStageMatch = {
  656. $match: AnyObject
  657. };
  658. export const generateGrantCondition = async(
  659. user, _userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  660. ): Promise<PipelineStageMatch> => {
  661. let userGroups = _userGroups;
  662. if (user != null && userGroups == null) {
  663. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  664. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  665. }
  666. const grantConditions: AnyObject[] = [
  667. { grant: null },
  668. { grant: GRANT_PUBLIC },
  669. ];
  670. if (showAnyoneKnowsLink) {
  671. grantConditions.push({ grant: GRANT_RESTRICTED });
  672. }
  673. if (showPagesRestrictedByOwner) {
  674. grantConditions.push(
  675. { grant: GRANT_SPECIFIED },
  676. { grant: GRANT_OWNER },
  677. );
  678. }
  679. else if (user != null) {
  680. grantConditions.push(
  681. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  682. { grant: GRANT_OWNER, grantedUsers: user._id },
  683. );
  684. }
  685. if (showPagesRestrictedByGroup) {
  686. grantConditions.push(
  687. { grant: GRANT_USER_GROUP },
  688. );
  689. }
  690. else if (userGroups != null && userGroups.length > 0) {
  691. grantConditions.push(
  692. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  693. );
  694. }
  695. return {
  696. $match: {
  697. $or: grantConditions,
  698. },
  699. };
  700. };