page.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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 escapeStringRegexp from 'escape-string-regexp';
  8. import nodePath from 'path';
  9. import { getOrCreateModel, pagePathUtils, pathUtils } from '@growi/core';
  10. import loggerFactory from '../../utils/logger';
  11. import Crowi from '../crowi';
  12. import { IPage } from '../../interfaces/page';
  13. import { getPageSchema, extractToAncestorsPaths, populateDataToShowRevision } from './obsolete-page';
  14. import { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  15. import { PageRedirectModel } from './page-redirect';
  16. const { isTopPage, collectAncestorPaths } = pagePathUtils;
  17. const logger = loggerFactory('growi:models:page');
  18. /*
  19. * define schema
  20. */
  21. const GRANT_PUBLIC = 1;
  22. const GRANT_RESTRICTED = 2;
  23. const GRANT_SPECIFIED = 3; // DEPRECATED
  24. const GRANT_OWNER = 4;
  25. const GRANT_USER_GROUP = 5;
  26. const PAGE_GRANT_ERROR = 1;
  27. const STATUS_PUBLISHED = 'published';
  28. const STATUS_DELETED = 'deleted';
  29. export interface PageDocument extends IPage, Document {}
  30. type TargetAndAncestorsResult = {
  31. targetAndAncestors: PageDocument[]
  32. rootPage: PageDocument
  33. }
  34. export type CreateMethod = (path: string, body: string, user, options) => Promise<PageDocument & { _id: any }>
  35. export interface PageModel extends Model<PageDocument> {
  36. [x: string]: any; // for obsolete methods
  37. createEmptyPagesByPaths(paths: string[], onlyMigratedAsExistingPages?: boolean, publicOnly?: boolean): Promise<void>
  38. getParentAndFillAncestors(path: string, user): Promise<PageDocument & { _id: any }>
  39. findByIdsAndViewer(pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]>
  40. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: boolean, includeEmpty?: boolean): Promise<PageDocument[]>
  41. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  42. findChildrenByParentPathOrIdAndViewer(parentPathOrId: string, user, userGroups?): Promise<PageDocument[]>
  43. findAncestorsChildrenByPathAndViewer(path: string, user, userGroups?): Promise<Record<string, PageDocument[]>>
  44. generateGrantCondition(
  45. user, userGroups, showAnyoneKnowsLink?: boolean, showPagesRestrictedByOwner?: boolean, showPagesRestrictedByGroup?: boolean,
  46. ): { $or: any[] }
  47. PageQueryBuilder: typeof PageQueryBuilder
  48. GRANT_PUBLIC
  49. GRANT_RESTRICTED
  50. GRANT_SPECIFIED
  51. GRANT_OWNER
  52. GRANT_USER_GROUP
  53. PAGE_GRANT_ERROR
  54. STATUS_PUBLISHED
  55. STATUS_DELETED
  56. }
  57. type IObjectId = mongoose.Types.ObjectId;
  58. const ObjectId = mongoose.Schema.Types.ObjectId;
  59. const schema = new Schema<PageDocument, PageModel>({
  60. parent: {
  61. type: ObjectId, ref: 'Page', index: true, default: null,
  62. },
  63. descendantCount: { type: Number, default: 0 },
  64. isEmpty: { type: Boolean, default: false },
  65. path: {
  66. type: String, required: true, index: true,
  67. },
  68. revision: { type: ObjectId, ref: 'Revision' },
  69. status: { type: String, default: STATUS_PUBLISHED, index: true },
  70. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  71. grantedUsers: [{ type: ObjectId, ref: 'User' }],
  72. grantedGroup: { type: ObjectId, ref: 'UserGroup', index: true },
  73. creator: { type: ObjectId, ref: 'User', index: true },
  74. lastUpdateUser: { type: ObjectId, ref: 'User' },
  75. liker: [{ type: ObjectId, ref: 'User' }],
  76. seenUsers: [{ type: ObjectId, ref: 'User' }],
  77. commentCount: { type: Number, default: 0 },
  78. slackChannels: { type: String },
  79. pageIdOnHackmd: { type: String },
  80. revisionHackmdSynced: { type: ObjectId, ref: 'Revision' }, // the revision that is synced to HackMD
  81. hasDraftOnHackmd: { type: Boolean }, // set true if revision and revisionHackmdSynced are same but HackMD document has modified
  82. createdAt: { type: Date, default: new Date() },
  83. updatedAt: { type: Date, default: new Date() },
  84. deleteUser: { type: ObjectId, ref: 'User' },
  85. deletedAt: { type: Date },
  86. }, {
  87. toJSON: { getters: true },
  88. toObject: { getters: true },
  89. });
  90. // apply plugins
  91. schema.plugin(mongoosePaginate);
  92. schema.plugin(uniqueValidator);
  93. const hasSlash = (str: string): boolean => {
  94. return str.includes('/');
  95. };
  96. /*
  97. * Generate RegExp instance for one level lower path
  98. */
  99. const generateChildrenRegExp = (path: string): RegExp => {
  100. // https://regex101.com/r/laJGzj/1
  101. // ex. /any_level1
  102. if (isTopPage(path)) return new RegExp(/^\/[^/]+$/);
  103. // https://regex101.com/r/mrDJrx/1
  104. // ex. /parent/any_child OR /any_level1
  105. return new RegExp(`^${path}(\\/[^/]+)\\/?$`);
  106. };
  107. class PageQueryBuilder {
  108. query: any;
  109. constructor(query, includeEmpty = false) {
  110. this.query = query;
  111. if (!includeEmpty) {
  112. this.query = this.query
  113. .and({
  114. $or: [
  115. { isEmpty: false },
  116. { isEmpty: null }, // for v4 compatibility
  117. ],
  118. });
  119. }
  120. }
  121. addConditionToExcludeTrashed() {
  122. this.query = this.query
  123. .and({
  124. $or: [
  125. { status: null },
  126. { status: STATUS_PUBLISHED },
  127. ],
  128. });
  129. return this;
  130. }
  131. /**
  132. * generate the query to find the pages '{path}/*' and '{path}' self.
  133. * If top page, return without doing anything.
  134. */
  135. addConditionToListWithDescendants(path: string, option?) {
  136. // No request is set for the top page
  137. if (isTopPage(path)) {
  138. return this;
  139. }
  140. const pathNormalized = pathUtils.normalizePath(path);
  141. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  142. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  143. this.query = this.query
  144. .and({
  145. $or: [
  146. { path: pathNormalized },
  147. { path: new RegExp(`^${startsPattern}`) },
  148. ],
  149. });
  150. return this;
  151. }
  152. /**
  153. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  154. * If top page, return without doing anything.
  155. */
  156. addConditionToListOnlyDescendants(path, option) {
  157. // No request is set for the top page
  158. if (isTopPage(path)) {
  159. return this;
  160. }
  161. const pathWithTrailingSlash = pathUtils.addTrailingSlash(path);
  162. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  163. this.query = this.query
  164. .and({ path: new RegExp(`^${startsPattern}`) });
  165. return this;
  166. }
  167. addConditionToListOnlyAncestors(path) {
  168. const pathNormalized = pathUtils.normalizePath(path);
  169. const ancestorsPaths = extractToAncestorsPaths(pathNormalized);
  170. this.query = this.query
  171. .and({
  172. path: {
  173. $in: ancestorsPaths,
  174. },
  175. });
  176. return this;
  177. }
  178. /**
  179. * generate the query to find pages that start with `path`
  180. *
  181. * In normal case, returns '{path}/*' and '{path}' self.
  182. * If top page, return without doing anything.
  183. *
  184. * *option*
  185. * Left for backward compatibility
  186. */
  187. addConditionToListByStartWith(path, option?) {
  188. // No request is set for the top page
  189. if (isTopPage(path)) {
  190. return this;
  191. }
  192. const startsPattern = escapeStringRegexp(path);
  193. this.query = this.query
  194. .and({ path: new RegExp(`^${startsPattern}`) });
  195. return this;
  196. }
  197. async addConditionForParentNormalization(user) {
  198. // determine UserGroup condition
  199. let userGroups;
  200. if (user != null) {
  201. const UserGroupRelation = mongoose.model('UserGroupRelation') as any; // TODO: Typescriptize model
  202. userGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  203. }
  204. const grantConditions: any[] = [
  205. { grant: null },
  206. { grant: GRANT_PUBLIC },
  207. ];
  208. if (user != null) {
  209. grantConditions.push(
  210. { grant: GRANT_OWNER, grantedUsers: user._id },
  211. );
  212. }
  213. if (userGroups != null && userGroups.length > 0) {
  214. grantConditions.push(
  215. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  216. );
  217. }
  218. this.query = this.query
  219. .and({
  220. $or: grantConditions,
  221. });
  222. return this;
  223. }
  224. async addConditionAsMigratablePages(user) {
  225. this.query = this.query
  226. .and({
  227. $or: [
  228. { grant: { $ne: GRANT_RESTRICTED } },
  229. { grant: { $ne: GRANT_SPECIFIED } },
  230. ],
  231. });
  232. this.addConditionAsNotMigrated();
  233. this.addConditionAsNonRootPage();
  234. this.addConditionToExcludeTrashed();
  235. await this.addConditionForParentNormalization(user);
  236. return this;
  237. }
  238. addConditionToFilteringByViewer(user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false) {
  239. const condition = generateGrantCondition(user, userGroups, showAnyoneKnowsLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup);
  240. this.query = this.query
  241. .and(condition);
  242. return this;
  243. }
  244. addConditionToPagenate(offset, limit, sortOpt?) {
  245. this.query = this.query
  246. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  247. return this;
  248. }
  249. addConditionAsNonRootPage() {
  250. this.query = this.query.and({ path: { $ne: '/' } });
  251. return this;
  252. }
  253. addConditionAsNotMigrated() {
  254. this.query = this.query
  255. .and({ parent: null });
  256. return this;
  257. }
  258. addConditionAsMigrated() {
  259. this.query = this.query
  260. .and(
  261. {
  262. $or: [
  263. { parent: { $ne: null } },
  264. { path: '/' },
  265. ],
  266. },
  267. );
  268. return this;
  269. }
  270. /*
  271. * Add this condition when get any ancestor pages including the target's parent
  272. */
  273. addConditionToSortPagesByDescPath() {
  274. this.query = this.query.sort('-path');
  275. return this;
  276. }
  277. addConditionToSortPagesByAscPath() {
  278. this.query = this.query.sort('path');
  279. return this;
  280. }
  281. addConditionToMinimizeDataForRendering() {
  282. this.query = this.query.select('_id path isEmpty grant revision descendantCount');
  283. return this;
  284. }
  285. addConditionToListByPathsArray(paths) {
  286. this.query = this.query
  287. .and({
  288. path: {
  289. $in: paths,
  290. },
  291. });
  292. return this;
  293. }
  294. addConditionToListByPageIdsArray(pageIds) {
  295. this.query = this.query
  296. .and({
  297. _id: {
  298. $in: pageIds,
  299. },
  300. });
  301. return this;
  302. }
  303. addConditionToExcludeByPageIdsArray(pageIds) {
  304. this.query = this.query
  305. .and({
  306. _id: {
  307. $nin: pageIds,
  308. },
  309. });
  310. return this;
  311. }
  312. populateDataToList(userPublicFields) {
  313. this.query = this.query
  314. .populate({
  315. path: 'lastUpdateUser',
  316. select: userPublicFields,
  317. });
  318. return this;
  319. }
  320. populateDataToShowRevision(userPublicFields) {
  321. this.query = populateDataToShowRevision(this.query, userPublicFields);
  322. return this;
  323. }
  324. addConditionToFilteringByParentId(parentId) {
  325. this.query = this.query.and({ parent: parentId });
  326. return this;
  327. }
  328. }
  329. /**
  330. * Create empty pages if the page in paths didn't exist
  331. * @param onlyMigratedAsExistingPages Determine whether to include non-migrated pages as existing pages. If a page exists,
  332. * an empty page will not be created at that page's path.
  333. */
  334. schema.statics.createEmptyPagesByPaths = async function(paths: string[], user: any | null, onlyMigratedAsExistingPages = true): Promise<void> {
  335. // find existing parents
  336. const builder = new PageQueryBuilder(this.find({}, { _id: 0, path: 1 }), true);
  337. await this.addConditionToFilteringByViewerToEdit(builder, user);
  338. if (onlyMigratedAsExistingPages) {
  339. builder.addConditionAsMigrated();
  340. }
  341. const existingPages = await builder
  342. .addConditionToListByPathsArray(paths)
  343. .query
  344. .lean()
  345. .exec();
  346. const existingPagePaths = existingPages.map(page => page.path);
  347. // paths to create empty pages
  348. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  349. // insertMany empty pages
  350. try {
  351. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  352. }
  353. catch (err) {
  354. logger.error('Failed to insert empty pages.', err);
  355. throw err;
  356. }
  357. };
  358. schema.statics.createEmptyPage = async function(
  359. path: string, parent: any, descendantCount = 0, // TODO: improve type including IPage at https://redmine.weseek.co.jp/issues/86506
  360. ): Promise<PageDocument & { _id: any }> {
  361. if (parent == null) {
  362. throw Error('parent must not be null');
  363. }
  364. const Page = this;
  365. const page = new Page();
  366. page.path = path;
  367. page.isEmpty = true;
  368. page.parent = parent;
  369. page.descendantCount = descendantCount;
  370. return page.save();
  371. };
  372. /**
  373. * Replace an existing page with an empty page.
  374. * It updates the children's parent to the new empty page's _id.
  375. * @param exPage a page document to be replaced
  376. * @returns Promise<void>
  377. */
  378. schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false) {
  379. // find parent
  380. const parent = await this.findOne({ _id: exPage.parent });
  381. if (parent == null) {
  382. throw Error('parent to update does not exist. Prepare parent first.');
  383. }
  384. // create empty page at path
  385. const newTarget = pageToReplaceWith == null ? await this.createEmptyPage(exPage.path, parent, exPage.descendantCount) : pageToReplaceWith;
  386. // find children by ex-page _id
  387. const children = await this.find({ parent: exPage._id });
  388. // bulkWrite
  389. const operationForNewTarget = {
  390. updateOne: {
  391. filter: { _id: newTarget._id },
  392. update: {
  393. parent: parent._id,
  394. },
  395. },
  396. };
  397. const operationsForChildren = {
  398. updateMany: {
  399. filter: {
  400. _id: { $in: children.map(d => d._id) },
  401. },
  402. update: {
  403. parent: newTarget._id,
  404. },
  405. },
  406. };
  407. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  408. const isExPageEmpty = exPage.isEmpty;
  409. if (deleteExPageIfEmpty && isExPageEmpty) {
  410. await this.deleteOne({ _id: exPage._id });
  411. logger.warn('Deleted empty page since it was replaced with another page.');
  412. }
  413. return this.findById(newTarget._id);
  414. };
  415. /**
  416. * Find parent or create parent if not exists.
  417. * It also updates parent of ancestors
  418. * @param path string
  419. * @returns Promise<PageDocument>
  420. */
  421. schema.statics.getParentAndFillAncestors = async function(path: string, user): Promise<PageDocument> {
  422. const parentPath = nodePath.dirname(path);
  423. const builder1 = new PageQueryBuilder(this.find({ path: parentPath }), true);
  424. const pagesCanBeParent = await builder1
  425. .addConditionAsMigrated()
  426. .query
  427. .exec();
  428. if (pagesCanBeParent.length >= 1) {
  429. return pagesCanBeParent[0]; // the earliest page will be the result
  430. }
  431. /*
  432. * Fill parents if parent is null
  433. */
  434. const ancestorPaths = collectAncestorPaths(path); // paths of parents need to be created
  435. // just create ancestors with empty pages
  436. await this.createEmptyPagesByPaths(ancestorPaths, user);
  437. // find ancestors
  438. const builder2 = new PageQueryBuilder(this.find(), true);
  439. const ancestors = await builder2
  440. .addConditionToListByPathsArray(ancestorPaths)
  441. .addConditionToSortPagesByDescPath()
  442. .query
  443. .exec();
  444. const ancestorsMap = new Map(); // Map<path, page>
  445. ancestors.forEach(page => !ancestorsMap.has(page.path) && ancestorsMap.set(page.path, page)); // the earlier element should be the true ancestor
  446. // bulkWrite to update ancestors
  447. const nonRootAncestors = ancestors.filter(page => !isTopPage(page.path));
  448. const operations = nonRootAncestors.map((page) => {
  449. const parentPath = nodePath.dirname(page.path);
  450. return {
  451. updateOne: {
  452. filter: {
  453. _id: page._id,
  454. },
  455. update: {
  456. parent: ancestorsMap.get(parentPath)._id,
  457. },
  458. },
  459. };
  460. });
  461. await this.bulkWrite(operations);
  462. const createdParent = ancestorsMap.get(parentPath);
  463. return createdParent;
  464. };
  465. // Utility function to add viewer condition to PageQueryBuilder instance
  466. const addViewerCondition = async(queryBuilder: PageQueryBuilder, user, userGroups = null): Promise<void> => {
  467. let relatedUserGroups = userGroups;
  468. if (user != null && relatedUserGroups == null) {
  469. const UserGroupRelation: any = mongoose.model('UserGroupRelation');
  470. relatedUserGroups = await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user);
  471. }
  472. queryBuilder.addConditionToFilteringByViewer(user, relatedUserGroups, false);
  473. };
  474. /*
  475. * Find pages by ID and viewer.
  476. */
  477. schema.statics.findByIdsAndViewer = async function(pageIds: string[], user, userGroups?, includeEmpty?: boolean): Promise<PageDocument[]> {
  478. const baseQuery = this.find({ _id: { $in: pageIds } });
  479. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  480. await addViewerCondition(queryBuilder, user, userGroups);
  481. return queryBuilder.query.exec();
  482. };
  483. /*
  484. * Find a page by path and viewer. Pass false to useFindOne to use findOne method.
  485. */
  486. schema.statics.findByPathAndViewer = async function(
  487. path: string | null, user, userGroups = null, useFindOne = true, includeEmpty = false,
  488. ): Promise<PageDocument | PageDocument[] | null> {
  489. if (path == null) {
  490. throw new Error('path is required.');
  491. }
  492. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  493. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  494. await addViewerCondition(queryBuilder, user, userGroups);
  495. return queryBuilder.query.exec();
  496. };
  497. /*
  498. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  499. * The result will include the target as well
  500. */
  501. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  502. let path;
  503. if (!hasSlash(pathOrId)) {
  504. const _id = pathOrId;
  505. const page = await this.findOne({ _id });
  506. path = page == null ? '/' : page.path;
  507. }
  508. else {
  509. path = pathOrId;
  510. }
  511. const ancestorPaths = collectAncestorPaths(path);
  512. ancestorPaths.push(path); // include target
  513. // Do not populate
  514. const queryBuilder = new PageQueryBuilder(this.find(), true);
  515. await addViewerCondition(queryBuilder, user, userGroups);
  516. const _targetAndAncestors: PageDocument[] = await queryBuilder
  517. .addConditionAsMigrated()
  518. .addConditionToListByPathsArray(ancestorPaths)
  519. .addConditionToMinimizeDataForRendering()
  520. .addConditionToSortPagesByDescPath()
  521. .query
  522. .lean()
  523. .exec();
  524. // no same path pages
  525. const ancestorsMap = new Map<string, PageDocument>();
  526. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  527. const targetAndAncestors = Array.from(ancestorsMap.values());
  528. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  529. return { targetAndAncestors, rootPage };
  530. };
  531. /*
  532. * Find all children by parent's path or id. Using id should be prioritized
  533. */
  534. schema.statics.findChildrenByParentPathOrIdAndViewer = async function(parentPathOrId: string, user, userGroups = null): Promise<PageDocument[]> {
  535. let queryBuilder: PageQueryBuilder;
  536. if (hasSlash(parentPathOrId)) {
  537. const path = parentPathOrId;
  538. const regexp = generateChildrenRegExp(path);
  539. queryBuilder = new PageQueryBuilder(this.find({ path: { $regex: regexp } }), true);
  540. }
  541. else {
  542. const parentId = parentPathOrId;
  543. queryBuilder = new PageQueryBuilder(this.find({ parent: parentId } as any), true); // TODO: improve type
  544. }
  545. await addViewerCondition(queryBuilder, user, userGroups);
  546. return queryBuilder
  547. .addConditionToSortPagesByAscPath()
  548. .query
  549. .lean()
  550. .exec();
  551. };
  552. schema.statics.findAncestorsChildrenByPathAndViewer = async function(path: string, user, userGroups = null): Promise<Record<string, PageDocument[]>> {
  553. const ancestorPaths = isTopPage(path) ? ['/'] : collectAncestorPaths(path); // root path is necessary for rendering
  554. const regexps = ancestorPaths.map(path => new RegExp(generateChildrenRegExp(path))); // cannot use re2
  555. // get pages at once
  556. const queryBuilder = new PageQueryBuilder(this.find({ path: { $in: regexps } }), true);
  557. await addViewerCondition(queryBuilder, user, userGroups);
  558. const _pages = await queryBuilder
  559. .addConditionAsMigrated()
  560. .addConditionToMinimizeDataForRendering()
  561. .addConditionToSortPagesByAscPath()
  562. .query
  563. .lean()
  564. .exec();
  565. // mark target
  566. const pages = _pages.map((page: PageDocument & {isTarget?: boolean}) => {
  567. if (page.path === path) {
  568. page.isTarget = true;
  569. }
  570. return page;
  571. });
  572. /*
  573. * If any non-migrated page is found during creating the pathToChildren map, it will stop incrementing at that moment
  574. */
  575. const pathToChildren: Record<string, PageDocument[]> = {};
  576. const sortedPaths = ancestorPaths.sort((a, b) => a.length - b.length); // sort paths by path.length
  577. sortedPaths.every((path) => {
  578. const children = pages.filter(page => nodePath.dirname(page.path) === path);
  579. if (children.length === 0) {
  580. return false; // break when children do not exist
  581. }
  582. pathToChildren[path] = children;
  583. return true;
  584. });
  585. return pathToChildren;
  586. };
  587. /*
  588. * Utils from obsolete-page.js
  589. */
  590. async function pushRevision(pageData, newRevision, user) {
  591. await newRevision.save();
  592. pageData.revision = newRevision;
  593. pageData.lastUpdateUser = user;
  594. pageData.updatedAt = Date.now();
  595. return pageData.save();
  596. }
  597. /**
  598. * add/subtract descendantCount of pages with provided paths by increment.
  599. * increment can be negative number
  600. */
  601. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  602. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  603. };
  604. /**
  605. * recount descendantCount of a page with the provided id and return it
  606. */
  607. schema.statics.recountDescendantCount = async function(id: ObjectIdLike):Promise<number> {
  608. const res = await this.aggregate(
  609. [
  610. {
  611. $match: {
  612. parent: id,
  613. },
  614. },
  615. {
  616. $project: {
  617. parent: 1,
  618. isEmpty: 1,
  619. descendantCount: 1,
  620. },
  621. },
  622. {
  623. $group: {
  624. _id: '$parent',
  625. sumOfDescendantCount: {
  626. $sum: '$descendantCount',
  627. },
  628. sumOfDocsCount: {
  629. $sum: {
  630. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  631. },
  632. },
  633. },
  634. },
  635. {
  636. $set: {
  637. descendantCount: {
  638. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  639. },
  640. },
  641. },
  642. ],
  643. );
  644. return res.length === 0 ? 0 : res[0].descendantCount;
  645. };
  646. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  647. const self = this;
  648. const target = await this.findById(pageId);
  649. if (target == null) {
  650. throw Error('Target not found');
  651. }
  652. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  653. const parent = await self.findOne({ _id: target.parent });
  654. if (parent == null) {
  655. return ancestors;
  656. }
  657. return findAncestorsRecursively(parent, [...ancestors, parent]);
  658. }
  659. return findAncestorsRecursively(target);
  660. };
  661. // TODO: write test code
  662. /**
  663. * Recursively removes empty pages at leaf position.
  664. * @param pageId ObjectIdLike
  665. * @returns Promise<void>
  666. */
  667. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  668. const self = this;
  669. const initialPage = await this.findById(pageId);
  670. if (initialPage == null) {
  671. return;
  672. }
  673. if (!initialPage.isEmpty) {
  674. return;
  675. }
  676. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  677. if (!page.isEmpty) {
  678. return pageIds;
  679. }
  680. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  681. if (isChildrenOtherThanTargetExist) {
  682. return pageIds;
  683. }
  684. pageIds.push(page._id);
  685. const nextPage = await self.findById(page.parent);
  686. if (nextPage == null) {
  687. return pageIds;
  688. }
  689. return generatePageIdsToRemove(page, nextPage, pageIds);
  690. }
  691. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  692. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  693. };
  694. schema.statics.normalizeDescendantCountById = async function(pageId) {
  695. const children = await this.find({ parent: pageId });
  696. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  697. const sumChildPages = children.filter(p => !p.isEmpty).length;
  698. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  699. };
  700. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  701. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  702. };
  703. schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> {
  704. await this.deleteMany({
  705. _id: {
  706. $nin: pageIdsToNotRemove,
  707. },
  708. path: {
  709. $in: paths,
  710. },
  711. isEmpty: true,
  712. });
  713. };
  714. schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  715. export function generateGrantCondition(
  716. user, userGroups, showAnyoneKnowsLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  717. ): { $or: any[] } {
  718. const grantConditions: AnyObject[] = [
  719. { grant: null },
  720. { grant: GRANT_PUBLIC },
  721. ];
  722. if (showAnyoneKnowsLink) {
  723. grantConditions.push({ grant: GRANT_RESTRICTED });
  724. }
  725. if (showPagesRestrictedByOwner) {
  726. grantConditions.push(
  727. { grant: GRANT_SPECIFIED },
  728. { grant: GRANT_OWNER },
  729. );
  730. }
  731. else if (user != null) {
  732. grantConditions.push(
  733. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  734. { grant: GRANT_OWNER, grantedUsers: user._id },
  735. );
  736. }
  737. if (showPagesRestrictedByGroup) {
  738. grantConditions.push(
  739. { grant: GRANT_USER_GROUP },
  740. );
  741. }
  742. else if (userGroups != null && userGroups.length > 0) {
  743. grantConditions.push(
  744. { grant: GRANT_USER_GROUP, grantedGroup: { $in: userGroups } },
  745. );
  746. }
  747. return {
  748. $or: grantConditions,
  749. };
  750. }
  751. schema.statics.generateGrantCondition = generateGrantCondition;
  752. export type PageCreateOptions = {
  753. format?: string
  754. grantUserGroupId?: ObjectIdLike
  755. grant?: number
  756. }
  757. /*
  758. * Merge obsolete page model methods and define new methods which depend on crowi instance
  759. */
  760. export default (crowi: Crowi): any => {
  761. let pageEvent;
  762. if (crowi != null) {
  763. pageEvent = crowi.event('page');
  764. }
  765. schema.statics.create = async function(path: string, body: string, user, options: PageCreateOptions = {}) {
  766. if (crowi.pageGrantService == null || crowi.configManager == null || crowi.pageService == null || crowi.pageOperationService == null) {
  767. throw Error('Crowi is not setup');
  768. }
  769. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  770. // v4 compatible process
  771. if (!isV5Compatible) {
  772. return this.createV4(path, body, user, options);
  773. }
  774. const canOperate = await crowi.pageOperationService.canOperate(false, null, path);
  775. if (!canOperate) {
  776. throw Error(`Cannot operate create to path "${path}" right now.`);
  777. }
  778. const Page = this;
  779. const Revision = crowi.model('Revision');
  780. const {
  781. format = 'markdown', grantUserGroupId,
  782. } = options;
  783. let grant = options.grant;
  784. // sanitize path
  785. path = crowi.xss.process(path); // eslint-disable-line no-param-reassign
  786. // throw if exists
  787. const isExist = (await this.count({ path, isEmpty: false })) > 0; // not validate empty page
  788. if (isExist) {
  789. throw new Error('Cannot create new page to existed path');
  790. }
  791. // force public
  792. if (isTopPage(path)) {
  793. grant = GRANT_PUBLIC;
  794. }
  795. // find an existing empty page
  796. const emptyPage = await Page.findOne({ path, isEmpty: true });
  797. /*
  798. * UserGroup & Owner validation
  799. */
  800. if (grant !== GRANT_RESTRICTED) {
  801. let isGrantNormalized = false;
  802. try {
  803. // It must check descendants as well if emptyTarget is not null
  804. const shouldCheckDescendants = emptyPage != null;
  805. const newGrantedUserIds = grant === GRANT_OWNER ? [user._id] as IObjectId[] : undefined;
  806. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(path, grant, newGrantedUserIds, grantUserGroupId, shouldCheckDescendants);
  807. }
  808. catch (err) {
  809. logger.error(`Failed to validate grant of page at "${path}" of grant ${grant}:`, err);
  810. throw err;
  811. }
  812. if (!isGrantNormalized) {
  813. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  814. }
  815. }
  816. /*
  817. * update empty page if exists, if not, create a new page
  818. */
  819. let page;
  820. if (emptyPage != null) {
  821. page = emptyPage;
  822. const descendantCount = await this.recountDescendantCount(page._id);
  823. page.descendantCount = descendantCount;
  824. page.isEmpty = false;
  825. }
  826. else {
  827. page = new Page();
  828. }
  829. let parentId: IObjectId | string | null = null;
  830. const parent = await Page.getParentAndFillAncestors(path, user);
  831. if (!isTopPage(path)) {
  832. parentId = parent._id;
  833. }
  834. page.path = path;
  835. page.creator = user;
  836. page.lastUpdateUser = user;
  837. page.status = STATUS_PUBLISHED;
  838. // set parent to null when GRANT_RESTRICTED
  839. if (grant === GRANT_RESTRICTED) {
  840. page.parent = null;
  841. }
  842. else {
  843. page.parent = parentId;
  844. }
  845. page.applyScope(user, grant, grantUserGroupId);
  846. let savedPage = await page.save();
  847. /*
  848. * After save
  849. */
  850. // Delete PageRedirect if exists
  851. const PageRedirect = mongoose.model('PageRedirect') as unknown as PageRedirectModel;
  852. try {
  853. await PageRedirect.deleteOne({ fromPath: path });
  854. logger.warn(`Deleted page redirect after creating a new page at path "${path}".`);
  855. }
  856. catch (err) {
  857. // no throw
  858. logger.error('Failed to delete PageRedirect');
  859. }
  860. const newRevision = Revision.prepareRevision(savedPage, body, null, user, { format });
  861. savedPage = await pushRevision(savedPage, newRevision, user);
  862. await savedPage.populateDataToShowRevision();
  863. pageEvent.emit('create', savedPage, user);
  864. // update descendantCount asynchronously
  865. await crowi.pageService.updateDescendantCountOfAncestors(savedPage._id, 1, false);
  866. return savedPage;
  867. };
  868. schema.statics.updatePage = async function(pageData, body, previousBody, user, options = {}) {
  869. if (crowi.configManager == null || crowi.pageGrantService == null) {
  870. throw Error('Crowi is not set up');
  871. }
  872. const isPageMigrated = pageData.parent != null;
  873. const isV5Compatible = crowi.configManager.getConfig('crowi', 'app:isV5Compatible');
  874. if (!isV5Compatible || !isPageMigrated) {
  875. // v4 compatible process
  876. return this.updatePageV4(pageData, body, previousBody, user, options);
  877. }
  878. const Revision = mongoose.model('Revision') as any; // TODO: Typescriptize model
  879. const grant = options.grant || pageData.grant; // use the previous data if absence
  880. const grantUserGroupId: undefined | ObjectIdLike = options.grantUserGroupId ?? pageData.grantedGroup?._id.toString();
  881. const isSyncRevisionToHackmd = options.isSyncRevisionToHackmd;
  882. const grantedUserIds = pageData.grantedUserIds || [user._id];
  883. const newPageData = pageData;
  884. if (grant === GRANT_RESTRICTED) {
  885. newPageData.parent = null;
  886. }
  887. else {
  888. /*
  889. * UserGroup & Owner validation
  890. */
  891. let isGrantNormalized = false;
  892. try {
  893. const shouldCheckDescendants = true;
  894. isGrantNormalized = await crowi.pageGrantService.isGrantNormalized(pageData.path, grant, grantedUserIds, grantUserGroupId, shouldCheckDescendants);
  895. }
  896. catch (err) {
  897. logger.error(`Failed to validate grant of page at "${pageData.path}" of grant ${grant}:`, err);
  898. throw err;
  899. }
  900. if (!isGrantNormalized) {
  901. throw Error('The selected grant or grantedGroup is not assignable to this page.');
  902. }
  903. }
  904. newPageData.applyScope(user, grant, grantUserGroupId);
  905. // update existing page
  906. let savedPage = await newPageData.save();
  907. const newRevision = await Revision.prepareRevision(newPageData, body, previousBody, user);
  908. savedPage = await pushRevision(savedPage, newRevision, user);
  909. await savedPage.populateDataToShowRevision();
  910. if (isSyncRevisionToHackmd) {
  911. savedPage = await this.syncRevisionToHackmd(savedPage);
  912. }
  913. pageEvent.emit('update', savedPage, user);
  914. return savedPage;
  915. };
  916. // add old page schema methods
  917. const pageSchema = getPageSchema(crowi);
  918. schema.methods = { ...pageSchema.methods, ...schema.methods };
  919. schema.statics = { ...pageSchema.statics, ...schema.statics };
  920. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  921. };