page.ts 33 KB

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