page.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import assert from 'assert';
  3. import nodePath from 'path';
  4. import {
  5. type IPage,
  6. GroupType, type HasObjectId,
  7. } from '@growi/core';
  8. import type { IPagePopulatedToShowRevision } from '@growi/core/dist/interfaces';
  9. import { getIdForRef, isPopulated } from '@growi/core/dist/interfaces';
  10. import { isTopPage, hasSlash } from '@growi/core/dist/utils/page-path-utils';
  11. import { addTrailingSlash, normalizePath } from '@growi/core/dist/utils/path-utils';
  12. import escapeStringRegexp from 'escape-string-regexp';
  13. import type {
  14. Model, Document, AnyObject,
  15. HydratedDocument,
  16. Types,
  17. } from 'mongoose';
  18. import mongoose, { Schema } from 'mongoose';
  19. import mongoosePaginate from 'mongoose-paginate-v2';
  20. import uniqueValidator from 'mongoose-unique-validator';
  21. import type { ExternalUserGroupDocument } from '~/features/external-user-group/server/models/external-user-group';
  22. import ExternalUserGroupRelation from '~/features/external-user-group/server/models/external-user-group-relation';
  23. import type { IOptionsForCreate } from '~/interfaces/page';
  24. import type { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  25. import loggerFactory from '../../utils/logger';
  26. import { collectAncestorPaths } from '../util/collect-ancestor-paths';
  27. import { getOrCreateModel } from '../util/mongoose-utils';
  28. import { getPageSchema, extractToAncestorsPaths, populateDataToShowRevision } from './obsolete-page';
  29. import type { UserGroupDocument } from './user-group';
  30. import UserGroupRelation from './user-group-relation';
  31. const logger = loggerFactory('growi:models:page');
  32. /*
  33. * define schema
  34. */
  35. const GRANT_PUBLIC = 1;
  36. const GRANT_RESTRICTED = 2;
  37. const GRANT_SPECIFIED = 3; // DEPRECATED
  38. const GRANT_OWNER = 4;
  39. const GRANT_USER_GROUP = 5;
  40. const PAGE_GRANT_ERROR = 1;
  41. const STATUS_PUBLISHED = 'published';
  42. const STATUS_DELETED = 'deleted';
  43. export interface PageDocument extends IPage, Document<Types.ObjectId> {
  44. [x:string]: any // for obsolete methods
  45. getLatestRevisionBodyLength(): Promise<number | null | undefined>
  46. calculateAndUpdateLatestRevisionBodyLength(this: PageDocument): Promise<void>
  47. populateDataToShowRevision(shouldExcludeBody?: boolean): Promise<IPagePopulatedToShowRevision>
  48. }
  49. type TargetAndAncestorsResult = {
  50. targetAndAncestors: PageDocument[]
  51. rootPage: PageDocument
  52. }
  53. type PaginatedPages = {
  54. pages: PageDocument[],
  55. totalCount: number,
  56. limit: number,
  57. offset: number
  58. }
  59. export type FindRecentUpdatedPagesOption = {
  60. offset: number,
  61. limit: number,
  62. includeWipPage: boolean,
  63. includeTrashed: boolean,
  64. isRegExpEscapedFromPath: boolean,
  65. sort: 'updatedAt'
  66. desc: number
  67. hideRestrictedByOwner: boolean,
  68. hideRestrictedByGroup: boolean,
  69. }
  70. export type CreateMethod = (path: string, body: string, user, options: IOptionsForCreate) => Promise<HydratedDocument<PageDocument>>
  71. export interface PageModel extends Model<PageDocument> {
  72. [x: string]: any; // for obsolete static methods
  73. createEmptyPage(path: string, parent, descendantCount?: number): Promise<HydratedDocument<PageDocument>>
  74. findByIdAndViewer(pageId: ObjectIdLike, user, userGroups?, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument> | null>
  75. findByIdsAndViewer(
  76. pageIds: ObjectIdLike[], user, userGroups?, includeEmpty?: boolean, includeAnyoneWithTheLink?: boolean,
  77. ): Promise<HydratedDocument<PageDocument>[]>
  78. findByPath(path: string, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument> | null>
  79. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: true, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument> | null>
  80. findByPathAndViewer(path: string | null, user, userGroups?, useFindOne?: false, includeEmpty?: boolean): Promise<HydratedDocument<PageDocument>[]>
  81. countByPathAndViewer(path: string | null, user, userGroups?, includeEmpty?:boolean): Promise<number>
  82. findParentByPath(path: string | null): Promise<HydratedDocument<PageDocument> | null>
  83. findTargetAndAncestorsByPathOrId(pathOrId: string): Promise<TargetAndAncestorsResult>
  84. findRecentUpdatedPages(path: string, user, option: FindRecentUpdatedPagesOption, includeEmpty?: boolean): Promise<PaginatedPages>
  85. generateGrantCondition(
  86. user, userGroups: ObjectIdLike[] | null, includeAnyoneWithTheLink?: boolean, showPagesRestrictedByOwner?: boolean, showPagesRestrictedByGroup?: boolean,
  87. ): { $or: any[] }
  88. findNonEmptyClosestAncestor(path: string): Promise<HydratedDocument<PageDocument> | null>
  89. findNotEmptyParentByPathRecursively(path: string): Promise<HydratedDocument<PageDocument> | null>
  90. removeLeafEmptyPagesRecursively(pageId: ObjectIdLike): Promise<void>
  91. findTemplate(path: string): Promise<{
  92. templateBody?: string,
  93. templateTags?: string[],
  94. }>
  95. removeGroupsToDeleteFromPages(pages: PageDocument[], groupsToDelete: UserGroupDocument[] | ExternalUserGroupDocument[]): Promise<void>
  96. PageQueryBuilder: typeof PageQueryBuilder
  97. GRANT_PUBLIC
  98. GRANT_RESTRICTED
  99. GRANT_SPECIFIED
  100. GRANT_OWNER
  101. GRANT_USER_GROUP
  102. PAGE_GRANT_ERROR
  103. STATUS_PUBLISHED
  104. STATUS_DELETED
  105. }
  106. const schema = new Schema<PageDocument, PageModel>({
  107. parent: {
  108. type: Schema.Types.ObjectId, ref: 'Page', index: true, default: null,
  109. },
  110. descendantCount: { type: Number, default: 0 },
  111. isEmpty: { type: Boolean, default: false },
  112. path: {
  113. type: String, required: true, index: true,
  114. },
  115. revision: { type: Schema.Types.ObjectId, ref: 'Revision' },
  116. latestRevisionBodyLength: { type: Number },
  117. status: { type: String, default: STATUS_PUBLISHED, index: true },
  118. grant: { type: Number, default: GRANT_PUBLIC, index: true },
  119. grantedUsers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  120. grantedGroups: {
  121. type: [{
  122. type: {
  123. type: String,
  124. enum: Object.values(GroupType),
  125. required: true,
  126. default: 'UserGroup',
  127. },
  128. item: {
  129. type: Schema.Types.ObjectId,
  130. refPath: 'grantedGroups.type',
  131. required: true,
  132. index: true,
  133. },
  134. }],
  135. validate: [function(arr) {
  136. if (arr == null) return true;
  137. const uniqueItemValues = new Set(arr.map(e => e.item));
  138. return arr.length === uniqueItemValues.size;
  139. }, 'grantedGroups contains non unique item'],
  140. default: [],
  141. required: true,
  142. },
  143. creator: { type: Schema.Types.ObjectId, ref: 'User', index: true },
  144. lastUpdateUser: { type: Schema.Types.ObjectId, ref: 'User' },
  145. liker: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  146. seenUsers: [{ type: Schema.Types.ObjectId, ref: 'User' }],
  147. commentCount: { type: Number, default: 0 },
  148. expandContentWidth: { type: Boolean },
  149. wip: { type: Boolean },
  150. ttlTimestamp: { type: Date },
  151. updatedAt: { type: Date, default: Date.now }, // Do not use timetamps for updatedAt because it breaks 'updateMetadata: false' option
  152. deleteUser: { type: Schema.Types.ObjectId, ref: 'User' },
  153. deletedAt: { type: Date },
  154. }, {
  155. timestamps: { createdAt: true, updatedAt: false },
  156. toJSON: { getters: true },
  157. toObject: { getters: true },
  158. });
  159. // indexes
  160. schema.index({ createdAt: 1 });
  161. schema.index({ updatedAt: 1 });
  162. // apply plugins
  163. schema.plugin(mongoosePaginate);
  164. schema.plugin(uniqueValidator);
  165. export class PageQueryBuilder {
  166. query: any;
  167. constructor(query, includeEmpty = false) {
  168. this.query = query;
  169. if (!includeEmpty) {
  170. this.query = this.query
  171. .and({
  172. $or: [
  173. { isEmpty: false },
  174. { isEmpty: null }, // for v4 compatibility
  175. ],
  176. });
  177. }
  178. }
  179. /**
  180. * Used for filtering the pages at specified paths not to include unintentional pages.
  181. * @param pathsToFilter The paths to have additional filters as to be applicable
  182. * @returns PageQueryBuilder
  183. */
  184. addConditionToFilterByApplicableAncestors(pathsToFilter: string[]): PageQueryBuilder {
  185. this.query = this.query
  186. .and(
  187. {
  188. $or: [
  189. { path: '/' },
  190. { path: { $in: pathsToFilter }, grant: GRANT_PUBLIC, status: STATUS_PUBLISHED },
  191. { path: { $in: pathsToFilter }, parent: { $ne: null }, status: STATUS_PUBLISHED },
  192. { path: { $nin: pathsToFilter }, status: STATUS_PUBLISHED },
  193. ],
  194. },
  195. );
  196. return this;
  197. }
  198. addConditionToExcludeTrashed(): PageQueryBuilder {
  199. this.query = this.query
  200. .and({
  201. $or: [
  202. { status: null },
  203. { status: STATUS_PUBLISHED },
  204. ],
  205. });
  206. return this;
  207. }
  208. addConditionToExcludeWipPage(): PageQueryBuilder {
  209. this.query = this.query
  210. .and({
  211. $or: [
  212. { wip: undefined },
  213. { wip: false },
  214. ],
  215. });
  216. return this;
  217. }
  218. /**
  219. * generate the query to find the pages '{path}/*' and '{path}' self.
  220. * If top page, return without doing anything.
  221. */
  222. addConditionToListWithDescendants(path: string, option?): PageQueryBuilder {
  223. // No request is set for the top page
  224. if (isTopPage(path)) {
  225. return this;
  226. }
  227. const pathNormalized = normalizePath(path);
  228. const pathWithTrailingSlash = addTrailingSlash(path);
  229. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  230. this.query = this.query
  231. .and({
  232. $or: [
  233. { path: pathNormalized },
  234. { path: new RegExp(`^${startsPattern}`) },
  235. ],
  236. });
  237. return this;
  238. }
  239. /**
  240. * generate the query to find the pages '{path}/*' (exclude '{path}' self).
  241. */
  242. addConditionToListOnlyDescendants(path: string, option): PageQueryBuilder {
  243. // exclude the target page
  244. this.query = this.query.and({ path: { $ne: path } });
  245. if (isTopPage(path)) {
  246. return this;
  247. }
  248. const pathWithTrailingSlash = addTrailingSlash(path);
  249. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  250. this.query = this.query
  251. .and(
  252. { path: new RegExp(`^${startsPattern}`) },
  253. );
  254. return this;
  255. }
  256. addConditionToListOnlyAncestors(path: string): PageQueryBuilder {
  257. const pathNormalized = normalizePath(path);
  258. const ancestorsPaths = extractToAncestorsPaths(pathNormalized);
  259. this.query = this.query
  260. // exclude the target page
  261. .and({ path: { $ne: path } })
  262. .and(
  263. { path: { $in: ancestorsPaths } },
  264. );
  265. return this;
  266. }
  267. /**
  268. * generate the query to find pages that start with `path`
  269. *
  270. * In normal case, returns '{path}/*' and '{path}' self.
  271. * If top page, return without doing anything.
  272. *
  273. * *option*
  274. * Left for backward compatibility
  275. */
  276. addConditionToListByStartWith(str: string): PageQueryBuilder {
  277. const path = normalizePath(str);
  278. // No request is set for the top page
  279. if (isTopPage(path)) {
  280. return this;
  281. }
  282. const startsPattern = escapeStringRegexp(path);
  283. this.query = this.query
  284. .and({ path: new RegExp(`^${startsPattern}`) });
  285. return this;
  286. }
  287. addConditionToListByNotStartWith(str: string): PageQueryBuilder {
  288. const path = normalizePath(str);
  289. // No request is set for the top page
  290. if (isTopPage(path)) {
  291. return this;
  292. }
  293. const startsPattern = escapeStringRegexp(str);
  294. this.query = this.query
  295. .and({ path: new RegExp(`^(?!${startsPattern}).*$`) });
  296. return this;
  297. }
  298. addConditionToListByMatch(str: string): PageQueryBuilder {
  299. // No request is set for "/"
  300. if (str === '/') {
  301. return this;
  302. }
  303. const match = escapeStringRegexp(str);
  304. this.query = this.query
  305. .and({ path: new RegExp(`^(?=.*${match}).*$`) });
  306. return this;
  307. }
  308. addConditionToListByNotMatch(str: string): PageQueryBuilder {
  309. // No request is set for "/"
  310. if (str === '/') {
  311. return this;
  312. }
  313. const match = escapeStringRegexp(str);
  314. this.query = this.query
  315. .and({ path: new RegExp(`^(?!.*${match}).*$`) });
  316. return this;
  317. }
  318. async addConditionForParentNormalization(user): Promise<PageQueryBuilder> {
  319. // determine UserGroup condition
  320. const userGroups = user != null ? [
  321. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  322. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  323. ] : null;
  324. const grantConditions: any[] = [
  325. { grant: null },
  326. { grant: GRANT_PUBLIC },
  327. ];
  328. if (user != null) {
  329. grantConditions.push(
  330. { grant: GRANT_OWNER, grantedUsers: user._id },
  331. );
  332. }
  333. if (userGroups != null && userGroups.length > 0) {
  334. grantConditions.push(
  335. {
  336. grant: GRANT_USER_GROUP,
  337. grantedGroups: { $elemMatch: { item: { $in: userGroups } } },
  338. },
  339. );
  340. }
  341. this.query = this.query
  342. .and({
  343. $or: grantConditions,
  344. });
  345. return this;
  346. }
  347. async addConditionAsMigratablePages(user): Promise<PageQueryBuilder> {
  348. this.query = this.query
  349. .and({
  350. $or: [
  351. { grant: { $ne: GRANT_RESTRICTED } },
  352. { grant: { $ne: GRANT_SPECIFIED } },
  353. ],
  354. });
  355. this.addConditionAsRootOrNotOnTree();
  356. this.addConditionAsNonRootPage();
  357. this.addConditionToExcludeTrashed();
  358. await this.addConditionForParentNormalization(user);
  359. return this;
  360. }
  361. // add viewer condition to PageQueryBuilder instance
  362. async addViewerCondition(
  363. user,
  364. userGroups = null,
  365. includeAnyoneWithTheLink = false,
  366. showPagesRestrictedByOwner = false,
  367. showPagesRestrictedByGroup = false,
  368. ): Promise<PageQueryBuilder> {
  369. const relatedUserGroups = (user != null && userGroups == null) ? [
  370. ...(await UserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  371. ...(await ExternalUserGroupRelation.findAllUserGroupIdsRelatedToUser(user)),
  372. ] : userGroups;
  373. this.addConditionToFilteringByViewer(user, relatedUserGroups, includeAnyoneWithTheLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup);
  374. return this;
  375. }
  376. addConditionToFilteringByViewer(
  377. user, userGroups: ObjectIdLike[] | null, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  378. ): PageQueryBuilder {
  379. const condition = generateGrantCondition(user, userGroups, includeAnyoneWithTheLink, showPagesRestrictedByOwner, showPagesRestrictedByGroup);
  380. this.query = this.query
  381. .and(condition);
  382. return this;
  383. }
  384. addConditionForSystemDeletion(): PageQueryBuilder {
  385. const condition = generateGrantConditionForSystemDeletion();
  386. this.query = this.query.and(condition);
  387. return this;
  388. }
  389. addConditionToPagenate(offset, limit, sortOpt?): PageQueryBuilder {
  390. this.query = this.query
  391. .sort(sortOpt).skip(offset).limit(limit); // eslint-disable-line newline-per-chained-call
  392. return this;
  393. }
  394. addConditionAsNonRootPage(): PageQueryBuilder {
  395. this.query = this.query.and({ path: { $ne: '/' } });
  396. return this;
  397. }
  398. addConditionAsRootOrNotOnTree(): PageQueryBuilder {
  399. this.query = this.query
  400. .and({ parent: null });
  401. return this;
  402. }
  403. addConditionAsOnTree(): PageQueryBuilder {
  404. this.query = this.query
  405. .and(
  406. {
  407. $or: [
  408. { parent: { $ne: null } },
  409. { path: '/' },
  410. ],
  411. },
  412. );
  413. return this;
  414. }
  415. /*
  416. * Add this condition when get any ancestor pages including the target's parent
  417. */
  418. addConditionToSortPagesByDescPath(): PageQueryBuilder {
  419. this.query = this.query.sort('-path');
  420. return this;
  421. }
  422. addConditionToSortPagesByAscPath(): PageQueryBuilder {
  423. this.query = this.query.sort('path');
  424. return this;
  425. }
  426. addConditionToMinimizeDataForRendering(): PageQueryBuilder {
  427. this.query = this.query.select('_id path isEmpty grant revision descendantCount');
  428. return this;
  429. }
  430. addConditionToListByPathsArray(paths): PageQueryBuilder {
  431. this.query = this.query
  432. .and({
  433. path: {
  434. $in: paths,
  435. },
  436. });
  437. return this;
  438. }
  439. addConditionToListByPageIdsArray(pageIds): PageQueryBuilder {
  440. this.query = this.query
  441. .and({
  442. _id: {
  443. $in: pageIds,
  444. },
  445. });
  446. return this;
  447. }
  448. addConditionToExcludeByPageIdsArray(pageIds): PageQueryBuilder {
  449. this.query = this.query
  450. .and({
  451. _id: {
  452. $nin: pageIds,
  453. },
  454. });
  455. return this;
  456. }
  457. populateDataToList(userPublicFields): PageQueryBuilder {
  458. this.query = this.query
  459. .populate({
  460. path: 'lastUpdateUser',
  461. select: userPublicFields,
  462. });
  463. return this;
  464. }
  465. populateDataToShowRevision(userPublicFields): PageQueryBuilder {
  466. this.query = populateDataToShowRevision(this.query, userPublicFields);
  467. return this;
  468. }
  469. addConditionToFilteringByParentId(parentId): PageQueryBuilder {
  470. this.query = this.query.and({ parent: parentId });
  471. return this;
  472. }
  473. addConditionToListByPathsArrayWithGlob(paths: string[]): PageQueryBuilder {
  474. const conditions: Array<{ path: string | RegExp;}> = paths.map((path) => {
  475. if (path.endsWith('/*')) {
  476. const basePathWithoutGlob = path.slice(0, -2); // remove '/*'
  477. const pathWithTrailingSlash = addTrailingSlash(basePathWithoutGlob);
  478. const startsPattern = escapeStringRegexp(pathWithTrailingSlash);
  479. return { path: new RegExp(`^${startsPattern}`) };
  480. }
  481. return { path: normalizePath(path) };
  482. });
  483. this.query = this.query
  484. .and({
  485. $or: conditions,
  486. });
  487. return this;
  488. }
  489. }
  490. schema.statics.createEmptyPage = async function(
  491. path: string, parent: any, descendantCount = 0,
  492. ): Promise<HydratedDocument<PageDocument>> {
  493. if (parent == null) {
  494. throw Error('parent must not be null');
  495. }
  496. const page = new this();
  497. page.path = path;
  498. page.isEmpty = true;
  499. page.parent = parent;
  500. page.descendantCount = descendantCount;
  501. return page.save();
  502. };
  503. /**
  504. * Replace an existing page with an empty page.
  505. * It updates the children's parent to the new empty page's _id.
  506. * @param exPage a page document to be replaced
  507. * @returns Promise<void>
  508. */
  509. schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false) {
  510. // find parent
  511. const parent = await this.findOne({ _id: exPage.parent });
  512. if (parent == null) {
  513. throw Error('parent to update does not exist. Prepare parent first.');
  514. }
  515. // create empty page at path
  516. const newTarget = pageToReplaceWith == null ? await this.createEmptyPage(exPage.path, parent, exPage.descendantCount) : pageToReplaceWith;
  517. // find children by ex-page _id
  518. const children = await this.find({ parent: exPage._id });
  519. // bulkWrite
  520. const operationForNewTarget = {
  521. updateOne: {
  522. filter: { _id: newTarget._id },
  523. update: {
  524. parent: parent._id,
  525. },
  526. },
  527. };
  528. const operationsForChildren = {
  529. updateMany: {
  530. filter: {
  531. _id: { $in: children.map(d => d._id) },
  532. },
  533. update: {
  534. parent: newTarget._id,
  535. },
  536. },
  537. };
  538. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  539. const isExPageEmpty = exPage.isEmpty;
  540. if (deleteExPageIfEmpty && isExPageEmpty) {
  541. await this.deleteOne({ _id: exPage._id });
  542. logger.warn('Deleted empty page since it was replaced with another page.');
  543. }
  544. return this.findById(newTarget._id);
  545. };
  546. /*
  547. * Find pages by ID and viewer.
  548. */
  549. schema.statics.findByIdsAndViewer = async function(
  550. pageIds: string[], user, userGroups?, includeEmpty?: boolean, includeAnyoneWithTheLink?: boolean,
  551. ): Promise<PageDocument[]> {
  552. const baseQuery = this.find({ _id: { $in: pageIds } });
  553. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  554. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  555. return queryBuilder.query.exec();
  556. };
  557. /*
  558. * Find a page by path and viewer. Pass true to useFindOne to use findOne method.
  559. */
  560. schema.statics.findByPathAndViewer = async function(
  561. path: string | null, user, userGroups = null, useFindOne = false, includeEmpty = false,
  562. ): Promise<(PageDocument | PageDocument[]) & HasObjectId | null> {
  563. if (path == null) {
  564. throw new Error('path is required.');
  565. }
  566. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  567. const includeAnyoneWithTheLink = useFindOne;
  568. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  569. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  570. return queryBuilder.query.exec();
  571. };
  572. schema.statics.countByPathAndViewer = async function(path: string | null, user, userGroups = null, includeEmpty = false): Promise<number> {
  573. if (path == null) {
  574. throw new Error('path is required.');
  575. }
  576. const baseQuery = this.count({ path });
  577. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  578. await queryBuilder.addViewerCondition(user, userGroups);
  579. return queryBuilder.query.exec();
  580. };
  581. schema.statics.findRecentUpdatedPages = async function(
  582. path: string, user, options: FindRecentUpdatedPagesOption, includeEmpty = false,
  583. ): Promise<PaginatedPages> {
  584. const sortOpt = {};
  585. sortOpt[options.sort] = options.desc;
  586. const Page = this;
  587. const User = mongoose.model('User') as any;
  588. if (path == null) {
  589. throw new Error('path is required.');
  590. }
  591. const baseQuery = this.find({});
  592. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  593. if (!options.includeTrashed) {
  594. queryBuilder.addConditionToExcludeTrashed();
  595. }
  596. if (!options.includeWipPage) {
  597. queryBuilder.addConditionToExcludeWipPage();
  598. }
  599. queryBuilder.addConditionToListWithDescendants(path, options);
  600. queryBuilder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  601. await queryBuilder.addViewerCondition(user, undefined, undefined, !options.hideRestrictedByOwner, !options.hideRestrictedByGroup);
  602. const pages = await Page.paginate(queryBuilder.query.clone(), {
  603. lean: true, sort: sortOpt, offset: options.offset, limit: options.limit,
  604. });
  605. const results = {
  606. pages: pages.docs, totalCount: pages.totalDocs, offset: options.offset, limit: options.limit,
  607. };
  608. return results;
  609. };
  610. /*
  611. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  612. * The result will include the target as well
  613. */
  614. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  615. let path;
  616. if (!hasSlash(pathOrId)) {
  617. const _id = pathOrId;
  618. const page = await this.findOne({ _id });
  619. path = page == null ? '/' : page.path;
  620. }
  621. else {
  622. path = pathOrId;
  623. }
  624. const ancestorPaths = collectAncestorPaths(path);
  625. ancestorPaths.push(path); // include target
  626. // Do not populate
  627. const queryBuilder = new PageQueryBuilder(this.find(), true);
  628. await queryBuilder.addViewerCondition(user, userGroups);
  629. const _targetAndAncestors: PageDocument[] = await queryBuilder
  630. .addConditionAsOnTree()
  631. .addConditionToListByPathsArray(ancestorPaths)
  632. .addConditionToMinimizeDataForRendering()
  633. .addConditionToSortPagesByDescPath()
  634. .query
  635. .lean()
  636. .exec();
  637. // no same path pages
  638. const ancestorsMap = new Map<string, PageDocument>();
  639. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  640. const targetAndAncestors = Array.from(ancestorsMap.values());
  641. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  642. return { targetAndAncestors, rootPage };
  643. };
  644. /**
  645. * Create empty pages at paths at which no pages exist
  646. * @param paths Page paths
  647. * @param aggrPipelineForExistingPages AggregationPipeline object to find existing pages at paths
  648. */
  649. schema.statics.createEmptyPagesByPaths = async function(paths: string[], aggrPipelineForExistingPages: any[]): Promise<void> {
  650. const existingPages = await this.aggregate(aggrPipelineForExistingPages);
  651. const existingPagePaths = existingPages.map(page => page.path);
  652. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  653. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  654. };
  655. /**
  656. * Find a parent page by path
  657. */
  658. schema.statics.findParentByPath = async function(path: string): Promise<HydratedDocument<PageDocument> | null> {
  659. const parentPath = nodePath.dirname(path);
  660. const builder = new PageQueryBuilder(this.find({ path: parentPath }), true);
  661. const pagesCanBeParent = await builder
  662. .addConditionAsOnTree()
  663. .query
  664. .exec();
  665. if (pagesCanBeParent.length >= 1) {
  666. return pagesCanBeParent[0]; // the earliest page will be the result
  667. }
  668. return null;
  669. };
  670. /*
  671. * Utils from obsolete-page.js
  672. */
  673. export async function pushRevision(pageData, newRevision, user) {
  674. await newRevision.save();
  675. pageData.revision = newRevision;
  676. pageData.latestRevisionBodyLength = newRevision.body.length;
  677. pageData.lastUpdateUser = user?._id ?? user;
  678. pageData.updatedAt = Date.now();
  679. return pageData.save();
  680. }
  681. /**
  682. * add/subtract descendantCount of pages with provided paths by increment.
  683. * increment can be negative number
  684. */
  685. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  686. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  687. };
  688. /**
  689. * recount descendantCount of a page with the provided id and return it
  690. */
  691. schema.statics.recountDescendantCount = async function(id: ObjectIdLike): Promise<number> {
  692. const res = await this.aggregate(
  693. [
  694. {
  695. $match: {
  696. parent: id,
  697. },
  698. },
  699. {
  700. $project: {
  701. parent: 1,
  702. isEmpty: 1,
  703. descendantCount: 1,
  704. },
  705. },
  706. {
  707. $group: {
  708. _id: '$parent',
  709. sumOfDescendantCount: {
  710. $sum: '$descendantCount',
  711. },
  712. sumOfDocsCount: {
  713. $sum: {
  714. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  715. },
  716. },
  717. },
  718. },
  719. {
  720. $set: {
  721. descendantCount: {
  722. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  723. },
  724. },
  725. },
  726. ],
  727. );
  728. return res.length === 0 ? 0 : res[0].descendantCount;
  729. };
  730. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  731. const self = this;
  732. const target = await this.findById(pageId);
  733. if (target == null) {
  734. throw Error('Target not found');
  735. }
  736. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  737. const parent = await self.findOne({ _id: target.parent });
  738. if (parent == null) {
  739. return ancestors;
  740. }
  741. return findAncestorsRecursively(parent, [...ancestors, parent]);
  742. }
  743. return findAncestorsRecursively(target);
  744. };
  745. // TODO: write test code
  746. /**
  747. * Recursively removes empty pages at leaf position.
  748. * @param pageId ObjectIdLike
  749. * @returns Promise<void>
  750. */
  751. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  752. const self = this;
  753. const initialPage = await this.findById(pageId);
  754. if (initialPage == null) {
  755. return;
  756. }
  757. if (!initialPage.isEmpty) {
  758. return;
  759. }
  760. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  761. if (!page.isEmpty) {
  762. return pageIds;
  763. }
  764. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  765. if (isChildrenOtherThanTargetExist) {
  766. return pageIds;
  767. }
  768. pageIds.push(page._id);
  769. const nextPage = await self.findById(page.parent);
  770. if (nextPage == null) {
  771. return pageIds;
  772. }
  773. return generatePageIdsToRemove(page, nextPage, pageIds);
  774. }
  775. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  776. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  777. };
  778. schema.statics.normalizeDescendantCountById = async function(pageId) {
  779. const children = await this.find({ parent: pageId });
  780. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  781. const sumChildPages = children.filter(p => !p.isEmpty).length;
  782. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  783. };
  784. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  785. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  786. };
  787. schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> {
  788. await this.deleteMany({
  789. _id: {
  790. $nin: pageIdsToNotRemove,
  791. },
  792. path: {
  793. $in: paths,
  794. },
  795. isEmpty: true,
  796. });
  797. };
  798. /**
  799. * Find a not empty parent recursively.
  800. * @param {string} path
  801. * @returns {Promise<PageDocument | null>}
  802. */
  803. schema.statics.findNotEmptyParentByPathRecursively = async function(path: string): Promise<PageDocument | null> {
  804. const parent = await this.findParentByPath(path);
  805. if (parent == null) {
  806. return null;
  807. }
  808. const recursive = async(page: PageDocument): Promise<PageDocument> => {
  809. if (!page.isEmpty) {
  810. return page;
  811. }
  812. const next = await this.findById(page.parent);
  813. if (next == null || isTopPage(next.path)) {
  814. return page;
  815. }
  816. return recursive(next);
  817. };
  818. const notEmptyParent = await recursive(parent);
  819. return notEmptyParent;
  820. };
  821. schema.statics.findParent = async function(pageId): Promise<PageDocument | null> {
  822. return this.findOne({ _id: pageId });
  823. };
  824. schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  825. export function generateGrantCondition(
  826. user, userGroups: ObjectIdLike[] | null, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  827. ): { $or: any[] } {
  828. const grantConditions: AnyObject[] = [
  829. { grant: null },
  830. { grant: GRANT_PUBLIC },
  831. ];
  832. if (includeAnyoneWithTheLink) {
  833. grantConditions.push({ grant: GRANT_RESTRICTED });
  834. }
  835. if (showPagesRestrictedByOwner) {
  836. grantConditions.push(
  837. { grant: GRANT_SPECIFIED },
  838. { grant: GRANT_OWNER },
  839. );
  840. }
  841. else if (user != null) {
  842. grantConditions.push(
  843. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  844. { grant: GRANT_OWNER, grantedUsers: user._id },
  845. );
  846. }
  847. if (showPagesRestrictedByGroup) {
  848. grantConditions.push(
  849. { grant: GRANT_USER_GROUP },
  850. );
  851. }
  852. else if (userGroups != null && userGroups.length > 0) {
  853. grantConditions.push(
  854. {
  855. grant: GRANT_USER_GROUP,
  856. grantedGroups: { $elemMatch: { item: { $in: userGroups } } },
  857. },
  858. );
  859. }
  860. return {
  861. $or: grantConditions,
  862. };
  863. }
  864. schema.statics.generateGrantCondition = generateGrantCondition;
  865. function generateGrantConditionForSystemDeletion(): { $or: any[] } {
  866. const grantCondition: AnyObject[] = [
  867. { grant: null },
  868. { grant: GRANT_PUBLIC },
  869. { grant: GRANT_RESTRICTED },
  870. { grant: GRANT_SPECIFIED },
  871. { grant: GRANT_OWNER },
  872. { grant: GRANT_USER_GROUP },
  873. ];
  874. return {
  875. $or: grantCondition,
  876. };
  877. }
  878. schema.statics.generateGrantConditionForSystemDeletion = generateGrantConditionForSystemDeletion;
  879. // find ancestor page with isEmpty: false. If parameter path is '/', return null
  880. schema.statics.findNonEmptyClosestAncestor = async function(path: string): Promise<PageDocument | null> {
  881. if (path === '/') {
  882. return null;
  883. }
  884. const builderForAncestors = new PageQueryBuilder(this.find(), false); // empty page not included
  885. const ancestors = await builderForAncestors
  886. .addConditionToListOnlyAncestors(path) // only ancestor paths
  887. .addConditionToSortPagesByDescPath() // sort by path in Desc. Long to Short.
  888. .query
  889. .exec();
  890. return ancestors[0] ?? null;
  891. };
  892. schema.statics.removeGroupsToDeleteFromPages = async function(pages: PageDocument[], groupsToDelete: UserGroupDocument[] | ExternalUserGroupDocument[]) {
  893. const groupsToDeleteIds = groupsToDelete.map(group => group._id.toString());
  894. const pageGroups = pages.reduce((acc: { canPublicize: PageDocument[], cannotPublicize: PageDocument[] }, page) => {
  895. const canPublicize = page.grantedGroups.every(group => groupsToDeleteIds.includes(getIdForRef(group.item).toString()));
  896. acc[canPublicize ? 'canPublicize' : 'cannotPublicize'].push(page);
  897. return acc;
  898. }, { canPublicize: [], cannotPublicize: [] });
  899. // Only publicize pages that can only be accessed by the groups to be deleted
  900. const publicizeQueries = pageGroups.canPublicize.map((page) => {
  901. return {
  902. updateOne: {
  903. filter: { _id: page._id },
  904. update: {
  905. grantedGroups: [],
  906. grant: this.GRANT_PUBLIC,
  907. },
  908. },
  909. };
  910. });
  911. // Remove the groups to be deleted from the grantedGroups of the pages that can be accessed by other groups
  912. const removeFromGrantedGroupsQueries = pageGroups.cannotPublicize.map((page) => {
  913. return {
  914. updateOne: {
  915. filter: { _id: page._id },
  916. update: { $set: { grantedGroups: page.grantedGroups.filter(group => !groupsToDeleteIds.includes(getIdForRef(group.item).toString())) } },
  917. },
  918. };
  919. });
  920. await this.bulkWrite([...publicizeQueries, ...removeFromGrantedGroupsQueries]);
  921. };
  922. /*
  923. * get latest revision body length
  924. */
  925. schema.methods.getLatestRevisionBodyLength = async function(this: PageDocument): Promise<number | null | undefined> {
  926. if (!this.isLatestRevision() || this.revision == null) {
  927. return null;
  928. }
  929. if (this.latestRevisionBodyLength == null) {
  930. await this.calculateAndUpdateLatestRevisionBodyLength();
  931. }
  932. return this.latestRevisionBodyLength;
  933. };
  934. /*
  935. * calculate and update latestRevisionBodyLength
  936. */
  937. schema.methods.calculateAndUpdateLatestRevisionBodyLength = async function(this: PageDocument): Promise<void> {
  938. if (!this.isLatestRevision() || this.revision == null) {
  939. logger.error('revision field is required.');
  940. return;
  941. }
  942. // eslint-disable-next-line rulesdir/no-populate
  943. const populatedPageDocument = await this.populate<PageDocument>('revision', 'body');
  944. assert(populatedPageDocument.revision != null);
  945. assert(isPopulated(populatedPageDocument.revision));
  946. this.latestRevisionBodyLength = populatedPageDocument.revision.body.length;
  947. await this.save();
  948. };
  949. schema.methods.publish = function() {
  950. this.wip = undefined;
  951. this.ttlTimestamp = undefined;
  952. };
  953. schema.methods.unpublish = function() {
  954. this.wip = true;
  955. this.ttlTimestamp = undefined;
  956. };
  957. schema.methods.makeWip = function(disableTtl: boolean) {
  958. this.wip = true;
  959. if (!disableTtl) {
  960. this.ttlTimestamp = new Date();
  961. }
  962. };
  963. /*
  964. * Merge obsolete page model methods and define new methods which depend on crowi instance
  965. */
  966. export default function PageModel(crowi): any {
  967. // add old page schema methods
  968. const pageSchema = getPageSchema(crowi);
  969. schema.methods = { ...pageSchema.methods, ...schema.methods };
  970. schema.statics = { ...pageSchema.statics, ...schema.statics };
  971. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  972. }