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 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. }
  474. schema.statics.createEmptyPage = async function(
  475. path: string, parent: any, descendantCount = 0,
  476. ): Promise<HydratedDocument<PageDocument>> {
  477. if (parent == null) {
  478. throw Error('parent must not be null');
  479. }
  480. const page = new this();
  481. page.path = path;
  482. page.isEmpty = true;
  483. page.parent = parent;
  484. page.descendantCount = descendantCount;
  485. return page.save();
  486. };
  487. /**
  488. * Replace an existing page with an empty page.
  489. * It updates the children's parent to the new empty page's _id.
  490. * @param exPage a page document to be replaced
  491. * @returns Promise<void>
  492. */
  493. schema.statics.replaceTargetWithPage = async function(exPage, pageToReplaceWith?, deleteExPageIfEmpty = false) {
  494. // find parent
  495. const parent = await this.findOne({ _id: exPage.parent });
  496. if (parent == null) {
  497. throw Error('parent to update does not exist. Prepare parent first.');
  498. }
  499. // create empty page at path
  500. const newTarget = pageToReplaceWith == null ? await this.createEmptyPage(exPage.path, parent, exPage.descendantCount) : pageToReplaceWith;
  501. // find children by ex-page _id
  502. const children = await this.find({ parent: exPage._id });
  503. // bulkWrite
  504. const operationForNewTarget = {
  505. updateOne: {
  506. filter: { _id: newTarget._id },
  507. update: {
  508. parent: parent._id,
  509. },
  510. },
  511. };
  512. const operationsForChildren = {
  513. updateMany: {
  514. filter: {
  515. _id: { $in: children.map(d => d._id) },
  516. },
  517. update: {
  518. parent: newTarget._id,
  519. },
  520. },
  521. };
  522. await this.bulkWrite([operationForNewTarget, operationsForChildren]);
  523. const isExPageEmpty = exPage.isEmpty;
  524. if (deleteExPageIfEmpty && isExPageEmpty) {
  525. await this.deleteOne({ _id: exPage._id });
  526. logger.warn('Deleted empty page since it was replaced with another page.');
  527. }
  528. return this.findById(newTarget._id);
  529. };
  530. /*
  531. * Find pages by ID and viewer.
  532. */
  533. schema.statics.findByIdsAndViewer = async function(
  534. pageIds: string[], user, userGroups?, includeEmpty?: boolean, includeAnyoneWithTheLink?: boolean,
  535. ): Promise<PageDocument[]> {
  536. const baseQuery = this.find({ _id: { $in: pageIds } });
  537. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  538. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  539. return queryBuilder.query.exec();
  540. };
  541. /*
  542. * Find a page by path and viewer. Pass true to useFindOne to use findOne method.
  543. */
  544. schema.statics.findByPathAndViewer = async function(
  545. path: string | null, user, userGroups = null, useFindOne = false, includeEmpty = false,
  546. ): Promise<(PageDocument | PageDocument[]) & HasObjectId | null> {
  547. if (path == null) {
  548. throw new Error('path is required.');
  549. }
  550. const baseQuery = useFindOne ? this.findOne({ path }) : this.find({ path });
  551. const includeAnyoneWithTheLink = useFindOne;
  552. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  553. await queryBuilder.addViewerCondition(user, userGroups, includeAnyoneWithTheLink);
  554. return queryBuilder.query.exec();
  555. };
  556. schema.statics.countByPathAndViewer = async function(path: string | null, user, userGroups = null, includeEmpty = false): Promise<number> {
  557. if (path == null) {
  558. throw new Error('path is required.');
  559. }
  560. const baseQuery = this.count({ path });
  561. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  562. await queryBuilder.addViewerCondition(user, userGroups);
  563. return queryBuilder.query.exec();
  564. };
  565. schema.statics.findRecentUpdatedPages = async function(
  566. path: string, user, options: FindRecentUpdatedPagesOption, includeEmpty = false,
  567. ): Promise<PaginatedPages> {
  568. const sortOpt = {};
  569. sortOpt[options.sort] = options.desc;
  570. const Page = this;
  571. const User = mongoose.model('User') as any;
  572. if (path == null) {
  573. throw new Error('path is required.');
  574. }
  575. const baseQuery = this.find({});
  576. const queryBuilder = new PageQueryBuilder(baseQuery, includeEmpty);
  577. if (!options.includeTrashed) {
  578. queryBuilder.addConditionToExcludeTrashed();
  579. }
  580. if (!options.includeWipPage) {
  581. queryBuilder.addConditionToExcludeWipPage();
  582. }
  583. queryBuilder.addConditionToListWithDescendants(path, options);
  584. queryBuilder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL);
  585. await queryBuilder.addViewerCondition(user, undefined, undefined, !options.hideRestrictedByOwner, !options.hideRestrictedByGroup);
  586. const pages = await Page.paginate(queryBuilder.query.clone(), {
  587. lean: true, sort: sortOpt, offset: options.offset, limit: options.limit,
  588. });
  589. const results = {
  590. pages: pages.docs, totalCount: pages.totalDocs, offset: options.offset, limit: options.limit,
  591. };
  592. return results;
  593. };
  594. /*
  595. * Find all ancestor pages by path. When duplicate pages found, it uses the oldest page as a result
  596. * The result will include the target as well
  597. */
  598. schema.statics.findTargetAndAncestorsByPathOrId = async function(pathOrId: string, user, userGroups): Promise<TargetAndAncestorsResult> {
  599. let path;
  600. if (!hasSlash(pathOrId)) {
  601. const _id = pathOrId;
  602. const page = await this.findOne({ _id });
  603. path = page == null ? '/' : page.path;
  604. }
  605. else {
  606. path = pathOrId;
  607. }
  608. const ancestorPaths = collectAncestorPaths(path);
  609. ancestorPaths.push(path); // include target
  610. // Do not populate
  611. const queryBuilder = new PageQueryBuilder(this.find(), true);
  612. await queryBuilder.addViewerCondition(user, userGroups);
  613. const _targetAndAncestors: PageDocument[] = await queryBuilder
  614. .addConditionAsOnTree()
  615. .addConditionToListByPathsArray(ancestorPaths)
  616. .addConditionToMinimizeDataForRendering()
  617. .addConditionToSortPagesByDescPath()
  618. .query
  619. .lean()
  620. .exec();
  621. // no same path pages
  622. const ancestorsMap = new Map<string, PageDocument>();
  623. _targetAndAncestors.forEach(page => ancestorsMap.set(page.path, page));
  624. const targetAndAncestors = Array.from(ancestorsMap.values());
  625. const rootPage = targetAndAncestors[targetAndAncestors.length - 1];
  626. return { targetAndAncestors, rootPage };
  627. };
  628. /**
  629. * Create empty pages at paths at which no pages exist
  630. * @param paths Page paths
  631. * @param aggrPipelineForExistingPages AggregationPipeline object to find existing pages at paths
  632. */
  633. schema.statics.createEmptyPagesByPaths = async function(paths: string[], aggrPipelineForExistingPages: any[]): Promise<void> {
  634. const existingPages = await this.aggregate(aggrPipelineForExistingPages);
  635. const existingPagePaths = existingPages.map(page => page.path);
  636. const notExistingPagePaths = paths.filter(path => !existingPagePaths.includes(path));
  637. await this.insertMany(notExistingPagePaths.map(path => ({ path, isEmpty: true })));
  638. };
  639. /**
  640. * Find a parent page by path
  641. */
  642. schema.statics.findParentByPath = async function(path: string): Promise<HydratedDocument<PageDocument> | null> {
  643. const parentPath = nodePath.dirname(path);
  644. const builder = new PageQueryBuilder(this.find({ path: parentPath }), true);
  645. const pagesCanBeParent = await builder
  646. .addConditionAsOnTree()
  647. .query
  648. .exec();
  649. if (pagesCanBeParent.length >= 1) {
  650. return pagesCanBeParent[0]; // the earliest page will be the result
  651. }
  652. return null;
  653. };
  654. /*
  655. * Utils from obsolete-page.js
  656. */
  657. export async function pushRevision(pageData, newRevision, user) {
  658. await newRevision.save();
  659. pageData.revision = newRevision;
  660. pageData.latestRevisionBodyLength = newRevision.body.length;
  661. pageData.lastUpdateUser = user?._id ?? user;
  662. pageData.updatedAt = Date.now();
  663. return pageData.save();
  664. }
  665. /**
  666. * add/subtract descendantCount of pages with provided paths by increment.
  667. * increment can be negative number
  668. */
  669. schema.statics.incrementDescendantCountOfPageIds = async function(pageIds: ObjectIdLike[], increment: number): Promise<void> {
  670. await this.updateMany({ _id: { $in: pageIds } }, { $inc: { descendantCount: increment } });
  671. };
  672. /**
  673. * recount descendantCount of a page with the provided id and return it
  674. */
  675. schema.statics.recountDescendantCount = async function(id: ObjectIdLike): Promise<number> {
  676. const res = await this.aggregate(
  677. [
  678. {
  679. $match: {
  680. parent: id,
  681. },
  682. },
  683. {
  684. $project: {
  685. parent: 1,
  686. isEmpty: 1,
  687. descendantCount: 1,
  688. },
  689. },
  690. {
  691. $group: {
  692. _id: '$parent',
  693. sumOfDescendantCount: {
  694. $sum: '$descendantCount',
  695. },
  696. sumOfDocsCount: {
  697. $sum: {
  698. $cond: { if: { $eq: ['$isEmpty', true] }, then: 0, else: 1 }, // exclude isEmpty true page from sumOfDocsCount
  699. },
  700. },
  701. },
  702. },
  703. {
  704. $set: {
  705. descendantCount: {
  706. $sum: ['$sumOfDescendantCount', '$sumOfDocsCount'],
  707. },
  708. },
  709. },
  710. ],
  711. );
  712. return res.length === 0 ? 0 : res[0].descendantCount;
  713. };
  714. schema.statics.findAncestorsUsingParentRecursively = async function(pageId: ObjectIdLike, shouldIncludeTarget: boolean) {
  715. const self = this;
  716. const target = await this.findById(pageId);
  717. if (target == null) {
  718. throw Error('Target not found');
  719. }
  720. async function findAncestorsRecursively(target, ancestors = shouldIncludeTarget ? [target] : []) {
  721. const parent = await self.findOne({ _id: target.parent });
  722. if (parent == null) {
  723. return ancestors;
  724. }
  725. return findAncestorsRecursively(parent, [...ancestors, parent]);
  726. }
  727. return findAncestorsRecursively(target);
  728. };
  729. // TODO: write test code
  730. /**
  731. * Recursively removes empty pages at leaf position.
  732. * @param pageId ObjectIdLike
  733. * @returns Promise<void>
  734. */
  735. schema.statics.removeLeafEmptyPagesRecursively = async function(pageId: ObjectIdLike): Promise<void> {
  736. const self = this;
  737. const initialPage = await this.findById(pageId);
  738. if (initialPage == null) {
  739. return;
  740. }
  741. if (!initialPage.isEmpty) {
  742. return;
  743. }
  744. async function generatePageIdsToRemove(childPage, page, pageIds: ObjectIdLike[] = []): Promise<ObjectIdLike[]> {
  745. if (!page.isEmpty) {
  746. return pageIds;
  747. }
  748. const isChildrenOtherThanTargetExist = await self.exists({ _id: { $ne: childPage?._id }, parent: page._id });
  749. if (isChildrenOtherThanTargetExist) {
  750. return pageIds;
  751. }
  752. pageIds.push(page._id);
  753. const nextPage = await self.findById(page.parent);
  754. if (nextPage == null) {
  755. return pageIds;
  756. }
  757. return generatePageIdsToRemove(page, nextPage, pageIds);
  758. }
  759. const pageIdsToRemove = await generatePageIdsToRemove(null, initialPage);
  760. await this.deleteMany({ _id: { $in: pageIdsToRemove } });
  761. };
  762. schema.statics.normalizeDescendantCountById = async function(pageId) {
  763. const children = await this.find({ parent: pageId });
  764. const sumChildrenDescendantCount = children.map(d => d.descendantCount).reduce((c1, c2) => c1 + c2);
  765. const sumChildPages = children.filter(p => !p.isEmpty).length;
  766. return this.updateOne({ _id: pageId }, { $set: { descendantCount: sumChildrenDescendantCount + sumChildPages } }, { new: true });
  767. };
  768. schema.statics.takeOffFromTree = async function(pageId: ObjectIdLike) {
  769. return this.findByIdAndUpdate(pageId, { $set: { parent: null } });
  770. };
  771. schema.statics.removeEmptyPages = async function(pageIdsToNotRemove: ObjectIdLike[], paths: string[]): Promise<void> {
  772. await this.deleteMany({
  773. _id: {
  774. $nin: pageIdsToNotRemove,
  775. },
  776. path: {
  777. $in: paths,
  778. },
  779. isEmpty: true,
  780. });
  781. };
  782. /**
  783. * Find a not empty parent recursively.
  784. * @param {string} path
  785. * @returns {Promise<PageDocument | null>}
  786. */
  787. schema.statics.findNotEmptyParentByPathRecursively = async function(path: string): Promise<PageDocument | null> {
  788. const parent = await this.findParentByPath(path);
  789. if (parent == null) {
  790. return null;
  791. }
  792. const recursive = async(page: PageDocument): Promise<PageDocument> => {
  793. if (!page.isEmpty) {
  794. return page;
  795. }
  796. const next = await this.findById(page.parent);
  797. if (next == null || isTopPage(next.path)) {
  798. return page;
  799. }
  800. return recursive(next);
  801. };
  802. const notEmptyParent = await recursive(parent);
  803. return notEmptyParent;
  804. };
  805. schema.statics.findParent = async function(pageId): Promise<PageDocument | null> {
  806. return this.findOne({ _id: pageId });
  807. };
  808. schema.statics.PageQueryBuilder = PageQueryBuilder as any; // mongoose does not support constructor type as statics attrs type
  809. export function generateGrantCondition(
  810. user, userGroups: ObjectIdLike[] | null, includeAnyoneWithTheLink = false, showPagesRestrictedByOwner = false, showPagesRestrictedByGroup = false,
  811. ): { $or: any[] } {
  812. const grantConditions: AnyObject[] = [
  813. { grant: null },
  814. { grant: GRANT_PUBLIC },
  815. ];
  816. if (includeAnyoneWithTheLink) {
  817. grantConditions.push({ grant: GRANT_RESTRICTED });
  818. }
  819. if (showPagesRestrictedByOwner) {
  820. grantConditions.push(
  821. { grant: GRANT_SPECIFIED },
  822. { grant: GRANT_OWNER },
  823. );
  824. }
  825. else if (user != null) {
  826. grantConditions.push(
  827. { grant: GRANT_SPECIFIED, grantedUsers: user._id },
  828. { grant: GRANT_OWNER, grantedUsers: user._id },
  829. );
  830. }
  831. if (showPagesRestrictedByGroup) {
  832. grantConditions.push(
  833. { grant: GRANT_USER_GROUP },
  834. );
  835. }
  836. else if (userGroups != null && userGroups.length > 0) {
  837. grantConditions.push(
  838. {
  839. grant: GRANT_USER_GROUP,
  840. grantedGroups: { $elemMatch: { item: { $in: userGroups } } },
  841. },
  842. );
  843. }
  844. return {
  845. $or: grantConditions,
  846. };
  847. }
  848. schema.statics.generateGrantCondition = generateGrantCondition;
  849. function generateGrantConditionForSystemDeletion(): { $or: any[] } {
  850. const grantCondition: AnyObject[] = [
  851. { grant: null },
  852. { grant: GRANT_PUBLIC },
  853. { grant: GRANT_RESTRICTED },
  854. { grant: GRANT_SPECIFIED },
  855. { grant: GRANT_OWNER },
  856. { grant: GRANT_USER_GROUP },
  857. ];
  858. return {
  859. $or: grantCondition,
  860. };
  861. }
  862. schema.statics.generateGrantConditionForSystemDeletion = generateGrantConditionForSystemDeletion;
  863. // find ancestor page with isEmpty: false. If parameter path is '/', return null
  864. schema.statics.findNonEmptyClosestAncestor = async function(path: string): Promise<PageDocument | null> {
  865. if (path === '/') {
  866. return null;
  867. }
  868. const builderForAncestors = new PageQueryBuilder(this.find(), false); // empty page not included
  869. const ancestors = await builderForAncestors
  870. .addConditionToListOnlyAncestors(path) // only ancestor paths
  871. .addConditionToSortPagesByDescPath() // sort by path in Desc. Long to Short.
  872. .query
  873. .exec();
  874. return ancestors[0] ?? null;
  875. };
  876. schema.statics.removeGroupsToDeleteFromPages = async function(pages: PageDocument[], groupsToDelete: UserGroupDocument[] | ExternalUserGroupDocument[]) {
  877. const groupsToDeleteIds = groupsToDelete.map(group => group._id.toString());
  878. const pageGroups = pages.reduce((acc: { canPublicize: PageDocument[], cannotPublicize: PageDocument[] }, page) => {
  879. const canPublicize = page.grantedGroups.every(group => groupsToDeleteIds.includes(getIdForRef(group.item).toString()));
  880. acc[canPublicize ? 'canPublicize' : 'cannotPublicize'].push(page);
  881. return acc;
  882. }, { canPublicize: [], cannotPublicize: [] });
  883. // Only publicize pages that can only be accessed by the groups to be deleted
  884. const publicizeQueries = pageGroups.canPublicize.map((page) => {
  885. return {
  886. updateOne: {
  887. filter: { _id: page._id },
  888. update: {
  889. grantedGroups: [],
  890. grant: this.GRANT_PUBLIC,
  891. },
  892. },
  893. };
  894. });
  895. // Remove the groups to be deleted from the grantedGroups of the pages that can be accessed by other groups
  896. const removeFromGrantedGroupsQueries = pageGroups.cannotPublicize.map((page) => {
  897. return {
  898. updateOne: {
  899. filter: { _id: page._id },
  900. update: { $set: { grantedGroups: page.grantedGroups.filter(group => !groupsToDeleteIds.includes(getIdForRef(group.item).toString())) } },
  901. },
  902. };
  903. });
  904. await this.bulkWrite([...publicizeQueries, ...removeFromGrantedGroupsQueries]);
  905. };
  906. /*
  907. * get latest revision body length
  908. */
  909. schema.methods.getLatestRevisionBodyLength = async function(this: PageDocument): Promise<number | null | undefined> {
  910. if (!this.isLatestRevision() || this.revision == null) {
  911. return null;
  912. }
  913. if (this.latestRevisionBodyLength == null) {
  914. await this.calculateAndUpdateLatestRevisionBodyLength();
  915. }
  916. return this.latestRevisionBodyLength;
  917. };
  918. /*
  919. * calculate and update latestRevisionBodyLength
  920. */
  921. schema.methods.calculateAndUpdateLatestRevisionBodyLength = async function(this: PageDocument): Promise<void> {
  922. if (!this.isLatestRevision() || this.revision == null) {
  923. logger.error('revision field is required.');
  924. return;
  925. }
  926. // eslint-disable-next-line rulesdir/no-populate
  927. const populatedPageDocument = await this.populate<PageDocument>('revision', 'body');
  928. assert(populatedPageDocument.revision != null);
  929. assert(isPopulated(populatedPageDocument.revision));
  930. this.latestRevisionBodyLength = populatedPageDocument.revision.body.length;
  931. await this.save();
  932. };
  933. schema.methods.publish = function() {
  934. this.wip = undefined;
  935. this.ttlTimestamp = undefined;
  936. };
  937. schema.methods.unpublish = function() {
  938. this.wip = true;
  939. this.ttlTimestamp = undefined;
  940. };
  941. schema.methods.makeWip = function(disableTtl: boolean) {
  942. this.wip = true;
  943. if (!disableTtl) {
  944. this.ttlTimestamp = new Date();
  945. }
  946. };
  947. /*
  948. * Merge obsolete page model methods and define new methods which depend on crowi instance
  949. */
  950. export default function PageModel(crowi): any {
  951. // add old page schema methods
  952. const pageSchema = getPageSchema(crowi);
  953. schema.methods = { ...pageSchema.methods, ...schema.methods };
  954. schema.statics = { ...pageSchema.statics, ...schema.statics };
  955. return getOrCreateModel<PageDocument, PageModel>('Page', schema as any); // TODO: improve type
  956. }