page.ts 26 KB

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