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