page.ts 34 KB

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